atagen

macltok

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