atagen

macltok

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