atagen

macltok

public
Star0
Watch0
66db1b3cd8955da257726f2f3028b931ba34c3c0
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/engine/mod.rs

31ce2453c82fatagen2026-09-24 13:07 UTC1
mod commands;
cbb715e11963atagen2026-10-24 23:24 UTC2
pub(crate) mod context;
a319bae745d8atagen2026-09-26 09:59 UTC3
pub(crate) mod executor;
31ce2453c82fatagen2026-09-24 13:07 UTC4
mod media;
31ce2453c82fatagen2026-09-24 13:07 UTC5
mod mutations;
fa51490b6ae9atagen2026-10-24 08:41 UTC6
mod packs;
38c4caecdb3datagen2026-09-26 13:35 UTC7
mod prepare;
80381e06a573atagen2026-10-25 03:02 UTC8
mod repair;
31ce2453c82fatagen2026-09-24 13:07 UTC9
mod room;
f12377bce9b9atagen2026-09-26 12:32 UTC10
mod session;
66db1b3cd895atagen2026-10-25 10:28 UTC11
mod thread_list;
31ce2453c82fatagen2026-09-24 13:07 UTC12
mod timeline;
0291516d40b5atagen2026-10-22 08:31 UTC13
mod url_preview;
31ce2453c82fatagen2026-09-24 13:07 UTC14
mod watchers;
31ce2453c82fatagen2026-09-24 13:07 UTC15
31ce2453c82fatagen2026-09-24 13:07 UTC16
use std::{
31ce2453c82fatagen2026-09-24 13:07 UTC17
    collections::{HashMap, VecDeque},
31ce2453c82fatagen2026-09-24 13:07 UTC18
    future::Future,
1fe480c16a3catagen2026-09-26 08:44 UTC19
    panic::AssertUnwindSafe,
31ce2453c82fatagen2026-09-24 13:07 UTC20
    sync::Arc,
31ce2453c82fatagen2026-09-24 13:07 UTC21
};
31ce2453c82fatagen2026-09-24 13:07 UTC22
1fe480c16a3catagen2026-09-26 08:44 UTC23
use futures_util::FutureExt;
1fe480c16a3catagen2026-09-26 08:44 UTC24
use matrix_sdk::{Client, SendOutsideWasm, SessionChange};
31ce2453c82fatagen2026-09-24 13:07 UTC25
use matrix_sdk_ui::sync_service::SyncService;
673563a76e43atagen2026-09-26 12:30 UTC26
use ruma::{OwnedDeviceId, OwnedRoomId};
31ce2453c82fatagen2026-09-24 13:07 UTC27
use thiserror::Error as ThisError;
fe4133dbcd47atagen2026-09-26 09:05 UTC28
use tokio::sync::{broadcast, mpsc, watch};
31ce2453c82fatagen2026-09-24 13:07 UTC29
31ce2453c82fatagen2026-09-24 13:07 UTC30
pub(crate) use media::MediaService;
f12377bce9b9atagen2026-09-26 12:32 UTC31
pub(crate) use session::Persistence;
31ce2453c82fatagen2026-09-24 13:07 UTC32
a250c7fa43fbatagen2026-09-26 13:35 UTC33
#[cfg(any(feature = "sqlite", feature = "indexeddb"))]
a250c7fa43fbatagen2026-09-26 13:35 UTC34
pub(crate) use crate::store_lock::StoreLock;
a250c7fa43fbatagen2026-09-26 13:35 UTC35
#[cfg(not(any(feature = "sqlite", feature = "indexeddb")))]
a250c7fa43fbatagen2026-09-26 13:35 UTC36
pub(crate) enum StoreLock {}
a250c7fa43fbatagen2026-09-26 13:35 UTC37
cbb715e11963atagen2026-10-24 23:24 UTC38
#[cfg(any(feature = "sqlite", feature = "indexeddb"))]
cbb715e11963atagen2026-10-24 23:24 UTC39
pub(crate) use crate::mentions::store::MentionsStore;
cbb715e11963atagen2026-10-24 23:24 UTC40
#[cfg(not(any(feature = "sqlite", feature = "indexeddb")))]
cbb715e11963atagen2026-10-24 23:24 UTC41
pub(crate) enum MentionsStore {}
cbb715e11963atagen2026-10-24 23:24 UTC42
31ce2453c82fatagen2026-09-24 13:07 UTC43
use self::{
31ce2453c82fatagen2026-09-24 13:07 UTC44
    commands::Job,
1fe480c16a3catagen2026-09-26 08:44 UTC45
    executor::{EngineBoxFuture, TaskSet},
31ce2453c82fatagen2026-09-24 13:07 UTC46
    mutations::{Mutation, MutationJob},
fa51490b6ae9atagen2026-10-24 08:41 UTC47
    packs::PackEdit,
5a52012c9b1datagen2026-09-24 23:45 UTC48
    room::{ActorNote, ActorRequest, RoomActor},
31ce2453c82fatagen2026-09-24 13:07 UTC49
    timeline::{SessionContext, Supervisor},
31ce2453c82fatagen2026-09-24 13:07 UTC50
};
31ce2453c82fatagen2026-09-24 13:07 UTC51
use crate::{
9bd34e25bb86atagen2026-10-24 07:23 UTC52
    AccountCommand, ClientHandle, Command, CommandOutput, ConnectionState, EncryptionCommand,
fa51490b6ae9atagen2026-10-24 08:41 UTC53
    EngineErrorKind, EngineFailure, Error, ErrorKind, Event, EventStream, ImagePackSource,
fa51490b6ae9atagen2026-10-24 08:41 UTC54
    LifecycleCommand, MediaCommand, NotificationCommand, PackCommand, RoomCommand, Termination,
66db1b3cd895atagen2026-10-25 10:28 UTC55
    ThreadListCommand, TimelineCommand,
0291516d40b5atagen2026-10-22 08:31 UTC56
    normalise::{ROOM_PACKS, ROOM_PREVIEW_URLS},
31ce2453c82fatagen2026-09-24 13:07 UTC57
    transport::{DriverPort, Request, Responder, transport_pair},
31ce2453c82fatagen2026-09-24 13:07 UTC58
};
31ce2453c82fatagen2026-09-24 13:07 UTC59
31ce2453c82fatagen2026-09-24 13:07 UTC60
#[derive(Clone, Debug, Eq, PartialEq)]
31ce2453c82fatagen2026-09-24 13:07 UTC61
#[non_exhaustive]
31ce2453c82fatagen2026-09-24 13:07 UTC62
pub struct EngineConfig {
31ce2453c82fatagen2026-09-24 13:07 UTC63
    pub command_capacity: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC64
    pub event_capacity: usize,
d9b96952ec60atagen2026-10-25 09:07 UTC65
    /// what a thread paginates as it opens, and a room if its recent load fails. 0 for neither
31ce2453c82fatagen2026-09-24 13:07 UTC66
    pub initial_history_limit: u16,
31ce2453c82fatagen2026-09-24 13:07 UTC67
    pub max_media_bytes: usize,
da8896938cf0atagen2026-10-25 10:04 UTC68
    /// media one event context session keeps registered, least recently used dropped first
da8896938cf0atagen2026-10-25 10:04 UTC69
    pub max_context_media: usize,
cbb715e11963atagen2026-10-24 23:24 UTC70
    pub max_mentions_bytes: usize,
cbb715e11963atagen2026-10-24 23:24 UTC71
    pub max_mentions_entries: usize,
cbb715e11963atagen2026-10-24 23:24 UTC72
    pub max_mention_context_events: usize,
cbb715e11963atagen2026-10-24 23:24 UTC73
    pub max_mention_candidates: usize,
38c4caecdb3datagen2026-09-26 13:35 UTC74
    /// warm a room up for sending when it's opened or someone starts typing in it
38c4caecdb3datagen2026-09-26 13:35 UTC75
    pub prepare_to_send: bool,
31ce2453c82fatagen2026-09-24 13:07 UTC76
}
31ce2453c82fatagen2026-09-24 13:07 UTC77
31ce2453c82fatagen2026-09-24 13:07 UTC78
impl EngineConfig {
31ce2453c82fatagen2026-09-24 13:07 UTC79
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC80
    pub const fn with_max_mentions_bytes(mut self, bytes: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC81
        self.max_mentions_bytes = bytes;
cbb715e11963atagen2026-10-24 23:24 UTC82
        self
cbb715e11963atagen2026-10-24 23:24 UTC83
    }
cbb715e11963atagen2026-10-24 23:24 UTC84
cbb715e11963atagen2026-10-24 23:24 UTC85
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC86
    pub const fn with_max_mentions_entries(mut self, entries: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC87
        self.max_mentions_entries = entries;
cbb715e11963atagen2026-10-24 23:24 UTC88
        self
cbb715e11963atagen2026-10-24 23:24 UTC89
    }
cbb715e11963atagen2026-10-24 23:24 UTC90
cbb715e11963atagen2026-10-24 23:24 UTC91
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC92
    pub const fn with_max_mention_context_events(mut self, events: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC93
        self.max_mention_context_events = events;
cbb715e11963atagen2026-10-24 23:24 UTC94
        self
cbb715e11963atagen2026-10-24 23:24 UTC95
    }
cbb715e11963atagen2026-10-24 23:24 UTC96
cbb715e11963atagen2026-10-24 23:24 UTC97
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC98
    pub const fn with_max_mention_candidates(mut self, candidates: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC99
        self.max_mention_candidates = candidates;
cbb715e11963atagen2026-10-24 23:24 UTC100
        self
cbb715e11963atagen2026-10-24 23:24 UTC101
    }
cbb715e11963atagen2026-10-24 23:24 UTC102
cbb715e11963atagen2026-10-24 23:24 UTC103
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC104
    pub const fn with_command_capacity(mut self, capacity: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC105
        self.command_capacity = capacity;
31ce2453c82fatagen2026-09-24 13:07 UTC106
        self
31ce2453c82fatagen2026-09-24 13:07 UTC107
    }
31ce2453c82fatagen2026-09-24 13:07 UTC108
31ce2453c82fatagen2026-09-24 13:07 UTC109
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC110
    pub const fn with_event_capacity(mut self, capacity: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC111
        self.event_capacity = capacity;
31ce2453c82fatagen2026-09-24 13:07 UTC112
        self
31ce2453c82fatagen2026-09-24 13:07 UTC113
    }
31ce2453c82fatagen2026-09-24 13:07 UTC114
31ce2453c82fatagen2026-09-24 13:07 UTC115
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC116
    pub const fn with_initial_history_limit(mut self, limit: u16) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC117
        self.initial_history_limit = limit;
31ce2453c82fatagen2026-09-24 13:07 UTC118
        self
31ce2453c82fatagen2026-09-24 13:07 UTC119
    }
31ce2453c82fatagen2026-09-24 13:07 UTC120
31ce2453c82fatagen2026-09-24 13:07 UTC121
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC122
    pub const fn with_max_media_bytes(mut self, bytes: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC123
        self.max_media_bytes = bytes;
31ce2453c82fatagen2026-09-24 13:07 UTC124
        self
31ce2453c82fatagen2026-09-24 13:07 UTC125
    }
31ce2453c82fatagen2026-09-24 13:07 UTC126
31ce2453c82fatagen2026-09-24 13:07 UTC127
    #[must_use]
da8896938cf0atagen2026-10-25 10:04 UTC128
    pub const fn with_max_context_media(mut self, media: usize) -> Self {
da8896938cf0atagen2026-10-25 10:04 UTC129
        self.max_context_media = media;
31ce2453c82fatagen2026-09-24 13:07 UTC130
        self
31ce2453c82fatagen2026-09-24 13:07 UTC131
    }
38c4caecdb3datagen2026-09-26 13:35 UTC132
38c4caecdb3datagen2026-09-26 13:35 UTC133
    #[must_use]
38c4caecdb3datagen2026-09-26 13:35 UTC134
    pub const fn with_prepare_to_send(mut self, prepare: bool) -> Self {
38c4caecdb3datagen2026-09-26 13:35 UTC135
        self.prepare_to_send = prepare;
38c4caecdb3datagen2026-09-26 13:35 UTC136
        self
38c4caecdb3datagen2026-09-26 13:35 UTC137
    }
31ce2453c82fatagen2026-09-24 13:07 UTC138
}
31ce2453c82fatagen2026-09-24 13:07 UTC139
31ce2453c82fatagen2026-09-24 13:07 UTC140
impl Default for EngineConfig {
31ce2453c82fatagen2026-09-24 13:07 UTC141
    fn default() -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC142
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC143
            command_capacity: 64,
31ce2453c82fatagen2026-09-24 13:07 UTC144
            event_capacity: 128,
31ce2453c82fatagen2026-09-24 13:07 UTC145
            initial_history_limit: 30,
31ce2453c82fatagen2026-09-24 13:07 UTC146
            max_media_bytes: 20 * 1024 * 1024,
da8896938cf0atagen2026-10-25 10:04 UTC147
            max_context_media: 1_024,
cbb715e11963atagen2026-10-24 23:24 UTC148
            max_mentions_bytes: 64 * 1024 * 1024,
cbb715e11963atagen2026-10-24 23:24 UTC149
            max_mentions_entries: 5_000,
cbb715e11963atagen2026-10-24 23:24 UTC150
            max_mention_context_events: 25_000,
cbb715e11963atagen2026-10-24 23:24 UTC151
            max_mention_candidates: 5_000,
38c4caecdb3datagen2026-09-26 13:35 UTC152
            prepare_to_send: true,
31ce2453c82fatagen2026-09-24 13:07 UTC153
        }
31ce2453c82fatagen2026-09-24 13:07 UTC154
    }
31ce2453c82fatagen2026-09-24 13:07 UTC155
}
31ce2453c82fatagen2026-09-24 13:07 UTC156
31ce2453c82fatagen2026-09-24 13:07 UTC157
#[derive(Debug, ThisError)]
31ce2453c82fatagen2026-09-24 13:07 UTC158
pub enum EngineError {
31ce2453c82fatagen2026-09-24 13:07 UTC159
    #[error("the Matrix client is not authenticated")]
31ce2453c82fatagen2026-09-24 13:07 UTC160
    Unauthenticated,
cbb715e11963atagen2026-10-24 23:24 UTC161
    #[error("command, event, media source, and mentions capacities must be nonzero")]
31ce2453c82fatagen2026-09-24 13:07 UTC162
    ZeroCapacity,
31ce2453c82fatagen2026-09-24 13:07 UTC163
    #[error("could not build the sync service")]
31ce2453c82fatagen2026-09-24 13:07 UTC164
    SyncService(#[source] matrix_sdk_ui::sync_service::Error),
31ce2453c82fatagen2026-09-24 13:07 UTC165
    #[error("the event receiver has closed")]
31ce2453c82fatagen2026-09-24 13:07 UTC166
    EventReceiverClosed,
31ce2453c82fatagen2026-09-24 13:07 UTC167
    #[error("engine task {task} panicked")]
31ce2453c82fatagen2026-09-24 13:07 UTC168
    TaskPanicked { task: String },
31ce2453c82fatagen2026-09-24 13:07 UTC169
}
31ce2453c82fatagen2026-09-24 13:07 UTC170
31ce2453c82fatagen2026-09-24 13:07 UTC171
impl EngineError {
31ce2453c82fatagen2026-09-24 13:07 UTC172
    fn failure(&self) -> EngineFailure {
31ce2453c82fatagen2026-09-24 13:07 UTC173
        EngineFailure {
31ce2453c82fatagen2026-09-24 13:07 UTC174
            kind: match self {
31ce2453c82fatagen2026-09-24 13:07 UTC175
                Self::EventReceiverClosed => EngineErrorKind::EventReceiverClosed,
31ce2453c82fatagen2026-09-24 13:07 UTC176
                Self::TaskPanicked { .. } => EngineErrorKind::Watcher,
913832a327a8atagen2026-10-25 09:33 UTC177
                Self::Unauthenticated | Self::ZeroCapacity | Self::SyncService(_) => {
913832a327a8atagen2026-10-25 09:33 UTC178
                    EngineErrorKind::Other
913832a327a8atagen2026-10-25 09:33 UTC179
                }
31ce2453c82fatagen2026-09-24 13:07 UTC180
            },
31ce2453c82fatagen2026-09-24 13:07 UTC181
            message: self.to_string(),
31ce2453c82fatagen2026-09-24 13:07 UTC182
        }
31ce2453c82fatagen2026-09-24 13:07 UTC183
    }
31ce2453c82fatagen2026-09-24 13:07 UTC184
}
31ce2453c82fatagen2026-09-24 13:07 UTC185
31ce2453c82fatagen2026-09-24 13:07 UTC186
#[derive(Clone)]
31ce2453c82fatagen2026-09-24 13:07 UTC187
enum TaskContext {
31ce2453c82fatagen2026-09-24 13:07 UTC188
    /// a panic here costs the caller an `Interrupted` answer and nothing else
31ce2453c82fatagen2026-09-24 13:07 UTC189
    Command(&'static str),
31ce2453c82fatagen2026-09-24 13:07 UTC190
    /// a panic here takes the engine with it
31ce2453c82fatagen2026-09-24 13:07 UTC191
    Watcher(&'static str),
31ce2453c82fatagen2026-09-24 13:07 UTC192
    RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC193
        room_id: OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC194
        generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC195
    },
31ce2453c82fatagen2026-09-24 13:07 UTC196
}
31ce2453c82fatagen2026-09-24 13:07 UTC197
31ce2453c82fatagen2026-09-24 13:07 UTC198
impl TaskContext {
31ce2453c82fatagen2026-09-24 13:07 UTC199
    fn label(&self) -> String {
31ce2453c82fatagen2026-09-24 13:07 UTC200
        match self {
31ce2453c82fatagen2026-09-24 13:07 UTC201
            Self::Command(name) | Self::Watcher(name) => (*name).to_owned(),
31ce2453c82fatagen2026-09-24 13:07 UTC202
            Self::RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC203
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC204
                generation,
31ce2453c82fatagen2026-09-24 13:07 UTC205
            } => format!("room actor {room_id} generation {generation}"),
31ce2453c82fatagen2026-09-24 13:07 UTC206
        }
31ce2453c82fatagen2026-09-24 13:07 UTC207
    }
31ce2453c82fatagen2026-09-24 13:07 UTC208
}
31ce2453c82fatagen2026-09-24 13:07 UTC209
7b376d620a3datagen2026-09-26 12:53 UTC210
/// tasks catch their own panics so each comes back with its context, since joining
7b376d620a3datagen2026-09-26 12:53 UTC211
/// through the sdk's executor gives no task id to look one up by. wasm has nothing to catch
1fe480c16a3catagen2026-09-26 08:44 UTC212
fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
1fe480c16a3catagen2026-09-26 08:44 UTC213
    payload
1fe480c16a3catagen2026-09-26 08:44 UTC214
        .downcast_ref::<&str>()
1fe480c16a3catagen2026-09-26 08:44 UTC215
        .map(ToString::to_string)
1fe480c16a3catagen2026-09-26 08:44 UTC216
        .or_else(|| payload.downcast_ref::<String>().cloned())
1fe480c16a3catagen2026-09-26 08:44 UTC217
        .unwrap_or_else(|| "task panicked with a non-string payload".to_owned())
1fe480c16a3catagen2026-09-26 08:44 UTC218
}
1fe480c16a3catagen2026-09-26 08:44 UTC219
31ce2453c82fatagen2026-09-24 13:07 UTC220
struct TaskRegistry {
1fe480c16a3catagen2026-09-26 08:44 UTC221
    tasks: TaskSet<(TaskContext, Option<String>)>,
31ce2453c82fatagen2026-09-24 13:07 UTC222
}
31ce2453c82fatagen2026-09-24 13:07 UTC223
31ce2453c82fatagen2026-09-24 13:07 UTC224
impl TaskRegistry {
31ce2453c82fatagen2026-09-24 13:07 UTC225
    fn spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC226
        &mut self,
31ce2453c82fatagen2026-09-24 13:07 UTC227
        context: TaskContext,
1fe480c16a3catagen2026-09-26 08:44 UTC228
        task: impl Future<Output = ()> + SendOutsideWasm + 'static,
1fe480c16a3catagen2026-09-26 08:44 UTC229
    ) {
1fe480c16a3catagen2026-09-26 08:44 UTC230
        self.tasks.spawn(async move {
1fe480c16a3catagen2026-09-26 08:44 UTC231
            let panic = AssertUnwindSafe(task)
1fe480c16a3catagen2026-09-26 08:44 UTC232
                .catch_unwind()
1fe480c16a3catagen2026-09-26 08:44 UTC233
                .await
1fe480c16a3catagen2026-09-26 08:44 UTC234
                .err()
1fe480c16a3catagen2026-09-26 08:44 UTC235
                .map(panic_message);
1fe480c16a3catagen2026-09-26 08:44 UTC236
            (context, panic)
1fe480c16a3catagen2026-09-26 08:44 UTC237
        });
31ce2453c82fatagen2026-09-24 13:07 UTC238
    }
31ce2453c82fatagen2026-09-24 13:07 UTC239
1fe480c16a3catagen2026-09-26 08:44 UTC240
    fn is_empty(&self) -> bool {
1fe480c16a3catagen2026-09-26 08:44 UTC241
        self.tasks.is_empty()
1fe480c16a3catagen2026-09-26 08:44 UTC242
    }
1fe480c16a3catagen2026-09-26 08:44 UTC243
1fe480c16a3catagen2026-09-26 08:44 UTC244
    async fn join_next(&mut self) -> Option<(TaskContext, Option<String>)> {
1fe480c16a3catagen2026-09-26 08:44 UTC245
        loop {
1fe480c16a3catagen2026-09-26 08:44 UTC246
            if let Ok(done) = self.tasks.join_next().await? {
1fe480c16a3catagen2026-09-26 08:44 UTC247
                return Some(done);
1fe480c16a3catagen2026-09-26 08:44 UTC248
            }
1fe480c16a3catagen2026-09-26 08:44 UTC249
        }
31ce2453c82fatagen2026-09-24 13:07 UTC250
    }
31ce2453c82fatagen2026-09-24 13:07 UTC251
31ce2453c82fatagen2026-09-24 13:07 UTC252
    async fn shutdown(&mut self) {
1fe480c16a3catagen2026-09-26 08:44 UTC253
        self.tasks.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC254
    }
31ce2453c82fatagen2026-09-24 13:07 UTC255
}
31ce2453c82fatagen2026-09-24 13:07 UTC256
31ce2453c82fatagen2026-09-24 13:07 UTC257
enum RoomSlot {
31ce2453c82fatagen2026-09-24 13:07 UTC258
    Active {
31ce2453c82fatagen2026-09-24 13:07 UTC259
        generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC260
        sender: mpsc::Sender<ActorRequest>,
31ce2453c82fatagen2026-09-24 13:07 UTC261
    },
31ce2453c82fatagen2026-09-24 13:07 UTC262
    /// opens and closes that arrive while the actor winds down, replayed in order once it's gone
31ce2453c82fatagen2026-09-24 13:07 UTC263
    Closing {
31ce2453c82fatagen2026-09-24 13:07 UTC264
        generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC265
        pending: VecDeque<Deferred>,
31ce2453c82fatagen2026-09-24 13:07 UTC266
    },
31ce2453c82fatagen2026-09-24 13:07 UTC267
}
31ce2453c82fatagen2026-09-24 13:07 UTC268
31ce2453c82fatagen2026-09-24 13:07 UTC269
impl RoomSlot {
31ce2453c82fatagen2026-09-24 13:07 UTC270
    const fn generation(&self) -> u64 {
31ce2453c82fatagen2026-09-24 13:07 UTC271
        match self {
31ce2453c82fatagen2026-09-24 13:07 UTC272
            Self::Active { generation, .. } | Self::Closing { generation, .. } => *generation,
31ce2453c82fatagen2026-09-24 13:07 UTC273
        }
31ce2453c82fatagen2026-09-24 13:07 UTC274
    }
31ce2453c82fatagen2026-09-24 13:07 UTC275
}
31ce2453c82fatagen2026-09-24 13:07 UTC276
31ce2453c82fatagen2026-09-24 13:07 UTC277
enum Deferred {
31ce2453c82fatagen2026-09-24 13:07 UTC278
    Open(Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC279
    Close(Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC280
}
31ce2453c82fatagen2026-09-24 13:07 UTC281
673563a76e43atagen2026-09-26 12:30 UTC282
/// logouts in flight, and a token rejection held back because one of them caused it
673563a76e43atagen2026-09-26 12:30 UTC283
#[derive(Default)]
673563a76e43atagen2026-09-26 12:30 UTC284
pub(super) struct Logouts {
673563a76e43atagen2026-09-26 12:30 UTC285
    pub(super) in_flight: usize,
673563a76e43atagen2026-09-26 12:30 UTC286
    pub(super) rejected: Option<Option<OwnedDeviceId>>,
673563a76e43atagen2026-09-26 12:30 UTC287
}
673563a76e43atagen2026-09-26 12:30 UTC288
31ce2453c82fatagen2026-09-24 13:07 UTC289
struct Queues {
31ce2453c82fatagen2026-09-24 13:07 UTC290
    mutations: mpsc::Receiver<MutationJob>,
31ce2453c82fatagen2026-09-24 13:07 UTC291
    notifications: mpsc::Receiver<Job<NotificationCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC292
    encryption: mpsc::Receiver<Job<EncryptionCommand>>,
66db1b3cd895atagen2026-10-25 10:28 UTC293
    thread_lists: mpsc::Receiver<Job<ThreadListCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC294
    session_changes: broadcast::Receiver<SessionChange>,
f12377bce9b9atagen2026-09-26 12:32 UTC295
    persistence: Option<Persistence>,
31ce2453c82fatagen2026-09-24 13:07 UTC296
}
31ce2453c82fatagen2026-09-24 13:07 UTC297
5a52012c9b1datagen2026-09-24 23:45 UTC298
/// requests other devices send us, handed from the sdk's event handler to the encryption worker
5a52012c9b1datagen2026-09-24 23:45 UTC299
type IncomingVerifications =
5a52012c9b1datagen2026-09-24 23:45 UTC300
    mpsc::UnboundedSender<matrix_sdk::encryption::verification::VerificationRequest>;
5a52012c9b1datagen2026-09-24 23:45 UTC301
31ce2453c82fatagen2026-09-24 13:07 UTC302
pub struct Engine {
31ce2453c82fatagen2026-09-24 13:07 UTC303
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC304
    sync: Arc<SyncService>,
31ce2453c82fatagen2026-09-24 13:07 UTC305
    port: DriverPort,
31ce2453c82fatagen2026-09-24 13:07 UTC306
    config: EngineConfig,
31ce2453c82fatagen2026-09-24 13:07 UTC307
    media: Arc<MediaService>,
da8896938cf0atagen2026-10-25 10:04 UTC308
    contexts: Arc<context::Sessions>,
31ce2453c82fatagen2026-09-24 13:07 UTC309
    tasks: TaskRegistry,
31ce2453c82fatagen2026-09-24 13:07 UTC310
    rooms: HashMap<OwnedRoomId, RoomSlot>,
31ce2453c82fatagen2026-09-24 13:07 UTC311
    next_generation: u64,
5a52012c9b1datagen2026-09-24 23:45 UTC312
    notes: mpsc::UnboundedReceiver<ActorNote>,
5a52012c9b1datagen2026-09-24 23:45 UTC313
    note_sender: mpsc::UnboundedSender<ActorNote>,
5a52012c9b1datagen2026-09-24 23:45 UTC314
    /// the rooms sliding sync should follow, applied off the run loop since it touches the store
5a52012c9b1datagen2026-09-24 23:45 UTC315
    subscriptions: watch::Sender<Vec<OwnedRoomId>>,
31ce2453c82fatagen2026-09-24 13:07 UTC316
    mutations: mpsc::Sender<MutationJob>,
31ce2453c82fatagen2026-09-24 13:07 UTC317
    notifications: mpsc::Sender<Job<NotificationCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC318
    encryption: mpsc::Sender<Job<EncryptionCommand>>,
66db1b3cd895atagen2026-10-25 10:28 UTC319
    thread_lists: mpsc::Sender<Job<ThreadListCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC320
    queues: Option<Queues>,
5a52012c9b1datagen2026-09-24 23:45 UTC321
    /// the client can outlive us, so the handler has to come off it when we stop
5a52012c9b1datagen2026-09-24 23:45 UTC322
    verification_handler: Option<matrix_sdk::event_handler::EventHandlerHandle>,
fe4133dbcd47atagen2026-09-26 09:05 UTC323
    stop: mpsc::UnboundedSender<Termination>,
fe4133dbcd47atagen2026-09-26 09:05 UTC324
    stops: mpsc::UnboundedReceiver<Termination>,
673563a76e43atagen2026-09-26 12:30 UTC325
    logouts: Arc<watch::Sender<Logouts>>,
38c4caecdb3datagen2026-09-26 13:35 UTC326
    preparations: prepare::Preparations,
a250c7fa43fbatagen2026-09-26 13:35 UTC327
    /// shared with every `ClientHandle`, so the store stays locked while the client is reachable
a250c7fa43fbatagen2026-09-26 13:35 UTC328
    _store_lock: Option<Arc<StoreLock>>,
cbb715e11963atagen2026-10-24 23:24 UTC329
    mentions: crate::mentions::service::Handle,
cbb715e11963atagen2026-10-24 23:24 UTC330
    mentions_service: Option<crate::mentions::service::Service>,
cbb715e11963atagen2026-10-24 23:24 UTC331
    mentions_updates: Option<watch::Receiver<crate::MentionsPage>>,
31ce2453c82fatagen2026-09-24 13:07 UTC332
}
31ce2453c82fatagen2026-09-24 13:07 UTC333
31ce2453c82fatagen2026-09-24 13:07 UTC334
impl Engine {
31ce2453c82fatagen2026-09-24 13:07 UTC335
    /// the escape hatch for a client you built yourself. `Session` is the usual way in
31ce2453c82fatagen2026-09-24 13:07 UTC336
    pub async fn from_client(
31ce2453c82fatagen2026-09-24 13:07 UTC337
        client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC338
        config: EngineConfig,
31ce2453c82fatagen2026-09-24 13:07 UTC339
    ) -> Result<(Self, ClientHandle, EventStream), EngineError> {
f12377bce9b9atagen2026-09-26 12:32 UTC340
        let session_changes = client.subscribe_to_session_changes();
cbb715e11963atagen2026-10-24 23:24 UTC341
        Self::with_persistence(client, config, session_changes, None, None, None).await
f12377bce9b9atagen2026-09-26 12:32 UTC342
    }
f12377bce9b9atagen2026-09-26 12:32 UTC343
f12377bce9b9atagen2026-09-26 12:32 UTC344
    /// `session_changes` is taken when the client is built, since the sdk can refresh
f12377bce9b9atagen2026-09-26 12:32 UTC345
    /// before an engine exists
f12377bce9b9atagen2026-09-26 12:32 UTC346
    pub(crate) async fn with_persistence(
f12377bce9b9atagen2026-09-26 12:32 UTC347
        client: Client,
f12377bce9b9atagen2026-09-26 12:32 UTC348
        config: EngineConfig,
f12377bce9b9atagen2026-09-26 12:32 UTC349
        session_changes: broadcast::Receiver<SessionChange>,
f12377bce9b9atagen2026-09-26 12:32 UTC350
        persistence: Option<Persistence>,
a250c7fa43fbatagen2026-09-26 13:35 UTC351
        store_lock: Option<StoreLock>,
82d37c369846atagen2026-10-25 10:55 UTC352
        mentions: Option<Result<MentionsStore, crate::mentions::service::Unopened>>,
f12377bce9b9atagen2026-09-26 12:32 UTC353
    ) -> Result<(Self, ClientHandle, EventStream), EngineError> {
31ce2453c82fatagen2026-09-24 13:07 UTC354
        if client.user_id().is_none() {
31ce2453c82fatagen2026-09-24 13:07 UTC355
            return Err(EngineError::Unauthenticated);
31ce2453c82fatagen2026-09-24 13:07 UTC356
        }
31ce2453c82fatagen2026-09-24 13:07 UTC357
        if config.command_capacity == 0
31ce2453c82fatagen2026-09-24 13:07 UTC358
            || config.event_capacity == 0
da8896938cf0atagen2026-10-25 10:04 UTC359
            || config.max_context_media == 0
cbb715e11963atagen2026-10-24 23:24 UTC360
            || config.max_mentions_entries == 0
cbb715e11963atagen2026-10-24 23:24 UTC361
            || config.max_mention_context_events == 0
cbb715e11963atagen2026-10-24 23:24 UTC362
            || config.max_mention_candidates == 0
31ce2453c82fatagen2026-09-24 13:07 UTC363
        {
31ce2453c82fatagen2026-09-24 13:07 UTC364
            return Err(EngineError::ZeroCapacity);
31ce2453c82fatagen2026-09-24 13:07 UTC365
        }
cbb715e11963atagen2026-10-24 23:24 UTC366
        let store_lock = store_lock.map(Arc::new);
cbb715e11963atagen2026-10-24 23:24 UTC367
        let media = Arc::new(MediaService::new(
cbb715e11963atagen2026-10-24 23:24 UTC368
            client.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC369
            config.max_media_bytes,
da8896938cf0atagen2026-10-25 10:04 UTC370
            config.max_context_media,
cbb715e11963atagen2026-10-24 23:24 UTC371
        ));
cbb715e11963atagen2026-10-24 23:24 UTC372
        let (mentions, mentions_service, mentions_updates) =
cbb715e11963atagen2026-10-24 23:24 UTC373
            crate::mentions::service::Service::new(
cbb715e11963atagen2026-10-24 23:24 UTC374
                client.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC375
                media.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC376
                mentions,
cbb715e11963atagen2026-10-24 23:24 UTC377
                config.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC378
            )
cbb715e11963atagen2026-10-24 23:24 UTC379
            .await
0d763e4284efatagen2026-10-25 09:31 UTC380
            // a missing user id is all it still refuses, and that was turned away above
0d763e4284efatagen2026-10-25 09:31 UTC381
            .map_err(|_| EngineError::Unauthenticated)?;
31ce2453c82fatagen2026-09-24 13:07 UTC382
        let sync = Arc::new(
31ce2453c82fatagen2026-09-24 13:07 UTC383
            SyncService::builder(client.clone())
31ce2453c82fatagen2026-09-24 13:07 UTC384
                .with_offline_mode()
0291516d40b5atagen2026-10-22 08:31 UTC385
                .with_room_list_extra_required_state(vec![
0291516d40b5atagen2026-10-22 08:31 UTC386
                    (ROOM_PACKS.into(), "*".to_owned()),
0291516d40b5atagen2026-10-22 08:31 UTC387
                    (ROOM_PREVIEW_URLS.into(), String::new()),
0291516d40b5atagen2026-10-22 08:31 UTC388
                ])
cbb715e11963atagen2026-10-24 23:24 UTC389
                .with_room_list_response_commit_hook(mentions.hook())
31ce2453c82fatagen2026-09-24 13:07 UTC390
                .build()
31ce2453c82fatagen2026-09-24 13:07 UTC391
                .await
31ce2453c82fatagen2026-09-24 13:07 UTC392
                .map_err(EngineError::SyncService)?,
31ce2453c82fatagen2026-09-24 13:07 UTC393
        );
31ce2453c82fatagen2026-09-24 13:07 UTC394
        let (handle, port, events) = transport_pair(
31ce2453c82fatagen2026-09-24 13:07 UTC395
            client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC396
            sync.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC397
            media.clone(),
a250c7fa43fbatagen2026-09-26 13:35 UTC398
            store_lock.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC399
            config.command_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC400
            config.event_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC401
        );
31ce2453c82fatagen2026-09-24 13:07 UTC402
        client.send_queue().enable_upload_progress(true);
411bc1c78b65atagen2026-10-22 07:39 UTC403
        client.send_queue().enable_global_upload_progress(true);
5a52012c9b1datagen2026-09-24 23:45 UTC404
        let (note_sender, notes) = mpsc::unbounded_channel();
fe4133dbcd47atagen2026-09-26 09:05 UTC405
        let (stop, stops) = mpsc::unbounded_channel();
31ce2453c82fatagen2026-09-24 13:07 UTC406
        let (mutations, mutation_queue) = mpsc::channel(config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC407
        let (notifications, notification_queue) = mpsc::channel(config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC408
        let (encryption, encryption_queue) = mpsc::channel(config.command_capacity);
66db1b3cd895atagen2026-10-25 10:28 UTC409
        let (thread_lists, thread_list_queue) = mpsc::channel(config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC410
        let engine = Self {
1f875b103b27atagen2026-10-25 10:44 UTC411
            contexts: Arc::new(context::Sessions::new(port.event_sender())),
31ce2453c82fatagen2026-09-24 13:07 UTC412
            client,
31ce2453c82fatagen2026-09-24 13:07 UTC413
            sync,
31ce2453c82fatagen2026-09-24 13:07 UTC414
            port,
31ce2453c82fatagen2026-09-24 13:07 UTC415
            config,
31ce2453c82fatagen2026-09-24 13:07 UTC416
            media,
31ce2453c82fatagen2026-09-24 13:07 UTC417
            tasks: TaskRegistry {
1fe480c16a3catagen2026-09-26 08:44 UTC418
                tasks: TaskSet::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC419
            },
31ce2453c82fatagen2026-09-24 13:07 UTC420
            rooms: HashMap::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC421
            next_generation: 0,
5a52012c9b1datagen2026-09-24 23:45 UTC422
            notes,
5a52012c9b1datagen2026-09-24 23:45 UTC423
            note_sender,
5a52012c9b1datagen2026-09-24 23:45 UTC424
            subscriptions: watch::Sender::new(Vec::new()),
31ce2453c82fatagen2026-09-24 13:07 UTC425
            mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC426
            notifications,
31ce2453c82fatagen2026-09-24 13:07 UTC427
            encryption,
66db1b3cd895atagen2026-10-25 10:28 UTC428
            thread_lists,
31ce2453c82fatagen2026-09-24 13:07 UTC429
            queues: Some(Queues {
31ce2453c82fatagen2026-09-24 13:07 UTC430
                mutations: mutation_queue,
31ce2453c82fatagen2026-09-24 13:07 UTC431
                notifications: notification_queue,
31ce2453c82fatagen2026-09-24 13:07 UTC432
                encryption: encryption_queue,
66db1b3cd895atagen2026-10-25 10:28 UTC433
                thread_lists: thread_list_queue,
31ce2453c82fatagen2026-09-24 13:07 UTC434
                session_changes,
f12377bce9b9atagen2026-09-26 12:32 UTC435
                persistence,
31ce2453c82fatagen2026-09-24 13:07 UTC436
            }),
5a52012c9b1datagen2026-09-24 23:45 UTC437
            verification_handler: None,
38c4caecdb3datagen2026-09-26 13:35 UTC438
            preparations: prepare::Preparations::default(),
fe4133dbcd47atagen2026-09-26 09:05 UTC439
            stop,
fe4133dbcd47atagen2026-09-26 09:05 UTC440
            stops,
673563a76e43atagen2026-09-26 12:30 UTC441
            logouts: Arc::new(watch::Sender::new(Logouts::default())),
a250c7fa43fbatagen2026-09-26 13:35 UTC442
            _store_lock: store_lock,
cbb715e11963atagen2026-10-24 23:24 UTC443
            mentions,
cbb715e11963atagen2026-10-24 23:24 UTC444
            mentions_service: Some(mentions_service),
cbb715e11963atagen2026-10-24 23:24 UTC445
            mentions_updates: Some(mentions_updates),
31ce2453c82fatagen2026-09-24 13:07 UTC446
        };
31ce2453c82fatagen2026-09-24 13:07 UTC447
        Ok((engine, handle, events))
31ce2453c82fatagen2026-09-24 13:07 UTC448
    }
31ce2453c82fatagen2026-09-24 13:07 UTC449
5a52012c9b1datagen2026-09-24 23:45 UTC450
    /// boxed because the engine's future is deep enough to blow the compiler's query depth
5a52012c9b1datagen2026-09-24 23:45 UTC451
    /// in every crate that spawns it, which isn't something a client should have to fix
fe4133dbcd47atagen2026-09-26 09:05 UTC452
    pub fn run(self) -> EngineBoxFuture<'static, Result<Termination, EngineError>> {
5a52012c9b1datagen2026-09-24 23:45 UTC453
        Box::pin(self.run_inner())
5a52012c9b1datagen2026-09-24 23:45 UTC454
    }
5a52012c9b1datagen2026-09-24 23:45 UTC455
fe4133dbcd47atagen2026-09-26 09:05 UTC456
    async fn run_inner(mut self) -> Result<Termination, EngineError> {
31ce2453c82fatagen2026-09-24 13:07 UTC457
        let events = self.port.event_sender();
31ce2453c82fatagen2026-09-24 13:07 UTC458
        let user_id = self
31ce2453c82fatagen2026-09-24 13:07 UTC459
            .client
31ce2453c82fatagen2026-09-24 13:07 UTC460
            .user_id()
31ce2453c82fatagen2026-09-24 13:07 UTC461
            .expect("authentication was checked during construction")
31ce2453c82fatagen2026-09-24 13:07 UTC462
            .to_owned();
31ce2453c82fatagen2026-09-24 13:07 UTC463
        self.port
31ce2453c82fatagen2026-09-24 13:07 UTC464
            .connection_sender()
31ce2453c82fatagen2026-09-24 13:07 UTC465
            .send_replace(ConnectionState::Connecting);
31ce2453c82fatagen2026-09-24 13:07 UTC466
        for event in [
31ce2453c82fatagen2026-09-24 13:07 UTC467
            Event::Authenticated { user_id },
31ce2453c82fatagen2026-09-24 13:07 UTC468
            Event::ConnectionChanged(ConnectionState::Connecting),
31ce2453c82fatagen2026-09-24 13:07 UTC469
        ] {
31ce2453c82fatagen2026-09-24 13:07 UTC470
            if events.send(event).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC471
                self.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC472
                return Err(EngineError::EventReceiverClosed);
31ce2453c82fatagen2026-09-24 13:07 UTC473
            }
31ce2453c82fatagen2026-09-24 13:07 UTC474
        }
31ce2453c82fatagen2026-09-24 13:07 UTC475
        self.start_tasks();
31ce2453c82fatagen2026-09-24 13:07 UTC476
        self.sync.start().await;
31ce2453c82fatagen2026-09-24 13:07 UTC477
31ce2453c82fatagen2026-09-24 13:07 UTC478
        let mut shutdown_reply = None;
673563a76e43atagen2026-09-26 12:30 UTC479
        let mut handles_dropped = false;
673563a76e43atagen2026-09-26 12:30 UTC480
        let mut logouts = self.logouts.subscribe();
fe4133dbcd47atagen2026-09-26 09:05 UTC481
        let ending = loop {
31ce2453c82fatagen2026-09-24 13:07 UTC482
            tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC483
                biased;
fe4133dbcd47atagen2026-09-26 09:05 UTC484
                Some(termination) = self.stops.recv() => break Ok(termination),
673563a76e43atagen2026-09-26 12:30 UTC485
                () = events.closed() => break Err(EngineError::EventReceiverClosed),
673563a76e43atagen2026-09-26 12:30 UTC486
                () = settled(&mut logouts), if handles_dropped => {
673563a76e43atagen2026-09-26 12:30 UTC487
                    break Ok(Termination::HandlesDropped);
673563a76e43atagen2026-09-26 12:30 UTC488
                }
1fe480c16a3catagen2026-09-26 08:44 UTC489
                Some((context, panic)) = self.tasks.join_next(), if !self.tasks.is_empty() => {
1fe480c16a3catagen2026-09-26 08:44 UTC490
                    let Some(message) = panic else { continue };
31ce2453c82fatagen2026-09-24 13:07 UTC491
                    if let TaskContext::Command(label) = context {
1fe480c16a3catagen2026-09-26 08:44 UTC492
                        tracing::error!(label, panic = %message, "command task panicked");
31ce2453c82fatagen2026-09-24 13:07 UTC493
                        continue;
31ce2453c82fatagen2026-09-24 13:07 UTC494
                    }
fe4133dbcd47atagen2026-09-26 09:05 UTC495
                    break Err(EngineError::TaskPanicked { task: context.label() });
31ce2453c82fatagen2026-09-24 13:07 UTC496
                }
5a52012c9b1datagen2026-09-24 23:45 UTC497
                Some(note) = self.notes.recv() => self.actor_note(note).await,
673563a76e43atagen2026-09-26 12:30 UTC498
                request = self.port.recv(), if !handles_dropped => {
673563a76e43atagen2026-09-26 12:30 UTC499
                    // nobody's left to ask, but a logout they asked for still deserves to land
673563a76e43atagen2026-09-26 12:30 UTC500
                    let Some(request) = request else {
673563a76e43atagen2026-09-26 12:30 UTC501
                        handles_dropped = true;
673563a76e43atagen2026-09-26 12:30 UTC502
                        continue;
673563a76e43atagen2026-09-26 12:30 UTC503
                    };
5a52012c9b1datagen2026-09-24 23:45 UTC504
                    if let Some(reply) = self.dispatch(request).await {
5a52012c9b1datagen2026-09-24 23:45 UTC505
                        shutdown_reply = Some(reply);
fe4133dbcd47atagen2026-09-26 09:05 UTC506
                        break Ok(Termination::ShutDown);
5a52012c9b1datagen2026-09-24 23:45 UTC507
                    }
5a52012c9b1datagen2026-09-24 23:45 UTC508
                }
31ce2453c82fatagen2026-09-24 13:07 UTC509
            }
fe4133dbcd47atagen2026-09-26 09:05 UTC510
        };
31ce2453c82fatagen2026-09-24 13:07 UTC511
fe4133dbcd47atagen2026-09-26 09:05 UTC512
        if let Err(error) = &ending {
31ce2453c82fatagen2026-09-24 13:07 UTC513
            let _ = events.send(Event::Failed(error.failure())).await;
31ce2453c82fatagen2026-09-24 13:07 UTC514
        }
31ce2453c82fatagen2026-09-24 13:07 UTC515
        self.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC516
        let _ = events.send(Event::Stopped).await;
31ce2453c82fatagen2026-09-24 13:07 UTC517
        if let Some(reply) = shutdown_reply {
31ce2453c82fatagen2026-09-24 13:07 UTC518
            reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC519
        }
5a52012c9b1datagen2026-09-24 23:45 UTC520
        // everything else still queued answers `Interrupted` as it drops, but a shutdown did happen
5a52012c9b1datagen2026-09-24 23:45 UTC521
        while let Some(Request { command, reply }) = self.port.try_recv() {
5a52012c9b1datagen2026-09-24 23:45 UTC522
            if matches!(command, Command::Lifecycle(LifecycleCommand::Shutdown)) {
5a52012c9b1datagen2026-09-24 23:45 UTC523
                reply.done(Ok(()));
5a52012c9b1datagen2026-09-24 23:45 UTC524
            }
5a52012c9b1datagen2026-09-24 23:45 UTC525
        }
fe4133dbcd47atagen2026-09-26 09:05 UTC526
        ending
31ce2453c82fatagen2026-09-24 13:07 UTC527
    }
31ce2453c82fatagen2026-09-24 13:07 UTC528
31ce2453c82fatagen2026-09-24 13:07 UTC529
    fn start_tasks(&mut self) {
31ce2453c82fatagen2026-09-24 13:07 UTC530
        let queues = self.queues.take().expect("engine tasks start once");
cbb715e11963atagen2026-10-24 23:24 UTC531
        if let Some(service) = self.mentions_service.take() {
cbb715e11963atagen2026-10-24 23:24 UTC532
            self.tasks
cbb715e11963atagen2026-10-24 23:24 UTC533
                .spawn(TaskContext::Watcher("mentions service"), service.run());
cbb715e11963atagen2026-10-24 23:24 UTC534
        }
cbb715e11963atagen2026-10-24 23:24 UTC535
        if let Some(updates) = self.mentions_updates.take() {
cbb715e11963atagen2026-10-24 23:24 UTC536
            let events = self.port.event_sender();
cbb715e11963atagen2026-10-24 23:24 UTC537
            self.tasks.spawn(
cbb715e11963atagen2026-10-24 23:24 UTC538
                TaskContext::Watcher("mentions updates"),
cbb715e11963atagen2026-10-24 23:24 UTC539
                crate::mentions::service::watch_updates(updates, events),
cbb715e11963atagen2026-10-24 23:24 UTC540
            );
cbb715e11963atagen2026-10-24 23:24 UTC541
        }
5a52012c9b1datagen2026-09-24 23:45 UTC542
        let (incoming, incoming_verifications) = mpsc::unbounded_channel();
5a52012c9b1datagen2026-09-24 23:45 UTC543
        self.verification_handler = Some(self.verification_handler(incoming));
31ce2453c82fatagen2026-09-24 13:07 UTC544
        let client = &self.client;
31ce2453c82fatagen2026-09-24 13:07 UTC545
        let events = || self.port.event_sender();
f12377bce9b9atagen2026-09-26 12:32 UTC546
        let (notices, notice_queue) = mpsc::unbounded_channel();
66db1b3cd895atagen2026-10-25 10:28 UTC547
        let watchers: [(&'static str, EngineBoxFuture<'static, ()>); 15] = [
5a52012c9b1datagen2026-09-24 23:45 UTC548
            (
7c26fad34822atagen2026-09-26 09:41 UTC549
                "upload tracker",
0bfa3f46f0beatagen2026-09-26 09:12 UTC550
                Box::pin(watchers::uploads(
5a52012c9b1datagen2026-09-24 23:45 UTC551
                    client.clone(),
5a52012c9b1datagen2026-09-24 23:45 UTC552
                    client.send_queue().subscribe(),
5a52012c9b1datagen2026-09-24 23:45 UTC553
                    events(),
5a52012c9b1datagen2026-09-24 23:45 UTC554
                )),
5a52012c9b1datagen2026-09-24 23:45 UTC555
            ),
5a52012c9b1datagen2026-09-24 23:45 UTC556
            (
5a52012c9b1datagen2026-09-24 23:45 UTC557
                "room subscription watcher",
5a52012c9b1datagen2026-09-24 23:45 UTC558
                Box::pin(watchers::room_subscriptions(
5a52012c9b1datagen2026-09-24 23:45 UTC559
                    self.sync.clone(),
5a52012c9b1datagen2026-09-24 23:45 UTC560
                    self.subscriptions.subscribe(),
5a52012c9b1datagen2026-09-24 23:45 UTC561
                )),
5a52012c9b1datagen2026-09-24 23:45 UTC562
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC563
            (
31ce2453c82fatagen2026-09-24 13:07 UTC564
                "session change watcher",
f12377bce9b9atagen2026-09-26 12:32 UTC565
                Box::pin(session::session(
f12377bce9b9atagen2026-09-26 12:32 UTC566
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC567
                    queues.session_changes,
f12377bce9b9atagen2026-09-26 12:32 UTC568
                    queues.persistence,
f12377bce9b9atagen2026-09-26 12:32 UTC569
                    notices,
fe4133dbcd47atagen2026-09-26 09:05 UTC570
                    client
fe4133dbcd47atagen2026-09-26 09:05 UTC571
                        .device_id()
fe4133dbcd47atagen2026-09-26 09:05 UTC572
                        .expect("authentication was checked during construction")
fe4133dbcd47atagen2026-09-26 09:05 UTC573
                        .to_owned(),
673563a76e43atagen2026-09-26 12:30 UTC574
                    self.logouts.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC575
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC576
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC577
            (
f12377bce9b9atagen2026-09-26 12:32 UTC578
                "session notice watcher",
f12377bce9b9atagen2026-09-26 12:32 UTC579
                Box::pin(session::session_notices(
f12377bce9b9atagen2026-09-26 12:32 UTC580
                    notice_queue,
f12377bce9b9atagen2026-09-26 12:32 UTC581
                    events(),
f12377bce9b9atagen2026-09-26 12:32 UTC582
                    self.stop.clone(),
f12377bce9b9atagen2026-09-26 12:32 UTC583
                )),
f12377bce9b9atagen2026-09-26 12:32 UTC584
            ),
f12377bce9b9atagen2026-09-26 12:32 UTC585
            (
31ce2453c82fatagen2026-09-24 13:07 UTC586
                "connection state watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC587
                Box::pin(watchers::connection(
31ce2453c82fatagen2026-09-24 13:07 UTC588
                    self.sync.state(),
31ce2453c82fatagen2026-09-24 13:07 UTC589
                    self.sync.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC590
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC591
                    events(),
31ce2453c82fatagen2026-09-24 13:07 UTC592
                    self.port.connection_sender(),
31ce2453c82fatagen2026-09-24 13:07 UTC593
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC594
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC595
            (
31ce2453c82fatagen2026-09-24 13:07 UTC596
                "send queue watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC597
                Box::pin(watchers::send_queue_errors(
31ce2453c82fatagen2026-09-24 13:07 UTC598
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC599
                    client.send_queue().subscribe_errors(),
31ce2453c82fatagen2026-09-24 13:07 UTC600
                    self.port.connection_sender().subscribe(),
31ce2453c82fatagen2026-09-24 13:07 UTC601
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC602
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC603
            (
31ce2453c82fatagen2026-09-24 13:07 UTC604
                "encryption state watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC605
                Box::pin(watchers::encryption(client.clone(), events())),
31ce2453c82fatagen2026-09-24 13:07 UTC606
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC607
            (
31ce2453c82fatagen2026-09-24 13:07 UTC608
                "room list watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC609
                Box::pin(watchers::rooms(client.clone(), events())),
31ce2453c82fatagen2026-09-24 13:07 UTC610
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC611
            (
da8896938cf0atagen2026-10-25 10:04 UTC612
                "event context watcher",
da8896938cf0atagen2026-10-25 10:04 UTC613
                Box::pin(context::close_on_leave(
da8896938cf0atagen2026-10-25 10:04 UTC614
                    client.clone(),
da8896938cf0atagen2026-10-25 10:04 UTC615
                    self.media.clone(),
da8896938cf0atagen2026-10-25 10:04 UTC616
                    self.contexts.clone(),
da8896938cf0atagen2026-10-25 10:04 UTC617
                )),
da8896938cf0atagen2026-10-25 10:04 UTC618
            ),
da8896938cf0atagen2026-10-25 10:04 UTC619
            (
17e042fbc331atagen2026-10-08 12:39 UTC620
                "image pack watcher",
17e042fbc331atagen2026-10-08 12:39 UTC621
                Box::pin(watchers::image_packs(client.clone(), events())),
17e042fbc331atagen2026-10-08 12:39 UTC622
            ),
17e042fbc331atagen2026-10-08 12:39 UTC623
            (
31ce2453c82fatagen2026-09-24 13:07 UTC624
                "notification settings watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC625
                Box::pin(watchers::notification_settings(client.clone(), events())),
31ce2453c82fatagen2026-09-24 13:07 UTC626
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC627
            (
31ce2453c82fatagen2026-09-24 13:07 UTC628
                "room command worker",
31ce2453c82fatagen2026-09-24 13:07 UTC629
                Box::pin(mutations::run_scheduler(
31ce2453c82fatagen2026-09-24 13:07 UTC630
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC631
                    queues.mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC632
                    self.config.command_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC633
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC634
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC635
            (
31ce2453c82fatagen2026-09-24 13:07 UTC636
                "notification command worker",
31ce2453c82fatagen2026-09-24 13:07 UTC637
                Box::pin(commands::run_notifications(
31ce2453c82fatagen2026-09-24 13:07 UTC638
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC639
                    queues.notifications,
31ce2453c82fatagen2026-09-24 13:07 UTC640
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC641
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC642
            (
31ce2453c82fatagen2026-09-24 13:07 UTC643
                "encryption command worker",
31ce2453c82fatagen2026-09-24 13:07 UTC644
                Box::pin(commands::run_encryption(
31ce2453c82fatagen2026-09-24 13:07 UTC645
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC646
                    events(),
31ce2453c82fatagen2026-09-24 13:07 UTC647
                    queues.encryption,
5a52012c9b1datagen2026-09-24 23:45 UTC648
                    incoming_verifications,
31ce2453c82fatagen2026-09-24 13:07 UTC649
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC650
            ),
66db1b3cd895atagen2026-10-25 10:28 UTC651
            (
66db1b3cd895atagen2026-10-25 10:28 UTC652
                "thread list worker",
66db1b3cd895atagen2026-10-25 10:28 UTC653
                Box::pin(thread_list::run(
66db1b3cd895atagen2026-10-25 10:28 UTC654
                    client.clone(),
66db1b3cd895atagen2026-10-25 10:28 UTC655
                    events(),
66db1b3cd895atagen2026-10-25 10:28 UTC656
                    self.media.clone(),
66db1b3cd895atagen2026-10-25 10:28 UTC657
                    queues.thread_lists,
66db1b3cd895atagen2026-10-25 10:28 UTC658
                )),
66db1b3cd895atagen2026-10-25 10:28 UTC659
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC660
        ];
31ce2453c82fatagen2026-09-24 13:07 UTC661
        for (label, task) in watchers {
31ce2453c82fatagen2026-09-24 13:07 UTC662
            self.tasks.spawn(TaskContext::Watcher(label), task);
31ce2453c82fatagen2026-09-24 13:07 UTC663
        }
31ce2453c82fatagen2026-09-24 13:07 UTC664
    }
31ce2453c82fatagen2026-09-24 13:07 UTC665
5a52012c9b1datagen2026-09-24 23:45 UTC666
    fn verification_handler(
5a52012c9b1datagen2026-09-24 23:45 UTC667
        &self,
5a52012c9b1datagen2026-09-24 23:45 UTC668
        incoming: IncomingVerifications,
5a52012c9b1datagen2026-09-24 23:45 UTC669
    ) -> matrix_sdk::event_handler::EventHandlerHandle {
5a52012c9b1datagen2026-09-24 23:45 UTC670
        use matrix_sdk::ruma::events::key::verification::request::ToDeviceKeyVerificationRequestEvent;
5a52012c9b1datagen2026-09-24 23:45 UTC671
        self.client.add_event_handler(
5a52012c9b1datagen2026-09-24 23:45 UTC672
            move |event: ToDeviceKeyVerificationRequestEvent, client: Client| {
5a52012c9b1datagen2026-09-24 23:45 UTC673
                let incoming = incoming.clone();
5a52012c9b1datagen2026-09-24 23:45 UTC674
                async move {
5a52012c9b1datagen2026-09-24 23:45 UTC675
                    let request = client
5a52012c9b1datagen2026-09-24 23:45 UTC676
                        .encryption()
5a52012c9b1datagen2026-09-24 23:45 UTC677
                        .get_verification_request(
5a52012c9b1datagen2026-09-24 23:45 UTC678
                            &event.sender,
5a52012c9b1datagen2026-09-24 23:45 UTC679
                            event.content.transaction_id.as_str(),
5a52012c9b1datagen2026-09-24 23:45 UTC680
                        )
5a52012c9b1datagen2026-09-24 23:45 UTC681
                        .await;
5a52012c9b1datagen2026-09-24 23:45 UTC682
                    if let Some(request) = request {
5a52012c9b1datagen2026-09-24 23:45 UTC683
                        let _ = incoming.send(request);
5a52012c9b1datagen2026-09-24 23:45 UTC684
                    }
5a52012c9b1datagen2026-09-24 23:45 UTC685
                }
5a52012c9b1datagen2026-09-24 23:45 UTC686
            },
5a52012c9b1datagen2026-09-24 23:45 UTC687
        )
5a52012c9b1datagen2026-09-24 23:45 UTC688
    }
5a52012c9b1datagen2026-09-24 23:45 UTC689
31ce2453c82fatagen2026-09-24 13:07 UTC690
    /// hands back the shutdown request's responder, which is answered once we've stopped
31ce2453c82fatagen2026-09-24 13:07 UTC691
    async fn dispatch(&mut self, Request { command, reply }: Request) -> Option<Responder> {
31ce2453c82fatagen2026-09-24 13:07 UTC692
        let client = self.client.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC693
        match command {
31ce2453c82fatagen2026-09-24 13:07 UTC694
            Command::Lifecycle(LifecycleCommand::Shutdown) => return Some(reply),
31ce2453c82fatagen2026-09-24 13:07 UTC695
            Command::Account(AccountCommand::Logout) => {
31ce2453c82fatagen2026-09-24 13:07 UTC696
                let events = self.port.event_sender();
31ce2453c82fatagen2026-09-24 13:07 UTC697
                let stop = self.stop.clone();
673563a76e43atagen2026-09-26 12:30 UTC698
                let logouts = self.logouts.clone();
673563a76e43atagen2026-09-26 12:30 UTC699
                logouts.send_modify(|logouts| logouts.in_flight += 1);
31ce2453c82fatagen2026-09-24 13:07 UTC700
                self.spawn_command("logout", reply, async move {
673563a76e43atagen2026-09-26 12:30 UTC701
                    let result = client.logout().await;
673563a76e43atagen2026-09-26 12:30 UTC702
                    if result.is_ok() {
673563a76e43atagen2026-09-26 12:30 UTC703
                        let _ = events.send(Event::LoggedOut).await;
673563a76e43atagen2026-09-26 12:30 UTC704
                        let _ = stop.send(Termination::LoggedOut);
673563a76e43atagen2026-09-26 12:30 UTC705
                    }
673563a76e43atagen2026-09-26 12:30 UTC706
                    let mut rejected = None;
673563a76e43atagen2026-09-26 12:30 UTC707
                    logouts.send_if_modified(|logouts| {
673563a76e43atagen2026-09-26 12:30 UTC708
                        if result.is_err() && logouts.in_flight == 1 {
673563a76e43atagen2026-09-26 12:30 UTC709
                            rejected = logouts.rejected.take();
673563a76e43atagen2026-09-26 12:30 UTC710
                        }
673563a76e43atagen2026-09-26 12:30 UTC711
                        false
673563a76e43atagen2026-09-26 12:30 UTC712
                    });
673563a76e43atagen2026-09-26 12:30 UTC713
                    if let Some(soft_logout) = rejected {
f12377bce9b9atagen2026-09-26 12:32 UTC714
                        session::reject_session(&events, &stop, soft_logout).await;
673563a76e43atagen2026-09-26 12:30 UTC715
                    }
673563a76e43atagen2026-09-26 12:30 UTC716
                    logouts.send_modify(|logouts| logouts.in_flight -= 1);
673563a76e43atagen2026-09-26 12:30 UTC717
                    result.map_err(|source| Error::from_sdk("logout failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC718
                });
31ce2453c82fatagen2026-09-24 13:07 UTC719
            }
31ce2453c82fatagen2026-09-24 13:07 UTC720
            Command::Account(AccountCommand::SetAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC721
                event_type,
31ce2453c82fatagen2026-09-24 13:07 UTC722
                content,
31ce2453c82fatagen2026-09-24 13:07 UTC723
            }) => enqueue(
31ce2453c82fatagen2026-09-24 13:07 UTC724
                &self.mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC725
                Job {
31ce2453c82fatagen2026-09-24 13:07 UTC726
                    command: Mutation::GlobalAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC727
                        event_type,
31ce2453c82fatagen2026-09-24 13:07 UTC728
                        content,
31ce2453c82fatagen2026-09-24 13:07 UTC729
                    },
31ce2453c82fatagen2026-09-24 13:07 UTC730
                    reply,
31ce2453c82fatagen2026-09-24 13:07 UTC731
                },
31ce2453c82fatagen2026-09-24 13:07 UTC732
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC733
            Command::Account(AccountCommand::SetDisplayName(name)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC734
                self.spawn_command("set display name", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC735
                    client
31ce2453c82fatagen2026-09-24 13:07 UTC736
                        .account()
31ce2453c82fatagen2026-09-24 13:07 UTC737
                        .set_display_name(name.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC738
                        .await
31ce2453c82fatagen2026-09-24 13:07 UTC739
                        .map_err(|source| Error::from_sdk("setting display name failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC740
                });
31ce2453c82fatagen2026-09-24 13:07 UTC741
            }
31ce2453c82fatagen2026-09-24 13:07 UTC742
            Command::Account(AccountCommand::SetAvatar(avatar)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC743
                self.spawn_command("set avatar", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC744
                    client
31ce2453c82fatagen2026-09-24 13:07 UTC745
                        .account()
31ce2453c82fatagen2026-09-24 13:07 UTC746
                        .set_avatar_url(avatar.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC747
                        .await
31ce2453c82fatagen2026-09-24 13:07 UTC748
                        .map_err(|source| Error::from_sdk("setting avatar failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC749
                });
31ce2453c82fatagen2026-09-24 13:07 UTC750
            }
31ce2453c82fatagen2026-09-24 13:07 UTC751
            Command::Account(AccountCommand::UploadAvatar { mimetype, bytes }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC752
                let max_bytes = self.config.max_media_bytes;
31ce2453c82fatagen2026-09-24 13:07 UTC753
                self.spawn_command("upload avatar", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC754
                    commands::upload_avatar(&client, &mimetype, bytes, max_bytes).await
31ce2453c82fatagen2026-09-24 13:07 UTC755
                });
31ce2453c82fatagen2026-09-24 13:07 UTC756
            }
9bd34e25bb86atagen2026-10-24 07:23 UTC757
            Command::Account(AccountCommand::UploadMedia { mimetype, bytes }) => {
9bd34e25bb86atagen2026-10-24 07:23 UTC758
                let max_bytes = self.config.max_media_bytes;
9bd34e25bb86atagen2026-10-24 07:23 UTC759
                self.tasks
9bd34e25bb86atagen2026-10-24 07:23 UTC760
                    .spawn(TaskContext::Command("upload media"), async move {
9bd34e25bb86atagen2026-10-24 07:23 UTC761
                        let uploaded =
9bd34e25bb86atagen2026-10-24 07:23 UTC762
                            commands::upload_media(&client, &mimetype, bytes, max_bytes).await;
9bd34e25bb86atagen2026-10-24 07:23 UTC763
                        reply.send(uploaded.map(CommandOutput::Mxc));
9bd34e25bb86atagen2026-10-24 07:23 UTC764
                    });
9bd34e25bb86atagen2026-10-24 07:23 UTC765
            }
9bd34e25bb86atagen2026-10-24 07:23 UTC766
            Command::Account(AccountCommand::IgnoreUser(user_id)) => enqueue(
9bd34e25bb86atagen2026-10-24 07:23 UTC767
                &self.mutations,
9bd34e25bb86atagen2026-10-24 07:23 UTC768
                Job {
9bd34e25bb86atagen2026-10-24 07:23 UTC769
                    command: Mutation::Ignore {
9bd34e25bb86atagen2026-10-24 07:23 UTC770
                        user_id,
9bd34e25bb86atagen2026-10-24 07:23 UTC771
                        ignored: true,
9bd34e25bb86atagen2026-10-24 07:23 UTC772
                    },
9bd34e25bb86atagen2026-10-24 07:23 UTC773
                    reply,
9bd34e25bb86atagen2026-10-24 07:23 UTC774
                },
9bd34e25bb86atagen2026-10-24 07:23 UTC775
            ),
9bd34e25bb86atagen2026-10-24 07:23 UTC776
            Command::Account(AccountCommand::UnignoreUser(user_id)) => enqueue(
9bd34e25bb86atagen2026-10-24 07:23 UTC777
                &self.mutations,
9bd34e25bb86atagen2026-10-24 07:23 UTC778
                Job {
9bd34e25bb86atagen2026-10-24 07:23 UTC779
                    command: Mutation::Ignore {
9bd34e25bb86atagen2026-10-24 07:23 UTC780
                        user_id,
9bd34e25bb86atagen2026-10-24 07:23 UTC781
                        ignored: false,
9bd34e25bb86atagen2026-10-24 07:23 UTC782
                    },
9bd34e25bb86atagen2026-10-24 07:23 UTC783
                    reply,
9bd34e25bb86atagen2026-10-24 07:23 UTC784
                },
9bd34e25bb86atagen2026-10-24 07:23 UTC785
            ),
9bd34e25bb86atagen2026-10-24 07:23 UTC786
            Command::Account(AccountCommand::ReorderSpaces(order)) => enqueue(
9bd34e25bb86atagen2026-10-24 07:23 UTC787
                &self.mutations,
9bd34e25bb86atagen2026-10-24 07:23 UTC788
                Job {
9bd34e25bb86atagen2026-10-24 07:23 UTC789
                    command: Mutation::ReorderSpaces(order),
9bd34e25bb86atagen2026-10-24 07:23 UTC790
                    reply,
9bd34e25bb86atagen2026-10-24 07:23 UTC791
                },
9bd34e25bb86atagen2026-10-24 07:23 UTC792
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC793
            Command::Account(AccountCommand::RenameDevice {
31ce2453c82fatagen2026-09-24 13:07 UTC794
                device_id,
31ce2453c82fatagen2026-09-24 13:07 UTC795
                display_name,
31ce2453c82fatagen2026-09-24 13:07 UTC796
            }) => self.spawn_command("rename device", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC797
                commands::rename_device(&client, &device_id, &display_name).await
31ce2453c82fatagen2026-09-24 13:07 UTC798
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC799
            Command::Account(AccountCommand::DeleteDevices { device_ids, auth }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC800
                self.spawn_command("delete devices", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC801
                    commands::delete_devices(&client, &device_ids, auth).await
31ce2453c82fatagen2026-09-24 13:07 UTC802
                });
31ce2453c82fatagen2026-09-24 13:07 UTC803
            }
38c4caecdb3datagen2026-09-26 13:35 UTC804
            Command::Room(RoomCommand::Open(room_id)) => {
38c4caecdb3datagen2026-09-26 13:35 UTC805
                if self.config.prepare_to_send {
38c4caecdb3datagen2026-09-26 13:35 UTC806
                    self.prepare_quietly(room_id.clone());
38c4caecdb3datagen2026-09-26 13:35 UTC807
                }
38c4caecdb3datagen2026-09-26 13:35 UTC808
                self.open_room(room_id, reply).await;
38c4caecdb3datagen2026-09-26 13:35 UTC809
            }
31ce2453c82fatagen2026-09-24 13:07 UTC810
            Command::Room(RoomCommand::Close(room_id)) => self.close_room(room_id, reply).await,
38c4caecdb3datagen2026-09-26 13:35 UTC811
            Command::Room(RoomCommand::PrepareToSend(room_id)) => {
38c4caecdb3datagen2026-09-26 13:35 UTC812
                let flight = self.preparations.join(&client, room_id);
38c4caecdb3datagen2026-09-26 13:35 UTC813
                self.spawn_command("prepare to send", reply, flight);
38c4caecdb3datagen2026-09-26 13:35 UTC814
            }
31ce2453c82fatagen2026-09-24 13:07 UTC815
            Command::Room(RoomCommand::SetTyping { room_id, typing }) => {
38c4caecdb3datagen2026-09-26 13:35 UTC816
                if typing && self.config.prepare_to_send {
38c4caecdb3datagen2026-09-26 13:35 UTC817
                    self.prepare_quietly(room_id.clone());
38c4caecdb3datagen2026-09-26 13:35 UTC818
                }
31ce2453c82fatagen2026-09-24 13:07 UTC819
                self.spawn_command("typing", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC820
                    commands::set_typing(&client, &room_id, typing).await
31ce2453c82fatagen2026-09-24 13:07 UTC821
                });
31ce2453c82fatagen2026-09-24 13:07 UTC822
            }
31ce2453c82fatagen2026-09-24 13:07 UTC823
            Command::Room(RoomCommand::CancelSend {
31ce2453c82fatagen2026-09-24 13:07 UTC824
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC825
                transaction_id,
31ce2453c82fatagen2026-09-24 13:07 UTC826
            }) => self.spawn_command("cancel send", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC827
                commands::cancel_send(&client, &room_id, &transaction_id).await
31ce2453c82fatagen2026-09-24 13:07 UTC828
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC829
            Command::Room(RoomCommand::RetrySend {
31ce2453c82fatagen2026-09-24 13:07 UTC830
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC831
                transaction_id,
31ce2453c82fatagen2026-09-24 13:07 UTC832
            }) => self.spawn_command("retry send", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC833
                commands::retry_send(&client, &room_id, &transaction_id).await
31ce2453c82fatagen2026-09-24 13:07 UTC834
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC835
            Command::Room(command) => enqueue(
31ce2453c82fatagen2026-09-24 13:07 UTC836
                &self.mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC837
                Job {
31ce2453c82fatagen2026-09-24 13:07 UTC838
                    command: Mutation::Room(command),
31ce2453c82fatagen2026-09-24 13:07 UTC839
                    reply,
31ce2453c82fatagen2026-09-24 13:07 UTC840
                },
31ce2453c82fatagen2026-09-24 13:07 UTC841
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC842
            Command::Timeline(command) => self.route_timeline(command, reply),
89bc9f8d246datagen2026-10-24 13:40 UTC843
            Command::EventContext(command) => {
da8896938cf0atagen2026-10-25 10:04 UTC844
                let (client, media, contexts) =
da8896938cf0atagen2026-10-25 10:04 UTC845
                    (client.clone(), self.media.clone(), self.contexts.clone());
cbb715e11963atagen2026-10-24 23:24 UTC846
                self.tasks
cbb715e11963atagen2026-10-24 23:24 UTC847
                    .spawn(TaskContext::Command("event context"), async move {
da8896938cf0atagen2026-10-25 10:04 UTC848
                        reply.send(context::execute(client, media, contexts, command).await);
cbb715e11963atagen2026-10-24 23:24 UTC849
                    });
cbb715e11963atagen2026-10-24 23:24 UTC850
            }
cbb715e11963atagen2026-10-24 23:24 UTC851
            Command::Mentions(command) => {
cbb715e11963atagen2026-10-24 23:24 UTC852
                let mentions = self.mentions.clone();
cbb715e11963atagen2026-10-24 23:24 UTC853
                self.tasks
cbb715e11963atagen2026-10-24 23:24 UTC854
                    .spawn(TaskContext::Command("mentions command"), async move {
cbb715e11963atagen2026-10-24 23:24 UTC855
                        reply.send(mentions.execute(command).await);
cbb715e11963atagen2026-10-24 23:24 UTC856
                    });
89bc9f8d246datagen2026-10-24 13:40 UTC857
            }
80381e06a573atagen2026-10-25 03:02 UTC858
            Command::HistoryRepair(command) => self.route_repair(command, reply),
31ce2453c82fatagen2026-09-24 13:07 UTC859
            Command::Media(MediaCommand::Upload(upload)) => self.upload(upload, reply),
31ce2453c82fatagen2026-09-24 13:07 UTC860
            Command::Encryption(command) => enqueue(&self.encryption, Job { command, reply }),
31ce2453c82fatagen2026-09-24 13:07 UTC861
            Command::Notification(command) => {
31ce2453c82fatagen2026-09-24 13:07 UTC862
                enqueue(&self.notifications, Job { command, reply });
31ce2453c82fatagen2026-09-24 13:07 UTC863
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC864
            Command::Pack(command) => self.pack(command, reply),
66db1b3cd895atagen2026-10-25 10:28 UTC865
            Command::ThreadList(command) => enqueue(&self.thread_lists, Job { command, reply }),
31ce2453c82fatagen2026-09-24 13:07 UTC866
        }
31ce2453c82fatagen2026-09-24 13:07 UTC867
        None
31ce2453c82fatagen2026-09-24 13:07 UTC868
    }
31ce2453c82fatagen2026-09-24 13:07 UTC869
31ce2453c82fatagen2026-09-24 13:07 UTC870
    fn spawn_command(
31ce2453c82fatagen2026-09-24 13:07 UTC871
        &mut self,
31ce2453c82fatagen2026-09-24 13:07 UTC872
        label: &'static str,
31ce2453c82fatagen2026-09-24 13:07 UTC873
        reply: Responder,
1fe480c16a3catagen2026-09-26 08:44 UTC874
        work: impl Future<Output = Result<(), Error>> + SendOutsideWasm + 'static,
31ce2453c82fatagen2026-09-24 13:07 UTC875
    ) {
31ce2453c82fatagen2026-09-24 13:07 UTC876
        self.tasks.spawn(TaskContext::Command(label), async move {
31ce2453c82fatagen2026-09-24 13:07 UTC877
            reply.done(work.await);
31ce2453c82fatagen2026-09-24 13:07 UTC878
        });
31ce2453c82fatagen2026-09-24 13:07 UTC879
    }
31ce2453c82fatagen2026-09-24 13:07 UTC880
38c4caecdb3datagen2026-09-26 13:35 UTC881
    fn prepare_quietly(&mut self, room_id: OwnedRoomId) {
38c4caecdb3datagen2026-09-26 13:35 UTC882
        let flight = self.preparations.join(&self.client, room_id);
38c4caecdb3datagen2026-09-26 13:35 UTC883
        self.tasks
38c4caecdb3datagen2026-09-26 13:35 UTC884
            .spawn(TaskContext::Command("prepare to send"), async move {
38c4caecdb3datagen2026-09-26 13:35 UTC885
                let _ = flight.await;
38c4caecdb3datagen2026-09-26 13:35 UTC886
            });
38c4caecdb3datagen2026-09-26 13:35 UTC887
    }
38c4caecdb3datagen2026-09-26 13:35 UTC888
fa51490b6ae9atagen2026-10-24 08:41 UTC889
    fn pack(&mut self, command: PackCommand, reply: Responder) {
fa51490b6ae9atagen2026-10-24 08:41 UTC890
        let edit = |pack, edit| Mutation::Pack { pack, edit };
fa51490b6ae9atagen2026-10-24 08:41 UTC891
        let mutation = match command {
fa51490b6ae9atagen2026-10-24 08:41 UTC892
            PackCommand::CreateRoomPack {
fa51490b6ae9atagen2026-10-24 08:41 UTC893
                room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC894
                state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC895
                display_name,
fa51490b6ae9atagen2026-10-24 08:41 UTC896
            } => edit(
fa51490b6ae9atagen2026-10-24 08:41 UTC897
                ImagePackSource::Room { room_id, state_key },
fa51490b6ae9atagen2026-10-24 08:41 UTC898
                PackEdit::Create { display_name },
fa51490b6ae9atagen2026-10-24 08:41 UTC899
            ),
fa51490b6ae9atagen2026-10-24 08:41 UTC900
            PackCommand::Delete(pack) => edit(pack, PackEdit::Delete),
fa51490b6ae9atagen2026-10-24 08:41 UTC901
            PackCommand::SetMeta {
fa51490b6ae9atagen2026-10-24 08:41 UTC902
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC903
                display_name,
fa51490b6ae9atagen2026-10-24 08:41 UTC904
                avatar,
fa51490b6ae9atagen2026-10-24 08:41 UTC905
                usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC906
            } => edit(
fa51490b6ae9atagen2026-10-24 08:41 UTC907
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC908
                PackEdit::Meta {
fa51490b6ae9atagen2026-10-24 08:41 UTC909
                    display_name,
fa51490b6ae9atagen2026-10-24 08:41 UTC910
                    avatar,
fa51490b6ae9atagen2026-10-24 08:41 UTC911
                    usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC912
                },
fa51490b6ae9atagen2026-10-24 08:41 UTC913
            ),
fa51490b6ae9atagen2026-10-24 08:41 UTC914
            PackCommand::PutImage {
fa51490b6ae9atagen2026-10-24 08:41 UTC915
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC916
                shortcode,
fa51490b6ae9atagen2026-10-24 08:41 UTC917
                mxc,
fa51490b6ae9atagen2026-10-24 08:41 UTC918
                body,
fa51490b6ae9atagen2026-10-24 08:41 UTC919
                usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC920
                info,
fa51490b6ae9atagen2026-10-24 08:41 UTC921
            } => edit(
fa51490b6ae9atagen2026-10-24 08:41 UTC922
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC923
                PackEdit::Put {
fa51490b6ae9atagen2026-10-24 08:41 UTC924
                    shortcode,
fa51490b6ae9atagen2026-10-24 08:41 UTC925
                    mxc,
fa51490b6ae9atagen2026-10-24 08:41 UTC926
                    body,
fa51490b6ae9atagen2026-10-24 08:41 UTC927
                    usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC928
                    info,
fa51490b6ae9atagen2026-10-24 08:41 UTC929
                },
fa51490b6ae9atagen2026-10-24 08:41 UTC930
            ),
fa51490b6ae9atagen2026-10-24 08:41 UTC931
            PackCommand::RenameImage { pack, from, to } => {
fa51490b6ae9atagen2026-10-24 08:41 UTC932
                edit(pack, PackEdit::Rename { from, to })
fa51490b6ae9atagen2026-10-24 08:41 UTC933
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC934
            PackCommand::RemoveImage { pack, shortcode } => {
fa51490b6ae9atagen2026-10-24 08:41 UTC935
                edit(pack, PackEdit::Remove { shortcode })
fa51490b6ae9atagen2026-10-24 08:41 UTC936
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC937
            PackCommand::SetEnabledEverywhere {
fa51490b6ae9atagen2026-10-24 08:41 UTC938
                room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC939
                state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC940
                enabled,
fa51490b6ae9atagen2026-10-24 08:41 UTC941
            } => Mutation::PackEnabledEverywhere {
fa51490b6ae9atagen2026-10-24 08:41 UTC942
                room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC943
                state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC944
                enabled,
fa51490b6ae9atagen2026-10-24 08:41 UTC945
            },
fa51490b6ae9atagen2026-10-24 08:41 UTC946
            command => {
fa51490b6ae9atagen2026-10-24 08:41 UTC947
                let client = self.client.clone();
fa51490b6ae9atagen2026-10-24 08:41 UTC948
                let mutations = self.mutations.clone();
fa51490b6ae9atagen2026-10-24 08:41 UTC949
                let max_bytes = self.config.max_media_bytes;
fa51490b6ae9atagen2026-10-24 08:41 UTC950
                self.tasks.spawn(TaskContext::Command("pack"), async move {
fa51490b6ae9atagen2026-10-24 08:41 UTC951
                    reply.send(packs::run_detached(client, mutations, max_bytes, command).await);
fa51490b6ae9atagen2026-10-24 08:41 UTC952
                });
fa51490b6ae9atagen2026-10-24 08:41 UTC953
                return;
fa51490b6ae9atagen2026-10-24 08:41 UTC954
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC955
        };
fa51490b6ae9atagen2026-10-24 08:41 UTC956
        enqueue(
fa51490b6ae9atagen2026-10-24 08:41 UTC957
            &self.mutations,
fa51490b6ae9atagen2026-10-24 08:41 UTC958
            Job {
fa51490b6ae9atagen2026-10-24 08:41 UTC959
                command: mutation,
fa51490b6ae9atagen2026-10-24 08:41 UTC960
                reply,
fa51490b6ae9atagen2026-10-24 08:41 UTC961
            },
fa51490b6ae9atagen2026-10-24 08:41 UTC962
        );
fa51490b6ae9atagen2026-10-24 08:41 UTC963
    }
fa51490b6ae9atagen2026-10-24 08:41 UTC964
31ce2453c82fatagen2026-09-24 13:07 UTC965
    fn upload(&mut self, upload: crate::AttachmentUpload, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC966
        let Some(room) = self.client.get_room(upload.timeline_id.room_id()) else {
31ce2453c82fatagen2026-09-24 13:07 UTC967
            return reply.done(Err(Error::room_unknown()));
31ce2453c82fatagen2026-09-24 13:07 UTC968
        };
31ce2453c82fatagen2026-09-24 13:07 UTC969
        let max_bytes = self.config.max_media_bytes;
31ce2453c82fatagen2026-09-24 13:07 UTC970
        self.spawn_command("upload", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC971
            media::queue_upload(room, upload, max_bytes).await
31ce2453c82fatagen2026-09-24 13:07 UTC972
        });
31ce2453c82fatagen2026-09-24 13:07 UTC973
    }
31ce2453c82fatagen2026-09-24 13:07 UTC974
31ce2453c82fatagen2026-09-24 13:07 UTC975
    fn route_timeline(&mut self, command: TimelineCommand, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC976
        let sender = match self.rooms.get(command.room_id()) {
31ce2453c82fatagen2026-09-24 13:07 UTC977
            Some(RoomSlot::Active { sender, .. }) => Some(sender.clone()),
31ce2453c82fatagen2026-09-24 13:07 UTC978
            _ => None,
31ce2453c82fatagen2026-09-24 13:07 UTC979
        };
31ce2453c82fatagen2026-09-24 13:07 UTC980
        match (sender, command) {
31ce2453c82fatagen2026-09-24 13:07 UTC981
            (Some(sender), command) => send_actor(&sender, ActorRequest::Execute(command, reply)),
31ce2453c82fatagen2026-09-24 13:07 UTC982
            (
31ce2453c82fatagen2026-09-24 13:07 UTC983
                None,
31ce2453c82fatagen2026-09-24 13:07 UTC984
                TimelineCommand::MarkRead {
31ce2453c82fatagen2026-09-24 13:07 UTC985
                    timeline_id,
31ce2453c82fatagen2026-09-24 13:07 UTC986
                    event_id,
31ce2453c82fatagen2026-09-24 13:07 UTC987
                },
31ce2453c82fatagen2026-09-24 13:07 UTC988
            ) => {
31ce2453c82fatagen2026-09-24 13:07 UTC989
                let client = self.client.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC990
                self.spawn_command("mark read", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC991
                    commands::mark_read(&client, &timeline_id, event_id).await
31ce2453c82fatagen2026-09-24 13:07 UTC992
                });
31ce2453c82fatagen2026-09-24 13:07 UTC993
            }
31ce2453c82fatagen2026-09-24 13:07 UTC994
            (None, _) => reply.done(Err(Error::new(ErrorKind::RoomNotOpen, "room is not open"))),
31ce2453c82fatagen2026-09-24 13:07 UTC995
        }
31ce2453c82fatagen2026-09-24 13:07 UTC996
    }
31ce2453c82fatagen2026-09-24 13:07 UTC997
80381e06a573atagen2026-10-25 03:02 UTC998
    fn route_repair(&mut self, command: crate::HistoryRepairCommand, reply: Responder) {
80381e06a573atagen2026-10-25 03:02 UTC999
        use crate::HistoryRepairCommand;
80381e06a573atagen2026-10-25 03:02 UTC1000
        let room_id = match &command {
d9b96952ec60atagen2026-10-25 09:07 UTC1001
            HistoryRepairCommand::Cancel { room_id }
d9b96952ec60atagen2026-10-25 09:07 UTC1002
            | HistoryRepairCommand::RetryRecent { room_id }
c9f0fd0ee1ccatagen2026-10-25 06:16 UTC1003
            | HistoryRepairCommand::FillGap { room_id, .. } => room_id,
80381e06a573atagen2026-10-25 03:02 UTC1004
        };
80381e06a573atagen2026-10-25 03:02 UTC1005
        match self.rooms.get(room_id) {
80381e06a573atagen2026-10-25 03:02 UTC1006
            Some(RoomSlot::Active { sender, .. }) => {
80381e06a573atagen2026-10-25 03:02 UTC1007
                send_actor(sender, ActorRequest::Repair(command, reply))
80381e06a573atagen2026-10-25 03:02 UTC1008
            }
80381e06a573atagen2026-10-25 03:02 UTC1009
            Some(RoomSlot::Closing { .. }) => {
80381e06a573atagen2026-10-25 03:02 UTC1010
                reply.done(Err(Error::new(ErrorKind::RoomBusy, "room is closing")))
80381e06a573atagen2026-10-25 03:02 UTC1011
            }
80381e06a573atagen2026-10-25 03:02 UTC1012
            None => reply.done(Err(Error::new(ErrorKind::RoomNotOpen, "room is not open"))),
80381e06a573atagen2026-10-25 03:02 UTC1013
        }
80381e06a573atagen2026-10-25 03:02 UTC1014
    }
80381e06a573atagen2026-10-25 03:02 UTC1015
31ce2453c82fatagen2026-09-24 13:07 UTC1016
    async fn open_room(&mut self, room_id: OwnedRoomId, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1017
        match self.rooms.get_mut(&room_id) {
31ce2453c82fatagen2026-09-24 13:07 UTC1018
            Some(RoomSlot::Active { sender, .. }) => send_actor(sender, ActorRequest::Open(reply)),
31ce2453c82fatagen2026-09-24 13:07 UTC1019
            Some(RoomSlot::Closing { pending, .. }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1020
                defer(pending, Deferred::Open(reply), self.config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC1021
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1022
            None => self.start_actor(room_id, reply).await,
31ce2453c82fatagen2026-09-24 13:07 UTC1023
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1024
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1025
31ce2453c82fatagen2026-09-24 13:07 UTC1026
    async fn close_room(&mut self, room_id: OwnedRoomId, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1027
        let (generation, sender) = match self.rooms.get_mut(&room_id) {
31ce2453c82fatagen2026-09-24 13:07 UTC1028
            None => return reply.done(Ok(())),
31ce2453c82fatagen2026-09-24 13:07 UTC1029
            Some(RoomSlot::Closing { pending, .. }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1030
                return defer(
31ce2453c82fatagen2026-09-24 13:07 UTC1031
                    pending,
31ce2453c82fatagen2026-09-24 13:07 UTC1032
                    Deferred::Close(reply),
31ce2453c82fatagen2026-09-24 13:07 UTC1033
                    self.config.command_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC1034
                );
31ce2453c82fatagen2026-09-24 13:07 UTC1035
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1036
            Some(RoomSlot::Active { generation, sender }) => (*generation, sender.clone()),
31ce2453c82fatagen2026-09-24 13:07 UTC1037
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1038
        match sender.try_send(ActorRequest::Close(reply)) {
5a52012c9b1datagen2026-09-24 23:45 UTC1039
            Ok(()) => {}
5a52012c9b1datagen2026-09-24 23:45 UTC1040
            // the actor already left on its own, which is closed enough
5a52012c9b1datagen2026-09-24 23:45 UTC1041
            Err(mpsc::error::TrySendError::Closed(request)) => request.into_reply().done(Ok(())),
31ce2453c82fatagen2026-09-24 13:07 UTC1042
            Err(mpsc::error::TrySendError::Full(request)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1043
                return request.into_reply().done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC1044
                    ErrorKind::RoomBusy,
31ce2453c82fatagen2026-09-24 13:07 UTC1045
                    "room command queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC1046
                )));
31ce2453c82fatagen2026-09-24 13:07 UTC1047
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1048
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1049
        self.rooms.insert(
31ce2453c82fatagen2026-09-24 13:07 UTC1050
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC1051
            RoomSlot::Closing {
31ce2453c82fatagen2026-09-24 13:07 UTC1052
                generation,
31ce2453c82fatagen2026-09-24 13:07 UTC1053
                pending: VecDeque::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC1054
            },
31ce2453c82fatagen2026-09-24 13:07 UTC1055
        );
5a52012c9b1datagen2026-09-24 23:45 UTC1056
        self.update_room_subscriptions();
31ce2453c82fatagen2026-09-24 13:07 UTC1057
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1058
31ce2453c82fatagen2026-09-24 13:07 UTC1059
    async fn start_actor(&mut self, room_id: OwnedRoomId, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1060
        let Some(room) = self.client.get_room(&room_id) else {
31ce2453c82fatagen2026-09-24 13:07 UTC1061
            return reply.done(Err(Error::room_unknown()));
31ce2453c82fatagen2026-09-24 13:07 UTC1062
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1063
        self.next_generation = self.next_generation.wrapping_add(1);
31ce2453c82fatagen2026-09-24 13:07 UTC1064
        let generation = self.next_generation;
31ce2453c82fatagen2026-09-24 13:07 UTC1065
        let (sender, requests) = mpsc::channel(self.config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC1066
        let (supervisor, panics) = Supervisor::new();
31ce2453c82fatagen2026-09-24 13:07 UTC1067
        let actor = RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC1068
            room_id: room_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC1069
            generation,
31ce2453c82fatagen2026-09-24 13:07 UTC1070
            room,
31ce2453c82fatagen2026-09-24 13:07 UTC1071
            requests,
5a52012c9b1datagen2026-09-24 23:45 UTC1072
            notes: self.note_sender.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC1073
            context: SessionContext {
31ce2453c82fatagen2026-09-24 13:07 UTC1074
                events: self.port.event_sender(),
31ce2453c82fatagen2026-09-24 13:07 UTC1075
                media: self.media.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC1076
                current_user_id: self.client.user_id().map(ToOwned::to_owned),
31ce2453c82fatagen2026-09-24 13:07 UTC1077
                initial_history_limit: self.config.initial_history_limit,
31ce2453c82fatagen2026-09-24 13:07 UTC1078
                supervisor,
31ce2453c82fatagen2026-09-24 13:07 UTC1079
            },
31ce2453c82fatagen2026-09-24 13:07 UTC1080
            panics,
31ce2453c82fatagen2026-09-24 13:07 UTC1081
            opening: vec![reply],
31ce2453c82fatagen2026-09-24 13:07 UTC1082
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1083
        self.rooms
31ce2453c82fatagen2026-09-24 13:07 UTC1084
            .insert(room_id.clone(), RoomSlot::Active { generation, sender });
31ce2453c82fatagen2026-09-24 13:07 UTC1085
        self.tasks.spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC1086
            TaskContext::RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC1087
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC1088
                generation,
31ce2453c82fatagen2026-09-24 13:07 UTC1089
            },
31ce2453c82fatagen2026-09-24 13:07 UTC1090
            actor.run(),
31ce2453c82fatagen2026-09-24 13:07 UTC1091
        );
5a52012c9b1datagen2026-09-24 23:45 UTC1092
        self.update_room_subscriptions();
31ce2453c82fatagen2026-09-24 13:07 UTC1093
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1094
5a52012c9b1datagen2026-09-24 23:45 UTC1095
    async fn actor_note(&mut self, note: ActorNote) {
5a52012c9b1datagen2026-09-24 23:45 UTC1096
        let (room_id, generation) = match &note {
5a52012c9b1datagen2026-09-24 23:45 UTC1097
            ActorNote::Leaving {
5a52012c9b1datagen2026-09-24 23:45 UTC1098
                room_id,
5a52012c9b1datagen2026-09-24 23:45 UTC1099
                generation,
5a52012c9b1datagen2026-09-24 23:45 UTC1100
            }
5a52012c9b1datagen2026-09-24 23:45 UTC1101
            | ActorNote::Exited {
5a52012c9b1datagen2026-09-24 23:45 UTC1102
                room_id,
5a52012c9b1datagen2026-09-24 23:45 UTC1103
                generation,
5a52012c9b1datagen2026-09-24 23:45 UTC1104
                ..
5a52012c9b1datagen2026-09-24 23:45 UTC1105
            } => (room_id.clone(), *generation),
5a52012c9b1datagen2026-09-24 23:45 UTC1106
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1107
        if self
31ce2453c82fatagen2026-09-24 13:07 UTC1108
            .rooms
31ce2453c82fatagen2026-09-24 13:07 UTC1109
            .get(&room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC1110
            .is_none_or(|slot| slot.generation() != generation)
31ce2453c82fatagen2026-09-24 13:07 UTC1111
        {
31ce2453c82fatagen2026-09-24 13:07 UTC1112
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC1113
        }
5a52012c9b1datagen2026-09-24 23:45 UTC1114
        let ActorNote::Exited { leftovers, .. } = note else {
5a52012c9b1datagen2026-09-24 23:45 UTC1115
            if let Some(slot @ RoomSlot::Active { .. }) = self.rooms.get_mut(&room_id) {
5a52012c9b1datagen2026-09-24 23:45 UTC1116
                *slot = RoomSlot::Closing {
5a52012c9b1datagen2026-09-24 23:45 UTC1117
                    generation,
5a52012c9b1datagen2026-09-24 23:45 UTC1118
                    pending: VecDeque::new(),
5a52012c9b1datagen2026-09-24 23:45 UTC1119
                };
5a52012c9b1datagen2026-09-24 23:45 UTC1120
                self.update_room_subscriptions();
5a52012c9b1datagen2026-09-24 23:45 UTC1121
            }
5a52012c9b1datagen2026-09-24 23:45 UTC1122
            return;
5a52012c9b1datagen2026-09-24 23:45 UTC1123
        };
5a52012c9b1datagen2026-09-24 23:45 UTC1124
        let pending = match self.rooms.remove(&room_id) {
5a52012c9b1datagen2026-09-24 23:45 UTC1125
            Some(RoomSlot::Closing { pending, .. }) => pending,
5a52012c9b1datagen2026-09-24 23:45 UTC1126
            _ => VecDeque::new(),
5a52012c9b1datagen2026-09-24 23:45 UTC1127
        };
5a52012c9b1datagen2026-09-24 23:45 UTC1128
        // leftovers were sent before anything deferred, so they go first
5a52012c9b1datagen2026-09-24 23:45 UTC1129
        for request in leftovers {
5a52012c9b1datagen2026-09-24 23:45 UTC1130
            match request {
5a52012c9b1datagen2026-09-24 23:45 UTC1131
                ActorRequest::Open(reply) => self.open_room(room_id.clone(), reply).await,
5a52012c9b1datagen2026-09-24 23:45 UTC1132
                ActorRequest::Close(reply) => reply.done(Ok(())),
5a52012c9b1datagen2026-09-24 23:45 UTC1133
                ActorRequest::Execute(command, reply) => self.route_timeline(command, reply),
80381e06a573atagen2026-10-25 03:02 UTC1134
                ActorRequest::Repair(command, reply) => self.route_repair(command, reply),
31ce2453c82fatagen2026-09-24 13:07 UTC1135
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1136
        }
5a52012c9b1datagen2026-09-24 23:45 UTC1137
        for deferred in pending {
5a52012c9b1datagen2026-09-24 23:45 UTC1138
            match deferred {
5a52012c9b1datagen2026-09-24 23:45 UTC1139
                Deferred::Open(reply) => self.open_room(room_id.clone(), reply).await,
5a52012c9b1datagen2026-09-24 23:45 UTC1140
                Deferred::Close(reply) => self.close_room(room_id.clone(), reply).await,
5a52012c9b1datagen2026-09-24 23:45 UTC1141
            }
5a52012c9b1datagen2026-09-24 23:45 UTC1142
        }
5a52012c9b1datagen2026-09-24 23:45 UTC1143
        self.update_room_subscriptions();
31ce2453c82fatagen2026-09-24 13:07 UTC1144
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1145
5a52012c9b1datagen2026-09-24 23:45 UTC1146
    fn update_room_subscriptions(&self) {
31ce2453c82fatagen2026-09-24 13:07 UTC1147
        let room_ids = self
31ce2453c82fatagen2026-09-24 13:07 UTC1148
            .rooms
31ce2453c82fatagen2026-09-24 13:07 UTC1149
            .iter()
31ce2453c82fatagen2026-09-24 13:07 UTC1150
            .filter(|(_, slot)| matches!(slot, RoomSlot::Active { .. }))
5a52012c9b1datagen2026-09-24 23:45 UTC1151
            .map(|(room_id, _)| room_id.clone())
5a52012c9b1datagen2026-09-24 23:45 UTC1152
            .collect();
5a52012c9b1datagen2026-09-24 23:45 UTC1153
        self.subscriptions.send_replace(room_ids);
31ce2453c82fatagen2026-09-24 13:07 UTC1154
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1155
31ce2453c82fatagen2026-09-24 13:07 UTC1156
    async fn shutdown(&mut self) {
5a52012c9b1datagen2026-09-24 23:45 UTC1157
        if let Some(handler) = self.verification_handler.take() {
5a52012c9b1datagen2026-09-24 23:45 UTC1158
            self.client.remove_event_handler(handler);
5a52012c9b1datagen2026-09-24 23:45 UTC1159
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1160
        self.port.close();
cbb715e11963atagen2026-10-24 23:24 UTC1161
        self.sync.stop().await;
cbb715e11963atagen2026-10-24 23:24 UTC1162
        if self.mentions_service.is_none() {
cbb715e11963atagen2026-10-24 23:24 UTC1163
            self.mentions.stop().await;
cbb715e11963atagen2026-10-24 23:24 UTC1164
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1165
        self.tasks.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC1166
        self.rooms.clear();
da8896938cf0atagen2026-10-25 10:04 UTC1167
        self.contexts.clear().await;
31ce2453c82fatagen2026-09-24 13:07 UTC1168
        self.media.clear().await;
31ce2453c82fatagen2026-09-24 13:07 UTC1169
        self.port
31ce2453c82fatagen2026-09-24 13:07 UTC1170
            .connection_sender()
31ce2453c82fatagen2026-09-24 13:07 UTC1171
            .send_replace(ConnectionState::Stopped);
31ce2453c82fatagen2026-09-24 13:07 UTC1172
        let _ = self
31ce2453c82fatagen2026-09-24 13:07 UTC1173
            .port
31ce2453c82fatagen2026-09-24 13:07 UTC1174
            .event_sender()
31ce2453c82fatagen2026-09-24 13:07 UTC1175
            .send(Event::ConnectionChanged(ConnectionState::Stopped))
31ce2453c82fatagen2026-09-24 13:07 UTC1176
            .await;
31ce2453c82fatagen2026-09-24 13:07 UTC1177
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1178
}
31ce2453c82fatagen2026-09-24 13:07 UTC1179
31ce2453c82fatagen2026-09-24 13:07 UTC1180
fn send_actor(sender: &mpsc::Sender<ActorRequest>, request: ActorRequest) {
31ce2453c82fatagen2026-09-24 13:07 UTC1181
    if let Err(error) = sender.try_send(request) {
31ce2453c82fatagen2026-09-24 13:07 UTC1182
        let (request, error) = match error {
31ce2453c82fatagen2026-09-24 13:07 UTC1183
            mpsc::error::TrySendError::Full(request) => (
31ce2453c82fatagen2026-09-24 13:07 UTC1184
                request,
31ce2453c82fatagen2026-09-24 13:07 UTC1185
                Error::new(ErrorKind::RoomBusy, "room command queue is full"),
31ce2453c82fatagen2026-09-24 13:07 UTC1186
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC1187
            mpsc::error::TrySendError::Closed(request) => (
31ce2453c82fatagen2026-09-24 13:07 UTC1188
                request,
31ce2453c82fatagen2026-09-24 13:07 UTC1189
                Error::new(ErrorKind::RoomNotOpen, "room is not open"),
31ce2453c82fatagen2026-09-24 13:07 UTC1190
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC1191
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1192
        request.into_reply().done(Err(error));
31ce2453c82fatagen2026-09-24 13:07 UTC1193
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1194
}
31ce2453c82fatagen2026-09-24 13:07 UTC1195
31ce2453c82fatagen2026-09-24 13:07 UTC1196
fn defer(pending: &mut VecDeque<Deferred>, deferred: Deferred, capacity: usize) {
31ce2453c82fatagen2026-09-24 13:07 UTC1197
    if pending.len() < capacity {
31ce2453c82fatagen2026-09-24 13:07 UTC1198
        return pending.push_back(deferred);
31ce2453c82fatagen2026-09-24 13:07 UTC1199
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1200
    let (Deferred::Open(reply) | Deferred::Close(reply)) = deferred;
31ce2453c82fatagen2026-09-24 13:07 UTC1201
    reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC1202
        ErrorKind::RoomBusy,
31ce2453c82fatagen2026-09-24 13:07 UTC1203
        "room lifecycle queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC1204
    )));
31ce2453c82fatagen2026-09-24 13:07 UTC1205
}
31ce2453c82fatagen2026-09-24 13:07 UTC1206
673563a76e43atagen2026-09-26 12:30 UTC1207
async fn settled(logouts: &mut watch::Receiver<Logouts>) {
673563a76e43atagen2026-09-26 12:30 UTC1208
    let _ = logouts.wait_for(|logouts| logouts.in_flight == 0).await;
673563a76e43atagen2026-09-26 12:30 UTC1209
}
673563a76e43atagen2026-09-26 12:30 UTC1210
31ce2453c82fatagen2026-09-24 13:07 UTC1211
fn enqueue<T>(sender: &mpsc::Sender<Job<T>>, job: Job<T>) {
31ce2453c82fatagen2026-09-24 13:07 UTC1212
    if let Err(error) = sender.try_send(job) {
31ce2453c82fatagen2026-09-24 13:07 UTC1213
        let (job, error) = match error {
31ce2453c82fatagen2026-09-24 13:07 UTC1214
            mpsc::error::TrySendError::Full(job) => (
31ce2453c82fatagen2026-09-24 13:07 UTC1215
                job,
31ce2453c82fatagen2026-09-24 13:07 UTC1216
                Error::new(ErrorKind::QueueFull, "command queue is full"),
31ce2453c82fatagen2026-09-24 13:07 UTC1217
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC1218
            mpsc::error::TrySendError::Closed(job) => (job, Error::interrupted()),
31ce2453c82fatagen2026-09-24 13:07 UTC1219
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1220
        job.reply.done(Err(error));
31ce2453c82fatagen2026-09-24 13:07 UTC1221
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1222
}