atagen

macltok

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