atagen

macltok

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