atagen

macltok

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