atagen

macltok

public
Star0
Watch0
f137a3c74d1144698237fe4ac1bddd483f9ec85e
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/timeline.rsRust476 lines16.8 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;
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
    pagination: mpsc::Sender<PaginationRequest>,
81
    pagination_worker: JoinHandle<()>,
82
}
83
84
struct PaginationRequest {
85
    limit: u16,
86
    reply: Option<Responder>,
87
}
88
89
impl TimelineSession {
90
    pub(super) async fn start(
91
        id: TimelineId,
92
        timeline: Timeline,
93
        context: SessionContext,
94
    ) -> Result<Self, SendEventError> {
95
        let timeline = Arc::new(timeline);
96
        let scope = MediaScope::new();
97
        let watcher = start_watcher(&id, &timeline, &context, &scope).await?;
98
        let (pagination, requests) = mpsc::channel(PAGINATION_QUEUE);
99
        let pagination_worker = context.supervisor.spawn(
100
            "pagination worker",
101
            run_pagination(
102
                requests,
103
                timeline.clone(),
104
                context.events.clone(),
105
                id.clone(),
106
            ),
107
        );
108
        let session = Self {
109
            id,
110
            timeline,
111
            scope,
112
            watcher,
113
            pagination,
114
            pagination_worker,
115
            context,
116
        };
117
        if session.context.initial_history_limit > 0 {
118
            session.paginate(session.context.initial_history_limit, None);
119
        }
120
        Ok(session)
121
    }
122
123
    /// swaps in a fresh watcher. the old one is dead before the reset goes out,
124
    /// so no stale diff can land after it
125
    pub(super) async fn resync(&mut self) -> Result<(), Error> {
126
        self.watcher.abort();
127
        let _ = (&mut self.watcher).await;
128
        self.watcher = start_watcher(&self.id, &self.timeline, &self.context, &self.scope)
129
            .await
130
            .map_err(|_| Error::new(ErrorKind::Timeline, "timeline reset could not be sent"))?;
131
        Ok(())
132
    }
133
134
    pub(super) fn paginate(&self, limit: u16, reply: Option<Responder>) {
135
        if let Err(error) = self.pagination.try_send(PaginationRequest { limit, reply }) {
136
            let (request, error) = match error {
137
                mpsc::error::TrySendError::Full(request) => (
138
                    request,
139
                    Error::new(ErrorKind::QueueFull, "pagination queue is full"),
140
                ),
141
                mpsc::error::TrySendError::Closed(request) => (
142
                    request,
143
                    Error::new(ErrorKind::TimelineNotOpen, "timeline is closing"),
144
                ),
145
            };
146
            if let Some(reply) = request.reply {
147
                reply.done(Err(error));
148
            }
149
        }
150
    }
151
152
    /// pending paginations answer `Interrupted` as their responders drop
153
    pub(super) async fn close(mut self) {
154
        self.pagination_worker.abort();
155
        let _ = (&mut self.pagination_worker).await;
156
        self.watcher.abort();
157
        let _ = (&mut self.watcher).await;
158
        // after the watcher, or a last diff could register media for a timeline that's gone
159
        self.context.media.release(&self.scope).await;
160
        let _ = self
161
            .context
162
            .events
163
            .send(Event::TimelineClosed {
164
                timeline_id: self.id.clone(),
165
            })
166
            .await;
167
    }
168
169
    pub(super) async fn execute(
170
        &self,
171
        command: TimelineCommand,
172
        reply: Responder,
173
        work: &mut TaskSet<()>,
174
    ) {
175
        let timeline = self.timeline.clone();
176
        let thread_root = self.id.thread_root().cloned();
177
        let background: EngineBoxFuture<'static, Result<(), Error>> = match command {
178
            TimelineCommand::Paginate { limit, .. } => return self.paginate(limit, Some(reply)),
179
            // network-bound, so it runs beside the actor instead of queueing the room behind it
180
            TimelineCommand::Redact { target, reason, .. } => Box::pin(async move {
181
                timeline
182
                    .redact(&item_id(target), reason.as_deref())
183
                    .await
184
                    .map_err(timeline_error)
185
            }),
186
            TimelineCommand::ToggleReaction {
187
                target,
188
                key,
189
                shortcode,
190
                ..
191
            } => Box::pin(async move {
192
                timeline
193
                    .toggle_reaction_with_shortcode(&item_id(target), &key, shortcode.as_deref())
194
                    .await
195
                    .map(drop)
196
                    .map_err(timeline_error)
197
            }),
198
            TimelineCommand::MarkRead { event_id, .. } => Box::pin(async move {
199
                let receipt_failed =
200
                    |source| Error::from_sdk("sending read receipt failed", source);
201
                timeline
202
                    .send_single_receipt(ReceiptType::Read, event_id.clone())
203
                    .await
204
                    .map_err(receipt_failed)?;
205
                if thread_root.is_none() {
206
                    timeline
207
                        .send_single_receipt(ReceiptType::FullyRead, event_id)
208
                        .await
209
                        .map_err(receipt_failed)?;
210
                }
211
                Ok(())
212
            }),
213
            command => return reply.done(self.execute_serial(command).await),
214
        };
215
        work.spawn(async move { reply.done(background.await) });
216
    }
217
218
    /// sends stay on the actor so they hit the send queue in the order they were asked for
219
    async fn execute_serial(&self, command: TimelineCommand) -> Result<(), Error> {
220
        let timeline = &self.timeline;
221
        match command {
222
            TimelineCommand::Send { content, .. } => {
223
                let body = match &content {
224
                    MessageContent::Text { content, .. }
225
                    | MessageContent::Emote { content, .. }
226
                    | MessageContent::Notice { content, .. }
227
                    | MessageContent::Reply { content, .. } => &content.body,
228
                };
229
                if body.trim().is_empty() {
230
                    return Err(Error::new(ErrorKind::EmptyBody, "message body is empty"));
231
                }
232
                let content = match content {
233
                    MessageContent::Text { content, mentions } => {
234
                        message_content(content, mentions, Msgtype::Text).with_relation(None)
235
                    }
236
                    MessageContent::Emote { content, mentions } => {
237
                        message_content(content, mentions, Msgtype::Emote).with_relation(None)
238
                    }
239
                    MessageContent::Notice { content, mentions } => {
240
                        message_content(content, mentions, Msgtype::Notice).with_relation(None)
241
                    }
242
                    MessageContent::Reply {
243
                        event_id,
244
                        content,
245
                        mentions,
246
                        notify_replied_to,
247
                    } => {
248
                        self.reply_content(event_id, content, mentions, notify_replied_to)
249
                            .await?
250
                    }
251
                };
252
                timeline
253
                    .send(content.into())
254
                    .await
255
                    .map(drop)
256
                    .map_err(timeline_error)
257
            }
258
            TimelineCommand::Edit {
259
                target, content, ..
260
            } => {
261
                let (content, mentions, msgtype) = match content {
262
                    MessageEditContent::Text { content, mentions } => {
263
                        (content, mentions, Msgtype::Text)
264
                    }
265
                    MessageEditContent::Emote { content, mentions } => {
266
                        (content, mentions, Msgtype::Emote)
267
                    }
268
                };
269
                if content.body.trim().is_empty() {
270
                    return Err(Error::new(ErrorKind::EmptyBody, "message body is empty"));
271
                }
272
                timeline
273
                    .edit(
274
                        &item_id(target),
275
                        EditedContent::RoomMessage(message_content(content, mentions, msgtype)),
276
                    )
277
                    .await
278
                    .map_err(timeline_error)
279
            }
280
            _ => Err(Error::new(
281
                ErrorKind::Other,
282
                "timeline command was misrouted",
283
            )),
284
        }
285
    }
286
287
    async fn reply_content(
288
        &self,
289
        event_id: OwnedEventId,
290
        content: RichText,
291
        mentions: MessageMentions,
292
        notify_replied_to: bool,
293
    ) -> Result<matrix_sdk::ruma::events::room::message::RoomMessageEventContent, Error> {
294
        let thread_root = self.id.thread_root();
295
        let content = self
296
            .timeline
297
            .room()
298
            .make_reply_event(
299
                message_content(content, mentions, Msgtype::Text),
300
                SdkReply {
301
                    event_id,
302
                    enforce_thread: if thread_root.is_some() {
303
                        EnforceThread::Threaded(ReplyWithinThread::Yes)
304
                    } else {
305
                        EnforceThread::MaybeThreaded
306
                    },
307
                    add_mentions: if notify_replied_to {
308
                        AddMentions::Yes
309
                    } else {
310
                        AddMentions::No
311
                    },
312
                },
313
            )
314
            .await
315
            .map_err(|source| {
316
                Error::with_source(ErrorKind::Timeline, "reply operation failed", source)
317
            })?;
318
        if let Some(thread_root) = thread_root
319
            && !matches!(
320
                content.relates_to.as_ref(),
321
                Some(Relation::Thread(thread)) if &thread.event_id == thread_root
322
            )
323
        {
324
            return Err(Error::new(
325
                ErrorKind::Invalid,
326
                "reply target does not belong to the selected thread",
327
            ));
328
        }
329
        Ok(content)
330
    }
331
}
332
333
impl Drop for TimelineSession {
334
    fn drop(&mut self) {
335
        self.watcher.abort();
336
        self.pagination_worker.abort();
337
    }
338
}
339
340
fn item_id(target: EventRef) -> TimelineEventItemId {
341
    match target {
342
        EventRef::Remote(event_id) => TimelineEventItemId::EventId(event_id),
343
        EventRef::Local(transaction_id) => TimelineEventItemId::TransactionId(transaction_id),
344
    }
345
}
346
347
/// the sdk leaves a reply's target unloaded until someone asks, so the watcher asks, once per event
348
struct ReplyFetcher {
349
    timeline: Arc<Timeline>,
350
    asked: HashSet<OwnedEventId>,
351
    fetches: TaskSet<()>,
352
}
353
354
impl ReplyFetcher {
355
    fn fetch(&mut self, missing: Vec<OwnedEventId>) {
356
        for event_id in missing {
357
            if self.asked.insert(event_id.clone()) {
358
                let timeline = self.timeline.clone();
359
                self.fetches.spawn(async move {
360
                    if let Err(error) = timeline.fetch_details_for_event(&event_id).await {
361
                        tracing::debug!(%event_id, %error, "fetching reply details failed");
362
                    }
363
                });
364
            }
365
        }
366
    }
367
}
368
369
async fn start_watcher(
370
    id: &TimelineId,
371
    timeline: &Arc<Timeline>,
372
    context: &SessionContext,
373
    scope: &MediaScope,
374
) -> Result<JoinHandle<()>, SendEventError> {
375
    let (items, mut stream) = timeline.subscribe().await;
376
    let current_user_id = context.current_user_id.clone();
377
    let normalised = normalise_timeline(items.iter(), current_user_id.as_deref(), scope);
378
    context.media.register(normalised.media).await;
379
    context
380
        .events
381
        .send(Event::TimelineReset {
382
            timeline_id: id.clone(),
383
            items: normalised.items,
384
        })
385
        .await?;
386
    let mut replies = ReplyFetcher {
387
        timeline: timeline.clone(),
388
        asked: HashSet::new(),
389
        fetches: TaskSet::new(),
390
    };
391
    replies.fetch(normalised.missing_replies);
392
    let id = id.clone();
393
    let events = context.events.clone();
394
    let media = context.media.clone();
395
    let scope = scope.clone();
396
    Ok(context.supervisor.spawn("timeline watcher", async move {
397
        loop {
398
            let diffs = tokio::select! {
399
                diffs = stream.next() => match diffs {
400
                    Some(diffs) => diffs,
401
                    None => return,
402
                },
403
                Some(_) = replies.fetches.join_next(), if !replies.fetches.is_empty() => continue,
404
            };
405
            let normalised = normalise_timeline_diffs(diffs, current_user_id.as_deref(), &scope);
406
            media.register(normalised.media).await;
407
            replies.fetch(normalised.missing_replies);
408
            let event = Event::TimelineChanged {
409
                timeline_id: id.clone(),
410
                diffs: normalised.diffs,
411
            };
412
            if events.send(event).await.is_err() {
413
                return;
414
            }
415
        }
416
    }))
417
}
418
419
async fn run_pagination(
420
    mut requests: mpsc::Receiver<PaginationRequest>,
421
    timeline: Arc<Timeline>,
422
    events: EventSender,
423
    timeline_id: TimelineId,
424
) {
425
    while let Some(PaginationRequest { limit, reply }) = requests.recv().await {
426
        let history = |state| Event::HistoryChanged {
427
            timeline_id: timeline_id.clone(),
428
            state,
429
        };
430
        if events.send(history(HistoryState::Loading)).await.is_err() {
431
            return;
432
        }
433
        let result = timeline
434
            .paginate_backwards(limit.max(1))
435
            .await
436
            .map_err(timeline_error);
437
        let state = match &result {
438
            Ok(true) => HistoryState::StartReached,
439
            Ok(false) => HistoryState::Idle,
440
            Err(error) => HistoryState::Failed(error.to_string()),
441
        };
442
        let _ = events.send(history(state)).await;
443
        if let Some(reply) = reply {
444
            reply.done(result.map(drop));
445
        }
446
    }
447
}
448
449
#[derive(Clone, Copy)]
450
enum Msgtype {
451
    Text,
452
    Emote,
453
    Notice,
454
}
455
456
fn message_content(
457
    content: RichText,
458
    mentions: MessageMentions,
459
    msgtype: Msgtype,
460
) -> RoomMessageEventContentWithoutRelation {
461
    type Content = RoomMessageEventContentWithoutRelation;
462
    let (body, formatted_body) = (content.body, content.formatted_body);
463
    let content = match (msgtype, formatted_body) {
464
        (Msgtype::Text, Some(html)) => Content::text_html(body, html),
465
        (Msgtype::Text, None) => Content::text_plain(body),
466
        (Msgtype::Emote, Some(html)) => Content::emote_html(body, html),
467
        (Msgtype::Emote, None) => Content::emote_plain(body),
468
        (Msgtype::Notice, Some(html)) => Content::notice_html(body, html),
469
        (Msgtype::Notice, None) => Content::notice_plain(body),
470
    };
471
    content.add_mentions(sdk_mentions(mentions))
472
}
473
474
pub(super) fn timeline_error(source: matrix_sdk_ui::timeline::Error) -> Error {
475
    Error::with_source(ErrorKind::Timeline, "timeline operation failed", source)
476
}