| 1 | mod commands; |
| 2 | pub(crate) 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 | upload_reports: mpsc::Receiver<watchers::RoomUpload>, |
| 223 | } |
| 224 | |
| 225 | /// requests other devices send us, handed from the sdk's event handler to the encryption worker |
| 226 | type IncomingVerifications = |
| 227 | mpsc::UnboundedSender<matrix_sdk::encryption::verification::VerificationRequest>; |
| 228 | |
| 229 | pub struct Engine { |
| 230 | client: Client, |
| 231 | sync: Arc<SyncService>, |
| 232 | port: DriverPort, |
| 233 | config: EngineConfig, |
| 234 | media: Arc<MediaService>, |
| 235 | tasks: TaskRegistry, |
| 236 | rooms: HashMap<OwnedRoomId, RoomSlot>, |
| 237 | next_generation: u64, |
| 238 | notes: mpsc::UnboundedReceiver<ActorNote>, |
| 239 | note_sender: mpsc::UnboundedSender<ActorNote>, |
| 240 | /// the rooms sliding sync should follow, applied off the run loop since it touches the store |
| 241 | subscriptions: watch::Sender<Vec<OwnedRoomId>>, |
| 242 | mutations: mpsc::Sender<MutationJob>, |
| 243 | notifications: mpsc::Sender<Job<NotificationCommand>>, |
| 244 | encryption: mpsc::Sender<Job<EncryptionCommand>>, |
| 245 | queues: Option<Queues>, |
| 246 | /// one progress forwarder per room that has uploaded, and whether it's subscribed yet |
| 247 | uploads: HashMap<OwnedRoomId, watch::Receiver<bool>>, |
| 248 | upload_reports: mpsc::Sender<watchers::RoomUpload>, |
| 249 | /// the client can outlive us, so the handler has to come off it when we stop |
| 250 | verification_handler: Option<matrix_sdk::event_handler::EventHandlerHandle>, |
| 251 | stop: mpsc::UnboundedSender<Termination>, |
| 252 | stops: mpsc::UnboundedReceiver<Termination>, |
| 253 | } |
| 254 | |
| 255 | impl Engine { |
| 256 | /// the escape hatch for a client you built yourself. `Session` is the usual way in |
| 257 | pub async fn from_client( |
| 258 | client: Client, |
| 259 | config: EngineConfig, |
| 260 | ) -> Result<(Self, ClientHandle, EventStream), EngineError> { |
| 261 | if client.user_id().is_none() { |
| 262 | return Err(EngineError::Unauthenticated); |
| 263 | } |
| 264 | if config.command_capacity == 0 |
| 265 | || config.event_capacity == 0 |
| 266 | || config.max_media_sources == 0 |
| 267 | { |
| 268 | return Err(EngineError::ZeroCapacity); |
| 269 | } |
| 270 | let session_changes = client.subscribe_to_session_changes(); |
| 271 | let sync = Arc::new( |
| 272 | SyncService::builder(client.clone()) |
| 273 | .with_offline_mode() |
| 274 | .build() |
| 275 | .await |
| 276 | .map_err(EngineError::SyncService)?, |
| 277 | ); |
| 278 | let media = Arc::new(MediaService::new( |
| 279 | client.clone(), |
| 280 | config.max_media_bytes, |
| 281 | config.max_media_sources, |
| 282 | )); |
| 283 | let (handle, port, events) = transport_pair( |
| 284 | client.clone(), |
| 285 | sync.clone(), |
| 286 | media.clone(), |
| 287 | config.command_capacity, |
| 288 | config.event_capacity, |
| 289 | ); |
| 290 | client.send_queue().enable_upload_progress(true); |
| 291 | let (note_sender, notes) = mpsc::unbounded_channel(); |
| 292 | let (stop, stops) = mpsc::unbounded_channel(); |
| 293 | let (upload_reports, upload_report_queue) = mpsc::channel(config.event_capacity); |
| 294 | let (mutations, mutation_queue) = mpsc::channel(config.command_capacity); |
| 295 | let (notifications, notification_queue) = mpsc::channel(config.command_capacity); |
| 296 | let (encryption, encryption_queue) = mpsc::channel(config.command_capacity); |
| 297 | let engine = Self { |
| 298 | client, |
| 299 | sync, |
| 300 | port, |
| 301 | config, |
| 302 | media, |
| 303 | tasks: TaskRegistry { |
| 304 | tasks: TaskSet::new(), |
| 305 | }, |
| 306 | rooms: HashMap::new(), |
| 307 | next_generation: 0, |
| 308 | notes, |
| 309 | note_sender, |
| 310 | subscriptions: watch::Sender::new(Vec::new()), |
| 311 | mutations, |
| 312 | notifications, |
| 313 | encryption, |
| 314 | queues: Some(Queues { |
| 315 | mutations: mutation_queue, |
| 316 | notifications: notification_queue, |
| 317 | encryption: encryption_queue, |
| 318 | session_changes, |
| 319 | upload_reports: upload_report_queue, |
| 320 | }), |
| 321 | upload_reports, |
| 322 | uploads: HashMap::new(), |
| 323 | verification_handler: None, |
| 324 | stop, |
| 325 | stops, |
| 326 | }; |
| 327 | Ok((engine, handle, events)) |
| 328 | } |
| 329 | |
| 330 | /// boxed because the engine's future is deep enough to blow the compiler's query depth |
| 331 | /// in every crate that spawns it, which isn't something a client should have to fix |
| 332 | pub fn run(self) -> EngineBoxFuture<'static, Result<Termination, EngineError>> { |
| 333 | Box::pin(self.run_inner()) |
| 334 | } |
| 335 | |
| 336 | async fn run_inner(mut self) -> Result<Termination, EngineError> { |
| 337 | let events = self.port.event_sender(); |
| 338 | let user_id = self |
| 339 | .client |
| 340 | .user_id() |
| 341 | .expect("authentication was checked during construction") |
| 342 | .to_owned(); |
| 343 | self.port |
| 344 | .connection_sender() |
| 345 | .send_replace(ConnectionState::Connecting); |
| 346 | for event in [ |
| 347 | Event::Authenticated { user_id }, |
| 348 | Event::ConnectionChanged(ConnectionState::Connecting), |
| 349 | ] { |
| 350 | if events.send(event).await.is_err() { |
| 351 | self.shutdown().await; |
| 352 | return Err(EngineError::EventReceiverClosed); |
| 353 | } |
| 354 | } |
| 355 | self.start_tasks(); |
| 356 | self.resume_upload_forwarders().await; |
| 357 | self.sync.start().await; |
| 358 | |
| 359 | let mut shutdown_reply = None; |
| 360 | let ending = loop { |
| 361 | tokio::select! { |
| 362 | biased; |
| 363 | () = events.closed() => break Err(EngineError::EventReceiverClosed), |
| 364 | Some(termination) = self.stops.recv() => break Ok(termination), |
| 365 | Some((context, panic)) = self.tasks.join_next(), if !self.tasks.is_empty() => { |
| 366 | let Some(message) = panic else { continue }; |
| 367 | if let TaskContext::Command(label) = context { |
| 368 | tracing::error!(label, panic = %message, "command task panicked"); |
| 369 | continue; |
| 370 | } |
| 371 | break Err(EngineError::TaskPanicked { task: context.label() }); |
| 372 | } |
| 373 | Some(note) = self.notes.recv() => self.actor_note(note).await, |
| 374 | request = self.port.recv() => { |
| 375 | let Some(request) = request else { break Ok(Termination::HandlesDropped) }; |
| 376 | if let Some(reply) = self.dispatch(request).await { |
| 377 | shutdown_reply = Some(reply); |
| 378 | break Ok(Termination::ShutDown); |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | }; |
| 383 | |
| 384 | if let Err(error) = &ending { |
| 385 | let _ = events.send(Event::Failed(error.failure())).await; |
| 386 | } |
| 387 | self.shutdown().await; |
| 388 | let _ = events.send(Event::Stopped).await; |
| 389 | if let Some(reply) = shutdown_reply { |
| 390 | reply.done(Ok(())); |
| 391 | } |
| 392 | // everything else still queued answers `Interrupted` as it drops, but a shutdown did happen |
| 393 | while let Some(Request { command, reply }) = self.port.try_recv() { |
| 394 | if matches!(command, Command::Lifecycle(LifecycleCommand::Shutdown)) { |
| 395 | reply.done(Ok(())); |
| 396 | } |
| 397 | } |
| 398 | ending |
| 399 | } |
| 400 | |
| 401 | fn start_tasks(&mut self) { |
| 402 | let queues = self.queues.take().expect("engine tasks start once"); |
| 403 | let (incoming, incoming_verifications) = mpsc::unbounded_channel(); |
| 404 | self.verification_handler = Some(self.verification_handler(incoming)); |
| 405 | let client = &self.client; |
| 406 | let events = || self.port.event_sender(); |
| 407 | let watchers: [(&'static str, EngineBoxFuture<'static, ()>); 11] = [ |
| 408 | ( |
| 409 | "upload tracker", |
| 410 | Box::pin(watchers::uploads( |
| 411 | client.clone(), |
| 412 | client.send_queue().subscribe(), |
| 413 | queues.upload_reports, |
| 414 | events(), |
| 415 | )), |
| 416 | ), |
| 417 | ( |
| 418 | "room subscription watcher", |
| 419 | Box::pin(watchers::room_subscriptions( |
| 420 | self.sync.clone(), |
| 421 | self.subscriptions.subscribe(), |
| 422 | )), |
| 423 | ), |
| 424 | ( |
| 425 | "session change watcher", |
| 426 | Box::pin(watchers::session( |
| 427 | queues.session_changes, |
| 428 | events(), |
| 429 | client |
| 430 | .device_id() |
| 431 | .expect("authentication was checked during construction") |
| 432 | .to_owned(), |
| 433 | self.stop.clone(), |
| 434 | )), |
| 435 | ), |
| 436 | ( |
| 437 | "connection state watcher", |
| 438 | Box::pin(watchers::connection( |
| 439 | self.sync.state(), |
| 440 | self.sync.clone(), |
| 441 | client.clone(), |
| 442 | events(), |
| 443 | self.port.connection_sender(), |
| 444 | )), |
| 445 | ), |
| 446 | ( |
| 447 | "send queue watcher", |
| 448 | Box::pin(watchers::send_queue_errors( |
| 449 | client.clone(), |
| 450 | client.send_queue().subscribe_errors(), |
| 451 | self.port.connection_sender().subscribe(), |
| 452 | )), |
| 453 | ), |
| 454 | ( |
| 455 | "encryption state watcher", |
| 456 | Box::pin(watchers::encryption(client.clone(), events())), |
| 457 | ), |
| 458 | ( |
| 459 | "room list watcher", |
| 460 | Box::pin(watchers::rooms(client.clone(), events())), |
| 461 | ), |
| 462 | ( |
| 463 | "notification settings watcher", |
| 464 | Box::pin(watchers::notification_settings(client.clone(), events())), |
| 465 | ), |
| 466 | ( |
| 467 | "room command worker", |
| 468 | Box::pin(mutations::run_scheduler( |
| 469 | client.clone(), |
| 470 | queues.mutations, |
| 471 | self.config.command_capacity, |
| 472 | )), |
| 473 | ), |
| 474 | ( |
| 475 | "notification command worker", |
| 476 | Box::pin(commands::run_notifications( |
| 477 | client.clone(), |
| 478 | queues.notifications, |
| 479 | )), |
| 480 | ), |
| 481 | ( |
| 482 | "encryption command worker", |
| 483 | Box::pin(commands::run_encryption( |
| 484 | client.clone(), |
| 485 | events(), |
| 486 | queues.encryption, |
| 487 | incoming_verifications, |
| 488 | )), |
| 489 | ), |
| 490 | ]; |
| 491 | for (label, task) in watchers { |
| 492 | self.tasks.spawn(TaskContext::Watcher(label), task); |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | fn verification_handler( |
| 497 | &self, |
| 498 | incoming: IncomingVerifications, |
| 499 | ) -> matrix_sdk::event_handler::EventHandlerHandle { |
| 500 | use matrix_sdk::ruma::events::key::verification::request::ToDeviceKeyVerificationRequestEvent; |
| 501 | self.client.add_event_handler( |
| 502 | move |event: ToDeviceKeyVerificationRequestEvent, client: Client| { |
| 503 | let incoming = incoming.clone(); |
| 504 | async move { |
| 505 | let request = client |
| 506 | .encryption() |
| 507 | .get_verification_request( |
| 508 | &event.sender, |
| 509 | event.content.transaction_id.as_str(), |
| 510 | ) |
| 511 | .await; |
| 512 | if let Some(request) = request { |
| 513 | let _ = incoming.send(request); |
| 514 | } |
| 515 | } |
| 516 | }, |
| 517 | ) |
| 518 | } |
| 519 | |
| 520 | /// hands back the shutdown request's responder, which is answered once we've stopped |
| 521 | async fn dispatch(&mut self, Request { command, reply }: Request) -> Option<Responder> { |
| 522 | let client = self.client.clone(); |
| 523 | match command { |
| 524 | Command::Lifecycle(LifecycleCommand::Shutdown) => return Some(reply), |
| 525 | Command::Account(AccountCommand::Logout) => { |
| 526 | let events = self.port.event_sender(); |
| 527 | let stop = self.stop.clone(); |
| 528 | self.spawn_command("logout", reply, async move { |
| 529 | client |
| 530 | .logout() |
| 531 | .await |
| 532 | .map_err(|source| Error::from_sdk("logout failed", source))?; |
| 533 | let _ = events.send(Event::LoggedOut).await; |
| 534 | let _ = stop.send(Termination::LoggedOut); |
| 535 | Ok(()) |
| 536 | }); |
| 537 | } |
| 538 | Command::Account(AccountCommand::SetAccountData { |
| 539 | event_type, |
| 540 | content, |
| 541 | }) => enqueue( |
| 542 | &self.mutations, |
| 543 | Job { |
| 544 | command: Mutation::GlobalAccountData { |
| 545 | event_type, |
| 546 | content, |
| 547 | }, |
| 548 | reply, |
| 549 | }, |
| 550 | ), |
| 551 | Command::Account(AccountCommand::SetDisplayName(name)) => { |
| 552 | self.spawn_command("set display name", reply, async move { |
| 553 | client |
| 554 | .account() |
| 555 | .set_display_name(name.as_deref()) |
| 556 | .await |
| 557 | .map_err(|source| Error::from_sdk("setting display name failed", source)) |
| 558 | }); |
| 559 | } |
| 560 | Command::Account(AccountCommand::SetAvatar(avatar)) => { |
| 561 | self.spawn_command("set avatar", reply, async move { |
| 562 | client |
| 563 | .account() |
| 564 | .set_avatar_url(avatar.as_deref()) |
| 565 | .await |
| 566 | .map_err(|source| Error::from_sdk("setting avatar failed", source)) |
| 567 | }); |
| 568 | } |
| 569 | Command::Account(AccountCommand::UploadAvatar { mimetype, bytes }) => { |
| 570 | let max_bytes = self.config.max_media_bytes; |
| 571 | self.spawn_command("upload avatar", reply, async move { |
| 572 | commands::upload_avatar(&client, &mimetype, bytes, max_bytes).await |
| 573 | }); |
| 574 | } |
| 575 | Command::Account(AccountCommand::RenameDevice { |
| 576 | device_id, |
| 577 | display_name, |
| 578 | }) => self.spawn_command("rename device", reply, async move { |
| 579 | commands::rename_device(&client, &device_id, &display_name).await |
| 580 | }), |
| 581 | Command::Account(AccountCommand::DeleteDevices { device_ids, auth }) => { |
| 582 | self.spawn_command("delete devices", reply, async move { |
| 583 | commands::delete_devices(&client, &device_ids, auth).await |
| 584 | }); |
| 585 | } |
| 586 | Command::Room(RoomCommand::Open(room_id)) => self.open_room(room_id, reply).await, |
| 587 | Command::Room(RoomCommand::Close(room_id)) => self.close_room(room_id, reply).await, |
| 588 | Command::Room(RoomCommand::SetTyping { room_id, typing }) => { |
| 589 | self.spawn_command("typing", reply, async move { |
| 590 | commands::set_typing(&client, &room_id, typing).await |
| 591 | }); |
| 592 | } |
| 593 | Command::Room(RoomCommand::CancelSend { |
| 594 | room_id, |
| 595 | transaction_id, |
| 596 | }) => self.spawn_command("cancel send", reply, async move { |
| 597 | commands::cancel_send(&client, &room_id, &transaction_id).await |
| 598 | }), |
| 599 | Command::Room(RoomCommand::RetrySend { |
| 600 | room_id, |
| 601 | transaction_id, |
| 602 | }) => self.spawn_command("retry send", reply, async move { |
| 603 | commands::retry_send(&client, &room_id, &transaction_id).await |
| 604 | }), |
| 605 | Command::Room(command) => enqueue( |
| 606 | &self.mutations, |
| 607 | Job { |
| 608 | command: Mutation::Room(command), |
| 609 | reply, |
| 610 | }, |
| 611 | ), |
| 612 | Command::Timeline(command) => self.route_timeline(command, reply), |
| 613 | Command::Media(MediaCommand::Upload(upload)) => self.upload(upload, reply), |
| 614 | Command::Encryption(command) => enqueue(&self.encryption, Job { command, reply }), |
| 615 | Command::Notification(command) => { |
| 616 | enqueue(&self.notifications, Job { command, reply }); |
| 617 | } |
| 618 | } |
| 619 | None |
| 620 | } |
| 621 | |
| 622 | fn spawn_command( |
| 623 | &mut self, |
| 624 | label: &'static str, |
| 625 | reply: Responder, |
| 626 | work: impl Future<Output = Result<(), Error>> + SendOutsideWasm + 'static, |
| 627 | ) { |
| 628 | self.tasks.spawn(TaskContext::Command(label), async move { |
| 629 | reply.done(work.await); |
| 630 | }); |
| 631 | } |
| 632 | |
| 633 | fn upload(&mut self, upload: crate::AttachmentUpload, reply: Responder) { |
| 634 | let Some(room) = self.client.get_room(upload.timeline_id.room_id()) else { |
| 635 | return reply.done(Err(Error::room_unknown())); |
| 636 | }; |
| 637 | let mut ready = self.upload_forwarder(&room); |
| 638 | let max_bytes = self.config.max_media_bytes; |
| 639 | // queueing before the forwarder listens would lose the first progress ticks |
| 640 | self.spawn_command("upload", reply, async move { |
| 641 | ready |
| 642 | .wait_for(|subscribed| *subscribed) |
| 643 | .await |
| 644 | .map_err(|_| Error::new(ErrorKind::Store, "reading the media send queue failed"))?; |
| 645 | media::queue_upload(room, upload, max_bytes).await |
| 646 | }); |
| 647 | } |
| 648 | |
| 649 | fn upload_forwarder(&mut self, room: &matrix_sdk::Room) -> watch::Receiver<bool> { |
| 650 | self.uploads.retain(|_, ready| ready.has_changed().is_ok()); |
| 651 | if let Some(ready) = self.uploads.get(room.room_id()) { |
| 652 | return ready.clone(); |
| 653 | } |
| 654 | let (subscribed, ready) = watch::channel(false); |
| 655 | self.tasks.spawn( |
| 656 | TaskContext::Command("upload watcher"), |
| 657 | watchers::room_uploads(room.clone(), self.upload_reports.clone(), subscribed), |
| 658 | ); |
| 659 | self.uploads |
| 660 | .insert(room.room_id().to_owned(), ready.clone()); |
| 661 | ready |
| 662 | } |
| 663 | |
| 664 | /// the sdk resumes uploads left over from last time, and they deserve progress too |
| 665 | async fn resume_upload_forwarders(&mut self) { |
| 666 | let Ok(echoes) = self.client.send_queue().local_echoes().await else { |
| 667 | return; |
| 668 | }; |
| 669 | for room_id in echoes.keys() { |
| 670 | if let Some(room) = self.client.get_room(room_id) { |
| 671 | self.upload_forwarder(&room); |
| 672 | } |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | fn route_timeline(&mut self, command: TimelineCommand, reply: Responder) { |
| 677 | let sender = match self.rooms.get(command.room_id()) { |
| 678 | Some(RoomSlot::Active { sender, .. }) => Some(sender.clone()), |
| 679 | _ => None, |
| 680 | }; |
| 681 | match (sender, command) { |
| 682 | (Some(sender), command) => send_actor(&sender, ActorRequest::Execute(command, reply)), |
| 683 | ( |
| 684 | None, |
| 685 | TimelineCommand::MarkRead { |
| 686 | timeline_id, |
| 687 | event_id, |
| 688 | }, |
| 689 | ) => { |
| 690 | let client = self.client.clone(); |
| 691 | self.spawn_command("mark read", reply, async move { |
| 692 | commands::mark_read(&client, &timeline_id, event_id).await |
| 693 | }); |
| 694 | } |
| 695 | (None, _) => reply.done(Err(Error::new(ErrorKind::RoomNotOpen, "room is not open"))), |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | async fn open_room(&mut self, room_id: OwnedRoomId, reply: Responder) { |
| 700 | match self.rooms.get_mut(&room_id) { |
| 701 | Some(RoomSlot::Active { sender, .. }) => send_actor(sender, ActorRequest::Open(reply)), |
| 702 | Some(RoomSlot::Closing { pending, .. }) => { |
| 703 | defer(pending, Deferred::Open(reply), self.config.command_capacity); |
| 704 | } |
| 705 | None => self.start_actor(room_id, reply).await, |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | async fn close_room(&mut self, room_id: OwnedRoomId, reply: Responder) { |
| 710 | let (generation, sender) = match self.rooms.get_mut(&room_id) { |
| 711 | None => return reply.done(Ok(())), |
| 712 | Some(RoomSlot::Closing { pending, .. }) => { |
| 713 | return defer( |
| 714 | pending, |
| 715 | Deferred::Close(reply), |
| 716 | self.config.command_capacity, |
| 717 | ); |
| 718 | } |
| 719 | Some(RoomSlot::Active { generation, sender }) => (*generation, sender.clone()), |
| 720 | }; |
| 721 | match sender.try_send(ActorRequest::Close(reply)) { |
| 722 | Ok(()) => {} |
| 723 | // the actor already left on its own, which is closed enough |
| 724 | Err(mpsc::error::TrySendError::Closed(request)) => request.into_reply().done(Ok(())), |
| 725 | Err(mpsc::error::TrySendError::Full(request)) => { |
| 726 | return request.into_reply().done(Err(Error::new( |
| 727 | ErrorKind::RoomBusy, |
| 728 | "room command queue is full", |
| 729 | ))); |
| 730 | } |
| 731 | } |
| 732 | self.rooms.insert( |
| 733 | room_id, |
| 734 | RoomSlot::Closing { |
| 735 | generation, |
| 736 | pending: VecDeque::new(), |
| 737 | }, |
| 738 | ); |
| 739 | self.update_room_subscriptions(); |
| 740 | } |
| 741 | |
| 742 | async fn start_actor(&mut self, room_id: OwnedRoomId, reply: Responder) { |
| 743 | let Some(room) = self.client.get_room(&room_id) else { |
| 744 | return reply.done(Err(Error::room_unknown())); |
| 745 | }; |
| 746 | self.next_generation = self.next_generation.wrapping_add(1); |
| 747 | let generation = self.next_generation; |
| 748 | let (sender, requests) = mpsc::channel(self.config.command_capacity); |
| 749 | let (supervisor, panics) = Supervisor::new(); |
| 750 | let actor = RoomActor { |
| 751 | room_id: room_id.clone(), |
| 752 | generation, |
| 753 | room, |
| 754 | requests, |
| 755 | notes: self.note_sender.clone(), |
| 756 | context: SessionContext { |
| 757 | events: self.port.event_sender(), |
| 758 | media: self.media.clone(), |
| 759 | current_user_id: self.client.user_id().map(ToOwned::to_owned), |
| 760 | initial_history_limit: self.config.initial_history_limit, |
| 761 | supervisor, |
| 762 | }, |
| 763 | panics, |
| 764 | opening: vec![reply], |
| 765 | }; |
| 766 | self.rooms |
| 767 | .insert(room_id.clone(), RoomSlot::Active { generation, sender }); |
| 768 | self.tasks.spawn( |
| 769 | TaskContext::RoomActor { |
| 770 | room_id, |
| 771 | generation, |
| 772 | }, |
| 773 | actor.run(), |
| 774 | ); |
| 775 | self.update_room_subscriptions(); |
| 776 | } |
| 777 | |
| 778 | async fn actor_note(&mut self, note: ActorNote) { |
| 779 | let (room_id, generation) = match ¬e { |
| 780 | ActorNote::Leaving { |
| 781 | room_id, |
| 782 | generation, |
| 783 | } |
| 784 | | ActorNote::Exited { |
| 785 | room_id, |
| 786 | generation, |
| 787 | .. |
| 788 | } => (room_id.clone(), *generation), |
| 789 | }; |
| 790 | if self |
| 791 | .rooms |
| 792 | .get(&room_id) |
| 793 | .is_none_or(|slot| slot.generation() != generation) |
| 794 | { |
| 795 | return; |
| 796 | } |
| 797 | let ActorNote::Exited { leftovers, .. } = note else { |
| 798 | if let Some(slot @ RoomSlot::Active { .. }) = self.rooms.get_mut(&room_id) { |
| 799 | *slot = RoomSlot::Closing { |
| 800 | generation, |
| 801 | pending: VecDeque::new(), |
| 802 | }; |
| 803 | self.update_room_subscriptions(); |
| 804 | } |
| 805 | return; |
| 806 | }; |
| 807 | let pending = match self.rooms.remove(&room_id) { |
| 808 | Some(RoomSlot::Closing { pending, .. }) => pending, |
| 809 | _ => VecDeque::new(), |
| 810 | }; |
| 811 | // leftovers were sent before anything deferred, so they go first |
| 812 | for request in leftovers { |
| 813 | match request { |
| 814 | ActorRequest::Open(reply) => self.open_room(room_id.clone(), reply).await, |
| 815 | ActorRequest::Close(reply) => reply.done(Ok(())), |
| 816 | ActorRequest::Execute(command, reply) => self.route_timeline(command, reply), |
| 817 | } |
| 818 | } |
| 819 | for deferred in pending { |
| 820 | match deferred { |
| 821 | Deferred::Open(reply) => self.open_room(room_id.clone(), reply).await, |
| 822 | Deferred::Close(reply) => self.close_room(room_id.clone(), reply).await, |
| 823 | } |
| 824 | } |
| 825 | self.update_room_subscriptions(); |
| 826 | } |
| 827 | |
| 828 | fn update_room_subscriptions(&self) { |
| 829 | let room_ids = self |
| 830 | .rooms |
| 831 | .iter() |
| 832 | .filter(|(_, slot)| matches!(slot, RoomSlot::Active { .. })) |
| 833 | .map(|(room_id, _)| room_id.clone()) |
| 834 | .collect(); |
| 835 | self.subscriptions.send_replace(room_ids); |
| 836 | } |
| 837 | |
| 838 | async fn shutdown(&mut self) { |
| 839 | if let Some(handler) = self.verification_handler.take() { |
| 840 | self.client.remove_event_handler(handler); |
| 841 | } |
| 842 | self.port.close(); |
| 843 | self.tasks.shutdown().await; |
| 844 | self.rooms.clear(); |
| 845 | self.uploads.clear(); |
| 846 | self.media.clear().await; |
| 847 | self.sync.stop().await; |
| 848 | self.port |
| 849 | .connection_sender() |
| 850 | .send_replace(ConnectionState::Stopped); |
| 851 | let _ = self |
| 852 | .port |
| 853 | .event_sender() |
| 854 | .send(Event::ConnectionChanged(ConnectionState::Stopped)) |
| 855 | .await; |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | fn send_actor(sender: &mpsc::Sender<ActorRequest>, request: ActorRequest) { |
| 860 | if let Err(error) = sender.try_send(request) { |
| 861 | let (request, error) = match error { |
| 862 | mpsc::error::TrySendError::Full(request) => ( |
| 863 | request, |
| 864 | Error::new(ErrorKind::RoomBusy, "room command queue is full"), |
| 865 | ), |
| 866 | mpsc::error::TrySendError::Closed(request) => ( |
| 867 | request, |
| 868 | Error::new(ErrorKind::RoomNotOpen, "room is not open"), |
| 869 | ), |
| 870 | }; |
| 871 | request.into_reply().done(Err(error)); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | fn defer(pending: &mut VecDeque<Deferred>, deferred: Deferred, capacity: usize) { |
| 876 | if pending.len() < capacity { |
| 877 | return pending.push_back(deferred); |
| 878 | } |
| 879 | let (Deferred::Open(reply) | Deferred::Close(reply)) = deferred; |
| 880 | reply.done(Err(Error::new( |
| 881 | ErrorKind::RoomBusy, |
| 882 | "room lifecycle queue is full", |
| 883 | ))); |
| 884 | } |
| 885 | |
| 886 | fn enqueue<T>(sender: &mpsc::Sender<Job<T>>, job: Job<T>) { |
| 887 | if let Err(error) = sender.try_send(job) { |
| 888 | let (job, error) = match error { |
| 889 | mpsc::error::TrySendError::Full(job) => ( |
| 890 | job, |
| 891 | Error::new(ErrorKind::QueueFull, "command queue is full"), |
| 892 | ), |
| 893 | mpsc::error::TrySendError::Closed(job) => (job, Error::interrupted()), |
| 894 | }; |
| 895 | job.reply.done(Err(error)); |
| 896 | } |
| 897 | } |