atagen

macltok

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