atagen

macltok

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