atagen

macltok

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