atagen

macltok

public
Star0
Watch0
673563a76e43035cc5e30359bd79c23190068b4a
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();
0bfa3f46f0beatagen2026-09-26 09:12 UTC94
        let mut 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);
0bfa3f46f0beatagen2026-09-26 09:12 UTC115
        typing_watcher.0.abort();
0bfa3f46f0beatagen2026-09-26 09:12 UTC116
        let _ = (&mut typing_watcher.0).await;
0bfa3f46f0beatagen2026-09-26 09:12 UTC117
        let _ = self
0bfa3f46f0beatagen2026-09-26 09:12 UTC118
            .context
0bfa3f46f0beatagen2026-09-26 09:12 UTC119
            .events
0bfa3f46f0beatagen2026-09-26 09:12 UTC120
            .send(Event::TypingChanged(TypingState {
0bfa3f46f0beatagen2026-09-26 09:12 UTC121
                room_id: self.room_id.clone(),
0bfa3f46f0beatagen2026-09-26 09:12 UTC122
                users: Vec::new(),
0bfa3f46f0beatagen2026-09-26 09:12 UTC123
            }))
0bfa3f46f0beatagen2026-09-26 09:12 UTC124
            .await;
31ce2453c82fatagen2026-09-24 13:07 UTC125
        timelines.threads.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC126
        timelines.room.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC127
        if let Some(reply) = close {
31ce2453c82fatagen2026-09-24 13:07 UTC128
            reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC129
        }
31ce2453c82fatagen2026-09-24 13:07 UTC130
    }
31ce2453c82fatagen2026-09-24 13:07 UTC131
31ce2453c82fatagen2026-09-24 13:07 UTC132
    /// returns the close request's responder, if a close is why we stopped
31ce2453c82fatagen2026-09-24 13:07 UTC133
    async fn serve_open(&mut self, timelines: &mut Timelines) -> Option<Responder> {
31ce2453c82fatagen2026-09-24 13:07 UTC134
        let mut room_info = self.room.subscribe_info();
5a52012c9b1datagen2026-09-24 23:45 UTC135
        // a leave that landed while the timeline was building won't come round again
5a52012c9b1datagen2026-09-24 23:45 UTC136
        if matches!(self.room.state(), RoomState::Left | RoomState::Banned) {
5a52012c9b1datagen2026-09-24 23:45 UTC137
            return None;
5a52012c9b1datagen2026-09-24 23:45 UTC138
        }
31ce2453c82fatagen2026-09-24 13:07 UTC139
        loop {
31ce2453c82fatagen2026-09-24 13:07 UTC140
            tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC141
                Some(info) = room_info.next() => {
31ce2453c82fatagen2026-09-24 13:07 UTC142
                    if matches!(info.state(), RoomState::Left | RoomState::Banned) {
31ce2453c82fatagen2026-09-24 13:07 UTC143
                        tracing::debug!(room_id = %self.room_id, "room actor stopped because we left the room");
31ce2453c82fatagen2026-09-24 13:07 UTC144
                        return None;
31ce2453c82fatagen2026-09-24 13:07 UTC145
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC146
                }
31ce2453c82fatagen2026-09-24 13:07 UTC147
                request = self.requests.recv() => match request {
31ce2453c82fatagen2026-09-24 13:07 UTC148
                    None => return None,
31ce2453c82fatagen2026-09-24 13:07 UTC149
                    Some(ActorRequest::Close(reply)) => return Some(reply),
31ce2453c82fatagen2026-09-24 13:07 UTC150
                    Some(ActorRequest::Open(reply)) => reply.done(timelines.room.resync().await),
31ce2453c82fatagen2026-09-24 13:07 UTC151
                    Some(ActorRequest::Execute(command, reply)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC152
                        timelines.execute(command, reply, &self.room).await;
31ce2453c82fatagen2026-09-24 13:07 UTC153
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC154
                },
31ce2453c82fatagen2026-09-24 13:07 UTC155
                Some(built) = timelines.threads.builds.join_next(), if !timelines.threads.builds.is_empty() => {
31ce2453c82fatagen2026-09-24 13:07 UTC156
                    timelines.thread_built(built, &self.room_id, &self.context).await;
31ce2453c82fatagen2026-09-24 13:07 UTC157
                }
31ce2453c82fatagen2026-09-24 13:07 UTC158
                Some(label) = self.panics.recv() => panic!("{label} panicked in room {}", self.room_id),
31ce2453c82fatagen2026-09-24 13:07 UTC159
                Some(done) = timelines.work.join_next(), if !timelines.work.is_empty() => {
1fe480c16a3catagen2026-09-26 08:44 UTC160
                    if let Err(error) = done && is_panic(&error) {
31ce2453c82fatagen2026-09-24 13:07 UTC161
                        tracing::warn!(room_id = %self.room_id, %error, "timeline operation panicked");
31ce2453c82fatagen2026-09-24 13:07 UTC162
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC163
                }
31ce2453c82fatagen2026-09-24 13:07 UTC164
            }
31ce2453c82fatagen2026-09-24 13:07 UTC165
        }
31ce2453c82fatagen2026-09-24 13:07 UTC166
    }
31ce2453c82fatagen2026-09-24 13:07 UTC167
31ce2453c82fatagen2026-09-24 13:07 UTC168
    async fn refuse_everything(&mut self, error: matrix_sdk_ui::timeline::Error) {
31ce2453c82fatagen2026-09-24 13:07 UTC169
        tracing::warn!(%error, room_id = %self.room_id, "room actor could not build its timeline");
31ce2453c82fatagen2026-09-24 13:07 UTC170
        let error = Error::with_source(ErrorKind::Timeline, "room timeline build failed", error);
31ce2453c82fatagen2026-09-24 13:07 UTC171
        for reply in self.opening.drain(..) {
31ce2453c82fatagen2026-09-24 13:07 UTC172
            reply.done(Err(error.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC173
        }
31ce2453c82fatagen2026-09-24 13:07 UTC174
        self.requests.close();
31ce2453c82fatagen2026-09-24 13:07 UTC175
        while let Some(request) = self.requests.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC176
            request.into_reply().done(Err(error.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC177
        }
31ce2453c82fatagen2026-09-24 13:07 UTC178
    }
31ce2453c82fatagen2026-09-24 13:07 UTC179
}
31ce2453c82fatagen2026-09-24 13:07 UTC180
31ce2453c82fatagen2026-09-24 13:07 UTC181
async fn build_timeline(
31ce2453c82fatagen2026-09-24 13:07 UTC182
    room: &Room,
31ce2453c82fatagen2026-09-24 13:07 UTC183
    focus: TimelineFocus,
31ce2453c82fatagen2026-09-24 13:07 UTC184
) -> Result<Timeline, matrix_sdk_ui::timeline::Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC185
    room.timeline_builder()
31ce2453c82fatagen2026-09-24 13:07 UTC186
        .with_focus(focus)
31ce2453c82fatagen2026-09-24 13:07 UTC187
        .track_read_marker_and_receipts(TimelineReadReceiptTracking::AllEvents)
31ce2453c82fatagen2026-09-24 13:07 UTC188
        .build()
31ce2453c82fatagen2026-09-24 13:07 UTC189
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC190
}
31ce2453c82fatagen2026-09-24 13:07 UTC191
31ce2453c82fatagen2026-09-24 13:07 UTC192
async fn watch_typing(
31ce2453c82fatagen2026-09-24 13:07 UTC193
    room_id: OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC194
    mut typing: tokio::sync::broadcast::Receiver<Vec<ruma::OwnedUserId>>,
31ce2453c82fatagen2026-09-24 13:07 UTC195
    events: crate::transport::EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC196
) {
31ce2453c82fatagen2026-09-24 13:07 UTC197
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC198
        match typing.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC199
            Ok(users) => {
31ce2453c82fatagen2026-09-24 13:07 UTC200
                let state = TypingState {
31ce2453c82fatagen2026-09-24 13:07 UTC201
                    room_id: room_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC202
                    users,
31ce2453c82fatagen2026-09-24 13:07 UTC203
                };
31ce2453c82fatagen2026-09-24 13:07 UTC204
                if events.send(Event::TypingChanged(state)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC205
                    return;
31ce2453c82fatagen2026-09-24 13:07 UTC206
                }
31ce2453c82fatagen2026-09-24 13:07 UTC207
            }
31ce2453c82fatagen2026-09-24 13:07 UTC208
            Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC209
                tracing::warn!(%room_id, skipped, "typing watcher lagged");
31ce2453c82fatagen2026-09-24 13:07 UTC210
            }
31ce2453c82fatagen2026-09-24 13:07 UTC211
            Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
31ce2453c82fatagen2026-09-24 13:07 UTC212
        }
31ce2453c82fatagen2026-09-24 13:07 UTC213
    }
31ce2453c82fatagen2026-09-24 13:07 UTC214
}
31ce2453c82fatagen2026-09-24 13:07 UTC215
31ce2453c82fatagen2026-09-24 13:07 UTC216
struct Timelines {
31ce2453c82fatagen2026-09-24 13:07 UTC217
    room: TimelineSession,
31ce2453c82fatagen2026-09-24 13:07 UTC218
    threads: Threads,
1fe480c16a3catagen2026-09-26 08:44 UTC219
    work: TaskSet<()>,
31ce2453c82fatagen2026-09-24 13:07 UTC220
}
31ce2453c82fatagen2026-09-24 13:07 UTC221
31ce2453c82fatagen2026-09-24 13:07 UTC222
impl Timelines {
31ce2453c82fatagen2026-09-24 13:07 UTC223
    async fn execute(&mut self, command: TimelineCommand, reply: Responder, room: &Room) {
31ce2453c82fatagen2026-09-24 13:07 UTC224
        match command {
31ce2453c82fatagen2026-09-24 13:07 UTC225
            TimelineCommand::OpenThread { root_event_id, .. } => {
31ce2453c82fatagen2026-09-24 13:07 UTC226
                self.threads.open(root_event_id, reply, room);
31ce2453c82fatagen2026-09-24 13:07 UTC227
            }
31ce2453c82fatagen2026-09-24 13:07 UTC228
            TimelineCommand::CloseThread { root_event_id, .. } => {
31ce2453c82fatagen2026-09-24 13:07 UTC229
                reply.done(self.threads.close_one(&root_event_id).await);
31ce2453c82fatagen2026-09-24 13:07 UTC230
            }
31ce2453c82fatagen2026-09-24 13:07 UTC231
            TimelineCommand::Resync {
31ce2453c82fatagen2026-09-24 13:07 UTC232
                timeline_id: TimelineId::Room(_),
31ce2453c82fatagen2026-09-24 13:07 UTC233
            } => reply.done(self.room.resync().await),
31ce2453c82fatagen2026-09-24 13:07 UTC234
            command => {
31ce2453c82fatagen2026-09-24 13:07 UTC235
                let root = command
31ce2453c82fatagen2026-09-24 13:07 UTC236
                    .timeline_id()
31ce2453c82fatagen2026-09-24 13:07 UTC237
                    .and_then(TimelineId::thread_root)
31ce2453c82fatagen2026-09-24 13:07 UTC238
                    .cloned();
31ce2453c82fatagen2026-09-24 13:07 UTC239
                let Some(root) = root else {
31ce2453c82fatagen2026-09-24 13:07 UTC240
                    return self.room.execute(command, reply, &mut self.work).await;
31ce2453c82fatagen2026-09-24 13:07 UTC241
                };
5a52012c9b1datagen2026-09-24 23:45 UTC242
                if let TimelineCommand::MarkRead {
5a52012c9b1datagen2026-09-24 23:45 UTC243
                    timeline_id,
5a52012c9b1datagen2026-09-24 23:45 UTC244
                    event_id,
5a52012c9b1datagen2026-09-24 23:45 UTC245
                } = &command
5a52012c9b1datagen2026-09-24 23:45 UTC246
                    && !self.threads.open.contains_key(&root)
5a52012c9b1datagen2026-09-24 23:45 UTC247
                {
5a52012c9b1datagen2026-09-24 23:45 UTC248
                    let client = room.client();
5a52012c9b1datagen2026-09-24 23:45 UTC249
                    let (timeline_id, event_id) = (timeline_id.clone(), event_id.clone());
5a52012c9b1datagen2026-09-24 23:45 UTC250
                    self.work.spawn(async move {
5a52012c9b1datagen2026-09-24 23:45 UTC251
                        reply.done(
5a52012c9b1datagen2026-09-24 23:45 UTC252
                            super::commands::mark_read(&client, &timeline_id, event_id).await,
5a52012c9b1datagen2026-09-24 23:45 UTC253
                        );
5a52012c9b1datagen2026-09-24 23:45 UTC254
                    });
5a52012c9b1datagen2026-09-24 23:45 UTC255
                    return;
5a52012c9b1datagen2026-09-24 23:45 UTC256
                }
31ce2453c82fatagen2026-09-24 13:07 UTC257
                match self.threads.route(root, command, reply) {
31ce2453c82fatagen2026-09-24 13:07 UTC258
                    Routed::Open(session, TimelineCommand::Resync { .. }, reply) => {
31ce2453c82fatagen2026-09-24 13:07 UTC259
                        reply.done(session.resync().await);
31ce2453c82fatagen2026-09-24 13:07 UTC260
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC261
                    Routed::Open(session, command, reply) => {
31ce2453c82fatagen2026-09-24 13:07 UTC262
                        session.execute(command, reply, &mut self.work).await;
31ce2453c82fatagen2026-09-24 13:07 UTC263
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC264
                    Routed::Queued => {}
31ce2453c82fatagen2026-09-24 13:07 UTC265
                }
31ce2453c82fatagen2026-09-24 13:07 UTC266
            }
31ce2453c82fatagen2026-09-24 13:07 UTC267
        }
31ce2453c82fatagen2026-09-24 13:07 UTC268
    }
31ce2453c82fatagen2026-09-24 13:07 UTC269
31ce2453c82fatagen2026-09-24 13:07 UTC270
    async fn thread_built(
31ce2453c82fatagen2026-09-24 13:07 UTC271
        &mut self,
1fe480c16a3catagen2026-09-26 08:44 UTC272
        built: Result<Built, JoinError>,
31ce2453c82fatagen2026-09-24 13:07 UTC273
        room_id: &OwnedRoomId,
31ce2453c82fatagen2026-09-24 13:07 UTC274
        context: &SessionContext,
31ce2453c82fatagen2026-09-24 13:07 UTC275
    ) {
31ce2453c82fatagen2026-09-24 13:07 UTC276
        let Some((root, queued, timeline)) = self.threads.built(built) else {
31ce2453c82fatagen2026-09-24 13:07 UTC277
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC278
        };
31ce2453c82fatagen2026-09-24 13:07 UTC279
        let timeline = match timeline {
31ce2453c82fatagen2026-09-24 13:07 UTC280
            Ok(timeline) => timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC281
            Err(error) => {
31ce2453c82fatagen2026-09-24 13:07 UTC282
                tracing::warn!(%error, %room_id, %root, "thread timeline build failed");
31ce2453c82fatagen2026-09-24 13:07 UTC283
                let error =
31ce2453c82fatagen2026-09-24 13:07 UTC284
                    Error::with_source(ErrorKind::Timeline, "thread timeline build failed", error);
31ce2453c82fatagen2026-09-24 13:07 UTC285
                for (_, reply) in queued {
31ce2453c82fatagen2026-09-24 13:07 UTC286
                    reply.done(Err(error.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC287
                }
31ce2453c82fatagen2026-09-24 13:07 UTC288
                return;
31ce2453c82fatagen2026-09-24 13:07 UTC289
            }
31ce2453c82fatagen2026-09-24 13:07 UTC290
        };
31ce2453c82fatagen2026-09-24 13:07 UTC291
        let id = TimelineId::thread(room_id.clone(), root.clone());
31ce2453c82fatagen2026-09-24 13:07 UTC292
        let Ok(session) = TimelineSession::start(id, timeline, context.clone()).await else {
31ce2453c82fatagen2026-09-24 13:07 UTC293
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC294
        };
31ce2453c82fatagen2026-09-24 13:07 UTC295
        let session = self
31ce2453c82fatagen2026-09-24 13:07 UTC296
            .threads
31ce2453c82fatagen2026-09-24 13:07 UTC297
            .open
31ce2453c82fatagen2026-09-24 13:07 UTC298
            .entry(root)
31ce2453c82fatagen2026-09-24 13:07 UTC299
            .insert_entry(session)
31ce2453c82fatagen2026-09-24 13:07 UTC300
            .into_mut();
31ce2453c82fatagen2026-09-24 13:07 UTC301
        for (command, reply) in queued {
31ce2453c82fatagen2026-09-24 13:07 UTC302
            match command {
31ce2453c82fatagen2026-09-24 13:07 UTC303
                None => reply.done(Ok(())),
31ce2453c82fatagen2026-09-24 13:07 UTC304
                Some(TimelineCommand::Resync { .. }) => reply.done(session.resync().await),
31ce2453c82fatagen2026-09-24 13:07 UTC305
                Some(command) => session.execute(command, reply, &mut self.work).await,
31ce2453c82fatagen2026-09-24 13:07 UTC306
            }
31ce2453c82fatagen2026-09-24 13:07 UTC307
        }
31ce2453c82fatagen2026-09-24 13:07 UTC308
    }
31ce2453c82fatagen2026-09-24 13:07 UTC309
}
31ce2453c82fatagen2026-09-24 13:07 UTC310
31ce2453c82fatagen2026-09-24 13:07 UTC311
type Built = (
31ce2453c82fatagen2026-09-24 13:07 UTC312
    OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC313
    u64,
31ce2453c82fatagen2026-09-24 13:07 UTC314
    Result<Timeline, matrix_sdk_ui::timeline::Error>,
31ce2453c82fatagen2026-09-24 13:07 UTC315
);
31ce2453c82fatagen2026-09-24 13:07 UTC316
31ce2453c82fatagen2026-09-24 13:07 UTC317
/// `None` is the open itself, everything else waits behind it
31ce2453c82fatagen2026-09-24 13:07 UTC318
type Queued = VecDeque<(Option<TimelineCommand>, Responder)>;
31ce2453c82fatagen2026-09-24 13:07 UTC319
31ce2453c82fatagen2026-09-24 13:07 UTC320
enum Routed<'a> {
31ce2453c82fatagen2026-09-24 13:07 UTC321
    Open(&'a mut TimelineSession, TimelineCommand, Responder),
31ce2453c82fatagen2026-09-24 13:07 UTC322
    Queued,
31ce2453c82fatagen2026-09-24 13:07 UTC323
}
31ce2453c82fatagen2026-09-24 13:07 UTC324
31ce2453c82fatagen2026-09-24 13:07 UTC325
struct OpeningThread {
31ce2453c82fatagen2026-09-24 13:07 UTC326
    generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC327
    build: AbortHandle,
31ce2453c82fatagen2026-09-24 13:07 UTC328
    queued: Queued,
31ce2453c82fatagen2026-09-24 13:07 UTC329
}
31ce2453c82fatagen2026-09-24 13:07 UTC330
31ce2453c82fatagen2026-09-24 13:07 UTC331
struct Threads {
31ce2453c82fatagen2026-09-24 13:07 UTC332
    open: HashMap<OwnedEventId, TimelineSession>,
31ce2453c82fatagen2026-09-24 13:07 UTC333
    opening: HashMap<OwnedEventId, OpeningThread>,
1fe480c16a3catagen2026-09-26 08:44 UTC334
    builds: TaskSet<Built>,
31ce2453c82fatagen2026-09-24 13:07 UTC335
    next_generation: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC336
    queued: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC337
    capacity: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC338
}
31ce2453c82fatagen2026-09-24 13:07 UTC339
31ce2453c82fatagen2026-09-24 13:07 UTC340
impl Threads {
31ce2453c82fatagen2026-09-24 13:07 UTC341
    fn new(capacity: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC342
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC343
            open: HashMap::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC344
            opening: HashMap::new(),
1fe480c16a3catagen2026-09-26 08:44 UTC345
            builds: TaskSet::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC346
            next_generation: 0,
31ce2453c82fatagen2026-09-24 13:07 UTC347
            queued: 0,
31ce2453c82fatagen2026-09-24 13:07 UTC348
            capacity,
31ce2453c82fatagen2026-09-24 13:07 UTC349
        }
31ce2453c82fatagen2026-09-24 13:07 UTC350
    }
31ce2453c82fatagen2026-09-24 13:07 UTC351
31ce2453c82fatagen2026-09-24 13:07 UTC352
    fn enqueue(&mut self, root: &OwnedEventId, command: Option<TimelineCommand>, reply: Responder) {
31ce2453c82fatagen2026-09-24 13:07 UTC353
        if self.queued >= self.capacity {
31ce2453c82fatagen2026-09-24 13:07 UTC354
            return reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC355
                ErrorKind::QueueFull,
31ce2453c82fatagen2026-09-24 13:07 UTC356
                "thread command queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC357
            )));
31ce2453c82fatagen2026-09-24 13:07 UTC358
        }
31ce2453c82fatagen2026-09-24 13:07 UTC359
        let Some(opening) = self.opening.get_mut(root) else {
31ce2453c82fatagen2026-09-24 13:07 UTC360
            return reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC361
                ErrorKind::TimelineNotOpen,
31ce2453c82fatagen2026-09-24 13:07 UTC362
                "thread timeline is not open",
31ce2453c82fatagen2026-09-24 13:07 UTC363
            )));
31ce2453c82fatagen2026-09-24 13:07 UTC364
        };
31ce2453c82fatagen2026-09-24 13:07 UTC365
        opening.queued.push_back((command, reply));
31ce2453c82fatagen2026-09-24 13:07 UTC366
        self.queued += 1;
31ce2453c82fatagen2026-09-24 13:07 UTC367
    }
31ce2453c82fatagen2026-09-24 13:07 UTC368
31ce2453c82fatagen2026-09-24 13:07 UTC369
    fn open(&mut self, root: OwnedEventId, reply: Responder, room: &Room) {
31ce2453c82fatagen2026-09-24 13:07 UTC370
        if self.open.contains_key(&root) {
31ce2453c82fatagen2026-09-24 13:07 UTC371
            return reply.done(Ok(()));
31ce2453c82fatagen2026-09-24 13:07 UTC372
        }
31ce2453c82fatagen2026-09-24 13:07 UTC373
        if !self.opening.contains_key(&root) {
31ce2453c82fatagen2026-09-24 13:07 UTC374
            let generation = self.next_generation;
31ce2453c82fatagen2026-09-24 13:07 UTC375
            self.next_generation = self.next_generation.wrapping_add(1);
31ce2453c82fatagen2026-09-24 13:07 UTC376
            let room = room.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC377
            let build_root = root.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC378
            let build = self.builds.spawn(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC379
                let focus = TimelineFocus::Thread {
31ce2453c82fatagen2026-09-24 13:07 UTC380
                    root_event_id: build_root.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC381
                };
31ce2453c82fatagen2026-09-24 13:07 UTC382
                (build_root, generation, build_timeline(&room, focus).await)
31ce2453c82fatagen2026-09-24 13:07 UTC383
            });
31ce2453c82fatagen2026-09-24 13:07 UTC384
            self.opening.insert(
31ce2453c82fatagen2026-09-24 13:07 UTC385
                root.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC386
                OpeningThread {
31ce2453c82fatagen2026-09-24 13:07 UTC387
                    generation,
31ce2453c82fatagen2026-09-24 13:07 UTC388
                    build,
31ce2453c82fatagen2026-09-24 13:07 UTC389
                    queued: VecDeque::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC390
                },
31ce2453c82fatagen2026-09-24 13:07 UTC391
            );
31ce2453c82fatagen2026-09-24 13:07 UTC392
        }
31ce2453c82fatagen2026-09-24 13:07 UTC393
        self.enqueue(&root, None, reply);
31ce2453c82fatagen2026-09-24 13:07 UTC394
    }
31ce2453c82fatagen2026-09-24 13:07 UTC395
31ce2453c82fatagen2026-09-24 13:07 UTC396
    fn route(
31ce2453c82fatagen2026-09-24 13:07 UTC397
        &mut self,
31ce2453c82fatagen2026-09-24 13:07 UTC398
        root: OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC399
        command: TimelineCommand,
31ce2453c82fatagen2026-09-24 13:07 UTC400
        reply: Responder,
31ce2453c82fatagen2026-09-24 13:07 UTC401
    ) -> Routed<'_> {
31ce2453c82fatagen2026-09-24 13:07 UTC402
        if !self.open.contains_key(&root) {
31ce2453c82fatagen2026-09-24 13:07 UTC403
            self.enqueue(&root, Some(command), reply);
31ce2453c82fatagen2026-09-24 13:07 UTC404
            return Routed::Queued;
31ce2453c82fatagen2026-09-24 13:07 UTC405
        }
31ce2453c82fatagen2026-09-24 13:07 UTC406
        let session = self.open.get_mut(&root).expect("thread was just checked");
31ce2453c82fatagen2026-09-24 13:07 UTC407
        Routed::Open(session, command, reply)
31ce2453c82fatagen2026-09-24 13:07 UTC408
    }
31ce2453c82fatagen2026-09-24 13:07 UTC409
31ce2453c82fatagen2026-09-24 13:07 UTC410
    /// `None` when the build belongs to a thread that was closed while it ran
31ce2453c82fatagen2026-09-24 13:07 UTC411
    fn built(
31ce2453c82fatagen2026-09-24 13:07 UTC412
        &mut self,
1fe480c16a3catagen2026-09-26 08:44 UTC413
        built: Result<Built, JoinError>,
31ce2453c82fatagen2026-09-24 13:07 UTC414
    ) -> Option<(
31ce2453c82fatagen2026-09-24 13:07 UTC415
        OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC416
        Queued,
31ce2453c82fatagen2026-09-24 13:07 UTC417
        Result<Timeline, matrix_sdk_ui::timeline::Error>,
31ce2453c82fatagen2026-09-24 13:07 UTC418
    )> {
31ce2453c82fatagen2026-09-24 13:07 UTC419
        let (root, generation, timeline) = match built {
31ce2453c82fatagen2026-09-24 13:07 UTC420
            Ok(built) => built,
31ce2453c82fatagen2026-09-24 13:07 UTC421
            Err(error) if error.is_cancelled() => return None,
1fe480c16a3catagen2026-09-26 08:44 UTC422
            Err(error) => resume_unwind(error),
31ce2453c82fatagen2026-09-24 13:07 UTC423
        };
31ce2453c82fatagen2026-09-24 13:07 UTC424
        if self
31ce2453c82fatagen2026-09-24 13:07 UTC425
            .opening
31ce2453c82fatagen2026-09-24 13:07 UTC426
            .get(&root)
31ce2453c82fatagen2026-09-24 13:07 UTC427
            .is_none_or(|opening| opening.generation != generation)
31ce2453c82fatagen2026-09-24 13:07 UTC428
        {
31ce2453c82fatagen2026-09-24 13:07 UTC429
            return None;
31ce2453c82fatagen2026-09-24 13:07 UTC430
        }
31ce2453c82fatagen2026-09-24 13:07 UTC431
        let opening = self.opening.remove(&root)?;
31ce2453c82fatagen2026-09-24 13:07 UTC432
        self.queued -= opening.queued.len();
31ce2453c82fatagen2026-09-24 13:07 UTC433
        Some((root, opening.queued, timeline))
31ce2453c82fatagen2026-09-24 13:07 UTC434
    }
31ce2453c82fatagen2026-09-24 13:07 UTC435
31ce2453c82fatagen2026-09-24 13:07 UTC436
    async fn close_one(&mut self, root: &OwnedEventId) -> Result<(), Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC437
        if let Some(session) = self.open.remove(root) {
31ce2453c82fatagen2026-09-24 13:07 UTC438
            session.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC439
            return Ok(());
31ce2453c82fatagen2026-09-24 13:07 UTC440
        }
31ce2453c82fatagen2026-09-24 13:07 UTC441
        let Some(opening) = self.opening.remove(root) else {
31ce2453c82fatagen2026-09-24 13:07 UTC442
            return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC443
                ErrorKind::TimelineNotOpen,
31ce2453c82fatagen2026-09-24 13:07 UTC444
                "thread timeline is not open",
31ce2453c82fatagen2026-09-24 13:07 UTC445
            ));
31ce2453c82fatagen2026-09-24 13:07 UTC446
        };
31ce2453c82fatagen2026-09-24 13:07 UTC447
        opening.build.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC448
        self.queued -= opening.queued.len();
31ce2453c82fatagen2026-09-24 13:07 UTC449
        Ok(())
31ce2453c82fatagen2026-09-24 13:07 UTC450
    }
31ce2453c82fatagen2026-09-24 13:07 UTC451
31ce2453c82fatagen2026-09-24 13:07 UTC452
    async fn close(&mut self) {
1fe480c16a3catagen2026-09-26 08:44 UTC453
        self.builds.shutdown().await;
31ce2453c82fatagen2026-09-24 13:07 UTC454
        self.opening.clear();
31ce2453c82fatagen2026-09-24 13:07 UTC455
        for (_, session) in self.open.drain() {
31ce2453c82fatagen2026-09-24 13:07 UTC456
            session.close().await;
31ce2453c82fatagen2026-09-24 13:07 UTC457
        }
31ce2453c82fatagen2026-09-24 13:07 UTC458
    }
31ce2453c82fatagen2026-09-24 13:07 UTC459
}