atagen

macltok

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

Blame: src/engine/mod.rs

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