atagen

macltok

public
Star0
Watch0
4fec18288b9aa813e3dccd7e347ae17ecd967de8
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/room.rsRust459 lines15.4 KB
1
use std::collections::{HashMap, VecDeque};
2
3
use matrix_sdk::{Room, RoomState};
4
use matrix_sdk_ui::timeline::{RoomExt, Timeline, TimelineFocus, TimelineReadReceiptTracking};
5
use ruma::{OwnedEventId, OwnedRoomId};
6
use tokio::sync::mpsc;
7
8
use super::executor::{AbortHandle, JoinError, TaskSet, is_panic, resume_unwind};
9
use super::timeline::{SessionContext, TaskGuard, TimelineSession};
10
use crate::{
11
    Error, ErrorKind, Event, TimelineCommand, TimelineId, TypingState, transport::Responder,
12
};
13
14
pub(super) enum ActorRequest {
15
    /// opening an open room answers with a fresh reset
16
    Open(Responder),
17
    Execute(TimelineCommand, Responder),
18
    Close(Responder),
19
}
20
21
impl ActorRequest {
22
    pub(super) fn into_reply(self) -> Responder {
23
        match self {
24
            Self::Open(reply) | Self::Execute(_, reply) | Self::Close(reply) => reply,
25
        }
26
    }
27
}
28
29
pub(super) enum ActorNote {
30
    /// stopping on its own, after a leave or a kick. anything sent its way now comes back in `Exited`
31
    Leaving {
32
        room_id: OwnedRoomId,
33
        generation: u64,
34
    },
35
    Exited {
36
        room_id: OwnedRoomId,
37
        generation: u64,
38
        /// requests that arrived too late to be served, for the engine to answer or replay
39
        leftovers: Vec<ActorRequest>,
40
    },
41
}
42
43
pub(super) struct RoomActor {
44
    pub(super) room_id: OwnedRoomId,
45
    pub(super) generation: u64,
46
    pub(super) room: Room,
47
    pub(super) requests: mpsc::Receiver<ActorRequest>,
48
    pub(super) notes: mpsc::UnboundedSender<ActorNote>,
49
    pub(super) context: SessionContext,
50
    pub(super) panics: mpsc::UnboundedReceiver<&'static str>,
51
    pub(super) opening: Vec<Responder>,
52
}
53
54
impl RoomActor {
55
    pub(super) async fn run(mut self) {
56
        self.serve().await;
57
        self.requests.close();
58
        let mut leftovers = Vec::new();
59
        while let Ok(request) = self.requests.try_recv() {
60
            leftovers.push(request);
61
        }
62
        let _ = self.notes.send(ActorNote::Exited {
63
            room_id: self.room_id.clone(),
64
            generation: self.generation,
65
            leftovers,
66
        });
67
    }
68
69
    async fn serve(&mut self) {
70
        let timeline = match build_timeline(
71
            &self.room,
72
            TimelineFocus::Live {
73
                hide_threaded_events: true,
74
            },
75
        )
76
        .await
77
        {
78
            Ok(timeline) => timeline,
79
            Err(error) => return self.refuse_everything(error).await,
80
        };
81
        let Ok(room_timeline) = TimelineSession::start(
82
            TimelineId::Room(self.room_id.clone()),
83
            timeline,
84
            self.context.clone(),
85
        )
86
        .await
87
        else {
88
            return;
89
        };
90
        for reply in self.opening.drain(..) {
91
            reply.done(Ok(()));
92
        }
93
        let (typing_guard, typing) = self.room.subscribe_to_typing_notifications();
94
        let mut typing_watcher = TaskGuard(self.context.supervisor.spawn(
95
            "typing watcher",
96
            watch_typing(self.room_id.clone(), typing, self.context.events.clone()),
97
        ));
98
        let mut timelines = Timelines {
99
            room: room_timeline,
100
            threads: Threads::new(self.requests.max_capacity()),
101
            work: TaskSet::new(),
102
        };
103
        let close = self.serve_open(&mut timelines).await;
104
        if close.is_none() {
105
            self.requests.close();
106
            let _ = self.notes.send(ActorNote::Leaving {
107
                room_id: self.room_id.clone(),
108
                generation: self.generation,
109
            });
110
        }
111
112
        // let redactions and receipts that already left finish rather than lie about them
113
        while timelines.work.join_next().await.is_some() {}
114
        drop(typing_guard);
115
        typing_watcher.0.abort();
116
        let _ = (&mut typing_watcher.0).await;
117
        let _ = self
118
            .context
119
            .events
120
            .send(Event::TypingChanged(TypingState {
121
                room_id: self.room_id.clone(),
122
                users: Vec::new(),
123
            }))
124
            .await;
125
        timelines.threads.close().await;
126
        timelines.room.close().await;
127
        if let Some(reply) = close {
128
            reply.done(Ok(()));
129
        }
130
    }
131
132
    /// returns the close request's responder, if a close is why we stopped
133
    async fn serve_open(&mut self, timelines: &mut Timelines) -> Option<Responder> {
134
        let mut room_info = self.room.subscribe_info();
135
        // a leave that landed while the timeline was building won't come round again
136
        if matches!(self.room.state(), RoomState::Left | RoomState::Banned) {
137
            return None;
138
        }
139
        loop {
140
            tokio::select! {
141
                Some(info) = room_info.next() => {
142
                    if matches!(info.state(), RoomState::Left | RoomState::Banned) {
143
                        tracing::debug!(room_id = %self.room_id, "room actor stopped because we left the room");
144
                        return None;
145
                    }
146
                }
147
                request = self.requests.recv() => match request {
148
                    None => return None,
149
                    Some(ActorRequest::Close(reply)) => return Some(reply),
150
                    Some(ActorRequest::Open(reply)) => reply.done(timelines.room.resync().await),
151
                    Some(ActorRequest::Execute(command, reply)) => {
152
                        timelines.execute(command, reply, &self.room).await;
153
                    }
154
                },
155
                Some(built) = timelines.threads.builds.join_next(), if !timelines.threads.builds.is_empty() => {
156
                    timelines.thread_built(built, &self.room_id, &self.context).await;
157
                }
158
                Some(label) = self.panics.recv() => panic!("{label} panicked in room {}", self.room_id),
159
                Some(done) = timelines.work.join_next(), if !timelines.work.is_empty() => {
160
                    if let Err(error) = done && is_panic(&error) {
161
                        tracing::warn!(room_id = %self.room_id, %error, "timeline operation panicked");
162
                    }
163
                }
164
            }
165
        }
166
    }
167
168
    async fn refuse_everything(&mut self, error: matrix_sdk_ui::timeline::Error) {
169
        tracing::warn!(%error, room_id = %self.room_id, "room actor could not build its timeline");
170
        let error = Error::with_source(ErrorKind::Timeline, "room timeline build failed", error);
171
        for reply in self.opening.drain(..) {
172
            reply.done(Err(error.clone()));
173
        }
174
        self.requests.close();
175
        while let Some(request) = self.requests.recv().await {
176
            request.into_reply().done(Err(error.clone()));
177
        }
178
    }
179
}
180
181
async fn build_timeline(
182
    room: &Room,
183
    focus: TimelineFocus,
184
) -> Result<Timeline, matrix_sdk_ui::timeline::Error> {
185
    room.timeline_builder()
186
        .with_focus(focus)
187
        .track_read_marker_and_receipts(TimelineReadReceiptTracking::AllEvents)
188
        .build()
189
        .await
190
}
191
192
async fn watch_typing(
193
    room_id: OwnedRoomId,
194
    mut typing: tokio::sync::broadcast::Receiver<Vec<ruma::OwnedUserId>>,
195
    events: crate::transport::EventSender,
196
) {
197
    loop {
198
        match typing.recv().await {
199
            Ok(users) => {
200
                let state = TypingState {
201
                    room_id: room_id.clone(),
202
                    users,
203
                };
204
                if events.send(Event::TypingChanged(state)).await.is_err() {
205
                    return;
206
                }
207
            }
208
            Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
209
                tracing::warn!(%room_id, skipped, "typing watcher lagged");
210
            }
211
            Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
212
        }
213
    }
214
}
215
216
struct Timelines {
217
    room: TimelineSession,
218
    threads: Threads,
219
    work: TaskSet<()>,
220
}
221
222
impl Timelines {
223
    async fn execute(&mut self, command: TimelineCommand, reply: Responder, room: &Room) {
224
        match command {
225
            TimelineCommand::OpenThread { root_event_id, .. } => {
226
                self.threads.open(root_event_id, reply, room);
227
            }
228
            TimelineCommand::CloseThread { root_event_id, .. } => {
229
                reply.done(self.threads.close_one(&root_event_id).await);
230
            }
231
            TimelineCommand::Resync {
232
                timeline_id: TimelineId::Room(_),
233
            } => reply.done(self.room.resync().await),
234
            command => {
235
                let root = command
236
                    .timeline_id()
237
                    .and_then(TimelineId::thread_root)
238
                    .cloned();
239
                let Some(root) = root else {
240
                    return self.room.execute(command, reply, &mut self.work).await;
241
                };
242
                if let TimelineCommand::MarkRead {
243
                    timeline_id,
244
                    event_id,
245
                } = &command
246
                    && !self.threads.open.contains_key(&root)
247
                {
248
                    let client = room.client();
249
                    let (timeline_id, event_id) = (timeline_id.clone(), event_id.clone());
250
                    self.work.spawn(async move {
251
                        reply.done(
252
                            super::commands::mark_read(&client, &timeline_id, event_id).await,
253
                        );
254
                    });
255
                    return;
256
                }
257
                match self.threads.route(root, command, reply) {
258
                    Routed::Open(session, TimelineCommand::Resync { .. }, reply) => {
259
                        reply.done(session.resync().await);
260
                    }
261
                    Routed::Open(session, command, reply) => {
262
                        session.execute(command, reply, &mut self.work).await;
263
                    }
264
                    Routed::Queued => {}
265
                }
266
            }
267
        }
268
    }
269
270
    async fn thread_built(
271
        &mut self,
272
        built: Result<Built, JoinError>,
273
        room_id: &OwnedRoomId,
274
        context: &SessionContext,
275
    ) {
276
        let Some((root, queued, timeline)) = self.threads.built(built) else {
277
            return;
278
        };
279
        let timeline = match timeline {
280
            Ok(timeline) => timeline,
281
            Err(error) => {
282
                tracing::warn!(%error, %room_id, %root, "thread timeline build failed");
283
                let error =
284
                    Error::with_source(ErrorKind::Timeline, "thread timeline build failed", error);
285
                for (_, reply) in queued {
286
                    reply.done(Err(error.clone()));
287
                }
288
                return;
289
            }
290
        };
291
        let id = TimelineId::thread(room_id.clone(), root.clone());
292
        let Ok(session) = TimelineSession::start(id, timeline, context.clone()).await else {
293
            return;
294
        };
295
        let session = self
296
            .threads
297
            .open
298
            .entry(root)
299
            .insert_entry(session)
300
            .into_mut();
301
        for (command, reply) in queued {
302
            match command {
303
                None => reply.done(Ok(())),
304
                Some(TimelineCommand::Resync { .. }) => reply.done(session.resync().await),
305
                Some(command) => session.execute(command, reply, &mut self.work).await,
306
            }
307
        }
308
    }
309
}
310
311
type Built = (
312
    OwnedEventId,
313
    u64,
314
    Result<Timeline, matrix_sdk_ui::timeline::Error>,
315
);
316
317
/// `None` is the open itself, everything else waits behind it
318
type Queued = VecDeque<(Option<TimelineCommand>, Responder)>;
319
320
enum Routed<'a> {
321
    Open(&'a mut TimelineSession, TimelineCommand, Responder),
322
    Queued,
323
}
324
325
struct OpeningThread {
326
    generation: u64,
327
    build: AbortHandle,
328
    queued: Queued,
329
}
330
331
struct Threads {
332
    open: HashMap<OwnedEventId, TimelineSession>,
333
    opening: HashMap<OwnedEventId, OpeningThread>,
334
    builds: TaskSet<Built>,
335
    next_generation: u64,
336
    queued: usize,
337
    capacity: usize,
338
}
339
340
impl Threads {
341
    fn new(capacity: usize) -> Self {
342
        Self {
343
            open: HashMap::new(),
344
            opening: HashMap::new(),
345
            builds: TaskSet::new(),
346
            next_generation: 0,
347
            queued: 0,
348
            capacity,
349
        }
350
    }
351
352
    fn enqueue(&mut self, root: &OwnedEventId, command: Option<TimelineCommand>, reply: Responder) {
353
        if self.queued >= self.capacity {
354
            return reply.done(Err(Error::new(
355
                ErrorKind::QueueFull,
356
                "thread command queue is full",
357
            )));
358
        }
359
        let Some(opening) = self.opening.get_mut(root) else {
360
            return reply.done(Err(Error::new(
361
                ErrorKind::TimelineNotOpen,
362
                "thread timeline is not open",
363
            )));
364
        };
365
        opening.queued.push_back((command, reply));
366
        self.queued += 1;
367
    }
368
369
    fn open(&mut self, root: OwnedEventId, reply: Responder, room: &Room) {
370
        if self.open.contains_key(&root) {
371
            return reply.done(Ok(()));
372
        }
373
        if !self.opening.contains_key(&root) {
374
            let generation = self.next_generation;
375
            self.next_generation = self.next_generation.wrapping_add(1);
376
            let room = room.clone();
377
            let build_root = root.clone();
378
            let build = self.builds.spawn(async move {
379
                let focus = TimelineFocus::Thread {
380
                    root_event_id: build_root.clone(),
381
                };
382
                (build_root, generation, build_timeline(&room, focus).await)
383
            });
384
            self.opening.insert(
385
                root.clone(),
386
                OpeningThread {
387
                    generation,
388
                    build,
389
                    queued: VecDeque::new(),
390
                },
391
            );
392
        }
393
        self.enqueue(&root, None, reply);
394
    }
395
396
    fn route(
397
        &mut self,
398
        root: OwnedEventId,
399
        command: TimelineCommand,
400
        reply: Responder,
401
    ) -> Routed<'_> {
402
        if !self.open.contains_key(&root) {
403
            self.enqueue(&root, Some(command), reply);
404
            return Routed::Queued;
405
        }
406
        let session = self.open.get_mut(&root).expect("thread was just checked");
407
        Routed::Open(session, command, reply)
408
    }
409
410
    /// `None` when the build belongs to a thread that was closed while it ran
411
    fn built(
412
        &mut self,
413
        built: Result<Built, JoinError>,
414
    ) -> Option<(
415
        OwnedEventId,
416
        Queued,
417
        Result<Timeline, matrix_sdk_ui::timeline::Error>,
418
    )> {
419
        let (root, generation, timeline) = match built {
420
            Ok(built) => built,
421
            Err(error) if error.is_cancelled() => return None,
422
            Err(error) => resume_unwind(error),
423
        };
424
        if self
425
            .opening
426
            .get(&root)
427
            .is_none_or(|opening| opening.generation != generation)
428
        {
429
            return None;
430
        }
431
        let opening = self.opening.remove(&root)?;
432
        self.queued -= opening.queued.len();
433
        Some((root, opening.queued, timeline))
434
    }
435
436
    async fn close_one(&mut self, root: &OwnedEventId) -> Result<(), Error> {
437
        if let Some(session) = self.open.remove(root) {
438
            session.close().await;
439
            return Ok(());
440
        }
441
        let Some(opening) = self.opening.remove(root) else {
442
            return Err(Error::new(
443
                ErrorKind::TimelineNotOpen,
444
                "thread timeline is not open",
445
            ));
446
        };
447
        opening.build.abort();
448
        self.queued -= opening.queued.len();
449
        Ok(())
450
    }
451
452
    async fn close(&mut self) {
453
        self.builds.shutdown().await;
454
        self.opening.clear();
455
        for (_, session) in self.open.drain() {
456
            session.close().await;
457
        }
458
    }
459
}