atagen

macltok

public
Star0
Watch0
a951cb7cb7cab29ddf841442899e1e5da3a71249
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/room.rsRust476 lines16.3 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::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 {
226
                room_id,
227
                root_event_id,
228
            } => self
229
                .threads
230
                .open(TimelineId::thread(room_id, root_event_id), reply, room),
231
            TimelineCommand::CloseThread {
232
                room_id,
233
                root_event_id,
234
            } => {
235
                let id = TimelineId::thread(room_id, root_event_id);
236
                reply.done(self.threads.close_one(&id).await);
237
            }
238
            TimelineCommand::OpenPinned(room_id) => {
239
                self.threads.open(TimelineId::Pinned(room_id), reply, room);
240
            }
241
            TimelineCommand::ClosePinned(room_id) => {
242
                reply.done(self.threads.close_one(&TimelineId::Pinned(room_id)).await);
243
            }
244
            TimelineCommand::Resync {
245
                timeline_id: TimelineId::Room(_),
246
            } => reply.done(self.room.resync().await),
247
            command => {
248
                let Some(id) = command
249
                    .timeline_id()
250
                    .filter(|id| !matches!(id, TimelineId::Room(_)))
251
                    .cloned()
252
                else {
253
                    return self.room.execute(command, reply, &mut self.work).await;
254
                };
255
                if matches!(id, TimelineId::Pinned(_))
256
                    && matches!(
257
                        command,
258
                        TimelineCommand::Send { .. } | TimelineCommand::Paginate { .. }
259
                    )
260
                {
261
                    return reply.done(Err(Error::new(
262
                        ErrorKind::Invalid,
263
                        "the pinned timeline can't send or paginate",
264
                    )));
265
                }
266
                if let TimelineCommand::MarkRead {
267
                    timeline_id,
268
                    event_id,
269
                } = &command
270
                    && !self.threads.open.contains_key(&id)
271
                {
272
                    let client = room.client();
273
                    let (timeline_id, event_id) = (timeline_id.clone(), event_id.clone());
274
                    self.work.spawn(async move {
275
                        reply.done(
276
                            super::commands::mark_read(&client, &timeline_id, event_id).await,
277
                        );
278
                    });
279
                    return;
280
                }
281
                match self.threads.route(id, command, reply) {
282
                    Routed::Open(session, TimelineCommand::Resync { .. }, reply) => {
283
                        reply.done(session.resync().await);
284
                    }
285
                    Routed::Open(session, command, reply) => {
286
                        session.execute(command, reply, &mut self.work).await;
287
                    }
288
                    Routed::Queued => {}
289
                }
290
            }
291
        }
292
    }
293
294
    async fn thread_built(
295
        &mut self,
296
        built: Result<Built, JoinError>,
297
        room_id: &OwnedRoomId,
298
        context: &SessionContext,
299
    ) {
300
        let Some((id, queued, timeline)) = self.threads.built(built) else {
301
            return;
302
        };
303
        let timeline = match timeline {
304
            Ok(timeline) => timeline,
305
            Err(error) => {
306
                tracing::warn!(%error, %room_id, ?id, "timeline build failed");
307
                let error = Error::with_source(ErrorKind::Timeline, "timeline build failed", error);
308
                for (_, reply) in queued {
309
                    reply.done(Err(error.clone()));
310
                }
311
                return;
312
            }
313
        };
314
        let Ok(session) = TimelineSession::start(id.clone(), timeline, context.clone()).await
315
        else {
316
            return;
317
        };
318
        let session = self.threads.open.entry(id).insert_entry(session).into_mut();
319
        for (command, reply) in queued {
320
            match command {
321
                None => reply.done(Ok(())),
322
                Some(TimelineCommand::Resync { .. }) => reply.done(session.resync().await),
323
                Some(command) => session.execute(command, reply, &mut self.work).await,
324
            }
325
        }
326
    }
327
}
328
329
type Built = (
330
    TimelineId,
331
    u64,
332
    Result<Timeline, matrix_sdk_ui::timeline::Error>,
333
);
334
335
/// `None` is the open itself, everything else waits behind it
336
type Queued = VecDeque<(Option<TimelineCommand>, Responder)>;
337
338
enum Routed<'a> {
339
    Open(&'a mut TimelineSession, TimelineCommand, Responder),
340
    Queued,
341
}
342
343
struct OpeningThread {
344
    generation: u64,
345
    build: AbortHandle,
346
    queued: Queued,
347
}
348
349
/// threads and the pinned timeline, which build off the actor and queue what arrives meanwhile
350
struct Threads {
351
    open: HashMap<TimelineId, TimelineSession>,
352
    opening: HashMap<TimelineId, OpeningThread>,
353
    builds: TaskSet<Built>,
354
    next_generation: u64,
355
    queued: usize,
356
    capacity: usize,
357
}
358
359
impl Threads {
360
    fn new(capacity: usize) -> Self {
361
        Self {
362
            open: HashMap::new(),
363
            opening: HashMap::new(),
364
            builds: TaskSet::new(),
365
            next_generation: 0,
366
            queued: 0,
367
            capacity,
368
        }
369
    }
370
371
    fn enqueue(&mut self, id: &TimelineId, command: Option<TimelineCommand>, reply: Responder) {
372
        if self.queued >= self.capacity {
373
            return reply.done(Err(Error::new(
374
                ErrorKind::QueueFull,
375
                "thread command queue is full",
376
            )));
377
        }
378
        let Some(opening) = self.opening.get_mut(id) else {
379
            return reply.done(Err(Error::new(
380
                ErrorKind::TimelineNotOpen,
381
                "timeline is not open",
382
            )));
383
        };
384
        opening.queued.push_back((command, reply));
385
        self.queued += 1;
386
    }
387
388
    fn open(&mut self, id: TimelineId, reply: Responder, room: &Room) {
389
        if self.open.contains_key(&id) {
390
            return reply.done(Ok(()));
391
        }
392
        if !self.opening.contains_key(&id) {
393
            let generation = self.next_generation;
394
            self.next_generation = self.next_generation.wrapping_add(1);
395
            let room = room.clone();
396
            let build_id = id.clone();
397
            let build = self.builds.spawn(async move {
398
                let focus = match &build_id {
399
                    TimelineId::Thread { root_event_id, .. } => TimelineFocus::Thread {
400
                        root_event_id: root_event_id.clone(),
401
                    },
402
                    _ => TimelineFocus::PinnedEvents,
403
                };
404
                (build_id, generation, build_timeline(&room, focus).await)
405
            });
406
            self.opening.insert(
407
                id.clone(),
408
                OpeningThread {
409
                    generation,
410
                    build,
411
                    queued: VecDeque::new(),
412
                },
413
            );
414
        }
415
        self.enqueue(&id, None, reply);
416
    }
417
418
    fn route(&mut self, id: TimelineId, command: TimelineCommand, reply: Responder) -> Routed<'_> {
419
        if !self.open.contains_key(&id) {
420
            self.enqueue(&id, Some(command), reply);
421
            return Routed::Queued;
422
        }
423
        let session = self.open.get_mut(&id).expect("timeline was just checked");
424
        Routed::Open(session, command, reply)
425
    }
426
427
    /// `None` when the build belongs to a thread that was closed while it ran
428
    fn built(
429
        &mut self,
430
        built: Result<Built, JoinError>,
431
    ) -> Option<(
432
        TimelineId,
433
        Queued,
434
        Result<Timeline, matrix_sdk_ui::timeline::Error>,
435
    )> {
436
        let (id, generation, timeline) = match built {
437
            Ok(built) => built,
438
            Err(error) if error.is_cancelled() => return None,
439
            Err(error) => resume_unwind(error),
440
        };
441
        if self
442
            .opening
443
            .get(&id)
444
            .is_none_or(|opening| opening.generation != generation)
445
        {
446
            return None;
447
        }
448
        let opening = self.opening.remove(&id)?;
449
        self.queued -= opening.queued.len();
450
        Some((id, opening.queued, timeline))
451
    }
452
453
    async fn close_one(&mut self, id: &TimelineId) -> Result<(), Error> {
454
        if let Some(session) = self.open.remove(id) {
455
            session.close().await;
456
            return Ok(());
457
        }
458
        let Some(opening) = self.opening.remove(id) else {
459
            return Err(Error::new(
460
                ErrorKind::TimelineNotOpen,
461
                "timeline is not open",
462
            ));
463
        };
464
        opening.build.abort();
465
        self.queued -= opening.queued.len();
466
        Ok(())
467
    }
468
469
    async fn close(&mut self) {
470
        self.builds.shutdown().await;
471
        self.opening.clear();
472
        for (_, session) in self.open.drain() {
473
            session.close().await;
474
        }
475
    }
476
}