atagen

macltok

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