atagen

macltok

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