atagen

macltok

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