atagen

macltok

public
Star0
Watch0
02426f794ef3bdff89e4c0b11fdd136058c1614f
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/timeline.rsRust548 lines19.5 KB
1
use std::{collections::HashSet, future::Future, panic::AssertUnwindSafe, sync::Arc};
2
3
use futures_util::{FutureExt, StreamExt};
4
use matrix_sdk::SendOutsideWasm;
5
use matrix_sdk::{
6
    room::edit::EditedContent,
7
    room::reply::{EnforceThread, Reply as SdkReply},
8
    ruma::{
9
        api::client::receipt::create_receipt::v3::ReceiptType,
10
        events::room::message::{
11
            AddMentions, Relation, ReplyWithinThread, RoomMessageEventContentWithoutRelation,
12
        },
13
    },
14
};
15
use matrix_sdk_ui::timeline::{Timeline, TimelineEventItemId};
16
use ruma::{OwnedEventId, OwnedUserId};
17
use tokio::sync::{mpsc, oneshot};
18
19
use super::executor::{EngineBoxFuture, JoinHandle, TaskSet, spawn};
20
use crate::{
21
    Error, ErrorKind, Event, EventRef, HistoryState, MessageContent, MessageEditContent,
22
    MessageMentions, RichText, TimelineCommand, TimelineId,
23
    engine::MediaService,
24
    normalise::{MediaScope, normalise_timeline, normalise_timeline_diffs},
25
    transport::{EventSender, Responder, SendEventError},
26
    upload::sdk_mentions,
27
};
28
29
const PAGINATION_QUEUE: usize = 32;
30
31
/// long-lived tasks inside a room actor report panics here so the actor can die loudly
32
#[derive(Clone)]
33
pub(super) struct Supervisor(mpsc::UnboundedSender<&'static str>);
34
35
impl Supervisor {
36
    pub(super) fn new() -> (Self, mpsc::UnboundedReceiver<&'static str>) {
37
        let (sender, receiver) = mpsc::unbounded_channel();
38
        (Self(sender), receiver)
39
    }
40
41
    pub(super) fn spawn(
42
        &self,
43
        label: &'static str,
44
        task: impl Future<Output = ()> + SendOutsideWasm + 'static,
45
    ) -> JoinHandle<()> {
46
        let panics = self.0.clone();
47
        spawn(async move {
48
            if AssertUnwindSafe(task).catch_unwind().await.is_err() {
49
                let _ = panics.send(label);
50
            }
51
        })
52
    }
53
}
54
55
/// aborts its task when dropped, so an actor that dies mid-flight takes its helpers with it
56
pub(super) struct TaskGuard(pub(super) JoinHandle<()>);
57
58
impl Drop for TaskGuard {
59
    fn drop(&mut self) {
60
        self.0.abort();
61
    }
62
}
63
64
/// what a timeline session needs from the room that owns it
65
#[derive(Clone)]
66
pub(super) struct SessionContext {
67
    pub(super) events: EventSender,
68
    pub(super) media: Arc<MediaService>,
69
    pub(super) current_user_id: Option<OwnedUserId>,
70
    pub(super) initial_history_limit: u16,
71
    pub(super) supervisor: Supervisor,
72
}
73
74
pub(super) struct TimelineSession {
75
    pub(super) id: TimelineId,
76
    timeline: Arc<Timeline>,
77
    context: SessionContext,
78
    scope: MediaScope,
79
    watcher: JoinHandle<()>,
80
    fences: mpsc::UnboundedSender<Fence>,
81
    pagination: mpsc::Sender<PaginationRequest>,
82
    pagination_worker: JoinHandle<()>,
83
    member_fetch: JoinHandle<()>,
84
}
85
86
struct PaginationRequest {
87
    limit: u16,
88
    reply: Option<Responder>,
89
}
90
91
impl TimelineSession {
92
    pub(super) async fn start(
93
        id: TimelineId,
94
        timeline: Timeline,
95
        context: SessionContext,
96
    ) -> Result<Self, SendEventError> {
97
        let timeline = Arc::new(timeline);
98
        let scope = MediaScope::new();
99
        let (watcher, fences) = start_watcher(&id, &timeline, &context, &scope).await?;
100
        let (pagination, pagination_worker) = start_pagination_worker(&id, &timeline, &context);
101
        // under lazy-loaded members the sdk leaves sender profiles unavailable until someone
102
        // asks, and a /members fetched any other way never reaches the timeline's items
103
        let member_fetch = context.supervisor.spawn("member fetch", {
104
            let timeline = timeline.clone();
105
            async move { timeline.fetch_members().await }
106
        });
107
        let session = Self {
108
            id,
109
            timeline,
110
            scope,
111
            watcher,
112
            fences,
113
            pagination,
114
            pagination_worker,
115
            member_fetch,
116
            context,
117
        };
118
        if session.context.initial_history_limit > 0 && !matches!(session.id, TimelineId::Room(_)) {
119
            session.paginate(session.context.initial_history_limit, None);
120
        }
121
        Ok(session)
122
    }
123
124
    /// swaps in a fresh watcher. the old one is dead before the reset goes out,
125
    /// so no stale diff can land after it
126
    pub(super) async fn resync(&mut self) -> Result<(), Error> {
127
        self.watcher.abort();
128
        let _ = (&mut self.watcher).await;
129
        (self.watcher, self.fences) =
130
            start_watcher(&self.id, &self.timeline, &self.context, &self.scope)
131
                .await
132
                .map_err(|_| Error::new(ErrorKind::Timeline, "timeline reset could not be sent"))?;
133
        Ok(())
134
    }
135
136
    /// returns once the watcher has passed on the history the room cache committed
137
    pub(super) async fn publish_history(&self) -> Result<(), Error> {
138
        self.timeline
139
            .flush_history()
140
            .await
141
            .map_err(timeline_error)?;
142
        let (fence, drained) = oneshot::channel();
143
        self.fences.send(fence).map_err(|_| Error::interrupted())?;
144
        drained.await.map_err(|_| Error::interrupted())
145
    }
146
147
    pub(super) async fn has_events(&self) -> bool {
148
        self.timeline
149
            .items()
150
            .await
151
            .iter()
152
            .any(|item| item.as_event().is_some())
153
    }
154
155
    pub(super) fn paginate(&self, limit: u16, reply: Option<Responder>) {
156
        if let Err(error) = self.pagination.try_send(PaginationRequest { limit, reply }) {
157
            let (request, error) = match error {
158
                mpsc::error::TrySendError::Full(request) => (
159
                    request,
160
                    Error::new(ErrorKind::QueueFull, "pagination queue is full"),
161
                ),
162
                mpsc::error::TrySendError::Closed(request) => (
163
                    request,
164
                    Error::new(ErrorKind::TimelineNotOpen, "timeline is closing"),
165
                ),
166
            };
167
            if let Some(reply) = request.reply {
168
                reply.done(Err(error));
169
            }
170
        }
171
    }
172
173
    async fn stop_without_close(&mut self) {
174
        self.member_fetch.abort();
175
        self.pagination_worker.abort();
176
        self.watcher.abort();
177
        let _ = (&mut self.member_fetch).await;
178
        let _ = (&mut self.pagination_worker).await;
179
        let _ = (&mut self.watcher).await;
180
        // after the watcher, or a last diff could register media for a timeline that's gone
181
        self.context.media.release(&self.scope).await;
182
    }
183
184
    /// pending paginations answer `Interrupted` as their responders drop
185
    pub(super) async fn close(mut self) {
186
        self.stop_without_close().await;
187
        let _ = self
188
            .context
189
            .events
190
            .send(Event::TimelineClosed {
191
                timeline_id: self.id.clone(),
192
            })
193
            .await;
194
    }
195
196
    pub(super) async fn execute(
197
        &self,
198
        command: TimelineCommand,
199
        reply: Responder,
200
        work: &mut TaskSet<()>,
201
    ) {
202
        let timeline = self.timeline.clone();
203
        let thread_root = self.id.thread_root().cloned();
204
        let background: EngineBoxFuture<'static, Result<(), Error>> = match command {
205
            TimelineCommand::Paginate { limit, .. } => return self.paginate(limit, Some(reply)),
206
            // network-bound, so it runs beside the actor instead of queueing the room behind it
207
            TimelineCommand::Redact { target, reason, .. } => Box::pin(async move {
208
                timeline
209
                    .redact(&item_id(target), reason.as_deref())
210
                    .await
211
                    .map_err(timeline_error)
212
            }),
213
            TimelineCommand::ToggleReaction {
214
                target,
215
                key,
216
                shortcode,
217
                ..
218
            } => Box::pin(async move {
219
                timeline
220
                    .toggle_reaction_with_shortcode(&item_id(target), &key, shortcode.as_deref())
221
                    .await
222
                    .map(drop)
223
                    .map_err(timeline_error)
224
            }),
225
            TimelineCommand::MarkRead { event_id, .. } => Box::pin(async move {
226
                let receipt_failed =
227
                    |source| Error::from_sdk("sending read receipt failed", source);
228
                timeline
229
                    .send_single_receipt(ReceiptType::Read, event_id.clone())
230
                    .await
231
                    .map_err(receipt_failed)?;
232
                if thread_root.is_none() {
233
                    timeline
234
                        .send_single_receipt(ReceiptType::FullyRead, event_id)
235
                        .await
236
                        .map_err(receipt_failed)?;
237
                }
238
                Ok(())
239
            }),
240
            command => return reply.done(self.execute_serial(command).await),
241
        };
242
        work.spawn(async move { reply.done(background.await) });
243
    }
244
245
    /// sends stay on the actor so they hit the send queue in the order they were asked for
246
    async fn execute_serial(&self, command: TimelineCommand) -> Result<(), Error> {
247
        let timeline = &self.timeline;
248
        match command {
249
            TimelineCommand::Send { content, .. } => {
250
                let body = match &content {
251
                    MessageContent::Text { content, .. }
252
                    | MessageContent::Emote { content, .. }
253
                    | MessageContent::Notice { content, .. }
254
                    | MessageContent::Reply { content, .. } => &content.body,
255
                };
256
                if body.trim().is_empty() {
257
                    return Err(Error::new(ErrorKind::EmptyBody, "message body is empty"));
258
                }
259
                let content = match content {
260
                    MessageContent::Text { content, mentions } => {
261
                        message_content(content, mentions, Msgtype::Text).with_relation(None)
262
                    }
263
                    MessageContent::Emote { content, mentions } => {
264
                        message_content(content, mentions, Msgtype::Emote).with_relation(None)
265
                    }
266
                    MessageContent::Notice { content, mentions } => {
267
                        message_content(content, mentions, Msgtype::Notice).with_relation(None)
268
                    }
269
                    MessageContent::Reply {
270
                        event_id,
271
                        content,
272
                        mentions,
273
                        notify_replied_to,
274
                    } => {
275
                        self.reply_content(event_id, content, mentions, notify_replied_to)
276
                            .await?
277
                    }
278
                };
279
                timeline
280
                    .send(content.into())
281
                    .await
282
                    .map(drop)
283
                    .map_err(timeline_error)
284
            }
285
            TimelineCommand::Edit {
286
                target, content, ..
287
            } => {
288
                let (content, mentions, msgtype) = match content {
289
                    MessageEditContent::Text { content, mentions } => {
290
                        (content, mentions, Msgtype::Text)
291
                    }
292
                    MessageEditContent::Emote { content, mentions } => {
293
                        (content, mentions, Msgtype::Emote)
294
                    }
295
                };
296
                if content.body.trim().is_empty() {
297
                    return Err(Error::new(ErrorKind::EmptyBody, "message body is empty"));
298
                }
299
                timeline
300
                    .edit(
301
                        &item_id(target),
302
                        EditedContent::RoomMessage(message_content(content, mentions, msgtype)),
303
                    )
304
                    .await
305
                    .map_err(timeline_error)
306
            }
307
            _ => Err(Error::new(
308
                ErrorKind::Other,
309
                "timeline command was misrouted",
310
            )),
311
        }
312
    }
313
314
    async fn reply_content(
315
        &self,
316
        event_id: OwnedEventId,
317
        content: RichText,
318
        mentions: MessageMentions,
319
        notify_replied_to: bool,
320
    ) -> Result<matrix_sdk::ruma::events::room::message::RoomMessageEventContent, Error> {
321
        let thread_root = self.id.thread_root();
322
        let content = self
323
            .timeline
324
            .room()
325
            .make_reply_event(
326
                message_content(content, mentions, Msgtype::Text),
327
                SdkReply {
328
                    event_id,
329
                    enforce_thread: if thread_root.is_some() {
330
                        EnforceThread::Threaded(ReplyWithinThread::Yes)
331
                    } else {
332
                        EnforceThread::MaybeThreaded
333
                    },
334
                    add_mentions: if notify_replied_to {
335
                        AddMentions::Yes
336
                    } else {
337
                        AddMentions::No
338
                    },
339
                },
340
            )
341
            .await
342
            .map_err(|source| {
343
                Error::with_source(ErrorKind::Timeline, "reply operation failed", source)
344
            })?;
345
        if let Some(thread_root) = thread_root
346
            && !matches!(
347
                content.relates_to.as_ref(),
348
                Some(Relation::Thread(thread)) if &thread.event_id == thread_root
349
            )
350
        {
351
            return Err(Error::new(
352
                ErrorKind::Invalid,
353
                "reply target does not belong to the selected thread",
354
            ));
355
        }
356
        Ok(content)
357
    }
358
}
359
360
fn start_pagination_worker(
361
    id: &TimelineId,
362
    timeline: &Arc<Timeline>,
363
    context: &SessionContext,
364
) -> (mpsc::Sender<PaginationRequest>, JoinHandle<()>) {
365
    let (pagination, requests) = mpsc::channel(PAGINATION_QUEUE);
366
    let worker = context.supervisor.spawn(
367
        "pagination worker",
368
        run_pagination(
369
            requests,
370
            timeline.clone(),
371
            context.events.clone(),
372
            id.clone(),
373
        ),
374
    );
375
    (pagination, worker)
376
}
377
378
impl Drop for TimelineSession {
379
    fn drop(&mut self) {
380
        self.watcher.abort();
381
        self.pagination_worker.abort();
382
        self.member_fetch.abort();
383
    }
384
}
385
386
fn item_id(target: EventRef) -> TimelineEventItemId {
387
    match target {
388
        EventRef::Remote(event_id) => TimelineEventItemId::EventId(event_id),
389
        EventRef::Local(transaction_id) => TimelineEventItemId::TransactionId(transaction_id),
390
    }
391
}
392
393
/// the sdk leaves a reply's target unloaded until someone asks, so the watcher asks, once per event
394
struct ReplyFetcher {
395
    timeline: Arc<Timeline>,
396
    asked: HashSet<OwnedEventId>,
397
    fetches: TaskSet<()>,
398
}
399
400
impl ReplyFetcher {
401
    fn fetch(&mut self, missing: Vec<OwnedEventId>) {
402
        for event_id in missing {
403
            if self.asked.insert(event_id.clone()) {
404
                let timeline = self.timeline.clone();
405
                self.fetches.spawn(async move {
406
                    if let Err(error) = timeline.fetch_details_for_event(&event_id).await {
407
                        tracing::debug!(%event_id, %error, "fetching reply details failed");
408
                    }
409
                });
410
            }
411
        }
412
    }
413
}
414
415
/// asks the watcher to pass on every diff the timeline already holds, then answers
416
type Fence = oneshot::Sender<()>;
417
418
async fn start_watcher(
419
    id: &TimelineId,
420
    timeline: &Arc<Timeline>,
421
    context: &SessionContext,
422
    scope: &MediaScope,
423
) -> Result<(JoinHandle<()>, mpsc::UnboundedSender<Fence>), SendEventError> {
424
    let (items, mut stream) = timeline.subscribe().await;
425
    let current_user_id = context.current_user_id.clone();
426
    let normalised = normalise_timeline(items.iter(), current_user_id.as_deref(), scope);
427
    context.media.register(scope, normalised.media).await;
428
    context
429
        .events
430
        .send(Event::TimelineReset {
431
            timeline_id: id.clone(),
432
            items: normalised.items,
433
        })
434
        .await?;
435
    let mut replies = ReplyFetcher {
436
        timeline: timeline.clone(),
437
        asked: HashSet::new(),
438
        fetches: TaskSet::new(),
439
    };
440
    replies.fetch(normalised.missing_replies);
441
    let (fences, mut fence_requests) = mpsc::unbounded_channel::<Fence>();
442
    let id = id.clone();
443
    let events = context.events.clone();
444
    let media = context.media.clone();
445
    let scope = scope.clone();
446
    let task = context.supervisor.spawn("timeline watcher", async move {
447
        loop {
448
            let (diffs, fence) = tokio::select! {
449
                diffs = stream.next() => match diffs {
450
                    Some(diffs) => (vec![diffs], None),
451
                    None => return,
452
                },
453
                Some(fence) = fence_requests.recv() => {
454
                    let mut ready = Vec::new();
455
                    while let Some(diffs) = stream.next().now_or_never() {
456
                        match diffs {
457
                            Some(diffs) => ready.push(diffs),
458
                            None => return,
459
                        }
460
                    }
461
                    (ready, Some(fence))
462
                }
463
                Some(_) = replies.fetches.join_next(), if !replies.fetches.is_empty() => continue,
464
            };
465
            for diffs in diffs {
466
                let normalised =
467
                    normalise_timeline_diffs(diffs, current_user_id.as_deref(), &scope);
468
                media.register(&scope, normalised.media).await;
469
                replies.fetch(normalised.missing_replies);
470
                if normalised.diffs.is_empty() {
471
                    continue;
472
                }
473
                let event = Event::TimelineChanged {
474
                    timeline_id: id.clone(),
475
                    diffs: normalised.diffs,
476
                };
477
                if events.send(event).await.is_err() {
478
                    return;
479
                }
480
            }
481
            if let Some(fence) = fence {
482
                let _ = fence.send(());
483
            }
484
        }
485
    });
486
    Ok((task, fences))
487
}
488
489
async fn run_pagination(
490
    mut requests: mpsc::Receiver<PaginationRequest>,
491
    timeline: Arc<Timeline>,
492
    events: EventSender,
493
    timeline_id: TimelineId,
494
) {
495
    while let Some(PaginationRequest { limit, reply }) = requests.recv().await {
496
        let history = |state| Event::HistoryChanged {
497
            timeline_id: timeline_id.clone(),
498
            state,
499
        };
500
        if events.send(history(HistoryState::Loading)).await.is_err() {
501
            return;
502
        }
503
        tracing::debug!(?timeline_id, limit, "paginating backwards");
504
        let result = timeline
505
            .paginate_backwards(limit.max(1))
506
            .await
507
            .map_err(timeline_error);
508
        tracing::debug!(?timeline_id, ?result, "paginated backwards");
509
        let state = match &result {
510
            Ok(true) => HistoryState::StartReached,
511
            Ok(false) => HistoryState::Idle,
512
            Err(error) => HistoryState::Failed(error.to_string()),
513
        };
514
        let _ = events.send(history(state)).await;
515
        if let Some(reply) = reply {
516
            reply.done(result.map(drop));
517
        }
518
    }
519
}
520
521
#[derive(Clone, Copy)]
522
enum Msgtype {
523
    Text,
524
    Emote,
525
    Notice,
526
}
527
528
fn message_content(
529
    content: RichText,
530
    mentions: MessageMentions,
531
    msgtype: Msgtype,
532
) -> RoomMessageEventContentWithoutRelation {
533
    type Content = RoomMessageEventContentWithoutRelation;
534
    let (body, formatted_body) = (content.body, content.formatted_body);
535
    let content = match (msgtype, formatted_body) {
536
        (Msgtype::Text, Some(html)) => Content::text_html(body, html),
537
        (Msgtype::Text, None) => Content::text_plain(body),
538
        (Msgtype::Emote, Some(html)) => Content::emote_html(body, html),
539
        (Msgtype::Emote, None) => Content::emote_plain(body),
540
        (Msgtype::Notice, Some(html)) => Content::notice_html(body, html),
541
        (Msgtype::Notice, None) => Content::notice_plain(body),
542
    };
543
    content.add_mentions(sdk_mentions(mentions))
544
}
545
546
pub(super) fn timeline_error(source: matrix_sdk_ui::timeline::Error) -> Error {
547
    Error::with_source(ErrorKind::Timeline, "timeline operation failed", source)
548
}