| 1 | mod commands; |
| 2 | mod executor; |
| 3 | mod media; |
| 4 | mod mutations; |
| 5 | mod room; |
| 6 | mod timeline; |
| 7 | mod watchers; |
| 8 | |
| 9 | use std::{ |
| 10 | collections::{HashMap, VecDeque}, |
| 11 | future::Future, |
| 12 | panic::AssertUnwindSafe, |
| 13 | sync::Arc, |
| 14 | }; |
| 15 | |
| 16 | use futures_util::FutureExt; |
| 17 | use matrix_sdk::{Client, SendOutsideWasm, SessionChange}; |
| 18 | use matrix_sdk_ui::sync_service::SyncService; |
| 19 | use ruma::OwnedRoomId; |
| 20 | use thiserror::Error as ThisError; |
| 21 | use tokio::sync::{broadcast, mpsc, watch}; |
| 22 | |
| 23 | pub(crate) use media::MediaService; |
| 24 | |
| 25 | use self::{ |
| 26 | commands::Job, |
| 27 | executor::{EngineBoxFuture, TaskSet}, |
| 28 | mutations::{Mutation, MutationJob}, |
| 29 | room::{ActorNote, ActorRequest, RoomActor}, |
| 30 | timeline::{SessionContext, Supervisor}, |
| 31 | }; |
| 32 | use crate::{ |
| 33 | AccountCommand, ClientHandle, Command, ConnectionState, EncryptionCommand, EngineErrorKind, |
| 34 | EngineFailure, Error, ErrorKind, Event, EventStream, LifecycleCommand, MediaCommand, |
| 35 | NotificationCommand, RoomCommand, Termination, TimelineCommand, |
| 36 | transport::{DriverPort, Request, Responder, transport_pair}, |
| 37 | }; |
| 38 | |
| 39 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 40 | #[non_exhaustive] |
| 41 | pub struct EngineConfig { |
| 42 | pub command_capacity: usize, |
| 43 | pub event_capacity: usize, |
| 44 | pub initial_history_limit: u16, |
| 45 | pub max_media_bytes: usize, |
| 46 | pub max_media_sources: usize, |
| 47 | } |
| 48 | |
| 49 | impl EngineConfig { |
| 50 | #[must_use] |
| 51 | pub const fn with_command_capacity(mut self, capacity: usize) -> Self { |
| 52 | self.command_capacity = capacity; |
| 53 | self |
| 54 | } |
| 55 | |
| 56 | #[must_use] |
| 57 | pub const fn with_event_capacity(mut self, capacity: usize) -> Self { |
| 58 | self.event_capacity = capacity; |
| 59 | self |
| 60 | } |
| 61 | |
| 62 | #[must_use] |
| 63 | pub const fn with_initial_history_limit(mut self, limit: u16) -> Self { |
| 64 | self.initial_history_limit = limit; |
| 65 | self |
| 66 | } |
| 67 | |
| 68 | #[must_use] |
| 69 | pub const fn with_max_media_bytes(mut self, bytes: usize) -> Self { |
| 70 | self.max_media_bytes = bytes; |
| 71 | self |
| 72 | } |
| 73 | |
| 74 | #[must_use] |
| 75 | pub const fn with_max_media_sources(mut self, sources: usize) -> Self { |
| 76 | self.max_media_sources = sources; |
| 77 | self |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl Default for EngineConfig { |
| 82 | fn default() -> Self { |
| 83 | Self { |
| 84 | command_capacity: 64, |
| 85 | event_capacity: 128, |
| 86 | initial_history_limit: 30, |
| 87 | max_media_bytes: 20 * 1024 * 1024, |
| 88 | max_media_sources: 2_048, |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[derive(Debug, ThisError)] |
| 94 | pub enum EngineError { |
| 95 | #[error("the Matrix client is not authenticated")] |
| 96 | Unauthenticated, |
| 97 | #[error("command, event, and media source capacities must be nonzero")] |
| 98 | ZeroCapacity, |
| 99 | #[error("could not build the sync service")] |
| 100 | SyncService(#[source] matrix_sdk_ui::sync_service::Error), |
| 101 | #[error("the event receiver has closed")] |
| 102 | EventReceiverClosed, |
| 103 | #[error("engine task {task} panicked")] |
| 104 | TaskPanicked { task: String }, |
| 105 | } |
| 106 | |
| 107 | impl EngineError { |
| 108 | fn failure(&self) -> EngineFailure { |
| 109 | EngineFailure { |
| 110 | kind: match self { |
| 111 | Self::EventReceiverClosed => EngineErrorKind::EventReceiverClosed, |
| 112 | Self::TaskPanicked { .. } => EngineErrorKind::Watcher, |
| 113 | Self::Unauthenticated | Self::ZeroCapacity | Self::SyncService(_) => { |
| 114 | EngineErrorKind::Other |
| 115 | } |
| 116 | }, |
| 117 | message: self.to_string(), |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[derive(Clone)] |
| 123 | enum TaskContext { |
| 124 | /// a panic here costs the caller an `Interrupted` answer and nothing else |
| 125 | Command(&'static str), |
| 126 | /// a panic here takes the engine with it |
| 127 | Watcher(&'static str), |
| 128 | RoomActor { |
| 129 | room_id: OwnedRoomId, |
| 130 | generation: u64, |
| 131 | }, |
| 132 | } |
| 133 | |
| 134 | impl TaskContext { |
| 135 | fn label(&self) -> String { |
| 136 | match self { |
| 137 | Self::Command(name) | Self::Watcher(name) => (*name).to_owned(), |
| 138 | Self::RoomActor { |
| 139 | room_id, |
| 140 | generation, |
| 141 | } => format!("room actor {room_id} generation {generation}"), |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// tasks catch their own panics, since the sdk's wasm join error drops the payload |
| 147 | fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String { |
| 148 | payload |
| 149 | .downcast_ref::<&str>() |
| 150 | .map(ToString::to_string) |
| 151 | .or_else(|| payload.downcast_ref::<String>().cloned()) |
| 152 | .unwrap_or_else(|| "task panicked with a non-string payload".to_owned()) |
| 153 | } |
| 154 | |
| 155 | struct TaskRegistry { |
| 156 | tasks: TaskSet<(TaskContext, Option<String>)>, |
| 157 | } |
| 158 | |
| 159 | impl TaskRegistry { |
| 160 | fn spawn( |
| 161 | &mut self, |
| 162 | context: TaskContext, |
| 163 | task: impl Future<Output = ()> + SendOutsideWasm + 'static, |
| 164 | ) { |
| 165 | self.tasks.spawn(async move { |
| 166 | let panic = AssertUnwindSafe(task) |
| 167 | .catch_unwind() |
| 168 | .await |
| 169 | .err() |
| 170 | .map(panic_message); |
| 171 | (context, panic) |
| 172 | }); |
| 173 | } |
| 174 | |
| 175 | fn is_empty(&self) -> bool { |
| 176 | self.tasks.is_empty() |
| 177 | } |
| 178 | |
| 179 | async fn join_next(&mut self) -> Option<(TaskContext, Option<String>)> { |
| 180 | loop { |
| 181 | if let Ok(done) = self.tasks.join_next().await? { |
| 182 | return Some(done); |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | async fn shutdown(&mut self) { |
| 188 | self.tasks.shutdown().await; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | enum RoomSlot { |
| 193 | Active { |
| 194 | generation: u64, |
| 195 | sender: mpsc::Sender<ActorRequest>, |
| 196 | }, |
| 197 | /// opens and closes that arrive while the actor winds down, replayed in order once it's gone |
| 198 | Closing { |
| 199 | generation: u64, |
| 200 | pending: VecDeque<Deferred>, |
| 201 | }, |
| 202 | } |
| 203 | |
| 204 | impl RoomSlot { |
| 205 | const fn generation(&self) -> u64 { |
| 206 | match self { |
| 207 | Self::Active { generation, .. } | Self::Closing { generation, .. } => *generation, |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | enum Deferred { |
| 213 | Open(Responder), |
| 214 | Close(Responder), |
| 215 | } |
| 216 | |
| 217 | struct Queues { |
| 218 | mutations: mpsc::Receiver<MutationJob>, |
| 219 | notifications: mpsc::Receiver<Job<NotificationCommand>>, |
| 220 | encryption: mpsc::Receiver<Job<EncryptionCommand>>, |
| 221 | session_changes: broadcast::Receiver<SessionChange>, |
| 222 | } |
| 223 | |
| 224 | /// requests other devices send us, handed from the sdk's event handler to the encryption worker |
| 225 | type IncomingVerifications = |
| 226 | mpsc::UnboundedSender<matrix_sdk::encryption::verification::VerificationRequest>; |
| 227 | |
| 228 | pub struct Engine { |
| 229 | client: Client, |
| 230 | sync: Arc<SyncService>, |
| 231 | port: DriverPort, |
| 232 | config: EngineConfig, |
| 233 | media: Arc<MediaService>, |
| 234 | tasks: TaskRegistry, |
| 235 | rooms: HashMap<OwnedRoomId, RoomSlot>, |
| 236 | next_generation: u64, |
| 237 | notes: mpsc::UnboundedReceiver<ActorNote>, |
| 238 | note_sender: mpsc::UnboundedSender<ActorNote>, |
| 239 | /// the rooms sliding sync should follow, applied off the run loop since it touches the store |
| 240 | subscriptions: watch::Sender<Vec<OwnedRoomId>>, |
| 241 | mutations: mpsc::Sender<MutationJob>, |
| 242 | notifications: mpsc::Sender<Job<NotificationCommand>>, |
| 243 | encryption: mpsc::Sender<Job<EncryptionCommand>>, |
| 244 | queues: Option<Queues>, |
| 245 | /// one progress forwarder per room that has uploaded, and whether it's subscribed yet |
| 246 | uploads: HashMap<OwnedRoomId, watch::Receiver<bool>>, |
| 247 | /// the client can outlive us, so the handler has to come off it when we stop |
| 248 | verification_handler: Option<matrix_sdk::event_handler::EventHandlerHandle>, |
| 249 | stop: mpsc::UnboundedSender<Termination>, |
| 250 | stops: mpsc::UnboundedReceiver<Termination>, |
| 251 | } |
| 252 | |
| 253 | impl Engine { |
| 254 | /// the escape hatch for a client you built yourself. `Session` is the usual way in |
| 255 | pub async fn from_client( |
| 256 | client: Client, |
| 257 | config: EngineConfig, |
| 258 | ) -> Result<(Self, ClientHandle, EventStream), EngineError> { |
| 259 | if client.user_id().is_none() { |
| 260 | return Err(EngineError::Unauthenticated); |
| 261 | } |
| 262 | if config.command_capacity == 0 |
| 263 | || config.event_capacity == 0 |
| 264 | || config.max_media_sources == 0 |
| 265 | { |
| 266 | return Err(EngineError::ZeroCapacity); |
| 267 | } |
| 268 | let session_changes = client.subscribe_to_session_changes(); |
| 269 | let sync = Arc::new( |
| 270 | SyncService::builder(client.clone()) |
| 271 | .with_offline_mode() |
| 272 | .build() |
| 273 | .await |
| 274 | .map_err(EngineError::SyncService)?, |
| 275 | ); |
| 276 | let media = Arc::new(MediaService::new( |
| 277 | client.clone(), |
| 278 | config.max_media_bytes, |
| 279 | config.max_media_sources, |
| 280 | )); |
| 281 | let (handle, port, events) = transport_pair( |
| 282 | client.clone(), |
| 283 | sync.clone(), |
| 284 | media.clone(), |
| 285 | config.command_capacity, |
| 286 | config.event_capacity, |
| 287 | ); |
| 288 | client.send_queue().enable_upload_progress(true); |
| 289 | let (note_sender, notes) = mpsc::unbounded_channel(); |
| 290 | let (stop, stops) = mpsc::unbounded_channel(); |
| 291 | let (mutations, mutation_queue) = mpsc::channel(config.command_capacity); |
| 292 | let (notifications, notification_queue) = mpsc::channel(config.command_capacity); |
| 293 | let (encryption, encryption_queue) = mpsc::channel(config.command_capacity); |
| 294 | let engine = Self { |
| 295 | client, |
| 296 | sync, |
| 297 | port, |
| 298 | config, |
| 299 | media, |
| 300 | tasks: TaskRegistry { |
| 301 | tasks: TaskSet::new(), |
| 302 | }, |
| 303 | rooms: HashMap::new(), |
| 304 | next_generation: 0, |
| 305 | notes, |
| 306 | note_sender, |
| 307 | subscriptions: watch::Sender::new(Vec::new()), |
| 308 | mutations, |
| 309 | notifications, |
| 310 | encryption, |
| 311 | queues: Some(Queues { |
| 312 | mutations: mutation_queue, |
| 313 | notifications: notification_queue, |
| 314 | encryption: encryption_queue, |
| 315 | session_changes, |
| 316 | }), |
| 317 | uploads: HashMap::new(), |
| 318 | verification_handler: None, |
| 319 | stop, |
| 320 | stops, |
| 321 | }; |
| 322 | Ok((engine, handle, events)) |
| 323 | } |
| 324 | |
| 325 | /// boxed because the engine's future is deep enough to blow the compiler's query depth |
| 326 | /// in every crate that spawns it, which isn't something a client should have to fix |
| 327 | pub fn run(self) -> EngineBoxFuture<'static, Result<Termination, EngineError>> { |
| 328 | Box::pin(self.run_inner()) |
| 329 | } |
| 330 | |
| 331 | async fn run_inner(mut self) -> Result<Termination, EngineError> { |
| 332 | let events = self.port.event_sender(); |
| 333 | let user_id = self |
| 334 | .client |
| 335 | .user_id() |
| 336 | .expect("authentication was checked during construction") |
| 337 | .to_owned(); |
| 338 | self.port |
| 339 | .connection_sender() |
| 340 | .send_replace(ConnectionState::Connecting); |
| 341 | for event in [ |
| 342 | Event::Authenticated { user_id }, |
| 343 | Event::ConnectionChanged(ConnectionState::Connecting), |
| 344 | ] { |
| 345 | if events.send(event).await.is_err() { |
| 346 | self.shutdown().await; |
| 347 | return Err(EngineError::EventReceiverClosed); |
| 348 | } |
| 349 | } |
| 350 | self.start_tasks(); |
| 351 | self.resume_upload_forwarders().await; |
| 352 | self.sync.start().await; |
| 353 | |
| 354 | let mut shutdown_reply = None; |
| 355 | let ending = loop { |
| 356 | tokio::select! { |
| 357 | biased; |
| 358 | () = events.closed() => break Err(EngineError::EventReceiverClosed), |
| 359 | Some(termination) = self.stops.recv() => break Ok(termination), |
| 360 | Some((context, panic)) = self.tasks.join_next(), if !self.tasks.is_empty() => { |
| 361 | let Some(message) = panic else { continue }; |
| 362 | if let TaskContext::Command(label) = context { |
| 363 | tracing::error!(label, panic = %message, "command task panicked"); |
| 364 | continue; |
| 365 | } |
| 366 | break Err(EngineError::TaskPanicked { task: context.label() }); |
| 367 | } |
| 368 | Some(note) = self.notes.recv() => self.actor_note(note).await, |
| 369 | request = self.port.recv() => { |
| 370 | let Some(request) = request else { break Ok(Termination::HandlesDropped) }; |
| 371 | if let Some(reply) = self.dispatch(request).await { |
| 372 | shutdown_reply = Some(reply); |
| 373 | break Ok(Termination::ShutDown); |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | }; |
| 378 | |
| 379 | if let Err(error) = &ending { |
| 380 | let _ = events.send(Event::Failed(error.failure())).await; |
| 381 | } |
| 382 | self.shutdown().await; |
| 383 | let _ = events.send(Event::Stopped).await; |
| 384 | if let Some(reply) = shutdown_reply { |
| 385 | reply.done(Ok(())); |
| 386 | } |
| 387 | // everything else still queued answers `Interrupted` as it drops, but a shutdown did happen |
| 388 | while let Some(Request { command, reply }) = self.port.try_recv() { |
| 389 | if matches!(command, Command::Lifecycle(LifecycleCommand::Shutdown)) { |
| 390 | reply.done(Ok(())); |
| 391 | } |
| 392 | } |
| 393 | ending |
| 394 | } |
| 395 | |
| 396 | fn start_tasks(&mut self) { |
| 397 | let queues = self.queues.take().expect("engine tasks start once"); |
| 398 | let (incoming, incoming_verifications) = mpsc::unbounded_channel(); |
| 399 | self.verification_handler = Some(self.verification_handler(incoming)); |
| 400 | let client = &self.client; |
| 401 | let events = || self.port.event_sender(); |
| 402 | let watchers: [(&'static str, EngineBoxFuture<'static, ()>); 11] = [ |
| 403 | ( |
| 404 | "upload watcher", |
| 405 | Box::pin(watchers::uploads( |
| 406 | client.clone(), |
| 407 | client.send_queue().subscribe(), |
| 408 | events(), |
| 409 | )), |
| 410 | ), |
| 411 | ( |
| 412 | "room subscription watcher", |
| 413 | Box::pin(watchers::room_subscriptions( |
| 414 | self.sync.clone(), |
| 415 | self.subscriptions.subscribe(), |
| 416 | )), |
| 417 | ), |
| 418 | ( |
| 419 | "session change watcher", |
| 420 | Box::pin(watchers::session( |
| 421 | queues.session_changes, |
| 422 | events(), |
| 423 | client |
| 424 | .device_id() |
| 425 | .expect("authentication was checked during construction") |
| 426 | .to_owned(), |
| 427 | self.stop.clone(), |
| 428 | )), |
| 429 | ), |
| 430 | ( |
| 431 | "connection state watcher", |
| 432 | Box::pin(watchers::connection( |
| 433 | self.sync.state(), |
| 434 | self.sync.clone(), |
| 435 | client.clone(), |
| 436 | events(), |
| 437 | self.port.connection_sender(), |
| 438 | )), |
| 439 | ), |
| 440 | ( |
| 441 | "send queue watcher", |
| 442 | Box::pin(watchers::send_queue_errors( |
| 443 | client.clone(), |
| 444 | client.send_queue().subscribe_errors(), |
| 445 | self.port.connection_sender().subscribe(), |
| 446 | )), |
| 447 | ), |
| 448 | ( |
| 449 | "encryption state watcher", |
| 450 | Box::pin(watchers::encryption(client.clone(), events())), |
| 451 | ), |
| 452 | ( |
| 453 | "room list watcher", |
| 454 | Box::pin(watchers::rooms(client.clone(), events())), |
| 455 | ), |
| 456 | ( |
| 457 | "notification settings watcher", |
| 458 | Box::pin(watchers::notification_settings(client.clone(), events())), |
| 459 | ), |
| 460 | ( |
| 461 | "room command worker", |
| 462 | Box::pin(mutations::run_scheduler( |
| 463 | client.clone(), |
| 464 | queues.mutations, |
| 465 | self.config.command_capacity, |
| 466 | )), |
| 467 | ), |
| 468 | ( |
| 469 | "notification command worker", |
| 470 | Box::pin(commands::run_notifications( |
| 471 | client.clone(), |
| 472 | queues.notifications, |
| 473 | )), |
| 474 | ), |
| 475 | ( |
| 476 | "encryption command worker", |
| 477 | Box::pin(commands::run_encryption( |
| 478 | client.clone(), |
| 479 | events(), |
| 480 | queues.encryption, |
| 481 | incoming_verifications, |
| 482 | )), |
| 483 | ), |
| 484 | ]; |
| 485 | for (label, task) in watchers { |
| 486 | self.tasks.spawn(TaskContext::Watcher(label), task); |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | fn verification_handler( |
| 491 | &self, |
| 492 | incoming: IncomingVerifications, |
| 493 | ) -> matrix_sdk::event_handler::EventHandlerHandle { |
| 494 | use matrix_sdk::ruma::events::key::verification::request::ToDeviceKeyVerificationRequestEvent; |
| 495 | self.client.add_event_handler( |
| 496 | move |event: ToDeviceKeyVerificationRequestEvent, client: Client| { |
| 497 | let incoming = incoming.clone(); |
| 498 | async move { |
| 499 | let request = client |
| 500 | .encryption() |
| 501 | .get_verification_request( |
| 502 | &event.sender, |
| 503 | event.content.transaction_id.as_str(), |
| 504 | ) |
| 505 | .await; |
| 506 | if let Some(request) = request { |
| 507 | let _ = incoming.send(request); |
| 508 | } |
| 509 | } |
| 510 | }, |
| 511 | ) |
| 512 | } |
| 513 | |
| 514 | /// hands back the shutdown request's responder, which is answered once we've stopped |
| 515 | async fn dispatch(&mut self, Request { command, reply }: Request) -> Option<Responder> { |
| 516 | let client = self.client.clone(); |
| 517 | match command { |
| 518 | Command::Lifecycle(LifecycleCommand::Shutdown) => return Some(reply), |
| 519 | Command::Account(AccountCommand::Logout) => { |
| 520 | let events = self.port.event_sender(); |
| 521 | let stop = self.stop.clone(); |
| 522 | self.spawn_command("logout", reply, async move { |
| 523 | client |
| 524 | .logout() |
| 525 | .await |
| 526 | .map_err(|source| Error::from_sdk("logout failed", source))?; |
| 527 | let _ = events.send(Event::LoggedOut).await; |
| 528 | let _ = stop.send(Termination::LoggedOut); |
| 529 | Ok(()) |
| 530 | }); |
| 531 | } |
| 532 | Command::Account(AccountCommand::SetAccountData { |
| 533 | event_type, |
| 534 | content, |
| 535 | }) => enqueue( |
| 536 | &self.mutations, |
| 537 | Job { |
| 538 | command: Mutation::GlobalAccountData { |
| 539 | event_type, |
| 540 | content, |
| 541 | }, |
| 542 | reply, |
| 543 | }, |
| 544 | ), |
| 545 | Command::Account(AccountCommand::SetDisplayName(name)) => { |
| 546 | self.spawn_command("set display name", reply, async move { |
| 547 | client |
| 548 | .account() |
| 549 | .set_display_name(name.as_deref()) |
| 550 | .await |
| 551 | .map_err(|source| Error::from_sdk("setting display name failed", source)) |
| 552 | }); |
| 553 | } |
| 554 | Command::Account(AccountCommand::SetAvatar(avatar)) => { |
| 555 | self.spawn_command("set avatar", reply, async move { |
| 556 | client |
| 557 | .account() |
| 558 | .set_avatar_url(avatar.as_deref()) |
| 559 | .await |
| 560 | .map_err(|source| Error::from_sdk("setting avatar failed", source)) |
| 561 | }); |
| 562 | } |
| 563 | Command::Account(AccountCommand::UploadAvatar { mimetype, bytes }) => { |
| 564 | let max_bytes = self.config.max_media_bytes; |
| 565 | self.spawn_command("upload avatar", reply, async move { |
| 566 | commands::upload_avatar(&client, &mimetype, bytes, max_bytes).await |
| 567 | }); |
| 568 | } |
| 569 | Command::Account(AccountCommand::RenameDevice { |
| 570 | device_id, |
| 571 | display_name, |
| 572 | }) => self.spawn_command("rename device", reply, async move { |
| 573 | commands::rename_device(&client, &device_id, &display_name).await |
| 574 | }), |
| 575 | Command::Account(AccountCommand::DeleteDevices { device_ids, auth }) => { |
| 576 | self.spawn_command("delete devices", reply, async move { |
| 577 | commands::delete_devices(&client, &device_ids, auth).await |
| 578 | }); |
| 579 | } |
| 580 | Command::Room(RoomCommand::Open(room_id)) => self.open_room(room_id, reply).await, |
| 581 | Command::Room(RoomCommand::Close(room_id)) => self.close_room(room_id, reply).await, |
| 582 | Command::Room(RoomCommand::SetTyping { room_id, typing }) => { |
| 583 | self.spawn_command("typing", reply, async move { |
| 584 | commands::set_typing(&client, &room_id, typing).await |
| 585 | }); |
| 586 | } |
| 587 | Command::Room(RoomCommand::CancelSend { |
| 588 | room_id, |
| 589 | transaction_id, |
| 590 | }) => self.spawn_command("cancel send", reply, async move { |
| 591 | commands::cancel_send(&client, &room_id, &transaction_id).await |
| 592 | }), |
| 593 | Command::Room(RoomCommand::RetrySend { |
| 594 | room_id, |
| 595 | transaction_id, |
| 596 | }) => self.spawn_command("retry send", reply, async move { |
| 597 | commands::retry_send(&client, &room_id, &transaction_id).await |
| 598 | }), |
| 599 | Command::Room(command) => enqueue( |
| 600 | &self.mutations, |
| 601 | Job { |
| 602 | command: Mutation::Room(command), |
| 603 | reply, |
| 604 | }, |
| 605 | ), |
| 606 | Command::Timeline(command) => self.route_timeline(command, reply), |
| 607 | Command::Media(MediaCommand::Upload(upload)) => self.upload(upload, reply), |
| 608 | Command::Encryption(command) => enqueue(&self.encryption, Job { command, reply }), |
| 609 | Command::Notification(command) => { |
| 610 | enqueue(&self.notifications, Job { command, reply }); |
| 611 | } |
| 612 | } |
| 613 | None |
| 614 | } |
| 615 | |
| 616 | fn spawn_command( |
| 617 | &mut self, |
| 618 | label: &'static str, |
| 619 | reply: Responder, |
| 620 | work: impl Future<Output = Result<(), Error>> + SendOutsideWasm + 'static, |
| 621 | ) { |
| 622 | self.tasks.spawn(TaskContext::Command(label), async move { |
| 623 | reply.done(work.await); |
| 624 | }); |
| 625 | } |
| 626 | |
| 627 | fn upload(&mut self, upload: crate::AttachmentUpload, reply: Responder) { |
| 628 | let Some(room) = self.client.get_room(upload.timeline_id.room_id()) else { |
| 629 | return reply.done(Err(Error::room_unknown())); |
| 630 | }; |
| 631 | let mut ready = self.upload_forwarder(&room); |
| 632 | let max_bytes = self.config.max_media_bytes; |
| 633 | // queueing before the forwarder listens would lose the first progress ticks |
| 634 | self.spawn_command("upload", reply, async move { |
| 635 | ready |
| 636 | .wait_for(|subscribed| *subscribed) |
| 637 | .await |
| 638 | .map_err(|_| Error::new(ErrorKind::Store, "reading the media send queue failed"))?; |
| 639 | media::queue_upload(room, upload, max_bytes).await |
| 640 | }); |
| 641 | } |
| 642 | |
| 643 | fn upload_forwarder(&mut self, room: &matrix_sdk::Room) -> watch::Receiver<bool> { |
| 644 | self.uploads.retain(|_, ready| ready.has_changed().is_ok()); |
| 645 | if let Some(ready) = self.uploads.get(room.room_id()) { |
| 646 | return ready.clone(); |
| 647 | } |
| 648 | let (subscribed, ready) = watch::channel(false); |
| 649 | self.tasks.spawn( |
| 650 | TaskContext::Command("upload watcher"), |
| 651 | watchers::room_uploads(room.clone(), self.port.event_sender(), subscribed), |
| 652 | ); |
| 653 | self.uploads |
| 654 | .insert(room.room_id().to_owned(), ready.clone()); |
| 655 | ready |
| 656 | } |
| 657 | |
| 658 | /// the sdk resumes uploads left over from last time, and they deserve progress too |
| 659 | async fn resume_upload_forwarders(&mut self) { |
| 660 | let Ok(echoes) = self.client.send_queue().local_echoes().await else { |
| 661 | return; |
| 662 | }; |
| 663 | for room_id in echoes.keys() { |
| 664 | if let Some(room) = self.client.get_room(room_id) { |
| 665 | self.upload_forwarder(&room); |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | fn route_timeline(&mut self, command: TimelineCommand, reply: Responder) { |
| 671 | let sender = match self.rooms.get(command.room_id()) { |
| 672 | Some(RoomSlot::Active { sender, .. }) => Some(sender.clone()), |
| 673 | _ => None, |
| 674 | }; |
| 675 | match (sender, command) { |
| 676 | (Some(sender), command) => send_actor(&sender, ActorRequest::Execute(command, reply)), |
| 677 | ( |
| 678 | None, |
| 679 | TimelineCommand::MarkRead { |
| 680 | timeline_id, |
| 681 | event_id, |
| 682 | }, |
| 683 | ) => { |
| 684 | let client = self.client.clone(); |
| 685 | self.spawn_command("mark read", reply, async move { |
| 686 | commands::mark_read(&client, &timeline_id, event_id).await |
| 687 | }); |
| 688 | } |
| 689 | (None, _) => reply.done(Err(Error::new(ErrorKind::RoomNotOpen, "room is not open"))), |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | async fn open_room(&mut self, room_id: OwnedRoomId, reply: Responder) { |
| 694 | match self.rooms.get_mut(&room_id) { |
| 695 | Some(RoomSlot::Active { sender, .. }) => send_actor(sender, ActorRequest::Open(reply)), |
| 696 | Some(RoomSlot::Closing { pending, .. }) => { |
| 697 | defer(pending, Deferred::Open(reply), self.config.command_capacity); |
| 698 | } |
| 699 | None => self.start_actor(room_id, reply).await, |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | async fn close_room(&mut self, room_id: OwnedRoomId, reply: Responder) { |
| 704 | let (generation, sender) = match self.rooms.get_mut(&room_id) { |
| 705 | None => return reply.done(Ok(())), |
| 706 | Some(RoomSlot::Closing { pending, .. }) => { |
| 707 | return defer( |
| 708 | pending, |
| 709 | Deferred::Close(reply), |
| 710 | self.config.command_capacity, |
| 711 | ); |
| 712 | } |
| 713 | Some(RoomSlot::Active { generation, sender }) => (*generation, sender.clone()), |
| 714 | }; |
| 715 | match sender.try_send(ActorRequest::Close(reply)) { |
| 716 | Ok(()) => {} |
| 717 | // the actor already left on its own, which is closed enough |
| 718 | Err(mpsc::error::TrySendError::Closed(request)) => request.into_reply().done(Ok(())), |
| 719 | Err(mpsc::error::TrySendError::Full(request)) => { |
| 720 | return request.into_reply().done(Err(Error::new( |
| 721 | ErrorKind::RoomBusy, |
| 722 | "room command queue is full", |
| 723 | ))); |
| 724 | } |
| 725 | } |
| 726 | self.rooms.insert( |
| 727 | room_id, |
| 728 | RoomSlot::Closing { |
| 729 | generation, |
| 730 | pending: VecDeque::new(), |
| 731 | }, |
| 732 | ); |
| 733 | self.update_room_subscriptions(); |
| 734 | } |
| 735 | |
| 736 | async fn start_actor(&mut self, room_id: OwnedRoomId, reply: Responder) { |
| 737 | let Some(room) = self.client.get_room(&room_id) else { |
| 738 | return reply.done(Err(Error::room_unknown())); |
| 739 | }; |
| 740 | self.next_generation = self.next_generation.wrapping_add(1); |
| 741 | let generation = self.next_generation; |
| 742 | let (sender, requests) = mpsc::channel(self.config.command_capacity); |
| 743 | let (supervisor, panics) = Supervisor::new(); |
| 744 | let actor = RoomActor { |
| 745 | room_id: room_id.clone(), |
| 746 | generation, |
| 747 | room, |
| 748 | requests, |
| 749 | notes: self.note_sender.clone(), |
| 750 | context: SessionContext { |
| 751 | events: self.port.event_sender(), |
| 752 | media: self.media.clone(), |
| 753 | current_user_id: self.client.user_id().map(ToOwned::to_owned), |
| 754 | initial_history_limit: self.config.initial_history_limit, |
| 755 | supervisor, |
| 756 | }, |
| 757 | panics, |
| 758 | opening: vec![reply], |
| 759 | }; |
| 760 | self.rooms |
| 761 | .insert(room_id.clone(), RoomSlot::Active { generation, sender }); |
| 762 | self.tasks.spawn( |
| 763 | TaskContext::RoomActor { |
| 764 | room_id, |
| 765 | generation, |
| 766 | }, |
| 767 | actor.run(), |
| 768 | ); |
| 769 | self.update_room_subscriptions(); |
| 770 | } |
| 771 | |
| 772 | async fn actor_note(&mut self, note: ActorNote) { |
| 773 | let (room_id, generation) = match ¬e { |
| 774 | ActorNote::Leaving { |
| 775 | room_id, |
| 776 | generation, |
| 777 | } |
| 778 | | ActorNote::Exited { |
| 779 | room_id, |
| 780 | generation, |
| 781 | .. |
| 782 | } => (room_id.clone(), *generation), |
| 783 | }; |
| 784 | if self |
| 785 | .rooms |
| 786 | .get(&room_id) |
| 787 | .is_none_or(|slot| slot.generation() != generation) |
| 788 | { |
| 789 | return; |
| 790 | } |
| 791 | let ActorNote::Exited { leftovers, .. } = note else { |
| 792 | if let Some(slot @ RoomSlot::Active { .. }) = self.rooms.get_mut(&room_id) { |
| 793 | *slot = RoomSlot::Closing { |
| 794 | generation, |
| 795 | pending: VecDeque::new(), |
| 796 | }; |
| 797 | self.update_room_subscriptions(); |
| 798 | } |
| 799 | return; |
| 800 | }; |
| 801 | let pending = match self.rooms.remove(&room_id) { |
| 802 | Some(RoomSlot::Closing { pending, .. }) => pending, |
| 803 | _ => VecDeque::new(), |
| 804 | }; |
| 805 | // leftovers were sent before anything deferred, so they go first |
| 806 | for request in leftovers { |
| 807 | match request { |
| 808 | ActorRequest::Open(reply) => self.open_room(room_id.clone(), reply).await, |
| 809 | ActorRequest::Close(reply) => reply.done(Ok(())), |
| 810 | ActorRequest::Execute(command, reply) => self.route_timeline(command, reply), |
| 811 | } |
| 812 | } |
| 813 | for deferred in pending { |
| 814 | match deferred { |
| 815 | Deferred::Open(reply) => self.open_room(room_id.clone(), reply).await, |
| 816 | Deferred::Close(reply) => self.close_room(room_id.clone(), reply).await, |
| 817 | } |
| 818 | } |
| 819 | self.update_room_subscriptions(); |
| 820 | } |
| 821 | |
| 822 | fn update_room_subscriptions(&self) { |
| 823 | let room_ids = self |
| 824 | .rooms |
| 825 | .iter() |
| 826 | .filter(|(_, slot)| matches!(slot, RoomSlot::Active { .. })) |
| 827 | .map(|(room_id, _)| room_id.clone()) |
| 828 | .collect(); |
| 829 | self.subscriptions.send_replace(room_ids); |
| 830 | } |
| 831 | |
| 832 | async fn shutdown(&mut self) { |
| 833 | if let Some(handler) = self.verification_handler.take() { |
| 834 | self.client.remove_event_handler(handler); |
| 835 | } |
| 836 | self.port.close(); |
| 837 | self.tasks.shutdown().await; |
| 838 | self.rooms.clear(); |
| 839 | self.uploads.clear(); |
| 840 | self.media.clear().await; |
| 841 | self.sync.stop().await; |
| 842 | self.port |
| 843 | .connection_sender() |
| 844 | .send_replace(ConnectionState::Stopped); |
| 845 | let _ = self |
| 846 | .port |
| 847 | .event_sender() |
| 848 | .send(Event::ConnectionChanged(ConnectionState::Stopped)) |
| 849 | .await; |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | fn send_actor(sender: &mpsc::Sender<ActorRequest>, request: ActorRequest) { |
| 854 | if let Err(error) = sender.try_send(request) { |
| 855 | let (request, error) = match error { |
| 856 | mpsc::error::TrySendError::Full(request) => ( |
| 857 | request, |
| 858 | Error::new(ErrorKind::RoomBusy, "room command queue is full"), |
| 859 | ), |
| 860 | mpsc::error::TrySendError::Closed(request) => ( |
| 861 | request, |
| 862 | Error::new(ErrorKind::RoomNotOpen, "room is not open"), |
| 863 | ), |
| 864 | }; |
| 865 | request.into_reply().done(Err(error)); |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | fn defer(pending: &mut VecDeque<Deferred>, deferred: Deferred, capacity: usize) { |
| 870 | if pending.len() < capacity { |
| 871 | return pending.push_back(deferred); |
| 872 | } |
| 873 | let (Deferred::Open(reply) | Deferred::Close(reply)) = deferred; |
| 874 | reply.done(Err(Error::new( |
| 875 | ErrorKind::RoomBusy, |
| 876 | "room lifecycle queue is full", |
| 877 | ))); |
| 878 | } |
| 879 | |
| 880 | fn enqueue<T>(sender: &mpsc::Sender<Job<T>>, job: Job<T>) { |
| 881 | if let Err(error) = sender.try_send(job) { |
| 882 | let (job, error) = match error { |
| 883 | mpsc::error::TrySendError::Full(job) => ( |
| 884 | job, |
| 885 | Error::new(ErrorKind::QueueFull, "command queue is full"), |
| 886 | ), |
| 887 | mpsc::error::TrySendError::Closed(job) => (job, Error::interrupted()), |
| 888 | }; |
| 889 | job.reply.done(Err(error)); |
| 890 | } |
| 891 | } |