atagen

macltok

public
Star0
Watch0
38c4caecdb3db5c51b626ed6375b3c79e2fb0552
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/engine/mod.rs

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