atagen

macltok

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