atagen

macltok

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