atagen

macltok

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

Blame: src/engine/room.rs

31ce2453c82fatagen2026-09-24 13:07 UTC1
use std::collections::{HashMap, VecDeque};
31ce2453c82fatagen2026-09-24 13:07 UTC2
31ce2453c82fatagen2026-09-24 13:07 UTC3
use matrix_sdk::{Room, RoomState};
31ce2453c82fatagen2026-09-24 13:07 UTC4
use matrix_sdk_ui::timeline::{RoomExt, Timeline, TimelineFocus, TimelineReadReceiptTracking};
31ce2453c82fatagen2026-09-24 13:07 UTC5
use ruma::{OwnedEventId, OwnedRoomId};
1fe480c16a3catagen2026-09-26 08:44 UTC6
use tokio::sync::mpsc;
31ce2453c82fatagen2026-09-24 13:07 UTC7
1fe480c16a3catagen2026-09-26 08:44 UTC8
use super::executor::{AbortHandle, JoinError, TaskSet, is_panic, resume_unwind};
5a52012c9b1datagen2026-09-24 23:45 UTC9
use super::timeline::{SessionContext, TaskGuard, TimelineSession};
31ce2453c82fatagen2026-09-24 13:07 UTC10
use crate::{
31ce2453c82fatagen2026-09-24 13:07 UTC11
    Error, ErrorKind, Event, TimelineCommand, TimelineId, TypingState, transport::Responder,
31ce2453c82fatagen2026-09-24 13:07 UTC12
};
31ce2453c82fatagen2026-09-24 13:07 UTC13
31ce2453c82fatagen2026-09-24 13:07 UTC14
pub(super) enum ActorRequest {
31ce2453c82fatagen2026-09-24 13:07 UTC15
    /// opening an open room answers with a fresh reset
31ce2453c82fatagen2026-09-24 13:07 UTC16
    Open(Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC17
    Execute(TimelineCommand, Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC18
    Close(Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC19
}
31ce2453c82fatagen2026-09-24 13:07 UTC20
31ce2453c82fatagen2026-09-24 13:07 UTC21
impl ActorRequest {
31ce2453c82fatagen2026-09-24 13:07 UTC22
    pub(super) fn into_reply(self) -> Responder {
31ce2453c82fatagen2026-09-24 13:07 UTC23
        match self {
31ce2453c82fatagen2026-09-24 13:07 UTC24
            Self::Open(reply) | Self::Execute(_, reply) | Self::Close(reply) => reply,
31ce2453c82fatagen2026-09-24 13:07 UTC25
        }
31ce2453c82fatagen2026-09-24 13:07 UTC26
    }
31ce2453c82fatagen2026-09-24 13:07 UTC27
}
31ce2453c82fatagen2026-09-24 13:07 UTC28
5a52012c9b1datagen2026-09-24 23:45 UTC29
pub(super) enum ActorNote {
5a52012c9b1datagen2026-09-24 23:45 UTC30
    /// stopping on its own, after a leave or a kick. anything sent its way now comes back in `Exited`
5a52012c9b1datagen2026-09-24 23:45 UTC31
    Leaving {
5a52012c9b1datagen2026-09-24 23:45 UTC32
        room_id: OwnedRoomId,
5a52012c9b1datagen2026-09-24 23:45 UTC33
        generation: u64,
5a52012c9b1datagen2026-09-24 23:45 UTC34
    },
5a52012c9b1datagen2026-09-24 23:45 UTC35
    Exited {
5a52012c9b1datagen2026-09-24 23:45 UTC36
        room_id: OwnedRoomId,
5a52012c9b1datagen2026-09-24 23:45 UTC37
        generation: u64,
5a52012c9b1datagen2026-09-24 23:45 UTC38
        /// requests that arrived too late to be served, for the engine to answer or replay
5a52012c9b1datagen2026-09-24 23:45 UTC39
        leftovers: Vec<ActorRequest>,
5a52012c9b1datagen2026-09-24 23:45 UTC40
    },
31ce2453c82fatagen2026-09-24 13:07 UTC41
}
31ce2453c82fatagen2026-09-24 13:07 UTC42
31ce2453c82fatagen2026-09-24 13:07 UTC43
pub(super) struct RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC44
    pub(super) room_id: OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC45
    pub(super) generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC46
    pub(super) room: Room,
31ce2453c82fatagen2026-09-24 13:07 UTC47
    pub(super) requests: mpsc::Receiver<ActorRequest>,
5a52012c9b1datagen2026-09-24 23:45 UTC48
    pub(super) notes: mpsc::UnboundedSender<ActorNote>,
31ce2453c82fatagen2026-09-24 13:07 UTC49
    pub(super) context: SessionContext,
31ce2453c82fatagen2026-09-24 13:07 UTC50
    pub(super) panics: mpsc::UnboundedReceiver<&'static str>,
31ce2453c82fatagen2026-09-24 13:07 UTC51
    pub(super) opening: Vec<Responder>,
31ce2453c82fatagen2026-09-24 13:07 UTC52
}
31ce2453c82fatagen2026-09-24 13:07 UTC53
31ce2453c82fatagen2026-09-24 13:07 UTC54
impl RoomActor {
31ce2453c82fatagen2026-09-24 13:07 UTC55
    pub(super) async fn run(mut self) {
5a52012c9b1datagen2026-09-24 23:45 UTC56
        self.serve().await;
5a52012c9b1datagen2026-09-24 23:45 UTC57
        self.requests.close();
5a52012c9b1datagen2026-09-24 23:45 UTC58
        let mut leftovers = Vec::new();
5a52012c9b1datagen2026-09-24 23:45 UTC59
        while let Ok(request) = self.requests.try_recv() {
5a52012c9b1datagen2026-09-24 23:45 UTC60
            leftovers.push(request);
5a52012c9b1datagen2026-09-24 23:45 UTC61
        }
5a52012c9b1datagen2026-09-24 23:45 UTC62
        let _ = self.notes.send(ActorNote::Exited {
31ce2453c82fatagen2026-09-24 13:07 UTC63
            room_id: self.room_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC64
            generation: self.generation,
5a52012c9b1datagen2026-09-24 23:45 UTC65
            leftovers,
5a52012c9b1datagen2026-09-24 23:45 UTC66
        });
31ce2453c82fatagen2026-09-24 13:07 UTC67
    }
31ce2453c82fatagen2026-09-24 13:07 UTC68
31ce2453c82fatagen2026-09-24 13:07 UTC69
    async fn serve(&mut self) {
31ce2453c82fatagen2026-09-24 13:07 UTC70
        let timeline = match build_timeline(
31ce2453c82fatagen2026-09-24 13:07 UTC71
            &self.room,
31ce2453c82fatagen2026-09-24 13:07 UTC72
            TimelineFocus::Live {
31ce2453c82fatagen2026-09-24 13:07 UTC73
                hide_threaded_events: true,
31ce2453c82fatagen2026-09-24 13:07 UTC74
            },
31ce2453c82fatagen2026-09-24 13:07 UTC75
        )
31ce2453c82fatagen2026-09-24 13:07 UTC76
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC77
        {
31ce2453c82fatagen2026-09-24 13:07 UTC78
            Ok(timeline) => timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC79
            Err(error) => return self.refuse_everything(error).await,
31ce2453c82fatagen2026-09-24 13:07 UTC80
        };
31ce2453c82fatagen2026-09-24 13:07 UTC81
        let Ok(room_timeline) = TimelineSession::start(
31ce2453c82fatagen2026-09-24 13:07 UTC82
            TimelineId::Room(self.room_id.clone()),
31ce2453c82fatagen2026-09-24 13:07 UTC83
            timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC84
            self.context.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC85
        )
31ce2453c82fatagen2026-09-24 13:07 UTC86
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC87
        else {
31ce2453c82fatagen2026-09-24 13:07 UTC88
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC89
        };
31ce2453c82fatagen2026-09-24 13:07 UTC90
        for reply in self.opening.drain(..) {
31ce2453c82fatagen2026-09-24 13:07 UTC91
            reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC92
        }
31ce2453c82fatagen2026-09-24 13:07 UTC93
        let (typing_guard, typing) = self.room.subscribe_to_typing_notifications();
5a52012c9b1datagen2026-09-24 23:45 UTC94
        let typing_watcher = TaskGuard(self.context.supervisor.spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC95
            "typing watcher",
31ce2453c82fatagen2026-09-24 13:07 UTC96
            watch_typing(self.room_id.clone(), typing, self.context.events.clone()),
5a52012c9b1datagen2026-09-24 23:45 UTC97
        ));
31ce2453c82fatagen2026-09-24 13:07 UTC98
        let mut timelines = Timelines {
31ce2453c82fatagen2026-09-24 13:07 UTC99
            room: room_timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC100
            threads: Threads::new(self.requests.max_capacity()),
1fe480c16a3catagen2026-09-26 08:44 UTC101
            work: TaskSet::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC102
        };
31ce2453c82fatagen2026-09-24 13:07 UTC103
        let close = self.serve_open(&mut timelines).await;
5a52012c9b1datagen2026-09-24 23:45 UTC104
        if close.is_none() {
5a52012c9b1datagen2026-09-24 23:45 UTC105
            self.requests.close();
5a52012c9b1datagen2026-09-24 23:45 UTC106
            let _ = self.notes.send(ActorNote::Leaving {
5a52012c9b1datagen2026-09-24 23:45 UTC107
                room_id: self.room_id.clone(),
5a52012c9b1datagen2026-09-24 23:45 UTC108
                generation: self.generation,
5a52012c9b1datagen2026-09-24 23:45 UTC109
            });
5a52012c9b1datagen2026-09-24 23:45 UTC110
        }
31ce2453c82fatagen2026-09-24 13:07 UTC111
31ce2453c82fatagen2026-09-24 13:07 UTC112
        // let redactions and receipts that already left finish rather than lie about them
31ce2453c82fatagen2026-09-24 13:07 UTC113
        while timelines.work.join_next().await.is_some() {}
31ce2453c82fatagen2026-09-24 13:07 UTC114
        drop(typing_guard);
5a52012c9b1datagen2026-09-24 23:45 UTC115
        drop(typing_watcher);
31ce2453c82fatagen2026-09-24 13:07 UTC116
        timelines.threads.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC117
        timelines.room.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC118
        if let Some(reply) = close {
31ce2453c82fatagen2026-09-24 13:07 UTC119
            reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC120
        }
31ce2453c82fatagen2026-09-24 13:07 UTC121
    }
31ce2453c82fatagen2026-09-24 13:07 UTC122
31ce2453c82fatagen2026-09-24 13:07 UTC123
    /// returns the close request's responder, if a close is why we stopped
31ce2453c82fatagen2026-09-24 13:07 UTC124
    async fn serve_open(&mut self, timelines: &mut Timelines) -> Option<Responder> {
31ce2453c82fatagen2026-09-24 13:07 UTC125
        let mut room_info = self.room.subscribe_info();
5a52012c9b1datagen2026-09-24 23:45 UTC126
        // a leave that landed while the timeline was building won't come round again
5a52012c9b1datagen2026-09-24 23:45 UTC127
        if matches!(self.room.state(), RoomState::Left | RoomState::Banned) {
5a52012c9b1datagen2026-09-24 23:45 UTC128
            return None;
5a52012c9b1datagen2026-09-24 23:45 UTC129
        }
31ce2453c82fatagen2026-09-24 13:07 UTC130
        loop {
31ce2453c82fatagen2026-09-24 13:07 UTC131
            tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC132
                Some(info) = room_info.next() => {
31ce2453c82fatagen2026-09-24 13:07 UTC133
                    if matches!(info.state(), RoomState::Left | RoomState::Banned) {
31ce2453c82fatagen2026-09-24 13:07 UTC134
                        tracing::debug!(room_id = %self.room_id, "room actor stopped because we left the room");
31ce2453c82fatagen2026-09-24 13:07 UTC135
                        return None;
31ce2453c82fatagen2026-09-24 13:07 UTC136
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC137
                }
31ce2453c82fatagen2026-09-24 13:07 UTC138
                request = self.requests.recv() => match request {
31ce2453c82fatagen2026-09-24 13:07 UTC139
                    None => return None,
31ce2453c82fatagen2026-09-24 13:07 UTC140
                    Some(ActorRequest::Close(reply)) => return Some(reply),
31ce2453c82fatagen2026-09-24 13:07 UTC141
                    Some(ActorRequest::Open(reply)) => reply.done(timelines.room.resync().await),
31ce2453c82fatagen2026-09-24 13:07 UTC142
                    Some(ActorRequest::Execute(command, reply)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC143
                        timelines.execute(command, reply, &self.room).await;
31ce2453c82fatagen2026-09-24 13:07 UTC144
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC145
                },
31ce2453c82fatagen2026-09-24 13:07 UTC146
                Some(built) = timelines.threads.builds.join_next(), if !timelines.threads.builds.is_empty() => {
31ce2453c82fatagen2026-09-24 13:07 UTC147
                    timelines.thread_built(built, &self.room_id, &self.context).await;
31ce2453c82fatagen2026-09-24 13:07 UTC148
                }
31ce2453c82fatagen2026-09-24 13:07 UTC149
                Some(label) = self.panics.recv() => panic!("{label} panicked in room {}", self.room_id),
31ce2453c82fatagen2026-09-24 13:07 UTC150
                Some(done) = timelines.work.join_next(), if !timelines.work.is_empty() => {
1fe480c16a3catagen2026-09-26 08:44 UTC151
                    if let Err(error) = done && is_panic(&error) {
31ce2453c82fatagen2026-09-24 13:07 UTC152
                        tracing::warn!(room_id = %self.room_id, %error, "timeline operation panicked");
31ce2453c82fatagen2026-09-24 13:07 UTC153
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC154
                }
31ce2453c82fatagen2026-09-24 13:07 UTC155
            }
31ce2453c82fatagen2026-09-24 13:07 UTC156
        }
31ce2453c82fatagen2026-09-24 13:07 UTC157
    }
31ce2453c82fatagen2026-09-24 13:07 UTC158
31ce2453c82fatagen2026-09-24 13:07 UTC159
    async fn refuse_everything(&mut self, error: matrix_sdk_ui::timeline::Error) {
31ce2453c82fatagen2026-09-24 13:07 UTC160
        tracing::warn!(%error, room_id = %self.room_id, "room actor could not build its timeline");
31ce2453c82fatagen2026-09-24 13:07 UTC161
        let error = Error::with_source(ErrorKind::Timeline, "room timeline build failed", error);
31ce2453c82fatagen2026-09-24 13:07 UTC162
        for reply in self.opening.drain(..) {
31ce2453c82fatagen2026-09-24 13:07 UTC163
            reply.done(Err(error.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC164
        }
31ce2453c82fatagen2026-09-24 13:07 UTC165
        self.requests.close();
31ce2453c82fatagen2026-09-24 13:07 UTC166
        while let Some(request) = self.requests.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC167
            request.into_reply().done(Err(error.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC168
        }
31ce2453c82fatagen2026-09-24 13:07 UTC169
    }
31ce2453c82fatagen2026-09-24 13:07 UTC170
}
31ce2453c82fatagen2026-09-24 13:07 UTC171
31ce2453c82fatagen2026-09-24 13:07 UTC172
async fn build_timeline(
31ce2453c82fatagen2026-09-24 13:07 UTC173
    room: &Room,
31ce2453c82fatagen2026-09-24 13:07 UTC174
    focus: TimelineFocus,
31ce2453c82fatagen2026-09-24 13:07 UTC175
) -> Result<Timeline, matrix_sdk_ui::timeline::Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC176
    room.timeline_builder()
31ce2453c82fatagen2026-09-24 13:07 UTC177
        .with_focus(focus)
31ce2453c82fatagen2026-09-24 13:07 UTC178
        .track_read_marker_and_receipts(TimelineReadReceiptTracking::AllEvents)
31ce2453c82fatagen2026-09-24 13:07 UTC179
        .build()
31ce2453c82fatagen2026-09-24 13:07 UTC180
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC181
}
31ce2453c82fatagen2026-09-24 13:07 UTC182
31ce2453c82fatagen2026-09-24 13:07 UTC183
async fn watch_typing(
31ce2453c82fatagen2026-09-24 13:07 UTC184
    room_id: OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC185
    mut typing: tokio::sync::broadcast::Receiver<Vec<ruma::OwnedUserId>>,
31ce2453c82fatagen2026-09-24 13:07 UTC186
    events: crate::transport::EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC187
) {
31ce2453c82fatagen2026-09-24 13:07 UTC188
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC189
        match typing.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC190
            Ok(users) => {
31ce2453c82fatagen2026-09-24 13:07 UTC191
                let state = TypingState {
31ce2453c82fatagen2026-09-24 13:07 UTC192
                    room_id: room_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC193
                    users,
31ce2453c82fatagen2026-09-24 13:07 UTC194
                };
31ce2453c82fatagen2026-09-24 13:07 UTC195
                if events.send(Event::TypingChanged(state)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC196
                    return;
31ce2453c82fatagen2026-09-24 13:07 UTC197
                }
31ce2453c82fatagen2026-09-24 13:07 UTC198
            }
31ce2453c82fatagen2026-09-24 13:07 UTC199
            Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC200
                tracing::warn!(%room_id, skipped, "typing watcher lagged");
31ce2453c82fatagen2026-09-24 13:07 UTC201
            }
31ce2453c82fatagen2026-09-24 13:07 UTC202
            Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
31ce2453c82fatagen2026-09-24 13:07 UTC203
        }
31ce2453c82fatagen2026-09-24 13:07 UTC204
    }
31ce2453c82fatagen2026-09-24 13:07 UTC205
}
31ce2453c82fatagen2026-09-24 13:07 UTC206
31ce2453c82fatagen2026-09-24 13:07 UTC207
struct Timelines {
31ce2453c82fatagen2026-09-24 13:07 UTC208
    room: TimelineSession,
31ce2453c82fatagen2026-09-24 13:07 UTC209
    threads: Threads,
1fe480c16a3catagen2026-09-26 08:44 UTC210
    work: TaskSet<()>,
31ce2453c82fatagen2026-09-24 13:07 UTC211
}
31ce2453c82fatagen2026-09-24 13:07 UTC212
31ce2453c82fatagen2026-09-24 13:07 UTC213
impl Timelines {
31ce2453c82fatagen2026-09-24 13:07 UTC214
    async fn execute(&mut self, command: TimelineCommand, reply: Responder, room: &Room) {
31ce2453c82fatagen2026-09-24 13:07 UTC215
        match command {
31ce2453c82fatagen2026-09-24 13:07 UTC216
            TimelineCommand::OpenThread { root_event_id, .. } => {
31ce2453c82fatagen2026-09-24 13:07 UTC217
                self.threads.open(root_event_id, reply, room);
31ce2453c82fatagen2026-09-24 13:07 UTC218
            }
31ce2453c82fatagen2026-09-24 13:07 UTC219
            TimelineCommand::CloseThread { root_event_id, .. } => {
31ce2453c82fatagen2026-09-24 13:07 UTC220
                reply.done(self.threads.close_one(&root_event_id).await);
31ce2453c82fatagen2026-09-24 13:07 UTC221
            }
31ce2453c82fatagen2026-09-24 13:07 UTC222
            TimelineCommand::Resync {
31ce2453c82fatagen2026-09-24 13:07 UTC223
                timeline_id: TimelineId::Room(_),
31ce2453c82fatagen2026-09-24 13:07 UTC224
            } => reply.done(self.room.resync().await),
31ce2453c82fatagen2026-09-24 13:07 UTC225
            command => {
31ce2453c82fatagen2026-09-24 13:07 UTC226
                let root = command
31ce2453c82fatagen2026-09-24 13:07 UTC227
                    .timeline_id()
31ce2453c82fatagen2026-09-24 13:07 UTC228
                    .and_then(TimelineId::thread_root)
31ce2453c82fatagen2026-09-24 13:07 UTC229
                    .cloned();
31ce2453c82fatagen2026-09-24 13:07 UTC230
                let Some(root) = root else {
31ce2453c82fatagen2026-09-24 13:07 UTC231
                    return self.room.execute(command, reply, &mut self.work).await;
31ce2453c82fatagen2026-09-24 13:07 UTC232
                };
5a52012c9b1datagen2026-09-24 23:45 UTC233
                if let TimelineCommand::MarkRead {
5a52012c9b1datagen2026-09-24 23:45 UTC234
                    timeline_id,
5a52012c9b1datagen2026-09-24 23:45 UTC235
                    event_id,
5a52012c9b1datagen2026-09-24 23:45 UTC236
                } = &command
5a52012c9b1datagen2026-09-24 23:45 UTC237
                    && !self.threads.open.contains_key(&root)
5a52012c9b1datagen2026-09-24 23:45 UTC238
                {
5a52012c9b1datagen2026-09-24 23:45 UTC239
                    let client = room.client();
5a52012c9b1datagen2026-09-24 23:45 UTC240
                    let (timeline_id, event_id) = (timeline_id.clone(), event_id.clone());
5a52012c9b1datagen2026-09-24 23:45 UTC241
                    self.work.spawn(async move {
5a52012c9b1datagen2026-09-24 23:45 UTC242
                        reply.done(
5a52012c9b1datagen2026-09-24 23:45 UTC243
                            super::commands::mark_read(&client, &timeline_id, event_id).await,
5a52012c9b1datagen2026-09-24 23:45 UTC244
                        );
5a52012c9b1datagen2026-09-24 23:45 UTC245
                    });
5a52012c9b1datagen2026-09-24 23:45 UTC246
                    return;
5a52012c9b1datagen2026-09-24 23:45 UTC247
                }
31ce2453c82fatagen2026-09-24 13:07 UTC248
                match self.threads.route(root, command, reply) {
31ce2453c82fatagen2026-09-24 13:07 UTC249
                    Routed::Open(session, TimelineCommand::Resync { .. }, reply) => {
31ce2453c82fatagen2026-09-24 13:07 UTC250
                        reply.done(session.resync().await);
31ce2453c82fatagen2026-09-24 13:07 UTC251
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC252
                    Routed::Open(session, command, reply) => {
31ce2453c82fatagen2026-09-24 13:07 UTC253
                        session.execute(command, reply, &mut self.work).await;
31ce2453c82fatagen2026-09-24 13:07 UTC254
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC255
                    Routed::Queued => {}
31ce2453c82fatagen2026-09-24 13:07 UTC256
                }
31ce2453c82fatagen2026-09-24 13:07 UTC257
            }
31ce2453c82fatagen2026-09-24 13:07 UTC258
        }
31ce2453c82fatagen2026-09-24 13:07 UTC259
    }
31ce2453c82fatagen2026-09-24 13:07 UTC260
31ce2453c82fatagen2026-09-24 13:07 UTC261
    async fn thread_built(
31ce2453c82fatagen2026-09-24 13:07 UTC262
        &mut self,
1fe480c16a3catagen2026-09-26 08:44 UTC263
        built: Result<Built, JoinError>,
31ce2453c82fatagen2026-09-24 13:07 UTC264
        room_id: &OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC265
        context: &SessionContext,
31ce2453c82fatagen2026-09-24 13:07 UTC266
    ) {
31ce2453c82fatagen2026-09-24 13:07 UTC267
        let Some((root, queued, timeline)) = self.threads.built(built) else {
31ce2453c82fatagen2026-09-24 13:07 UTC268
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC269
        };
31ce2453c82fatagen2026-09-24 13:07 UTC270
        let timeline = match timeline {
31ce2453c82fatagen2026-09-24 13:07 UTC271
            Ok(timeline) => timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC272
            Err(error) => {
31ce2453c82fatagen2026-09-24 13:07 UTC273
                tracing::warn!(%error, %room_id, %root, "thread timeline build failed");
31ce2453c82fatagen2026-09-24 13:07 UTC274
                let error =
31ce2453c82fatagen2026-09-24 13:07 UTC275
                    Error::with_source(ErrorKind::Timeline, "thread timeline build failed", error);
31ce2453c82fatagen2026-09-24 13:07 UTC276
                for (_, reply) in queued {
31ce2453c82fatagen2026-09-24 13:07 UTC277
                    reply.done(Err(error.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC278
                }
31ce2453c82fatagen2026-09-24 13:07 UTC279
                return;
31ce2453c82fatagen2026-09-24 13:07 UTC280
            }
31ce2453c82fatagen2026-09-24 13:07 UTC281
        };
31ce2453c82fatagen2026-09-24 13:07 UTC282
        let id = TimelineId::thread(room_id.clone(), root.clone());
31ce2453c82fatagen2026-09-24 13:07 UTC283
        let Ok(session) = TimelineSession::start(id, timeline, context.clone()).await else {
31ce2453c82fatagen2026-09-24 13:07 UTC284
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC285
        };
31ce2453c82fatagen2026-09-24 13:07 UTC286
        let session = self
31ce2453c82fatagen2026-09-24 13:07 UTC287
            .threads
31ce2453c82fatagen2026-09-24 13:07 UTC288
            .open
31ce2453c82fatagen2026-09-24 13:07 UTC289
            .entry(root)
31ce2453c82fatagen2026-09-24 13:07 UTC290
            .insert_entry(session)
31ce2453c82fatagen2026-09-24 13:07 UTC291
            .into_mut();
31ce2453c82fatagen2026-09-24 13:07 UTC292
        for (command, reply) in queued {
31ce2453c82fatagen2026-09-24 13:07 UTC293
            match command {
31ce2453c82fatagen2026-09-24 13:07 UTC294
                None => reply.done(Ok(())),
31ce2453c82fatagen2026-09-24 13:07 UTC295
                Some(TimelineCommand::Resync { .. }) => reply.done(session.resync().await),
31ce2453c82fatagen2026-09-24 13:07 UTC296
                Some(command) => session.execute(command, reply, &mut self.work).await,
31ce2453c82fatagen2026-09-24 13:07 UTC297
            }
31ce2453c82fatagen2026-09-24 13:07 UTC298
        }
31ce2453c82fatagen2026-09-24 13:07 UTC299
    }
31ce2453c82fatagen2026-09-24 13:07 UTC300
}
31ce2453c82fatagen2026-09-24 13:07 UTC301
31ce2453c82fatagen2026-09-24 13:07 UTC302
type Built = (
31ce2453c82fatagen2026-09-24 13:07 UTC303
    OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC304
    u64,
31ce2453c82fatagen2026-09-24 13:07 UTC305
    Result<Timeline, matrix_sdk_ui::timeline::Error>,
31ce2453c82fatagen2026-09-24 13:07 UTC306
);
31ce2453c82fatagen2026-09-24 13:07 UTC307
31ce2453c82fatagen2026-09-24 13:07 UTC308
/// `None` is the open itself, everything else waits behind it
31ce2453c82fatagen2026-09-24 13:07 UTC309
type Queued = VecDeque<(Option<TimelineCommand>, Responder)>;
31ce2453c82fatagen2026-09-24 13:07 UTC310
31ce2453c82fatagen2026-09-24 13:07 UTC311
enum Routed<'a> {
31ce2453c82fatagen2026-09-24 13:07 UTC312
    Open(&'a mut TimelineSession, TimelineCommand, Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC313
    Queued,
31ce2453c82fatagen2026-09-24 13:07 UTC314
}
31ce2453c82fatagen2026-09-24 13:07 UTC315
31ce2453c82fatagen2026-09-24 13:07 UTC316
struct OpeningThread {
31ce2453c82fatagen2026-09-24 13:07 UTC317
    generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC318
    build: AbortHandle,
31ce2453c82fatagen2026-09-24 13:07 UTC319
    queued: Queued,
31ce2453c82fatagen2026-09-24 13:07 UTC320
}
31ce2453c82fatagen2026-09-24 13:07 UTC321
31ce2453c82fatagen2026-09-24 13:07 UTC322
struct Threads {
31ce2453c82fatagen2026-09-24 13:07 UTC323
    open: HashMap<OwnedEventId, TimelineSession>,
31ce2453c82fatagen2026-09-24 13:07 UTC324
    opening: HashMap<OwnedEventId, OpeningThread>,
1fe480c16a3catagen2026-09-26 08:44 UTC325
    builds: TaskSet<Built>,
31ce2453c82fatagen2026-09-24 13:07 UTC326
    next_generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC327
    queued: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC328
    capacity: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC329
}
31ce2453c82fatagen2026-09-24 13:07 UTC330
31ce2453c82fatagen2026-09-24 13:07 UTC331
impl Threads {
31ce2453c82fatagen2026-09-24 13:07 UTC332
    fn new(capacity: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC333
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC334
            open: HashMap::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC335
            opening: HashMap::new(),
1fe480c16a3catagen2026-09-26 08:44 UTC336
            builds: TaskSet::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC337
            next_generation: 0,
31ce2453c82fatagen2026-09-24 13:07 UTC338
            queued: 0,
31ce2453c82fatagen2026-09-24 13:07 UTC339
            capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC340
        }
31ce2453c82fatagen2026-09-24 13:07 UTC341
    }
31ce2453c82fatagen2026-09-24 13:07 UTC342
31ce2453c82fatagen2026-09-24 13:07 UTC343
    fn enqueue(&mut self, root: &OwnedEventId, command: Option<TimelineCommand>, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC344
        if self.queued >= self.capacity {
31ce2453c82fatagen2026-09-24 13:07 UTC345
            return reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC346
                ErrorKind::QueueFull,
31ce2453c82fatagen2026-09-24 13:07 UTC347
                "thread command queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC348
            )));
31ce2453c82fatagen2026-09-24 13:07 UTC349
        }
31ce2453c82fatagen2026-09-24 13:07 UTC350
        let Some(opening) = self.opening.get_mut(root) else {
31ce2453c82fatagen2026-09-24 13:07 UTC351
            return reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC352
                ErrorKind::TimelineNotOpen,
31ce2453c82fatagen2026-09-24 13:07 UTC353
                "thread timeline is not open",
31ce2453c82fatagen2026-09-24 13:07 UTC354
            )));
31ce2453c82fatagen2026-09-24 13:07 UTC355
        };
31ce2453c82fatagen2026-09-24 13:07 UTC356
        opening.queued.push_back((command, reply));
31ce2453c82fatagen2026-09-24 13:07 UTC357
        self.queued += 1;
31ce2453c82fatagen2026-09-24 13:07 UTC358
    }
31ce2453c82fatagen2026-09-24 13:07 UTC359
31ce2453c82fatagen2026-09-24 13:07 UTC360
    fn open(&mut self, root: OwnedEventId, reply: Responder, room: &Room) {
31ce2453c82fatagen2026-09-24 13:07 UTC361
        if self.open.contains_key(&root) {
31ce2453c82fatagen2026-09-24 13:07 UTC362
            return reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC363
        }
31ce2453c82fatagen2026-09-24 13:07 UTC364
        if !self.opening.contains_key(&root) {
31ce2453c82fatagen2026-09-24 13:07 UTC365
            let generation = self.next_generation;
31ce2453c82fatagen2026-09-24 13:07 UTC366
            self.next_generation = self.next_generation.wrapping_add(1);
31ce2453c82fatagen2026-09-24 13:07 UTC367
            let room = room.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC368
            let build_root = root.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC369
            let build = self.builds.spawn(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC370
                let focus = TimelineFocus::Thread {
31ce2453c82fatagen2026-09-24 13:07 UTC371
                    root_event_id: build_root.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC372
                };
31ce2453c82fatagen2026-09-24 13:07 UTC373
                (build_root, generation, build_timeline(&room, focus).await)
31ce2453c82fatagen2026-09-24 13:07 UTC374
            });
31ce2453c82fatagen2026-09-24 13:07 UTC375
            self.opening.insert(
31ce2453c82fatagen2026-09-24 13:07 UTC376
                root.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC377
                OpeningThread {
31ce2453c82fatagen2026-09-24 13:07 UTC378
                    generation,
31ce2453c82fatagen2026-09-24 13:07 UTC379
                    build,
31ce2453c82fatagen2026-09-24 13:07 UTC380
                    queued: VecDeque::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC381
                },
31ce2453c82fatagen2026-09-24 13:07 UTC382
            );
31ce2453c82fatagen2026-09-24 13:07 UTC383
        }
31ce2453c82fatagen2026-09-24 13:07 UTC384
        self.enqueue(&root, None, reply);
31ce2453c82fatagen2026-09-24 13:07 UTC385
    }
31ce2453c82fatagen2026-09-24 13:07 UTC386
31ce2453c82fatagen2026-09-24 13:07 UTC387
    fn route(
31ce2453c82fatagen2026-09-24 13:07 UTC388
        &mut self,
31ce2453c82fatagen2026-09-24 13:07 UTC389
        root: OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC390
        command: TimelineCommand,
31ce2453c82fatagen2026-09-24 13:07 UTC391
        reply: Responder,
31ce2453c82fatagen2026-09-24 13:07 UTC392
    ) -> Routed<'_> {
31ce2453c82fatagen2026-09-24 13:07 UTC393
        if !self.open.contains_key(&root) {
31ce2453c82fatagen2026-09-24 13:07 UTC394
            self.enqueue(&root, Some(command), reply);
31ce2453c82fatagen2026-09-24 13:07 UTC395
            return Routed::Queued;
31ce2453c82fatagen2026-09-24 13:07 UTC396
        }
31ce2453c82fatagen2026-09-24 13:07 UTC397
        let session = self.open.get_mut(&root).expect("thread was just checked");
31ce2453c82fatagen2026-09-24 13:07 UTC398
        Routed::Open(session, command, reply)
31ce2453c82fatagen2026-09-24 13:07 UTC399
    }
31ce2453c82fatagen2026-09-24 13:07 UTC400
31ce2453c82fatagen2026-09-24 13:07 UTC401
    /// `None` when the build belongs to a thread that was closed while it ran
31ce2453c82fatagen2026-09-24 13:07 UTC402
    fn built(
31ce2453c82fatagen2026-09-24 13:07 UTC403
        &mut self,
1fe480c16a3catagen2026-09-26 08:44 UTC404
        built: Result<Built, JoinError>,
31ce2453c82fatagen2026-09-24 13:07 UTC405
    ) -> Option<(
31ce2453c82fatagen2026-09-24 13:07 UTC406
        OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC407
        Queued,
31ce2453c82fatagen2026-09-24 13:07 UTC408
        Result<Timeline, matrix_sdk_ui::timeline::Error>,
31ce2453c82fatagen2026-09-24 13:07 UTC409
    )> {
31ce2453c82fatagen2026-09-24 13:07 UTC410
        let (root, generation, timeline) = match built {
31ce2453c82fatagen2026-09-24 13:07 UTC411
            Ok(built) => built,
31ce2453c82fatagen2026-09-24 13:07 UTC412
            Err(error) if error.is_cancelled() => return None,
1fe480c16a3catagen2026-09-26 08:44 UTC413
            Err(error) => resume_unwind(error),
31ce2453c82fatagen2026-09-24 13:07 UTC414
        };
31ce2453c82fatagen2026-09-24 13:07 UTC415
        if self
31ce2453c82fatagen2026-09-24 13:07 UTC416
            .opening
31ce2453c82fatagen2026-09-24 13:07 UTC417
            .get(&root)
31ce2453c82fatagen2026-09-24 13:07 UTC418
            .is_none_or(|opening| opening.generation != generation)
31ce2453c82fatagen2026-09-24 13:07 UTC419
        {
31ce2453c82fatagen2026-09-24 13:07 UTC420
            return None;
31ce2453c82fatagen2026-09-24 13:07 UTC421
        }
31ce2453c82fatagen2026-09-24 13:07 UTC422
        let opening = self.opening.remove(&root)?;
31ce2453c82fatagen2026-09-24 13:07 UTC423
        self.queued -= opening.queued.len();
31ce2453c82fatagen2026-09-24 13:07 UTC424
        Some((root, opening.queued, timeline))
31ce2453c82fatagen2026-09-24 13:07 UTC425
    }
31ce2453c82fatagen2026-09-24 13:07 UTC426
31ce2453c82fatagen2026-09-24 13:07 UTC427
    async fn close_one(&mut self, root: &OwnedEventId) -> Result<(), Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC428
        if let Some(session) = self.open.remove(root) {
31ce2453c82fatagen2026-09-24 13:07 UTC429
            session.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC430
            return Ok(());
31ce2453c82fatagen2026-09-24 13:07 UTC431
        }
31ce2453c82fatagen2026-09-24 13:07 UTC432
        let Some(opening) = self.opening.remove(root) else {
31ce2453c82fatagen2026-09-24 13:07 UTC433
            return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC434
                ErrorKind::TimelineNotOpen,
31ce2453c82fatagen2026-09-24 13:07 UTC435
                "thread timeline is not open",
31ce2453c82fatagen2026-09-24 13:07 UTC436
            ));
31ce2453c82fatagen2026-09-24 13:07 UTC437
        };
31ce2453c82fatagen2026-09-24 13:07 UTC438
        opening.build.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC439
        self.queued -= opening.queued.len();
31ce2453c82fatagen2026-09-24 13:07 UTC440
        Ok(())
31ce2453c82fatagen2026-09-24 13:07 UTC441
    }
31ce2453c82fatagen2026-09-24 13:07 UTC442
31ce2453c82fatagen2026-09-24 13:07 UTC443
    async fn close(&mut self) {
1fe480c16a3catagen2026-09-26 08:44 UTC444
        self.builds.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC445
        self.opening.clear();
31ce2453c82fatagen2026-09-24 13:07 UTC446
        for (_, session) in self.open.drain() {
31ce2453c82fatagen2026-09-24 13:07 UTC447
            session.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC448
        }
31ce2453c82fatagen2026-09-24 13:07 UTC449
    }
31ce2453c82fatagen2026-09-24 13:07 UTC450
}