atagen

macltok

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