atagen

macltok

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

Blame: src/engine/mod.rs

31ce2453c82fatagen2026-09-24 13:07 UTC1
mod commands;
cbb715e11963atagen2026-10-24 23:24 UTC2
pub(crate) mod context;
a319bae745d8atagen2026-09-26 09:59 UTC3
pub(crate) mod executor;
31ce2453c82fatagen2026-09-24 13:07 UTC4
mod media;
31ce2453c82fatagen2026-09-24 13:07 UTC5
mod mutations;
fa51490b6ae9atagen2026-10-24 08:41 UTC6
mod packs;
38c4caecdb3datagen2026-09-26 13:35 UTC7
mod prepare;
80381e06a573atagen2026-10-25 03:02 UTC8
mod repair;
31ce2453c82fatagen2026-09-24 13:07 UTC9
mod room;
f12377bce9b9atagen2026-09-26 12:32 UTC10
mod session;
66db1b3cd895atagen2026-10-25 10:28 UTC11
mod thread_list;
31ce2453c82fatagen2026-09-24 13:07 UTC12
mod timeline;
0291516d40b5atagen2026-10-22 08:31 UTC13
mod url_preview;
31ce2453c82fatagen2026-09-24 13:07 UTC14
mod watchers;
31ce2453c82fatagen2026-09-24 13:07 UTC15
31ce2453c82fatagen2026-09-24 13:07 UTC16
use std::{
31ce2453c82fatagen2026-09-24 13:07 UTC17
    collections::{HashMap, VecDeque},
31ce2453c82fatagen2026-09-24 13:07 UTC18
    future::Future,
1fe480c16a3catagen2026-09-26 08:44 UTC19
    panic::AssertUnwindSafe,
31ce2453c82fatagen2026-09-24 13:07 UTC20
    sync::Arc,
31ce2453c82fatagen2026-09-24 13:07 UTC21
};
31ce2453c82fatagen2026-09-24 13:07 UTC22
1fe480c16a3catagen2026-09-26 08:44 UTC23
use futures_util::FutureExt;
1fe480c16a3catagen2026-09-26 08:44 UTC24
use matrix_sdk::{Client, SendOutsideWasm, SessionChange};
31ce2453c82fatagen2026-09-24 13:07 UTC25
use matrix_sdk_ui::sync_service::SyncService;
673563a76e43atagen2026-09-26 12:30 UTC26
use ruma::{OwnedDeviceId, OwnedRoomId};
31ce2453c82fatagen2026-09-24 13:07 UTC27
use thiserror::Error as ThisError;
fe4133dbcd47atagen2026-09-26 09:05 UTC28
use tokio::sync::{broadcast, mpsc, watch};
31ce2453c82fatagen2026-09-24 13:07 UTC29
31ce2453c82fatagen2026-09-24 13:07 UTC30
pub(crate) use media::MediaService;
f12377bce9b9atagen2026-09-26 12:32 UTC31
pub(crate) use session::Persistence;
31ce2453c82fatagen2026-09-24 13:07 UTC32
a250c7fa43fbatagen2026-09-26 13:35 UTC33
#[cfg(any(feature = "sqlite", feature = "indexeddb"))]
a250c7fa43fbatagen2026-09-26 13:35 UTC34
pub(crate) use crate::store_lock::StoreLock;
a250c7fa43fbatagen2026-09-26 13:35 UTC35
#[cfg(not(any(feature = "sqlite", feature = "indexeddb")))]
a250c7fa43fbatagen2026-09-26 13:35 UTC36
pub(crate) enum StoreLock {}
a250c7fa43fbatagen2026-09-26 13:35 UTC37
cbb715e11963atagen2026-10-24 23:24 UTC38
#[cfg(any(feature = "sqlite", feature = "indexeddb"))]
cbb715e11963atagen2026-10-24 23:24 UTC39
pub(crate) use crate::mentions::store::MentionsStore;
cbb715e11963atagen2026-10-24 23:24 UTC40
#[cfg(not(any(feature = "sqlite", feature = "indexeddb")))]
cbb715e11963atagen2026-10-24 23:24 UTC41
pub(crate) enum MentionsStore {}
cbb715e11963atagen2026-10-24 23:24 UTC42
c9effeac326aatagen2026-10-25 10:32 UTC43
#[cfg(any(feature = "sqlite", feature = "indexeddb"))]
c9effeac326aatagen2026-10-25 10:32 UTC44
pub(crate) use crate::search::store::SearchStore;
c9effeac326aatagen2026-10-25 10:32 UTC45
#[cfg(not(any(feature = "sqlite", feature = "indexeddb")))]
c9effeac326aatagen2026-10-25 10:32 UTC46
pub(crate) enum SearchStore {}
c9effeac326aatagen2026-10-25 10:32 UTC47
31ce2453c82fatagen2026-09-24 13:07 UTC48
use self::{
31ce2453c82fatagen2026-09-24 13:07 UTC49
    commands::Job,
1fe480c16a3catagen2026-09-26 08:44 UTC50
    executor::{EngineBoxFuture, TaskSet},
31ce2453c82fatagen2026-09-24 13:07 UTC51
    mutations::{Mutation, MutationJob},
fa51490b6ae9atagen2026-10-24 08:41 UTC52
    packs::PackEdit,
5a52012c9b1datagen2026-09-24 23:45 UTC53
    room::{ActorNote, ActorRequest, RoomActor},
31ce2453c82fatagen2026-09-24 13:07 UTC54
    timeline::{SessionContext, Supervisor},
31ce2453c82fatagen2026-09-24 13:07 UTC55
};
31ce2453c82fatagen2026-09-24 13:07 UTC56
use crate::{
9bd34e25bb86atagen2026-10-24 07:23 UTC57
    AccountCommand, ClientHandle, Command, CommandOutput, ConnectionState, EncryptionCommand,
fa51490b6ae9atagen2026-10-24 08:41 UTC58
    EngineErrorKind, EngineFailure, Error, ErrorKind, Event, EventStream, ImagePackSource,
fa51490b6ae9atagen2026-10-24 08:41 UTC59
    LifecycleCommand, MediaCommand, NotificationCommand, PackCommand, RoomCommand, Termination,
66db1b3cd895atagen2026-10-25 10:28 UTC60
    ThreadListCommand, TimelineCommand,
0291516d40b5atagen2026-10-22 08:31 UTC61
    normalise::{ROOM_PACKS, ROOM_PREVIEW_URLS},
31ce2453c82fatagen2026-09-24 13:07 UTC62
    transport::{DriverPort, Request, Responder, transport_pair},
31ce2453c82fatagen2026-09-24 13:07 UTC63
};
31ce2453c82fatagen2026-09-24 13:07 UTC64
31ce2453c82fatagen2026-09-24 13:07 UTC65
#[derive(Clone, Debug, Eq, PartialEq)]
31ce2453c82fatagen2026-09-24 13:07 UTC66
#[non_exhaustive]
31ce2453c82fatagen2026-09-24 13:07 UTC67
pub struct EngineConfig {
31ce2453c82fatagen2026-09-24 13:07 UTC68
    pub command_capacity: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC69
    pub event_capacity: usize,
d9b96952ec60atagen2026-10-25 09:07 UTC70
    /// what a thread paginates as it opens, and a room if its recent load fails. 0 for neither
31ce2453c82fatagen2026-09-24 13:07 UTC71
    pub initial_history_limit: u16,
31ce2453c82fatagen2026-09-24 13:07 UTC72
    pub max_media_bytes: usize,
da8896938cf0atagen2026-10-25 10:04 UTC73
    /// media one event context session keeps registered, least recently used dropped first
da8896938cf0atagen2026-10-25 10:04 UTC74
    pub max_context_media: usize,
cbb715e11963atagen2026-10-24 23:24 UTC75
    pub max_mentions_bytes: usize,
cbb715e11963atagen2026-10-24 23:24 UTC76
    pub max_mentions_entries: usize,
cbb715e11963atagen2026-10-24 23:24 UTC77
    pub max_mention_context_events: usize,
cbb715e11963atagen2026-10-24 23:24 UTC78
    pub max_mention_candidates: usize,
38c4caecdb3datagen2026-09-26 13:35 UTC79
    /// warm a room up for sending when it's opened or someone starts typing in it
38c4caecdb3datagen2026-09-26 13:35 UTC80
    pub prepare_to_send: bool,
c9effeac326aatagen2026-10-25 10:32 UTC81
    /// `/messages` pages each joined room gets per engine run for search backfill. 0 for none
c9effeac326aatagen2026-10-25 10:32 UTC82
    pub search_backfill_pages_per_room: u16,
c9effeac326aatagen2026-10-25 10:32 UTC83
    pub search_backfill_page_size: u16,
c9effeac326aatagen2026-10-25 10:32 UTC84
    /// the least time between two backfill requests, across every room
c9effeac326aatagen2026-10-25 10:32 UTC85
    pub search_backfill_interval_ms: u64,
c9effeac326aatagen2026-10-25 10:32 UTC86
    /// undecryptable messages kept to index once their keys turn up, newest first
c9effeac326aatagen2026-10-25 10:32 UTC87
    pub max_search_undecrypted: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC88
}
31ce2453c82fatagen2026-09-24 13:07 UTC89
31ce2453c82fatagen2026-09-24 13:07 UTC90
impl EngineConfig {
31ce2453c82fatagen2026-09-24 13:07 UTC91
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC92
    pub const fn with_max_mentions_bytes(mut self, bytes: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC93
        self.max_mentions_bytes = bytes;
cbb715e11963atagen2026-10-24 23:24 UTC94
        self
cbb715e11963atagen2026-10-24 23:24 UTC95
    }
cbb715e11963atagen2026-10-24 23:24 UTC96
cbb715e11963atagen2026-10-24 23:24 UTC97
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC98
    pub const fn with_max_mentions_entries(mut self, entries: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC99
        self.max_mentions_entries = entries;
cbb715e11963atagen2026-10-24 23:24 UTC100
        self
cbb715e11963atagen2026-10-24 23:24 UTC101
    }
cbb715e11963atagen2026-10-24 23:24 UTC102
cbb715e11963atagen2026-10-24 23:24 UTC103
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC104
    pub const fn with_max_mention_context_events(mut self, events: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC105
        self.max_mention_context_events = events;
cbb715e11963atagen2026-10-24 23:24 UTC106
        self
cbb715e11963atagen2026-10-24 23:24 UTC107
    }
cbb715e11963atagen2026-10-24 23:24 UTC108
cbb715e11963atagen2026-10-24 23:24 UTC109
    #[must_use]
cbb715e11963atagen2026-10-24 23:24 UTC110
    pub const fn with_max_mention_candidates(mut self, candidates: usize) -> Self {
cbb715e11963atagen2026-10-24 23:24 UTC111
        self.max_mention_candidates = candidates;
cbb715e11963atagen2026-10-24 23:24 UTC112
        self
cbb715e11963atagen2026-10-24 23:24 UTC113
    }
cbb715e11963atagen2026-10-24 23:24 UTC114
cbb715e11963atagen2026-10-24 23:24 UTC115
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC116
    pub const fn with_command_capacity(mut self, capacity: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC117
        self.command_capacity = capacity;
31ce2453c82fatagen2026-09-24 13:07 UTC118
        self
31ce2453c82fatagen2026-09-24 13:07 UTC119
    }
31ce2453c82fatagen2026-09-24 13:07 UTC120
31ce2453c82fatagen2026-09-24 13:07 UTC121
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC122
    pub const fn with_event_capacity(mut self, capacity: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC123
        self.event_capacity = capacity;
31ce2453c82fatagen2026-09-24 13:07 UTC124
        self
31ce2453c82fatagen2026-09-24 13:07 UTC125
    }
31ce2453c82fatagen2026-09-24 13:07 UTC126
31ce2453c82fatagen2026-09-24 13:07 UTC127
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC128
    pub const fn with_initial_history_limit(mut self, limit: u16) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC129
        self.initial_history_limit = limit;
31ce2453c82fatagen2026-09-24 13:07 UTC130
        self
31ce2453c82fatagen2026-09-24 13:07 UTC131
    }
31ce2453c82fatagen2026-09-24 13:07 UTC132
31ce2453c82fatagen2026-09-24 13:07 UTC133
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC134
    pub const fn with_max_media_bytes(mut self, bytes: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC135
        self.max_media_bytes = bytes;
31ce2453c82fatagen2026-09-24 13:07 UTC136
        self
31ce2453c82fatagen2026-09-24 13:07 UTC137
    }
31ce2453c82fatagen2026-09-24 13:07 UTC138
31ce2453c82fatagen2026-09-24 13:07 UTC139
    #[must_use]
da8896938cf0atagen2026-10-25 10:04 UTC140
    pub const fn with_max_context_media(mut self, media: usize) -> Self {
da8896938cf0atagen2026-10-25 10:04 UTC141
        self.max_context_media = media;
31ce2453c82fatagen2026-09-24 13:07 UTC142
        self
31ce2453c82fatagen2026-09-24 13:07 UTC143
    }
38c4caecdb3datagen2026-09-26 13:35 UTC144
38c4caecdb3datagen2026-09-26 13:35 UTC145
    #[must_use]
38c4caecdb3datagen2026-09-26 13:35 UTC146
    pub const fn with_prepare_to_send(mut self, prepare: bool) -> Self {
38c4caecdb3datagen2026-09-26 13:35 UTC147
        self.prepare_to_send = prepare;
38c4caecdb3datagen2026-09-26 13:35 UTC148
        self
38c4caecdb3datagen2026-09-26 13:35 UTC149
    }
c9effeac326aatagen2026-10-25 10:32 UTC150
c9effeac326aatagen2026-10-25 10:32 UTC151
    #[must_use]
c9effeac326aatagen2026-10-25 10:32 UTC152
    pub const fn with_search_backfill_pages_per_room(mut self, pages: u16) -> Self {
c9effeac326aatagen2026-10-25 10:32 UTC153
        self.search_backfill_pages_per_room = pages;
c9effeac326aatagen2026-10-25 10:32 UTC154
        self
c9effeac326aatagen2026-10-25 10:32 UTC155
    }
c9effeac326aatagen2026-10-25 10:32 UTC156
c9effeac326aatagen2026-10-25 10:32 UTC157
    #[must_use]
c9effeac326aatagen2026-10-25 10:32 UTC158
    pub const fn with_search_backfill_page_size(mut self, events: u16) -> Self {
c9effeac326aatagen2026-10-25 10:32 UTC159
        self.search_backfill_page_size = events;
c9effeac326aatagen2026-10-25 10:32 UTC160
        self
c9effeac326aatagen2026-10-25 10:32 UTC161
    }
c9effeac326aatagen2026-10-25 10:32 UTC162
c9effeac326aatagen2026-10-25 10:32 UTC163
    #[must_use]
c9effeac326aatagen2026-10-25 10:32 UTC164
    pub const fn with_search_backfill_interval_ms(mut self, interval_ms: u64) -> Self {
c9effeac326aatagen2026-10-25 10:32 UTC165
        self.search_backfill_interval_ms = interval_ms;
c9effeac326aatagen2026-10-25 10:32 UTC166
        self
c9effeac326aatagen2026-10-25 10:32 UTC167
    }
c9effeac326aatagen2026-10-25 10:32 UTC168
c9effeac326aatagen2026-10-25 10:32 UTC169
    #[must_use]
c9effeac326aatagen2026-10-25 10:32 UTC170
    pub const fn with_max_search_undecrypted(mut self, events: usize) -> Self {
c9effeac326aatagen2026-10-25 10:32 UTC171
        self.max_search_undecrypted = events;
c9effeac326aatagen2026-10-25 10:32 UTC172
        self
c9effeac326aatagen2026-10-25 10:32 UTC173
    }
31ce2453c82fatagen2026-09-24 13:07 UTC174
}
31ce2453c82fatagen2026-09-24 13:07 UTC175
31ce2453c82fatagen2026-09-24 13:07 UTC176
impl Default for EngineConfig {
31ce2453c82fatagen2026-09-24 13:07 UTC177
    fn default() -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC178
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC179
            command_capacity: 64,
31ce2453c82fatagen2026-09-24 13:07 UTC180
            event_capacity: 128,
31ce2453c82fatagen2026-09-24 13:07 UTC181
            initial_history_limit: 30,
31ce2453c82fatagen2026-09-24 13:07 UTC182
            max_media_bytes: 20 * 1024 * 1024,
da8896938cf0atagen2026-10-25 10:04 UTC183
            max_context_media: 1_024,
cbb715e11963atagen2026-10-24 23:24 UTC184
            max_mentions_bytes: 64 * 1024 * 1024,
cbb715e11963atagen2026-10-24 23:24 UTC185
            max_mentions_entries: 5_000,
cbb715e11963atagen2026-10-24 23:24 UTC186
            max_mention_context_events: 25_000,
cbb715e11963atagen2026-10-24 23:24 UTC187
            max_mention_candidates: 5_000,
38c4caecdb3datagen2026-09-26 13:35 UTC188
            prepare_to_send: true,
c9effeac326aatagen2026-10-25 10:32 UTC189
            search_backfill_pages_per_room: 10,
c9effeac326aatagen2026-10-25 10:32 UTC190
            search_backfill_page_size: 100,
c9effeac326aatagen2026-10-25 10:32 UTC191
            search_backfill_interval_ms: 2_000,
c9effeac326aatagen2026-10-25 10:32 UTC192
            max_search_undecrypted: 2_000,
31ce2453c82fatagen2026-09-24 13:07 UTC193
        }
31ce2453c82fatagen2026-09-24 13:07 UTC194
    }
31ce2453c82fatagen2026-09-24 13:07 UTC195
}
31ce2453c82fatagen2026-09-24 13:07 UTC196
31ce2453c82fatagen2026-09-24 13:07 UTC197
#[derive(Debug, ThisError)]
31ce2453c82fatagen2026-09-24 13:07 UTC198
pub enum EngineError {
31ce2453c82fatagen2026-09-24 13:07 UTC199
    #[error("the Matrix client is not authenticated")]
31ce2453c82fatagen2026-09-24 13:07 UTC200
    Unauthenticated,
cbb715e11963atagen2026-10-24 23:24 UTC201
    #[error("command, event, media source, and mentions capacities must be nonzero")]
31ce2453c82fatagen2026-09-24 13:07 UTC202
    ZeroCapacity,
31ce2453c82fatagen2026-09-24 13:07 UTC203
    #[error("could not build the sync service")]
31ce2453c82fatagen2026-09-24 13:07 UTC204
    SyncService(#[source] matrix_sdk_ui::sync_service::Error),
31ce2453c82fatagen2026-09-24 13:07 UTC205
    #[error("the event receiver has closed")]
31ce2453c82fatagen2026-09-24 13:07 UTC206
    EventReceiverClosed,
31ce2453c82fatagen2026-09-24 13:07 UTC207
    #[error("engine task {task} panicked")]
31ce2453c82fatagen2026-09-24 13:07 UTC208
    TaskPanicked { task: String },
31ce2453c82fatagen2026-09-24 13:07 UTC209
}
31ce2453c82fatagen2026-09-24 13:07 UTC210
31ce2453c82fatagen2026-09-24 13:07 UTC211
impl EngineError {
31ce2453c82fatagen2026-09-24 13:07 UTC212
    fn failure(&self) -> EngineFailure {
31ce2453c82fatagen2026-09-24 13:07 UTC213
        EngineFailure {
31ce2453c82fatagen2026-09-24 13:07 UTC214
            kind: match self {
31ce2453c82fatagen2026-09-24 13:07 UTC215
                Self::EventReceiverClosed => EngineErrorKind::EventReceiverClosed,
31ce2453c82fatagen2026-09-24 13:07 UTC216
                Self::TaskPanicked { .. } => EngineErrorKind::Watcher,
913832a327a8atagen2026-10-25 09:33 UTC217
                Self::Unauthenticated | Self::ZeroCapacity | Self::SyncService(_) => {
913832a327a8atagen2026-10-25 09:33 UTC218
                    EngineErrorKind::Other
913832a327a8atagen2026-10-25 09:33 UTC219
                }
31ce2453c82fatagen2026-09-24 13:07 UTC220
            },
31ce2453c82fatagen2026-09-24 13:07 UTC221
            message: self.to_string(),
31ce2453c82fatagen2026-09-24 13:07 UTC222
        }
31ce2453c82fatagen2026-09-24 13:07 UTC223
    }
31ce2453c82fatagen2026-09-24 13:07 UTC224
}
31ce2453c82fatagen2026-09-24 13:07 UTC225
31ce2453c82fatagen2026-09-24 13:07 UTC226
#[derive(Clone)]
31ce2453c82fatagen2026-09-24 13:07 UTC227
enum TaskContext {
31ce2453c82fatagen2026-09-24 13:07 UTC228
    /// a panic here costs the caller an `Interrupted` answer and nothing else
31ce2453c82fatagen2026-09-24 13:07 UTC229
    Command(&'static str),
31ce2453c82fatagen2026-09-24 13:07 UTC230
    /// a panic here takes the engine with it
31ce2453c82fatagen2026-09-24 13:07 UTC231
    Watcher(&'static str),
31ce2453c82fatagen2026-09-24 13:07 UTC232
    RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC233
        room_id: OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC234
        generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC235
    },
31ce2453c82fatagen2026-09-24 13:07 UTC236
}
31ce2453c82fatagen2026-09-24 13:07 UTC237
31ce2453c82fatagen2026-09-24 13:07 UTC238
impl TaskContext {
31ce2453c82fatagen2026-09-24 13:07 UTC239
    fn label(&self) -> String {
31ce2453c82fatagen2026-09-24 13:07 UTC240
        match self {
31ce2453c82fatagen2026-09-24 13:07 UTC241
            Self::Command(name) | Self::Watcher(name) => (*name).to_owned(),
31ce2453c82fatagen2026-09-24 13:07 UTC242
            Self::RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC243
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC244
                generation,
31ce2453c82fatagen2026-09-24 13:07 UTC245
            } => format!("room actor {room_id} generation {generation}"),
31ce2453c82fatagen2026-09-24 13:07 UTC246
        }
31ce2453c82fatagen2026-09-24 13:07 UTC247
    }
31ce2453c82fatagen2026-09-24 13:07 UTC248
}
31ce2453c82fatagen2026-09-24 13:07 UTC249
6a5963d5bd63atagen2026-10-28 05:03 UTC250
/// tuwunel resends every room in range each time the room list grows, so the sdk's 100 a step
6a5963d5bd63atagen2026-10-28 05:03 UTC251
/// had a 399 room account hand most rooms to the event cache four or five times
6a5963d5bd63atagen2026-10-28 05:03 UTC252
const ROOM_LIST_GROWING_BATCH: u32 = 500;
6a5963d5bd63atagen2026-10-28 05:03 UTC253
7b376d620a3datagen2026-09-26 12:53 UTC254
/// tasks catch their own panics so each comes back with its context, since joining
7b376d620a3datagen2026-09-26 12:53 UTC255
/// through the sdk's executor gives no task id to look one up by. wasm has nothing to catch
1fe480c16a3catagen2026-09-26 08:44 UTC256
fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
1fe480c16a3catagen2026-09-26 08:44 UTC257
    payload
1fe480c16a3catagen2026-09-26 08:44 UTC258
        .downcast_ref::<&str>()
1fe480c16a3catagen2026-09-26 08:44 UTC259
        .map(ToString::to_string)
1fe480c16a3catagen2026-09-26 08:44 UTC260
        .or_else(|| payload.downcast_ref::<String>().cloned())
1fe480c16a3catagen2026-09-26 08:44 UTC261
        .unwrap_or_else(|| "task panicked with a non-string payload".to_owned())
1fe480c16a3catagen2026-09-26 08:44 UTC262
}
1fe480c16a3catagen2026-09-26 08:44 UTC263
31ce2453c82fatagen2026-09-24 13:07 UTC264
struct TaskRegistry {
1fe480c16a3catagen2026-09-26 08:44 UTC265
    tasks: TaskSet<(TaskContext, Option<String>)>,
31ce2453c82fatagen2026-09-24 13:07 UTC266
}
31ce2453c82fatagen2026-09-24 13:07 UTC267
31ce2453c82fatagen2026-09-24 13:07 UTC268
impl TaskRegistry {
31ce2453c82fatagen2026-09-24 13:07 UTC269
    fn spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC270
        &mut self,
31ce2453c82fatagen2026-09-24 13:07 UTC271
        context: TaskContext,
1fe480c16a3catagen2026-09-26 08:44 UTC272
        task: impl Future<Output = ()> + SendOutsideWasm + 'static,
1fe480c16a3catagen2026-09-26 08:44 UTC273
    ) {
1fe480c16a3catagen2026-09-26 08:44 UTC274
        self.tasks.spawn(async move {
1fe480c16a3catagen2026-09-26 08:44 UTC275
            let panic = AssertUnwindSafe(task)
1fe480c16a3catagen2026-09-26 08:44 UTC276
                .catch_unwind()
1fe480c16a3catagen2026-09-26 08:44 UTC277
                .await
1fe480c16a3catagen2026-09-26 08:44 UTC278
                .err()
1fe480c16a3catagen2026-09-26 08:44 UTC279
                .map(panic_message);
1fe480c16a3catagen2026-09-26 08:44 UTC280
            (context, panic)
1fe480c16a3catagen2026-09-26 08:44 UTC281
        });
31ce2453c82fatagen2026-09-24 13:07 UTC282
    }
31ce2453c82fatagen2026-09-24 13:07 UTC283
1fe480c16a3catagen2026-09-26 08:44 UTC284
    fn is_empty(&self) -> bool {
1fe480c16a3catagen2026-09-26 08:44 UTC285
        self.tasks.is_empty()
1fe480c16a3catagen2026-09-26 08:44 UTC286
    }
1fe480c16a3catagen2026-09-26 08:44 UTC287
1fe480c16a3catagen2026-09-26 08:44 UTC288
    async fn join_next(&mut self) -> Option<(TaskContext, Option<String>)> {
1fe480c16a3catagen2026-09-26 08:44 UTC289
        loop {
1fe480c16a3catagen2026-09-26 08:44 UTC290
            if let Ok(done) = self.tasks.join_next().await? {
1fe480c16a3catagen2026-09-26 08:44 UTC291
                return Some(done);
1fe480c16a3catagen2026-09-26 08:44 UTC292
            }
1fe480c16a3catagen2026-09-26 08:44 UTC293
        }
31ce2453c82fatagen2026-09-24 13:07 UTC294
    }
31ce2453c82fatagen2026-09-24 13:07 UTC295
31ce2453c82fatagen2026-09-24 13:07 UTC296
    async fn shutdown(&mut self) {
1fe480c16a3catagen2026-09-26 08:44 UTC297
        self.tasks.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC298
    }
31ce2453c82fatagen2026-09-24 13:07 UTC299
}
31ce2453c82fatagen2026-09-24 13:07 UTC300
31ce2453c82fatagen2026-09-24 13:07 UTC301
enum RoomSlot {
31ce2453c82fatagen2026-09-24 13:07 UTC302
    Active {
31ce2453c82fatagen2026-09-24 13:07 UTC303
        generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC304
        sender: mpsc::Sender<ActorRequest>,
31ce2453c82fatagen2026-09-24 13:07 UTC305
    },
31ce2453c82fatagen2026-09-24 13:07 UTC306
    /// opens and closes that arrive while the actor winds down, replayed in order once it's gone
31ce2453c82fatagen2026-09-24 13:07 UTC307
    Closing {
31ce2453c82fatagen2026-09-24 13:07 UTC308
        generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC309
        pending: VecDeque<Deferred>,
31ce2453c82fatagen2026-09-24 13:07 UTC310
    },
31ce2453c82fatagen2026-09-24 13:07 UTC311
}
31ce2453c82fatagen2026-09-24 13:07 UTC312
31ce2453c82fatagen2026-09-24 13:07 UTC313
impl RoomSlot {
31ce2453c82fatagen2026-09-24 13:07 UTC314
    const fn generation(&self) -> u64 {
31ce2453c82fatagen2026-09-24 13:07 UTC315
        match self {
31ce2453c82fatagen2026-09-24 13:07 UTC316
            Self::Active { generation, .. } | Self::Closing { generation, .. } => *generation,
31ce2453c82fatagen2026-09-24 13:07 UTC317
        }
31ce2453c82fatagen2026-09-24 13:07 UTC318
    }
31ce2453c82fatagen2026-09-24 13:07 UTC319
}
31ce2453c82fatagen2026-09-24 13:07 UTC320
31ce2453c82fatagen2026-09-24 13:07 UTC321
enum Deferred {
31ce2453c82fatagen2026-09-24 13:07 UTC322
    Open(Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC323
    Close(Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC324
}
31ce2453c82fatagen2026-09-24 13:07 UTC325
673563a76e43atagen2026-09-26 12:30 UTC326
/// logouts in flight, and a token rejection held back because one of them caused it
673563a76e43atagen2026-09-26 12:30 UTC327
#[derive(Default)]
673563a76e43atagen2026-09-26 12:30 UTC328
pub(super) struct Logouts {
673563a76e43atagen2026-09-26 12:30 UTC329
    pub(super) in_flight: usize,
673563a76e43atagen2026-09-26 12:30 UTC330
    pub(super) rejected: Option<Option<OwnedDeviceId>>,
673563a76e43atagen2026-09-26 12:30 UTC331
}
673563a76e43atagen2026-09-26 12:30 UTC332
31ce2453c82fatagen2026-09-24 13:07 UTC333
struct Queues {
31ce2453c82fatagen2026-09-24 13:07 UTC334
    mutations: mpsc::Receiver<MutationJob>,
31ce2453c82fatagen2026-09-24 13:07 UTC335
    notifications: mpsc::Receiver<Job<NotificationCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC336
    encryption: mpsc::Receiver<Job<EncryptionCommand>>,
66db1b3cd895atagen2026-10-25 10:28 UTC337
    thread_lists: mpsc::Receiver<Job<ThreadListCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC338
    session_changes: broadcast::Receiver<SessionChange>,
f12377bce9b9atagen2026-09-26 12:32 UTC339
    persistence: Option<Persistence>,
31ce2453c82fatagen2026-09-24 13:07 UTC340
}
31ce2453c82fatagen2026-09-24 13:07 UTC341
5a52012c9b1datagen2026-09-24 23:45 UTC342
/// requests other devices send us, handed from the sdk's event handler to the encryption worker
5a52012c9b1datagen2026-09-24 23:45 UTC343
type IncomingVerifications =
5a52012c9b1datagen2026-09-24 23:45 UTC344
    mpsc::UnboundedSender<matrix_sdk::encryption::verification::VerificationRequest>;
5a52012c9b1datagen2026-09-24 23:45 UTC345
31ce2453c82fatagen2026-09-24 13:07 UTC346
pub struct Engine {
31ce2453c82fatagen2026-09-24 13:07 UTC347
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC348
    sync: Arc<SyncService>,
31ce2453c82fatagen2026-09-24 13:07 UTC349
    port: DriverPort,
31ce2453c82fatagen2026-09-24 13:07 UTC350
    config: EngineConfig,
31ce2453c82fatagen2026-09-24 13:07 UTC351
    media: Arc<MediaService>,
da8896938cf0atagen2026-10-25 10:04 UTC352
    contexts: Arc<context::Sessions>,
31ce2453c82fatagen2026-09-24 13:07 UTC353
    tasks: TaskRegistry,
31ce2453c82fatagen2026-09-24 13:07 UTC354
    rooms: HashMap<OwnedRoomId, RoomSlot>,
31ce2453c82fatagen2026-09-24 13:07 UTC355
    next_generation: u64,
5a52012c9b1datagen2026-09-24 23:45 UTC356
    notes: mpsc::UnboundedReceiver<ActorNote>,
5a52012c9b1datagen2026-09-24 23:45 UTC357
    note_sender: mpsc::UnboundedSender<ActorNote>,
5a52012c9b1datagen2026-09-24 23:45 UTC358
    /// the rooms sliding sync should follow, applied off the run loop since it touches the store
5a52012c9b1datagen2026-09-24 23:45 UTC359
    subscriptions: watch::Sender<Vec<OwnedRoomId>>,
31ce2453c82fatagen2026-09-24 13:07 UTC360
    mutations: mpsc::Sender<MutationJob>,
31ce2453c82fatagen2026-09-24 13:07 UTC361
    notifications: mpsc::Sender<Job<NotificationCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC362
    encryption: mpsc::Sender<Job<EncryptionCommand>>,
66db1b3cd895atagen2026-10-25 10:28 UTC363
    thread_lists: mpsc::Sender<Job<ThreadListCommand>>,
31ce2453c82fatagen2026-09-24 13:07 UTC364
    queues: Option<Queues>,
5a52012c9b1datagen2026-09-24 23:45 UTC365
    /// the client can outlive us, so the handler has to come off it when we stop
5a52012c9b1datagen2026-09-24 23:45 UTC366
    verification_handler: Option<matrix_sdk::event_handler::EventHandlerHandle>,
fe4133dbcd47atagen2026-09-26 09:05 UTC367
    stop: mpsc::UnboundedSender<Termination>,
fe4133dbcd47atagen2026-09-26 09:05 UTC368
    stops: mpsc::UnboundedReceiver<Termination>,
673563a76e43atagen2026-09-26 12:30 UTC369
    logouts: Arc<watch::Sender<Logouts>>,
38c4caecdb3datagen2026-09-26 13:35 UTC370
    preparations: prepare::Preparations,
a250c7fa43fbatagen2026-09-26 13:35 UTC371
    /// shared with every `ClientHandle`, so the store stays locked while the client is reachable
a250c7fa43fbatagen2026-09-26 13:35 UTC372
    _store_lock: Option<Arc<StoreLock>>,
cbb715e11963atagen2026-10-24 23:24 UTC373
    mentions: crate::mentions::service::Handle,
cbb715e11963atagen2026-10-24 23:24 UTC374
    mentions_service: Option<crate::mentions::service::Service>,
cbb715e11963atagen2026-10-24 23:24 UTC375
    mentions_updates: Option<watch::Receiver<crate::MentionsPage>>,
c9effeac326aatagen2026-10-25 10:32 UTC376
    search: crate::search::Handle,
c9effeac326aatagen2026-10-25 10:32 UTC377
    search_service: Option<crate::search::Service>,
31ce2453c82fatagen2026-09-24 13:07 UTC378
}
31ce2453c82fatagen2026-09-24 13:07 UTC379
31ce2453c82fatagen2026-09-24 13:07 UTC380
impl Engine {
31ce2453c82fatagen2026-09-24 13:07 UTC381
    /// the escape hatch for a client you built yourself. `Session` is the usual way in
31ce2453c82fatagen2026-09-24 13:07 UTC382
    pub async fn from_client(
31ce2453c82fatagen2026-09-24 13:07 UTC383
        client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC384
        config: EngineConfig,
31ce2453c82fatagen2026-09-24 13:07 UTC385
    ) -> Result<(Self, ClientHandle, EventStream), EngineError> {
f12377bce9b9atagen2026-09-26 12:32 UTC386
        let session_changes = client.subscribe_to_session_changes();
c9effeac326aatagen2026-10-25 10:32 UTC387
        Self::with_persistence(client, config, session_changes, None, None, None, None).await
f12377bce9b9atagen2026-09-26 12:32 UTC388
    }
f12377bce9b9atagen2026-09-26 12:32 UTC389
f12377bce9b9atagen2026-09-26 12:32 UTC390
    /// `session_changes` is taken when the client is built, since the sdk can refresh
f12377bce9b9atagen2026-09-26 12:32 UTC391
    /// before an engine exists
f12377bce9b9atagen2026-09-26 12:32 UTC392
    pub(crate) async fn with_persistence(
f12377bce9b9atagen2026-09-26 12:32 UTC393
        client: Client,
f12377bce9b9atagen2026-09-26 12:32 UTC394
        config: EngineConfig,
f12377bce9b9atagen2026-09-26 12:32 UTC395
        session_changes: broadcast::Receiver<SessionChange>,
f12377bce9b9atagen2026-09-26 12:32 UTC396
        persistence: Option<Persistence>,
a250c7fa43fbatagen2026-09-26 13:35 UTC397
        store_lock: Option<StoreLock>,
82d37c369846atagen2026-10-25 10:55 UTC398
        mentions: Option<Result<MentionsStore, crate::mentions::service::Unopened>>,
c9effeac326aatagen2026-10-25 10:32 UTC399
        search: Option<Result<SearchStore, crate::Error>>,
f12377bce9b9atagen2026-09-26 12:32 UTC400
    ) -> Result<(Self, ClientHandle, EventStream), EngineError> {
31ce2453c82fatagen2026-09-24 13:07 UTC401
        if client.user_id().is_none() {
31ce2453c82fatagen2026-09-24 13:07 UTC402
            return Err(EngineError::Unauthenticated);
31ce2453c82fatagen2026-09-24 13:07 UTC403
        }
31ce2453c82fatagen2026-09-24 13:07 UTC404
        if config.command_capacity == 0
31ce2453c82fatagen2026-09-24 13:07 UTC405
            || config.event_capacity == 0
da8896938cf0atagen2026-10-25 10:04 UTC406
            || config.max_context_media == 0
cbb715e11963atagen2026-10-24 23:24 UTC407
            || config.max_mentions_entries == 0
cbb715e11963atagen2026-10-24 23:24 UTC408
            || config.max_mention_context_events == 0
cbb715e11963atagen2026-10-24 23:24 UTC409
            || config.max_mention_candidates == 0
31ce2453c82fatagen2026-09-24 13:07 UTC410
        {
31ce2453c82fatagen2026-09-24 13:07 UTC411
            return Err(EngineError::ZeroCapacity);
31ce2453c82fatagen2026-09-24 13:07 UTC412
        }
cbb715e11963atagen2026-10-24 23:24 UTC413
        let store_lock = store_lock.map(Arc::new);
cbb715e11963atagen2026-10-24 23:24 UTC414
        let media = Arc::new(MediaService::new(
cbb715e11963atagen2026-10-24 23:24 UTC415
            client.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC416
            config.max_media_bytes,
da8896938cf0atagen2026-10-25 10:04 UTC417
            config.max_context_media,
cbb715e11963atagen2026-10-24 23:24 UTC418
        ));
cbb715e11963atagen2026-10-24 23:24 UTC419
        let (mentions, mentions_service, mentions_updates) =
cbb715e11963atagen2026-10-24 23:24 UTC420
            crate::mentions::service::Service::new(
cbb715e11963atagen2026-10-24 23:24 UTC421
                client.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC422
                media.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC423
                mentions,
cbb715e11963atagen2026-10-24 23:24 UTC424
                config.clone(),
cbb715e11963atagen2026-10-24 23:24 UTC425
            )
cbb715e11963atagen2026-10-24 23:24 UTC426
            .await
0d763e4284efatagen2026-10-25 09:31 UTC427
            // a missing user id is all it still refuses, and that was turned away above
0d763e4284efatagen2026-10-25 09:31 UTC428
            .map_err(|_| EngineError::Unauthenticated)?;
31ce2453c82fatagen2026-09-24 13:07 UTC429
        let sync = Arc::new(
31ce2453c82fatagen2026-09-24 13:07 UTC430
            SyncService::builder(client.clone())
31ce2453c82fatagen2026-09-24 13:07 UTC431
                .with_offline_mode()
0291516d40b5atagen2026-10-22 08:31 UTC432
                .with_room_list_extra_required_state(vec![
0291516d40b5atagen2026-10-22 08:31 UTC433
                    (ROOM_PACKS.into(), "*".to_owned()),
0291516d40b5atagen2026-10-22 08:31 UTC434
                    (ROOM_PREVIEW_URLS.into(), String::new()),
0291516d40b5atagen2026-10-22 08:31 UTC435
                ])
cbb715e11963atagen2026-10-24 23:24 UTC436
                .with_room_list_response_commit_hook(mentions.hook())
6a5963d5bd63atagen2026-10-28 05:03 UTC437
                .with_room_list_growing_batch_size(ROOM_LIST_GROWING_BATCH)
31ce2453c82fatagen2026-09-24 13:07 UTC438
                .build()
31ce2453c82fatagen2026-09-24 13:07 UTC439
                .await
31ce2453c82fatagen2026-09-24 13:07 UTC440
                .map_err(EngineError::SyncService)?,
31ce2453c82fatagen2026-09-24 13:07 UTC441
        );
31ce2453c82fatagen2026-09-24 13:07 UTC442
        let (handle, port, events) = transport_pair(
31ce2453c82fatagen2026-09-24 13:07 UTC443
            client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC444
            sync.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC445
            media.clone(),
a250c7fa43fbatagen2026-09-26 13:35 UTC446
            store_lock.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC447
            config.command_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC448
            config.event_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC449
        );
74befbc72bafatagen2026-10-25 11:18 UTC450
        let (search, search_service) = crate::search::Service::new(
74befbc72bafatagen2026-10-25 11:18 UTC451
            client.clone(),
74befbc72bafatagen2026-10-25 11:18 UTC452
            media.clone(),
74befbc72bafatagen2026-10-25 11:18 UTC453
            search,
74befbc72bafatagen2026-10-25 11:18 UTC454
            port.event_sender(),
74befbc72bafatagen2026-10-25 11:18 UTC455
            &config,
74befbc72bafatagen2026-10-25 11:18 UTC456
        );
31ce2453c82fatagen2026-09-24 13:07 UTC457
        client.send_queue().enable_upload_progress(true);
411bc1c78b65atagen2026-10-22 07:39 UTC458
        client.send_queue().enable_global_upload_progress(true);
5a52012c9b1datagen2026-09-24 23:45 UTC459
        let (note_sender, notes) = mpsc::unbounded_channel();
fe4133dbcd47atagen2026-09-26 09:05 UTC460
        let (stop, stops) = mpsc::unbounded_channel();
31ce2453c82fatagen2026-09-24 13:07 UTC461
        let (mutations, mutation_queue) = mpsc::channel(config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC462
        let (notifications, notification_queue) = mpsc::channel(config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC463
        let (encryption, encryption_queue) = mpsc::channel(config.command_capacity);
66db1b3cd895atagen2026-10-25 10:28 UTC464
        let (thread_lists, thread_list_queue) = mpsc::channel(config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC465
        let engine = Self {
1f875b103b27atagen2026-10-25 10:44 UTC466
            contexts: Arc::new(context::Sessions::new(port.event_sender())),
31ce2453c82fatagen2026-09-24 13:07 UTC467
            client,
31ce2453c82fatagen2026-09-24 13:07 UTC468
            sync,
31ce2453c82fatagen2026-09-24 13:07 UTC469
            port,
31ce2453c82fatagen2026-09-24 13:07 UTC470
            config,
31ce2453c82fatagen2026-09-24 13:07 UTC471
            media,
31ce2453c82fatagen2026-09-24 13:07 UTC472
            tasks: TaskRegistry {
1fe480c16a3catagen2026-09-26 08:44 UTC473
                tasks: TaskSet::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC474
            },
31ce2453c82fatagen2026-09-24 13:07 UTC475
            rooms: HashMap::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC476
            next_generation: 0,
5a52012c9b1datagen2026-09-24 23:45 UTC477
            notes,
5a52012c9b1datagen2026-09-24 23:45 UTC478
            note_sender,
5a52012c9b1datagen2026-09-24 23:45 UTC479
            subscriptions: watch::Sender::new(Vec::new()),
31ce2453c82fatagen2026-09-24 13:07 UTC480
            mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC481
            notifications,
31ce2453c82fatagen2026-09-24 13:07 UTC482
            encryption,
66db1b3cd895atagen2026-10-25 10:28 UTC483
            thread_lists,
31ce2453c82fatagen2026-09-24 13:07 UTC484
            queues: Some(Queues {
31ce2453c82fatagen2026-09-24 13:07 UTC485
                mutations: mutation_queue,
31ce2453c82fatagen2026-09-24 13:07 UTC486
                notifications: notification_queue,
31ce2453c82fatagen2026-09-24 13:07 UTC487
                encryption: encryption_queue,
66db1b3cd895atagen2026-10-25 10:28 UTC488
                thread_lists: thread_list_queue,
31ce2453c82fatagen2026-09-24 13:07 UTC489
                session_changes,
f12377bce9b9atagen2026-09-26 12:32 UTC490
                persistence,
31ce2453c82fatagen2026-09-24 13:07 UTC491
            }),
5a52012c9b1datagen2026-09-24 23:45 UTC492
            verification_handler: None,
38c4caecdb3datagen2026-09-26 13:35 UTC493
            preparations: prepare::Preparations::default(),
fe4133dbcd47atagen2026-09-26 09:05 UTC494
            stop,
fe4133dbcd47atagen2026-09-26 09:05 UTC495
            stops,
673563a76e43atagen2026-09-26 12:30 UTC496
            logouts: Arc::new(watch::Sender::new(Logouts::default())),
a250c7fa43fbatagen2026-09-26 13:35 UTC497
            _store_lock: store_lock,
cbb715e11963atagen2026-10-24 23:24 UTC498
            mentions,
cbb715e11963atagen2026-10-24 23:24 UTC499
            mentions_service: Some(mentions_service),
cbb715e11963atagen2026-10-24 23:24 UTC500
            mentions_updates: Some(mentions_updates),
c9effeac326aatagen2026-10-25 10:32 UTC501
            search,
c9effeac326aatagen2026-10-25 10:32 UTC502
            search_service: Some(search_service),
31ce2453c82fatagen2026-09-24 13:07 UTC503
        };
31ce2453c82fatagen2026-09-24 13:07 UTC504
        Ok((engine, handle, events))
31ce2453c82fatagen2026-09-24 13:07 UTC505
    }
31ce2453c82fatagen2026-09-24 13:07 UTC506
5a52012c9b1datagen2026-09-24 23:45 UTC507
    /// boxed because the engine's future is deep enough to blow the compiler's query depth
5a52012c9b1datagen2026-09-24 23:45 UTC508
    /// in every crate that spawns it, which isn't something a client should have to fix
fe4133dbcd47atagen2026-09-26 09:05 UTC509
    pub fn run(self) -> EngineBoxFuture<'static, Result<Termination, EngineError>> {
5a52012c9b1datagen2026-09-24 23:45 UTC510
        Box::pin(self.run_inner())
5a52012c9b1datagen2026-09-24 23:45 UTC511
    }
5a52012c9b1datagen2026-09-24 23:45 UTC512
fe4133dbcd47atagen2026-09-26 09:05 UTC513
    async fn run_inner(mut self) -> Result<Termination, EngineError> {
31ce2453c82fatagen2026-09-24 13:07 UTC514
        let events = self.port.event_sender();
31ce2453c82fatagen2026-09-24 13:07 UTC515
        let user_id = self
31ce2453c82fatagen2026-09-24 13:07 UTC516
            .client
31ce2453c82fatagen2026-09-24 13:07 UTC517
            .user_id()
31ce2453c82fatagen2026-09-24 13:07 UTC518
            .expect("authentication was checked during construction")
31ce2453c82fatagen2026-09-24 13:07 UTC519
            .to_owned();
31ce2453c82fatagen2026-09-24 13:07 UTC520
        self.port
31ce2453c82fatagen2026-09-24 13:07 UTC521
            .connection_sender()
31ce2453c82fatagen2026-09-24 13:07 UTC522
            .send_replace(ConnectionState::Connecting);
31ce2453c82fatagen2026-09-24 13:07 UTC523
        for event in [
31ce2453c82fatagen2026-09-24 13:07 UTC524
            Event::Authenticated { user_id },
31ce2453c82fatagen2026-09-24 13:07 UTC525
            Event::ConnectionChanged(ConnectionState::Connecting),
31ce2453c82fatagen2026-09-24 13:07 UTC526
        ] {
31ce2453c82fatagen2026-09-24 13:07 UTC527
            if events.send(event).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC528
                self.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC529
                return Err(EngineError::EventReceiverClosed);
31ce2453c82fatagen2026-09-24 13:07 UTC530
            }
31ce2453c82fatagen2026-09-24 13:07 UTC531
        }
31ce2453c82fatagen2026-09-24 13:07 UTC532
        self.start_tasks();
31ce2453c82fatagen2026-09-24 13:07 UTC533
        self.sync.start().await;
31ce2453c82fatagen2026-09-24 13:07 UTC534
31ce2453c82fatagen2026-09-24 13:07 UTC535
        let mut shutdown_reply = None;
673563a76e43atagen2026-09-26 12:30 UTC536
        let mut handles_dropped = false;
673563a76e43atagen2026-09-26 12:30 UTC537
        let mut logouts = self.logouts.subscribe();
fe4133dbcd47atagen2026-09-26 09:05 UTC538
        let ending = loop {
31ce2453c82fatagen2026-09-24 13:07 UTC539
            tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC540
                biased;
fe4133dbcd47atagen2026-09-26 09:05 UTC541
                Some(termination) = self.stops.recv() => break Ok(termination),
673563a76e43atagen2026-09-26 12:30 UTC542
                () = events.closed() => break Err(EngineError::EventReceiverClosed),
673563a76e43atagen2026-09-26 12:30 UTC543
                () = settled(&mut logouts), if handles_dropped => {
673563a76e43atagen2026-09-26 12:30 UTC544
                    break Ok(Termination::HandlesDropped);
673563a76e43atagen2026-09-26 12:30 UTC545
                }
1fe480c16a3catagen2026-09-26 08:44 UTC546
                Some((context, panic)) = self.tasks.join_next(), if !self.tasks.is_empty() => {
1fe480c16a3catagen2026-09-26 08:44 UTC547
                    let Some(message) = panic else { continue };
31ce2453c82fatagen2026-09-24 13:07 UTC548
                    if let TaskContext::Command(label) = context {
1fe480c16a3catagen2026-09-26 08:44 UTC549
                        tracing::error!(label, panic = %message, "command task panicked");
31ce2453c82fatagen2026-09-24 13:07 UTC550
                        continue;
31ce2453c82fatagen2026-09-24 13:07 UTC551
                    }
fe4133dbcd47atagen2026-09-26 09:05 UTC552
                    break Err(EngineError::TaskPanicked { task: context.label() });
31ce2453c82fatagen2026-09-24 13:07 UTC553
                }
5a52012c9b1datagen2026-09-24 23:45 UTC554
                Some(note) = self.notes.recv() => self.actor_note(note).await,
673563a76e43atagen2026-09-26 12:30 UTC555
                request = self.port.recv(), if !handles_dropped => {
673563a76e43atagen2026-09-26 12:30 UTC556
                    // nobody's left to ask, but a logout they asked for still deserves to land
673563a76e43atagen2026-09-26 12:30 UTC557
                    let Some(request) = request else {
673563a76e43atagen2026-09-26 12:30 UTC558
                        handles_dropped = true;
673563a76e43atagen2026-09-26 12:30 UTC559
                        continue;
673563a76e43atagen2026-09-26 12:30 UTC560
                    };
5a52012c9b1datagen2026-09-24 23:45 UTC561
                    if let Some(reply) = self.dispatch(request).await {
5a52012c9b1datagen2026-09-24 23:45 UTC562
                        shutdown_reply = Some(reply);
fe4133dbcd47atagen2026-09-26 09:05 UTC563
                        break Ok(Termination::ShutDown);
5a52012c9b1datagen2026-09-24 23:45 UTC564
                    }
5a52012c9b1datagen2026-09-24 23:45 UTC565
                }
31ce2453c82fatagen2026-09-24 13:07 UTC566
            }
fe4133dbcd47atagen2026-09-26 09:05 UTC567
        };
31ce2453c82fatagen2026-09-24 13:07 UTC568
fe4133dbcd47atagen2026-09-26 09:05 UTC569
        if let Err(error) = &ending {
31ce2453c82fatagen2026-09-24 13:07 UTC570
            let _ = events.send(Event::Failed(error.failure())).await;
31ce2453c82fatagen2026-09-24 13:07 UTC571
        }
31ce2453c82fatagen2026-09-24 13:07 UTC572
        self.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC573
        let _ = events.send(Event::Stopped).await;
31ce2453c82fatagen2026-09-24 13:07 UTC574
        if let Some(reply) = shutdown_reply {
31ce2453c82fatagen2026-09-24 13:07 UTC575
            reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC576
        }
5a52012c9b1datagen2026-09-24 23:45 UTC577
        // everything else still queued answers `Interrupted` as it drops, but a shutdown did happen
5a52012c9b1datagen2026-09-24 23:45 UTC578
        while let Some(Request { command, reply }) = self.port.try_recv() {
5a52012c9b1datagen2026-09-24 23:45 UTC579
            if matches!(command, Command::Lifecycle(LifecycleCommand::Shutdown)) {
5a52012c9b1datagen2026-09-24 23:45 UTC580
                reply.done(Ok(()));
5a52012c9b1datagen2026-09-24 23:45 UTC581
            }
5a52012c9b1datagen2026-09-24 23:45 UTC582
        }
fe4133dbcd47atagen2026-09-26 09:05 UTC583
        ending
31ce2453c82fatagen2026-09-24 13:07 UTC584
    }
31ce2453c82fatagen2026-09-24 13:07 UTC585
31ce2453c82fatagen2026-09-24 13:07 UTC586
    fn start_tasks(&mut self) {
31ce2453c82fatagen2026-09-24 13:07 UTC587
        let queues = self.queues.take().expect("engine tasks start once");
cbb715e11963atagen2026-10-24 23:24 UTC588
        if let Some(service) = self.mentions_service.take() {
cbb715e11963atagen2026-10-24 23:24 UTC589
            self.tasks
cbb715e11963atagen2026-10-24 23:24 UTC590
                .spawn(TaskContext::Watcher("mentions service"), service.run());
cbb715e11963atagen2026-10-24 23:24 UTC591
        }
c9effeac326aatagen2026-10-25 10:32 UTC592
        if let Some(service) = self.search_service.take() {
c9effeac326aatagen2026-10-25 10:32 UTC593
            self.tasks
c9effeac326aatagen2026-10-25 10:32 UTC594
                .spawn(TaskContext::Watcher("search service"), service.run());
c9effeac326aatagen2026-10-25 10:32 UTC595
        }
cbb715e11963atagen2026-10-24 23:24 UTC596
        if let Some(updates) = self.mentions_updates.take() {
cbb715e11963atagen2026-10-24 23:24 UTC597
            let events = self.port.event_sender();
cbb715e11963atagen2026-10-24 23:24 UTC598
            self.tasks.spawn(
cbb715e11963atagen2026-10-24 23:24 UTC599
                TaskContext::Watcher("mentions updates"),
cbb715e11963atagen2026-10-24 23:24 UTC600
                crate::mentions::service::watch_updates(updates, events),
cbb715e11963atagen2026-10-24 23:24 UTC601
            );
cbb715e11963atagen2026-10-24 23:24 UTC602
        }
5a52012c9b1datagen2026-09-24 23:45 UTC603
        let (incoming, incoming_verifications) = mpsc::unbounded_channel();
5a52012c9b1datagen2026-09-24 23:45 UTC604
        self.verification_handler = Some(self.verification_handler(incoming));
31ce2453c82fatagen2026-09-24 13:07 UTC605
        let client = &self.client;
31ce2453c82fatagen2026-09-24 13:07 UTC606
        let events = || self.port.event_sender();
f12377bce9b9atagen2026-09-26 12:32 UTC607
        let (notices, notice_queue) = mpsc::unbounded_channel();
743123167e29atagen2026-10-26 04:02 UTC608
        let (enabling_recovery, recovery_enabling) = watch::channel(false);
66db1b3cd895atagen2026-10-25 10:28 UTC609
        let watchers: [(&'static str, EngineBoxFuture<'static, ()>); 15] = [
5a52012c9b1datagen2026-09-24 23:45 UTC610
            (
7c26fad34822atagen2026-09-26 09:41 UTC611
                "upload tracker",
0bfa3f46f0beatagen2026-09-26 09:12 UTC612
                Box::pin(watchers::uploads(
5a52012c9b1datagen2026-09-24 23:45 UTC613
                    client.clone(),
5a52012c9b1datagen2026-09-24 23:45 UTC614
                    client.send_queue().subscribe(),
5a52012c9b1datagen2026-09-24 23:45 UTC615
                    events(),
5a52012c9b1datagen2026-09-24 23:45 UTC616
                )),
5a52012c9b1datagen2026-09-24 23:45 UTC617
            ),
5a52012c9b1datagen2026-09-24 23:45 UTC618
            (
5a52012c9b1datagen2026-09-24 23:45 UTC619
                "room subscription watcher",
5a52012c9b1datagen2026-09-24 23:45 UTC620
                Box::pin(watchers::room_subscriptions(
5a52012c9b1datagen2026-09-24 23:45 UTC621
                    self.sync.clone(),
5a52012c9b1datagen2026-09-24 23:45 UTC622
                    self.subscriptions.subscribe(),
5a52012c9b1datagen2026-09-24 23:45 UTC623
                )),
5a52012c9b1datagen2026-09-24 23:45 UTC624
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC625
            (
31ce2453c82fatagen2026-09-24 13:07 UTC626
                "session change watcher",
f12377bce9b9atagen2026-09-26 12:32 UTC627
                Box::pin(session::session(
f12377bce9b9atagen2026-09-26 12:32 UTC628
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC629
                    queues.session_changes,
f12377bce9b9atagen2026-09-26 12:32 UTC630
                    queues.persistence,
f12377bce9b9atagen2026-09-26 12:32 UTC631
                    notices,
fe4133dbcd47atagen2026-09-26 09:05 UTC632
                    client
fe4133dbcd47atagen2026-09-26 09:05 UTC633
                        .device_id()
fe4133dbcd47atagen2026-09-26 09:05 UTC634
                        .expect("authentication was checked during construction")
fe4133dbcd47atagen2026-09-26 09:05 UTC635
                        .to_owned(),
673563a76e43atagen2026-09-26 12:30 UTC636
                    self.logouts.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC637
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC638
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC639
            (
f12377bce9b9atagen2026-09-26 12:32 UTC640
                "session notice watcher",
f12377bce9b9atagen2026-09-26 12:32 UTC641
                Box::pin(session::session_notices(
f12377bce9b9atagen2026-09-26 12:32 UTC642
                    notice_queue,
f12377bce9b9atagen2026-09-26 12:32 UTC643
                    events(),
f12377bce9b9atagen2026-09-26 12:32 UTC644
                    self.stop.clone(),
f12377bce9b9atagen2026-09-26 12:32 UTC645
                )),
f12377bce9b9atagen2026-09-26 12:32 UTC646
            ),
f12377bce9b9atagen2026-09-26 12:32 UTC647
            (
31ce2453c82fatagen2026-09-24 13:07 UTC648
                "connection state watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC649
                Box::pin(watchers::connection(
31ce2453c82fatagen2026-09-24 13:07 UTC650
                    self.sync.state(),
31ce2453c82fatagen2026-09-24 13:07 UTC651
                    self.sync.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC652
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC653
                    events(),
31ce2453c82fatagen2026-09-24 13:07 UTC654
                    self.port.connection_sender(),
31ce2453c82fatagen2026-09-24 13:07 UTC655
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC656
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC657
            (
31ce2453c82fatagen2026-09-24 13:07 UTC658
                "send queue watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC659
                Box::pin(watchers::send_queue_errors(
31ce2453c82fatagen2026-09-24 13:07 UTC660
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC661
                    client.send_queue().subscribe_errors(),
31ce2453c82fatagen2026-09-24 13:07 UTC662
                    self.port.connection_sender().subscribe(),
31ce2453c82fatagen2026-09-24 13:07 UTC663
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC664
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC665
            (
31ce2453c82fatagen2026-09-24 13:07 UTC666
                "encryption state watcher",
743123167e29atagen2026-10-26 04:02 UTC667
                Box::pin(watchers::encryption(
743123167e29atagen2026-10-26 04:02 UTC668
                    client.clone(),
743123167e29atagen2026-10-26 04:02 UTC669
                    events(),
743123167e29atagen2026-10-26 04:02 UTC670
                    recovery_enabling,
743123167e29atagen2026-10-26 04:02 UTC671
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC672
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC673
            (
31ce2453c82fatagen2026-09-24 13:07 UTC674
                "room list watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC675
                Box::pin(watchers::rooms(client.clone(), events())),
31ce2453c82fatagen2026-09-24 13:07 UTC676
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC677
            (
da8896938cf0atagen2026-10-25 10:04 UTC678
                "event context watcher",
da8896938cf0atagen2026-10-25 10:04 UTC679
                Box::pin(context::close_on_leave(
da8896938cf0atagen2026-10-25 10:04 UTC680
                    client.clone(),
da8896938cf0atagen2026-10-25 10:04 UTC681
                    self.media.clone(),
da8896938cf0atagen2026-10-25 10:04 UTC682
                    self.contexts.clone(),
da8896938cf0atagen2026-10-25 10:04 UTC683
                )),
da8896938cf0atagen2026-10-25 10:04 UTC684
            ),
da8896938cf0atagen2026-10-25 10:04 UTC685
            (
17e042fbc331atagen2026-10-08 12:39 UTC686
                "image pack watcher",
17e042fbc331atagen2026-10-08 12:39 UTC687
                Box::pin(watchers::image_packs(client.clone(), events())),
17e042fbc331atagen2026-10-08 12:39 UTC688
            ),
17e042fbc331atagen2026-10-08 12:39 UTC689
            (
31ce2453c82fatagen2026-09-24 13:07 UTC690
                "notification settings watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC691
                Box::pin(watchers::notification_settings(client.clone(), events())),
31ce2453c82fatagen2026-09-24 13:07 UTC692
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC693
            (
31ce2453c82fatagen2026-09-24 13:07 UTC694
                "room command worker",
31ce2453c82fatagen2026-09-24 13:07 UTC695
                Box::pin(mutations::run_scheduler(
31ce2453c82fatagen2026-09-24 13:07 UTC696
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC697
                    queues.mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC698
                    self.config.command_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC699
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC700
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC701
            (
31ce2453c82fatagen2026-09-24 13:07 UTC702
                "notification command worker",
31ce2453c82fatagen2026-09-24 13:07 UTC703
                Box::pin(commands::run_notifications(
31ce2453c82fatagen2026-09-24 13:07 UTC704
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC705
                    queues.notifications,
31ce2453c82fatagen2026-09-24 13:07 UTC706
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC707
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC708
            (
31ce2453c82fatagen2026-09-24 13:07 UTC709
                "encryption command worker",
31ce2453c82fatagen2026-09-24 13:07 UTC710
                Box::pin(commands::run_encryption(
31ce2453c82fatagen2026-09-24 13:07 UTC711
                    client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC712
                    events(),
31ce2453c82fatagen2026-09-24 13:07 UTC713
                    queues.encryption,
5a52012c9b1datagen2026-09-24 23:45 UTC714
                    incoming_verifications,
743123167e29atagen2026-10-26 04:02 UTC715
                    enabling_recovery,
31ce2453c82fatagen2026-09-24 13:07 UTC716
                )),
31ce2453c82fatagen2026-09-24 13:07 UTC717
            ),
66db1b3cd895atagen2026-10-25 10:28 UTC718
            (
66db1b3cd895atagen2026-10-25 10:28 UTC719
                "thread list worker",
66db1b3cd895atagen2026-10-25 10:28 UTC720
                Box::pin(thread_list::run(
66db1b3cd895atagen2026-10-25 10:28 UTC721
                    client.clone(),
66db1b3cd895atagen2026-10-25 10:28 UTC722
                    events(),
66db1b3cd895atagen2026-10-25 10:28 UTC723
                    self.media.clone(),
66db1b3cd895atagen2026-10-25 10:28 UTC724
                    queues.thread_lists,
66db1b3cd895atagen2026-10-25 10:28 UTC725
                )),
66db1b3cd895atagen2026-10-25 10:28 UTC726
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC727
        ];
31ce2453c82fatagen2026-09-24 13:07 UTC728
        for (label, task) in watchers {
31ce2453c82fatagen2026-09-24 13:07 UTC729
            self.tasks.spawn(TaskContext::Watcher(label), task);
31ce2453c82fatagen2026-09-24 13:07 UTC730
        }
31ce2453c82fatagen2026-09-24 13:07 UTC731
    }
31ce2453c82fatagen2026-09-24 13:07 UTC732
5a52012c9b1datagen2026-09-24 23:45 UTC733
    fn verification_handler(
5a52012c9b1datagen2026-09-24 23:45 UTC734
        &self,
5a52012c9b1datagen2026-09-24 23:45 UTC735
        incoming: IncomingVerifications,
5a52012c9b1datagen2026-09-24 23:45 UTC736
    ) -> matrix_sdk::event_handler::EventHandlerHandle {
5a52012c9b1datagen2026-09-24 23:45 UTC737
        use matrix_sdk::ruma::events::key::verification::request::ToDeviceKeyVerificationRequestEvent;
5a52012c9b1datagen2026-09-24 23:45 UTC738
        self.client.add_event_handler(
5a52012c9b1datagen2026-09-24 23:45 UTC739
            move |event: ToDeviceKeyVerificationRequestEvent, client: Client| {
5a52012c9b1datagen2026-09-24 23:45 UTC740
                let incoming = incoming.clone();
5a52012c9b1datagen2026-09-24 23:45 UTC741
                async move {
5a52012c9b1datagen2026-09-24 23:45 UTC742
                    let request = client
5a52012c9b1datagen2026-09-24 23:45 UTC743
                        .encryption()
5a52012c9b1datagen2026-09-24 23:45 UTC744
                        .get_verification_request(
5a52012c9b1datagen2026-09-24 23:45 UTC745
                            &event.sender,
5a52012c9b1datagen2026-09-24 23:45 UTC746
                            event.content.transaction_id.as_str(),
5a52012c9b1datagen2026-09-24 23:45 UTC747
                        )
5a52012c9b1datagen2026-09-24 23:45 UTC748
                        .await;
5a52012c9b1datagen2026-09-24 23:45 UTC749
                    if let Some(request) = request {
5a52012c9b1datagen2026-09-24 23:45 UTC750
                        let _ = incoming.send(request);
5a52012c9b1datagen2026-09-24 23:45 UTC751
                    }
5a52012c9b1datagen2026-09-24 23:45 UTC752
                }
5a52012c9b1datagen2026-09-24 23:45 UTC753
            },
5a52012c9b1datagen2026-09-24 23:45 UTC754
        )
5a52012c9b1datagen2026-09-24 23:45 UTC755
    }
5a52012c9b1datagen2026-09-24 23:45 UTC756
31ce2453c82fatagen2026-09-24 13:07 UTC757
    /// hands back the shutdown request's responder, which is answered once we've stopped
31ce2453c82fatagen2026-09-24 13:07 UTC758
    async fn dispatch(&mut self, Request { command, reply }: Request) -> Option<Responder> {
2819830aef32atagen2026-10-26 08:42 UTC759
        tracing::debug!(command = %executor::label(&command), "engine command");
31ce2453c82fatagen2026-09-24 13:07 UTC760
        let client = self.client.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC761
        match command {
31ce2453c82fatagen2026-09-24 13:07 UTC762
            Command::Lifecycle(LifecycleCommand::Shutdown) => return Some(reply),
2006a11ce142atagen2026-10-26 04:02 UTC763
            Command::Account(AccountCommand::Logout { remove_pushers }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC764
                let events = self.port.event_sender();
31ce2453c82fatagen2026-09-24 13:07 UTC765
                let stop = self.stop.clone();
673563a76e43atagen2026-09-26 12:30 UTC766
                let logouts = self.logouts.clone();
673563a76e43atagen2026-09-26 12:30 UTC767
                logouts.send_modify(|logouts| logouts.in_flight += 1);
31ce2453c82fatagen2026-09-24 13:07 UTC768
                self.spawn_command("logout", reply, async move {
2006a11ce142atagen2026-10-26 04:02 UTC769
                    for pusher in remove_pushers {
2006a11ce142atagen2026-10-26 04:02 UTC770
                        if let Err(error) = crate::transport::remove_pusher(&client, pusher).await {
2006a11ce142atagen2026-10-26 04:02 UTC771
                            tracing::debug!(%error, "removing a pusher before logout failed");
2006a11ce142atagen2026-10-26 04:02 UTC772
                        }
2006a11ce142atagen2026-10-26 04:02 UTC773
                    }
673563a76e43atagen2026-09-26 12:30 UTC774
                    let result = client.logout().await;
673563a76e43atagen2026-09-26 12:30 UTC775
                    if result.is_ok() {
673563a76e43atagen2026-09-26 12:30 UTC776
                        let _ = events.send(Event::LoggedOut).await;
673563a76e43atagen2026-09-26 12:30 UTC777
                        let _ = stop.send(Termination::LoggedOut);
673563a76e43atagen2026-09-26 12:30 UTC778
                    }
673563a76e43atagen2026-09-26 12:30 UTC779
                    let mut rejected = None;
673563a76e43atagen2026-09-26 12:30 UTC780
                    logouts.send_if_modified(|logouts| {
673563a76e43atagen2026-09-26 12:30 UTC781
                        if result.is_err() && logouts.in_flight == 1 {
673563a76e43atagen2026-09-26 12:30 UTC782
                            rejected = logouts.rejected.take();
673563a76e43atagen2026-09-26 12:30 UTC783
                        }
673563a76e43atagen2026-09-26 12:30 UTC784
                        false
673563a76e43atagen2026-09-26 12:30 UTC785
                    });
673563a76e43atagen2026-09-26 12:30 UTC786
                    if let Some(soft_logout) = rejected {
f12377bce9b9atagen2026-09-26 12:32 UTC787
                        session::reject_session(&events, &stop, soft_logout).await;
673563a76e43atagen2026-09-26 12:30 UTC788
                    }
673563a76e43atagen2026-09-26 12:30 UTC789
                    logouts.send_modify(|logouts| logouts.in_flight -= 1);
673563a76e43atagen2026-09-26 12:30 UTC790
                    result.map_err(|source| Error::from_sdk("logout failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC791
                });
31ce2453c82fatagen2026-09-24 13:07 UTC792
            }
31ce2453c82fatagen2026-09-24 13:07 UTC793
            Command::Account(AccountCommand::SetAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC794
                event_type,
31ce2453c82fatagen2026-09-24 13:07 UTC795
                content,
31ce2453c82fatagen2026-09-24 13:07 UTC796
            }) => enqueue(
31ce2453c82fatagen2026-09-24 13:07 UTC797
                &self.mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC798
                Job {
31ce2453c82fatagen2026-09-24 13:07 UTC799
                    command: Mutation::GlobalAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC800
                        event_type,
31ce2453c82fatagen2026-09-24 13:07 UTC801
                        content,
31ce2453c82fatagen2026-09-24 13:07 UTC802
                    },
31ce2453c82fatagen2026-09-24 13:07 UTC803
                    reply,
31ce2453c82fatagen2026-09-24 13:07 UTC804
                },
31ce2453c82fatagen2026-09-24 13:07 UTC805
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC806
            Command::Account(AccountCommand::SetDisplayName(name)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC807
                self.spawn_command("set display name", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC808
                    client
31ce2453c82fatagen2026-09-24 13:07 UTC809
                        .account()
31ce2453c82fatagen2026-09-24 13:07 UTC810
                        .set_display_name(name.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC811
                        .await
31ce2453c82fatagen2026-09-24 13:07 UTC812
                        .map_err(|source| Error::from_sdk("setting display name failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC813
                });
31ce2453c82fatagen2026-09-24 13:07 UTC814
            }
31ce2453c82fatagen2026-09-24 13:07 UTC815
            Command::Account(AccountCommand::SetAvatar(avatar)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC816
                self.spawn_command("set avatar", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC817
                    client
31ce2453c82fatagen2026-09-24 13:07 UTC818
                        .account()
31ce2453c82fatagen2026-09-24 13:07 UTC819
                        .set_avatar_url(avatar.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC820
                        .await
31ce2453c82fatagen2026-09-24 13:07 UTC821
                        .map_err(|source| Error::from_sdk("setting avatar failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC822
                });
31ce2453c82fatagen2026-09-24 13:07 UTC823
            }
31ce2453c82fatagen2026-09-24 13:07 UTC824
            Command::Account(AccountCommand::UploadAvatar { mimetype, bytes }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC825
                let max_bytes = self.config.max_media_bytes;
31ce2453c82fatagen2026-09-24 13:07 UTC826
                self.spawn_command("upload avatar", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC827
                    commands::upload_avatar(&client, &mimetype, bytes, max_bytes).await
31ce2453c82fatagen2026-09-24 13:07 UTC828
                });
31ce2453c82fatagen2026-09-24 13:07 UTC829
            }
9bd34e25bb86atagen2026-10-24 07:23 UTC830
            Command::Account(AccountCommand::UploadMedia { mimetype, bytes }) => {
9bd34e25bb86atagen2026-10-24 07:23 UTC831
                let max_bytes = self.config.max_media_bytes;
9bd34e25bb86atagen2026-10-24 07:23 UTC832
                self.tasks
9bd34e25bb86atagen2026-10-24 07:23 UTC833
                    .spawn(TaskContext::Command("upload media"), async move {
9bd34e25bb86atagen2026-10-24 07:23 UTC834
                        let uploaded =
9bd34e25bb86atagen2026-10-24 07:23 UTC835
                            commands::upload_media(&client, &mimetype, bytes, max_bytes).await;
9bd34e25bb86atagen2026-10-24 07:23 UTC836
                        reply.send(uploaded.map(CommandOutput::Mxc));
9bd34e25bb86atagen2026-10-24 07:23 UTC837
                    });
9bd34e25bb86atagen2026-10-24 07:23 UTC838
            }
9bd34e25bb86atagen2026-10-24 07:23 UTC839
            Command::Account(AccountCommand::IgnoreUser(user_id)) => enqueue(
9bd34e25bb86atagen2026-10-24 07:23 UTC840
                &self.mutations,
9bd34e25bb86atagen2026-10-24 07:23 UTC841
                Job {
9bd34e25bb86atagen2026-10-24 07:23 UTC842
                    command: Mutation::Ignore {
9bd34e25bb86atagen2026-10-24 07:23 UTC843
                        user_id,
9bd34e25bb86atagen2026-10-24 07:23 UTC844
                        ignored: true,
9bd34e25bb86atagen2026-10-24 07:23 UTC845
                    },
9bd34e25bb86atagen2026-10-24 07:23 UTC846
                    reply,
9bd34e25bb86atagen2026-10-24 07:23 UTC847
                },
9bd34e25bb86atagen2026-10-24 07:23 UTC848
            ),
9bd34e25bb86atagen2026-10-24 07:23 UTC849
            Command::Account(AccountCommand::UnignoreUser(user_id)) => enqueue(
9bd34e25bb86atagen2026-10-24 07:23 UTC850
                &self.mutations,
9bd34e25bb86atagen2026-10-24 07:23 UTC851
                Job {
9bd34e25bb86atagen2026-10-24 07:23 UTC852
                    command: Mutation::Ignore {
9bd34e25bb86atagen2026-10-24 07:23 UTC853
                        user_id,
9bd34e25bb86atagen2026-10-24 07:23 UTC854
                        ignored: false,
9bd34e25bb86atagen2026-10-24 07:23 UTC855
                    },
9bd34e25bb86atagen2026-10-24 07:23 UTC856
                    reply,
9bd34e25bb86atagen2026-10-24 07:23 UTC857
                },
9bd34e25bb86atagen2026-10-24 07:23 UTC858
            ),
9bd34e25bb86atagen2026-10-24 07:23 UTC859
            Command::Account(AccountCommand::ReorderSpaces(order)) => enqueue(
9bd34e25bb86atagen2026-10-24 07:23 UTC860
                &self.mutations,
9bd34e25bb86atagen2026-10-24 07:23 UTC861
                Job {
9bd34e25bb86atagen2026-10-24 07:23 UTC862
                    command: Mutation::ReorderSpaces(order),
9bd34e25bb86atagen2026-10-24 07:23 UTC863
                    reply,
9bd34e25bb86atagen2026-10-24 07:23 UTC864
                },
9bd34e25bb86atagen2026-10-24 07:23 UTC865
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC866
            Command::Account(AccountCommand::RenameDevice {
31ce2453c82fatagen2026-09-24 13:07 UTC867
                device_id,
31ce2453c82fatagen2026-09-24 13:07 UTC868
                display_name,
31ce2453c82fatagen2026-09-24 13:07 UTC869
            }) => self.spawn_command("rename device", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC870
                commands::rename_device(&client, &device_id, &display_name).await
31ce2453c82fatagen2026-09-24 13:07 UTC871
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC872
            Command::Account(AccountCommand::DeleteDevices { device_ids, auth }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC873
                self.spawn_command("delete devices", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC874
                    commands::delete_devices(&client, &device_ids, auth).await
31ce2453c82fatagen2026-09-24 13:07 UTC875
                });
31ce2453c82fatagen2026-09-24 13:07 UTC876
            }
38c4caecdb3datagen2026-09-26 13:35 UTC877
            Command::Room(RoomCommand::Open(room_id)) => {
38c4caecdb3datagen2026-09-26 13:35 UTC878
                if self.config.prepare_to_send {
38c4caecdb3datagen2026-09-26 13:35 UTC879
                    self.prepare_quietly(room_id.clone());
38c4caecdb3datagen2026-09-26 13:35 UTC880
                }
38c4caecdb3datagen2026-09-26 13:35 UTC881
                self.open_room(room_id, reply).await;
38c4caecdb3datagen2026-09-26 13:35 UTC882
            }
31ce2453c82fatagen2026-09-24 13:07 UTC883
            Command::Room(RoomCommand::Close(room_id)) => self.close_room(room_id, reply).await,
38c4caecdb3datagen2026-09-26 13:35 UTC884
            Command::Room(RoomCommand::PrepareToSend(room_id)) => {
38c4caecdb3datagen2026-09-26 13:35 UTC885
                let flight = self.preparations.join(&client, room_id);
38c4caecdb3datagen2026-09-26 13:35 UTC886
                self.spawn_command("prepare to send", reply, flight);
38c4caecdb3datagen2026-09-26 13:35 UTC887
            }
31ce2453c82fatagen2026-09-24 13:07 UTC888
            Command::Room(RoomCommand::SetTyping { room_id, typing }) => {
38c4caecdb3datagen2026-09-26 13:35 UTC889
                if typing && self.config.prepare_to_send {
38c4caecdb3datagen2026-09-26 13:35 UTC890
                    self.prepare_quietly(room_id.clone());
38c4caecdb3datagen2026-09-26 13:35 UTC891
                }
31ce2453c82fatagen2026-09-24 13:07 UTC892
                self.spawn_command("typing", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC893
                    commands::set_typing(&client, &room_id, typing).await
31ce2453c82fatagen2026-09-24 13:07 UTC894
                });
31ce2453c82fatagen2026-09-24 13:07 UTC895
            }
31ce2453c82fatagen2026-09-24 13:07 UTC896
            Command::Room(RoomCommand::CancelSend {
31ce2453c82fatagen2026-09-24 13:07 UTC897
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC898
                transaction_id,
31ce2453c82fatagen2026-09-24 13:07 UTC899
            }) => self.spawn_command("cancel send", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC900
                commands::cancel_send(&client, &room_id, &transaction_id).await
31ce2453c82fatagen2026-09-24 13:07 UTC901
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC902
            Command::Room(RoomCommand::RetrySend {
31ce2453c82fatagen2026-09-24 13:07 UTC903
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC904
                transaction_id,
31ce2453c82fatagen2026-09-24 13:07 UTC905
            }) => self.spawn_command("retry send", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC906
                commands::retry_send(&client, &room_id, &transaction_id).await
31ce2453c82fatagen2026-09-24 13:07 UTC907
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC908
            Command::Room(command) => enqueue(
31ce2453c82fatagen2026-09-24 13:07 UTC909
                &self.mutations,
31ce2453c82fatagen2026-09-24 13:07 UTC910
                Job {
31ce2453c82fatagen2026-09-24 13:07 UTC911
                    command: Mutation::Room(command),
31ce2453c82fatagen2026-09-24 13:07 UTC912
                    reply,
31ce2453c82fatagen2026-09-24 13:07 UTC913
                },
31ce2453c82fatagen2026-09-24 13:07 UTC914
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC915
            Command::Timeline(command) => self.route_timeline(command, reply),
89bc9f8d246datagen2026-10-24 13:40 UTC916
            Command::EventContext(command) => {
da8896938cf0atagen2026-10-25 10:04 UTC917
                let (client, media, contexts) =
da8896938cf0atagen2026-10-25 10:04 UTC918
                    (client.clone(), self.media.clone(), self.contexts.clone());
cbb715e11963atagen2026-10-24 23:24 UTC919
                self.tasks
cbb715e11963atagen2026-10-24 23:24 UTC920
                    .spawn(TaskContext::Command("event context"), async move {
da8896938cf0atagen2026-10-25 10:04 UTC921
                        reply.send(context::execute(client, media, contexts, command).await);
cbb715e11963atagen2026-10-24 23:24 UTC922
                    });
cbb715e11963atagen2026-10-24 23:24 UTC923
            }
cbb715e11963atagen2026-10-24 23:24 UTC924
            Command::Mentions(command) => {
cbb715e11963atagen2026-10-24 23:24 UTC925
                let mentions = self.mentions.clone();
cbb715e11963atagen2026-10-24 23:24 UTC926
                self.tasks
cbb715e11963atagen2026-10-24 23:24 UTC927
                    .spawn(TaskContext::Command("mentions command"), async move {
cbb715e11963atagen2026-10-24 23:24 UTC928
                        reply.send(mentions.execute(command).await);
cbb715e11963atagen2026-10-24 23:24 UTC929
                    });
89bc9f8d246datagen2026-10-24 13:40 UTC930
            }
c9effeac326aatagen2026-10-25 10:32 UTC931
            Command::Search(command) => {
c9effeac326aatagen2026-10-25 10:32 UTC932
                let search = self.search.clone();
c9effeac326aatagen2026-10-25 10:32 UTC933
                self.tasks
c9effeac326aatagen2026-10-25 10:32 UTC934
                    .spawn(TaskContext::Command("search command"), async move {
c9effeac326aatagen2026-10-25 10:32 UTC935
                        reply.send(search.execute(command).await);
c9effeac326aatagen2026-10-25 10:32 UTC936
                    });
c9effeac326aatagen2026-10-25 10:32 UTC937
            }
80381e06a573atagen2026-10-25 03:02 UTC938
            Command::HistoryRepair(command) => self.route_repair(command, reply),
31ce2453c82fatagen2026-09-24 13:07 UTC939
            Command::Media(MediaCommand::Upload(upload)) => self.upload(upload, reply),
31ce2453c82fatagen2026-09-24 13:07 UTC940
            Command::Encryption(command) => enqueue(&self.encryption, Job { command, reply }),
31ce2453c82fatagen2026-09-24 13:07 UTC941
            Command::Notification(command) => {
31ce2453c82fatagen2026-09-24 13:07 UTC942
                enqueue(&self.notifications, Job { command, reply });
31ce2453c82fatagen2026-09-24 13:07 UTC943
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC944
            Command::Pack(command) => self.pack(command, reply),
66db1b3cd895atagen2026-10-25 10:28 UTC945
            Command::ThreadList(command) => enqueue(&self.thread_lists, Job { command, reply }),
31ce2453c82fatagen2026-09-24 13:07 UTC946
        }
31ce2453c82fatagen2026-09-24 13:07 UTC947
        None
31ce2453c82fatagen2026-09-24 13:07 UTC948
    }
31ce2453c82fatagen2026-09-24 13:07 UTC949
31ce2453c82fatagen2026-09-24 13:07 UTC950
    fn spawn_command(
31ce2453c82fatagen2026-09-24 13:07 UTC951
        &mut self,
31ce2453c82fatagen2026-09-24 13:07 UTC952
        label: &'static str,
31ce2453c82fatagen2026-09-24 13:07 UTC953
        reply: Responder,
1fe480c16a3catagen2026-09-26 08:44 UTC954
        work: impl Future<Output = Result<(), Error>> + SendOutsideWasm + 'static,
31ce2453c82fatagen2026-09-24 13:07 UTC955
    ) {
31ce2453c82fatagen2026-09-24 13:07 UTC956
        self.tasks.spawn(TaskContext::Command(label), async move {
31ce2453c82fatagen2026-09-24 13:07 UTC957
            reply.done(work.await);
31ce2453c82fatagen2026-09-24 13:07 UTC958
        });
31ce2453c82fatagen2026-09-24 13:07 UTC959
    }
31ce2453c82fatagen2026-09-24 13:07 UTC960
38c4caecdb3datagen2026-09-26 13:35 UTC961
    fn prepare_quietly(&mut self, room_id: OwnedRoomId) {
38c4caecdb3datagen2026-09-26 13:35 UTC962
        let flight = self.preparations.join(&self.client, room_id);
38c4caecdb3datagen2026-09-26 13:35 UTC963
        self.tasks
38c4caecdb3datagen2026-09-26 13:35 UTC964
            .spawn(TaskContext::Command("prepare to send"), async move {
38c4caecdb3datagen2026-09-26 13:35 UTC965
                let _ = flight.await;
38c4caecdb3datagen2026-09-26 13:35 UTC966
            });
38c4caecdb3datagen2026-09-26 13:35 UTC967
    }
38c4caecdb3datagen2026-09-26 13:35 UTC968
fa51490b6ae9atagen2026-10-24 08:41 UTC969
    fn pack(&mut self, command: PackCommand, reply: Responder) {
fa51490b6ae9atagen2026-10-24 08:41 UTC970
        let edit = |pack, edit| Mutation::Pack { pack, edit };
fa51490b6ae9atagen2026-10-24 08:41 UTC971
        let mutation = match command {
fa51490b6ae9atagen2026-10-24 08:41 UTC972
            PackCommand::CreateRoomPack {
fa51490b6ae9atagen2026-10-24 08:41 UTC973
                room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC974
                state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC975
                display_name,
fa51490b6ae9atagen2026-10-24 08:41 UTC976
            } => edit(
fa51490b6ae9atagen2026-10-24 08:41 UTC977
                ImagePackSource::Room { room_id, state_key },
fa51490b6ae9atagen2026-10-24 08:41 UTC978
                PackEdit::Create { display_name },
fa51490b6ae9atagen2026-10-24 08:41 UTC979
            ),
fa51490b6ae9atagen2026-10-24 08:41 UTC980
            PackCommand::Delete(pack) => edit(pack, PackEdit::Delete),
fa51490b6ae9atagen2026-10-24 08:41 UTC981
            PackCommand::SetMeta {
fa51490b6ae9atagen2026-10-24 08:41 UTC982
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC983
                display_name,
fa51490b6ae9atagen2026-10-24 08:41 UTC984
                avatar,
fa51490b6ae9atagen2026-10-24 08:41 UTC985
                usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC986
            } => edit(
fa51490b6ae9atagen2026-10-24 08:41 UTC987
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC988
                PackEdit::Meta {
fa51490b6ae9atagen2026-10-24 08:41 UTC989
                    display_name,
fa51490b6ae9atagen2026-10-24 08:41 UTC990
                    avatar,
fa51490b6ae9atagen2026-10-24 08:41 UTC991
                    usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC992
                },
fa51490b6ae9atagen2026-10-24 08:41 UTC993
            ),
fa51490b6ae9atagen2026-10-24 08:41 UTC994
            PackCommand::PutImage {
fa51490b6ae9atagen2026-10-24 08:41 UTC995
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC996
                shortcode,
fa51490b6ae9atagen2026-10-24 08:41 UTC997
                mxc,
fa51490b6ae9atagen2026-10-24 08:41 UTC998
                body,
fa51490b6ae9atagen2026-10-24 08:41 UTC999
                usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC1000
                info,
fa51490b6ae9atagen2026-10-24 08:41 UTC1001
            } => edit(
fa51490b6ae9atagen2026-10-24 08:41 UTC1002
                pack,
fa51490b6ae9atagen2026-10-24 08:41 UTC1003
                PackEdit::Put {
fa51490b6ae9atagen2026-10-24 08:41 UTC1004
                    shortcode,
fa51490b6ae9atagen2026-10-24 08:41 UTC1005
                    mxc,
fa51490b6ae9atagen2026-10-24 08:41 UTC1006
                    body,
fa51490b6ae9atagen2026-10-24 08:41 UTC1007
                    usage,
fa51490b6ae9atagen2026-10-24 08:41 UTC1008
                    info,
fa51490b6ae9atagen2026-10-24 08:41 UTC1009
                },
fa51490b6ae9atagen2026-10-24 08:41 UTC1010
            ),
fa51490b6ae9atagen2026-10-24 08:41 UTC1011
            PackCommand::RenameImage { pack, from, to } => {
fa51490b6ae9atagen2026-10-24 08:41 UTC1012
                edit(pack, PackEdit::Rename { from, to })
fa51490b6ae9atagen2026-10-24 08:41 UTC1013
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC1014
            PackCommand::RemoveImage { pack, shortcode } => {
fa51490b6ae9atagen2026-10-24 08:41 UTC1015
                edit(pack, PackEdit::Remove { shortcode })
fa51490b6ae9atagen2026-10-24 08:41 UTC1016
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC1017
            PackCommand::SetEnabledEverywhere {
fa51490b6ae9atagen2026-10-24 08:41 UTC1018
                room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC1019
                state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC1020
                enabled,
fa51490b6ae9atagen2026-10-24 08:41 UTC1021
            } => Mutation::PackEnabledEverywhere {
fa51490b6ae9atagen2026-10-24 08:41 UTC1022
                room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC1023
                state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC1024
                enabled,
fa51490b6ae9atagen2026-10-24 08:41 UTC1025
            },
fa51490b6ae9atagen2026-10-24 08:41 UTC1026
            command => {
fa51490b6ae9atagen2026-10-24 08:41 UTC1027
                let client = self.client.clone();
fa51490b6ae9atagen2026-10-24 08:41 UTC1028
                let mutations = self.mutations.clone();
fa51490b6ae9atagen2026-10-24 08:41 UTC1029
                let max_bytes = self.config.max_media_bytes;
fa51490b6ae9atagen2026-10-24 08:41 UTC1030
                self.tasks.spawn(TaskContext::Command("pack"), async move {
fa51490b6ae9atagen2026-10-24 08:41 UTC1031
                    reply.send(packs::run_detached(client, mutations, max_bytes, command).await);
fa51490b6ae9atagen2026-10-24 08:41 UTC1032
                });
fa51490b6ae9atagen2026-10-24 08:41 UTC1033
                return;
fa51490b6ae9atagen2026-10-24 08:41 UTC1034
            }
fa51490b6ae9atagen2026-10-24 08:41 UTC1035
        };
fa51490b6ae9atagen2026-10-24 08:41 UTC1036
        enqueue(
fa51490b6ae9atagen2026-10-24 08:41 UTC1037
            &self.mutations,
fa51490b6ae9atagen2026-10-24 08:41 UTC1038
            Job {
fa51490b6ae9atagen2026-10-24 08:41 UTC1039
                command: mutation,
fa51490b6ae9atagen2026-10-24 08:41 UTC1040
                reply,
fa51490b6ae9atagen2026-10-24 08:41 UTC1041
            },
fa51490b6ae9atagen2026-10-24 08:41 UTC1042
        );
fa51490b6ae9atagen2026-10-24 08:41 UTC1043
    }
fa51490b6ae9atagen2026-10-24 08:41 UTC1044
31ce2453c82fatagen2026-09-24 13:07 UTC1045
    fn upload(&mut self, upload: crate::AttachmentUpload, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1046
        let Some(room) = self.client.get_room(upload.timeline_id.room_id()) else {
31ce2453c82fatagen2026-09-24 13:07 UTC1047
            return reply.done(Err(Error::room_unknown()));
31ce2453c82fatagen2026-09-24 13:07 UTC1048
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1049
        let max_bytes = self.config.max_media_bytes;
31ce2453c82fatagen2026-09-24 13:07 UTC1050
        self.spawn_command("upload", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC1051
            media::queue_upload(room, upload, max_bytes).await
31ce2453c82fatagen2026-09-24 13:07 UTC1052
        });
31ce2453c82fatagen2026-09-24 13:07 UTC1053
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1054
31ce2453c82fatagen2026-09-24 13:07 UTC1055
    fn route_timeline(&mut self, command: TimelineCommand, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1056
        let sender = match self.rooms.get(command.room_id()) {
31ce2453c82fatagen2026-09-24 13:07 UTC1057
            Some(RoomSlot::Active { sender, .. }) => Some(sender.clone()),
31ce2453c82fatagen2026-09-24 13:07 UTC1058
            _ => None,
31ce2453c82fatagen2026-09-24 13:07 UTC1059
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1060
        match (sender, command) {
31ce2453c82fatagen2026-09-24 13:07 UTC1061
            (Some(sender), command) => send_actor(&sender, ActorRequest::Execute(command, reply)),
31ce2453c82fatagen2026-09-24 13:07 UTC1062
            (
31ce2453c82fatagen2026-09-24 13:07 UTC1063
                None,
31ce2453c82fatagen2026-09-24 13:07 UTC1064
                TimelineCommand::MarkRead {
31ce2453c82fatagen2026-09-24 13:07 UTC1065
                    timeline_id,
31ce2453c82fatagen2026-09-24 13:07 UTC1066
                    event_id,
31ce2453c82fatagen2026-09-24 13:07 UTC1067
                },
31ce2453c82fatagen2026-09-24 13:07 UTC1068
            ) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1069
                let client = self.client.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC1070
                self.spawn_command("mark read", reply, async move {
31ce2453c82fatagen2026-09-24 13:07 UTC1071
                    commands::mark_read(&client, &timeline_id, event_id).await
31ce2453c82fatagen2026-09-24 13:07 UTC1072
                });
31ce2453c82fatagen2026-09-24 13:07 UTC1073
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1074
            (None, _) => reply.done(Err(Error::new(ErrorKind::RoomNotOpen, "room is not open"))),
31ce2453c82fatagen2026-09-24 13:07 UTC1075
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1076
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1077
80381e06a573atagen2026-10-25 03:02 UTC1078
    fn route_repair(&mut self, command: crate::HistoryRepairCommand, reply: Responder) {
80381e06a573atagen2026-10-25 03:02 UTC1079
        use crate::HistoryRepairCommand;
80381e06a573atagen2026-10-25 03:02 UTC1080
        let room_id = match &command {
d9b96952ec60atagen2026-10-25 09:07 UTC1081
            HistoryRepairCommand::Cancel { room_id }
d9b96952ec60atagen2026-10-25 09:07 UTC1082
            | HistoryRepairCommand::RetryRecent { room_id }
c9f0fd0ee1ccatagen2026-10-25 06:16 UTC1083
            | HistoryRepairCommand::FillGap { room_id, .. } => room_id,
80381e06a573atagen2026-10-25 03:02 UTC1084
        };
80381e06a573atagen2026-10-25 03:02 UTC1085
        match self.rooms.get(room_id) {
80381e06a573atagen2026-10-25 03:02 UTC1086
            Some(RoomSlot::Active { sender, .. }) => {
80381e06a573atagen2026-10-25 03:02 UTC1087
                send_actor(sender, ActorRequest::Repair(command, reply))
80381e06a573atagen2026-10-25 03:02 UTC1088
            }
80381e06a573atagen2026-10-25 03:02 UTC1089
            Some(RoomSlot::Closing { .. }) => {
80381e06a573atagen2026-10-25 03:02 UTC1090
                reply.done(Err(Error::new(ErrorKind::RoomBusy, "room is closing")))
80381e06a573atagen2026-10-25 03:02 UTC1091
            }
80381e06a573atagen2026-10-25 03:02 UTC1092
            None => reply.done(Err(Error::new(ErrorKind::RoomNotOpen, "room is not open"))),
80381e06a573atagen2026-10-25 03:02 UTC1093
        }
80381e06a573atagen2026-10-25 03:02 UTC1094
    }
80381e06a573atagen2026-10-25 03:02 UTC1095
31ce2453c82fatagen2026-09-24 13:07 UTC1096
    async fn open_room(&mut self, room_id: OwnedRoomId, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1097
        match self.rooms.get_mut(&room_id) {
31ce2453c82fatagen2026-09-24 13:07 UTC1098
            Some(RoomSlot::Active { sender, .. }) => send_actor(sender, ActorRequest::Open(reply)),
31ce2453c82fatagen2026-09-24 13:07 UTC1099
            Some(RoomSlot::Closing { pending, .. }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1100
                defer(pending, Deferred::Open(reply), self.config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC1101
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1102
            None => self.start_actor(room_id, reply).await,
31ce2453c82fatagen2026-09-24 13:07 UTC1103
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1104
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1105
31ce2453c82fatagen2026-09-24 13:07 UTC1106
    async fn close_room(&mut self, room_id: OwnedRoomId, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1107
        let (generation, sender) = match self.rooms.get_mut(&room_id) {
31ce2453c82fatagen2026-09-24 13:07 UTC1108
            None => return reply.done(Ok(())),
31ce2453c82fatagen2026-09-24 13:07 UTC1109
            Some(RoomSlot::Closing { pending, .. }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1110
                return defer(
31ce2453c82fatagen2026-09-24 13:07 UTC1111
                    pending,
31ce2453c82fatagen2026-09-24 13:07 UTC1112
                    Deferred::Close(reply),
31ce2453c82fatagen2026-09-24 13:07 UTC1113
                    self.config.command_capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC1114
                );
31ce2453c82fatagen2026-09-24 13:07 UTC1115
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1116
            Some(RoomSlot::Active { generation, sender }) => (*generation, sender.clone()),
31ce2453c82fatagen2026-09-24 13:07 UTC1117
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1118
        match sender.try_send(ActorRequest::Close(reply)) {
5a52012c9b1datagen2026-09-24 23:45 UTC1119
            Ok(()) => {}
5a52012c9b1datagen2026-09-24 23:45 UTC1120
            // the actor already left on its own, which is closed enough
5a52012c9b1datagen2026-09-24 23:45 UTC1121
            Err(mpsc::error::TrySendError::Closed(request)) => request.into_reply().done(Ok(())),
31ce2453c82fatagen2026-09-24 13:07 UTC1122
            Err(mpsc::error::TrySendError::Full(request)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC1123
                return request.into_reply().done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC1124
                    ErrorKind::RoomBusy,
31ce2453c82fatagen2026-09-24 13:07 UTC1125
                    "room command queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC1126
                )));
31ce2453c82fatagen2026-09-24 13:07 UTC1127
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1128
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1129
        self.rooms.insert(
31ce2453c82fatagen2026-09-24 13:07 UTC1130
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC1131
            RoomSlot::Closing {
31ce2453c82fatagen2026-09-24 13:07 UTC1132
                generation,
31ce2453c82fatagen2026-09-24 13:07 UTC1133
                pending: VecDeque::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC1134
            },
31ce2453c82fatagen2026-09-24 13:07 UTC1135
        );
5a52012c9b1datagen2026-09-24 23:45 UTC1136
        self.update_room_subscriptions();
31ce2453c82fatagen2026-09-24 13:07 UTC1137
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1138
31ce2453c82fatagen2026-09-24 13:07 UTC1139
    async fn start_actor(&mut self, room_id: OwnedRoomId, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC1140
        let Some(room) = self.client.get_room(&room_id) else {
31ce2453c82fatagen2026-09-24 13:07 UTC1141
            return reply.done(Err(Error::room_unknown()));
31ce2453c82fatagen2026-09-24 13:07 UTC1142
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1143
        self.next_generation = self.next_generation.wrapping_add(1);
31ce2453c82fatagen2026-09-24 13:07 UTC1144
        let generation = self.next_generation;
31ce2453c82fatagen2026-09-24 13:07 UTC1145
        let (sender, requests) = mpsc::channel(self.config.command_capacity);
31ce2453c82fatagen2026-09-24 13:07 UTC1146
        let (supervisor, panics) = Supervisor::new();
31ce2453c82fatagen2026-09-24 13:07 UTC1147
        let actor = RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC1148
            room_id: room_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC1149
            generation,
31ce2453c82fatagen2026-09-24 13:07 UTC1150
            room,
31ce2453c82fatagen2026-09-24 13:07 UTC1151
            requests,
5a52012c9b1datagen2026-09-24 23:45 UTC1152
            notes: self.note_sender.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC1153
            context: SessionContext {
31ce2453c82fatagen2026-09-24 13:07 UTC1154
                events: self.port.event_sender(),
31ce2453c82fatagen2026-09-24 13:07 UTC1155
                media: self.media.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC1156
                current_user_id: self.client.user_id().map(ToOwned::to_owned),
31ce2453c82fatagen2026-09-24 13:07 UTC1157
                initial_history_limit: self.config.initial_history_limit,
31ce2453c82fatagen2026-09-24 13:07 UTC1158
                supervisor,
31ce2453c82fatagen2026-09-24 13:07 UTC1159
            },
31ce2453c82fatagen2026-09-24 13:07 UTC1160
            panics,
31ce2453c82fatagen2026-09-24 13:07 UTC1161
            opening: vec![reply],
31ce2453c82fatagen2026-09-24 13:07 UTC1162
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1163
        self.rooms
31ce2453c82fatagen2026-09-24 13:07 UTC1164
            .insert(room_id.clone(), RoomSlot::Active { generation, sender });
31ce2453c82fatagen2026-09-24 13:07 UTC1165
        self.tasks.spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC1166
            TaskContext::RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC1167
                room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC1168
                generation,
31ce2453c82fatagen2026-09-24 13:07 UTC1169
            },
31ce2453c82fatagen2026-09-24 13:07 UTC1170
            actor.run(),
31ce2453c82fatagen2026-09-24 13:07 UTC1171
        );
5a52012c9b1datagen2026-09-24 23:45 UTC1172
        self.update_room_subscriptions();
31ce2453c82fatagen2026-09-24 13:07 UTC1173
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1174
5a52012c9b1datagen2026-09-24 23:45 UTC1175
    async fn actor_note(&mut self, note: ActorNote) {
5a52012c9b1datagen2026-09-24 23:45 UTC1176
        let (room_id, generation) = match &note {
5a52012c9b1datagen2026-09-24 23:45 UTC1177
            ActorNote::Leaving {
5a52012c9b1datagen2026-09-24 23:45 UTC1178
                room_id,
5a52012c9b1datagen2026-09-24 23:45 UTC1179
                generation,
5a52012c9b1datagen2026-09-24 23:45 UTC1180
            }
5a52012c9b1datagen2026-09-24 23:45 UTC1181
            | ActorNote::Exited {
5a52012c9b1datagen2026-09-24 23:45 UTC1182
                room_id,
5a52012c9b1datagen2026-09-24 23:45 UTC1183
                generation,
5a52012c9b1datagen2026-09-24 23:45 UTC1184
                ..
5a52012c9b1datagen2026-09-24 23:45 UTC1185
            } => (room_id.clone(), *generation),
5a52012c9b1datagen2026-09-24 23:45 UTC1186
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1187
        if self
31ce2453c82fatagen2026-09-24 13:07 UTC1188
            .rooms
31ce2453c82fatagen2026-09-24 13:07 UTC1189
            .get(&room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC1190
            .is_none_or(|slot| slot.generation() != generation)
31ce2453c82fatagen2026-09-24 13:07 UTC1191
        {
31ce2453c82fatagen2026-09-24 13:07 UTC1192
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC1193
        }
5a52012c9b1datagen2026-09-24 23:45 UTC1194
        let ActorNote::Exited { leftovers, .. } = note else {
5a52012c9b1datagen2026-09-24 23:45 UTC1195
            if let Some(slot @ RoomSlot::Active { .. }) = self.rooms.get_mut(&room_id) {
5a52012c9b1datagen2026-09-24 23:45 UTC1196
                *slot = RoomSlot::Closing {
5a52012c9b1datagen2026-09-24 23:45 UTC1197
                    generation,
5a52012c9b1datagen2026-09-24 23:45 UTC1198
                    pending: VecDeque::new(),
5a52012c9b1datagen2026-09-24 23:45 UTC1199
                };
5a52012c9b1datagen2026-09-24 23:45 UTC1200
                self.update_room_subscriptions();
5a52012c9b1datagen2026-09-24 23:45 UTC1201
            }
5a52012c9b1datagen2026-09-24 23:45 UTC1202
            return;
5a52012c9b1datagen2026-09-24 23:45 UTC1203
        };
5a52012c9b1datagen2026-09-24 23:45 UTC1204
        let pending = match self.rooms.remove(&room_id) {
5a52012c9b1datagen2026-09-24 23:45 UTC1205
            Some(RoomSlot::Closing { pending, .. }) => pending,
5a52012c9b1datagen2026-09-24 23:45 UTC1206
            _ => VecDeque::new(),
5a52012c9b1datagen2026-09-24 23:45 UTC1207
        };
5a52012c9b1datagen2026-09-24 23:45 UTC1208
        // leftovers were sent before anything deferred, so they go first
5a52012c9b1datagen2026-09-24 23:45 UTC1209
        for request in leftovers {
5a52012c9b1datagen2026-09-24 23:45 UTC1210
            match request {
5a52012c9b1datagen2026-09-24 23:45 UTC1211
                ActorRequest::Open(reply) => self.open_room(room_id.clone(), reply).await,
5a52012c9b1datagen2026-09-24 23:45 UTC1212
                ActorRequest::Close(reply) => reply.done(Ok(())),
5a52012c9b1datagen2026-09-24 23:45 UTC1213
                ActorRequest::Execute(command, reply) => self.route_timeline(command, reply),
80381e06a573atagen2026-10-25 03:02 UTC1214
                ActorRequest::Repair(command, reply) => self.route_repair(command, reply),
31ce2453c82fatagen2026-09-24 13:07 UTC1215
            }
31ce2453c82fatagen2026-09-24 13:07 UTC1216
        }
5a52012c9b1datagen2026-09-24 23:45 UTC1217
        for deferred in pending {
5a52012c9b1datagen2026-09-24 23:45 UTC1218
            match deferred {
5a52012c9b1datagen2026-09-24 23:45 UTC1219
                Deferred::Open(reply) => self.open_room(room_id.clone(), reply).await,
5a52012c9b1datagen2026-09-24 23:45 UTC1220
                Deferred::Close(reply) => self.close_room(room_id.clone(), reply).await,
5a52012c9b1datagen2026-09-24 23:45 UTC1221
            }
5a52012c9b1datagen2026-09-24 23:45 UTC1222
        }
5a52012c9b1datagen2026-09-24 23:45 UTC1223
        self.update_room_subscriptions();
31ce2453c82fatagen2026-09-24 13:07 UTC1224
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1225
5a52012c9b1datagen2026-09-24 23:45 UTC1226
    fn update_room_subscriptions(&self) {
31ce2453c82fatagen2026-09-24 13:07 UTC1227
        let room_ids = self
31ce2453c82fatagen2026-09-24 13:07 UTC1228
            .rooms
31ce2453c82fatagen2026-09-24 13:07 UTC1229
            .iter()
31ce2453c82fatagen2026-09-24 13:07 UTC1230
            .filter(|(_, slot)| matches!(slot, RoomSlot::Active { .. }))
5a52012c9b1datagen2026-09-24 23:45 UTC1231
            .map(|(room_id, _)| room_id.clone())
5a52012c9b1datagen2026-09-24 23:45 UTC1232
            .collect();
5a52012c9b1datagen2026-09-24 23:45 UTC1233
        self.subscriptions.send_replace(room_ids);
31ce2453c82fatagen2026-09-24 13:07 UTC1234
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1235
31ce2453c82fatagen2026-09-24 13:07 UTC1236
    async fn shutdown(&mut self) {
5a52012c9b1datagen2026-09-24 23:45 UTC1237
        if let Some(handler) = self.verification_handler.take() {
5a52012c9b1datagen2026-09-24 23:45 UTC1238
            self.client.remove_event_handler(handler);
5a52012c9b1datagen2026-09-24 23:45 UTC1239
        }
31ce2453c82fatagen2026-09-24 13:07 UTC1240
        self.port.close();
3dab4a4e73f4atagen2026-10-28 06:21 UTC1241
        tracing::debug!(step = "sync", "engine shutdown step");
cbb715e11963atagen2026-10-24 23:24 UTC1242
        self.sync.stop().await;
cbb715e11963atagen2026-10-24 23:24 UTC1243
        if self.mentions_service.is_none() {
3dab4a4e73f4atagen2026-10-28 06:21 UTC1244
            tracing::debug!(step = "mentions", "engine shutdown step");
cbb715e11963atagen2026-10-24 23:24 UTC1245
            self.mentions.stop().await;
cbb715e11963atagen2026-10-24 23:24 UTC1246
        }
c9effeac326aatagen2026-10-25 10:32 UTC1247
        if self.search_service.is_none() {
3dab4a4e73f4atagen2026-10-28 06:21 UTC1248
            tracing::debug!(step = "search", "engine shutdown step");
c9effeac326aatagen2026-10-25 10:32 UTC1249
            self.search.stop().await;
c9effeac326aatagen2026-10-25 10:32 UTC1250
        }
3dab4a4e73f4atagen2026-10-28 06:21 UTC1251
        tracing::debug!(step = "tasks", "engine shutdown step");
31ce2453c82fatagen2026-09-24 13:07 UTC1252
        self.tasks.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC1253
        self.rooms.clear();
3dab4a4e73f4atagen2026-10-28 06:21 UTC1254
        tracing::debug!(step = "contexts", "engine shutdown step");
da8896938cf0atagen2026-10-25 10:04 UTC1255
        self.contexts.clear().await;
3dab4a4e73f4atagen2026-10-28 06:21 UTC1256
        tracing::debug!(step = "media", "engine shutdown step");
31ce2453c82fatagen2026-09-24 13:07 UTC1257
        self.media.clear().await;
3dab4a4e73f4atagen2026-10-28 06:21 UTC1258
        tracing::debug!(step = "done", "engine shutdown step");
31ce2453c82fatagen2026-09-24 13:07 UTC1259
        self.port
31ce2453c82fatagen2026-09-24 13:07 UTC1260
            .connection_sender()
31ce2453c82fatagen2026-09-24 13:07 UTC1261
            .send_replace(ConnectionState::Stopped);
31ce2453c82fatagen2026-09-24 13:07 UTC1262
        let _ = self
31ce2453c82fatagen2026-09-24 13:07 UTC1263
            .port
31ce2453c82fatagen2026-09-24 13:07 UTC1264
            .event_sender()
31ce2453c82fatagen2026-09-24 13:07 UTC1265
            .send(Event::ConnectionChanged(ConnectionState::Stopped))
31ce2453c82fatagen2026-09-24 13:07 UTC1266
            .await;
31ce2453c82fatagen2026-09-24 13:07 UTC1267
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1268
}
31ce2453c82fatagen2026-09-24 13:07 UTC1269
31ce2453c82fatagen2026-09-24 13:07 UTC1270
fn send_actor(sender: &mpsc::Sender<ActorRequest>, request: ActorRequest) {
31ce2453c82fatagen2026-09-24 13:07 UTC1271
    if let Err(error) = sender.try_send(request) {
31ce2453c82fatagen2026-09-24 13:07 UTC1272
        let (request, error) = match error {
31ce2453c82fatagen2026-09-24 13:07 UTC1273
            mpsc::error::TrySendError::Full(request) => (
31ce2453c82fatagen2026-09-24 13:07 UTC1274
                request,
31ce2453c82fatagen2026-09-24 13:07 UTC1275
                Error::new(ErrorKind::RoomBusy, "room command queue is full"),
31ce2453c82fatagen2026-09-24 13:07 UTC1276
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC1277
            mpsc::error::TrySendError::Closed(request) => (
31ce2453c82fatagen2026-09-24 13:07 UTC1278
                request,
31ce2453c82fatagen2026-09-24 13:07 UTC1279
                Error::new(ErrorKind::RoomNotOpen, "room is not open"),
31ce2453c82fatagen2026-09-24 13:07 UTC1280
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC1281
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1282
        request.into_reply().done(Err(error));
31ce2453c82fatagen2026-09-24 13:07 UTC1283
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1284
}
31ce2453c82fatagen2026-09-24 13:07 UTC1285
31ce2453c82fatagen2026-09-24 13:07 UTC1286
fn defer(pending: &mut VecDeque<Deferred>, deferred: Deferred, capacity: usize) {
31ce2453c82fatagen2026-09-24 13:07 UTC1287
    if pending.len() < capacity {
31ce2453c82fatagen2026-09-24 13:07 UTC1288
        return pending.push_back(deferred);
31ce2453c82fatagen2026-09-24 13:07 UTC1289
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1290
    let (Deferred::Open(reply) | Deferred::Close(reply)) = deferred;
31ce2453c82fatagen2026-09-24 13:07 UTC1291
    reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC1292
        ErrorKind::RoomBusy,
31ce2453c82fatagen2026-09-24 13:07 UTC1293
        "room lifecycle queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC1294
    )));
31ce2453c82fatagen2026-09-24 13:07 UTC1295
}
31ce2453c82fatagen2026-09-24 13:07 UTC1296
673563a76e43atagen2026-09-26 12:30 UTC1297
async fn settled(logouts: &mut watch::Receiver<Logouts>) {
673563a76e43atagen2026-09-26 12:30 UTC1298
    let _ = logouts.wait_for(|logouts| logouts.in_flight == 0).await;
673563a76e43atagen2026-09-26 12:30 UTC1299
}
673563a76e43atagen2026-09-26 12:30 UTC1300
31ce2453c82fatagen2026-09-24 13:07 UTC1301
fn enqueue<T>(sender: &mpsc::Sender<Job<T>>, job: Job<T>) {
31ce2453c82fatagen2026-09-24 13:07 UTC1302
    if let Err(error) = sender.try_send(job) {
31ce2453c82fatagen2026-09-24 13:07 UTC1303
        let (job, error) = match error {
31ce2453c82fatagen2026-09-24 13:07 UTC1304
            mpsc::error::TrySendError::Full(job) => (
31ce2453c82fatagen2026-09-24 13:07 UTC1305
                job,
31ce2453c82fatagen2026-09-24 13:07 UTC1306
                Error::new(ErrorKind::QueueFull, "command queue is full"),
31ce2453c82fatagen2026-09-24 13:07 UTC1307
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC1308
            mpsc::error::TrySendError::Closed(job) => (job, Error::interrupted()),
31ce2453c82fatagen2026-09-24 13:07 UTC1309
        };
31ce2453c82fatagen2026-09-24 13:07 UTC1310
        job.reply.done(Err(error));
31ce2453c82fatagen2026-09-24 13:07 UTC1311
    }
31ce2453c82fatagen2026-09-24 13:07 UTC1312
}