| 1 | use std::{future::Future, panic::AssertUnwindSafe, pin::Pin, sync::Arc}; |
| 2 | |
| 3 | use futures_util::{FutureExt, StreamExt}; |
| 4 | use matrix_sdk::{ |
| 5 | room::edit::EditedContent, |
| 6 | room::reply::{EnforceThread, Reply as SdkReply}, |
| 7 | ruma::{ |
| 8 | api::client::receipt::create_receipt::v3::ReceiptType, |
| 9 | events::{ |
| 10 | Mentions, |
| 11 | room::message::{ |
| 12 | AddMentions, Relation, ReplyWithinThread, RoomMessageEventContentWithoutRelation, |
| 13 | }, |
| 14 | }, |
| 15 | }, |
| 16 | }; |
| 17 | use matrix_sdk_ui::timeline::{Timeline, TimelineEventItemId}; |
| 18 | use ruma::{OwnedEventId, OwnedUserId}; |
| 19 | use tokio::{ |
| 20 | sync::mpsc, |
| 21 | task::{JoinHandle, JoinSet}, |
| 22 | }; |
| 23 | |
| 24 | use crate::{ |
| 25 | Error, ErrorKind, Event, HistoryState, MessageContent, MessageEditContent, MessageMentions, |
| 26 | RichText, TimelineCommand, TimelineId, |
| 27 | engine::MediaService, |
| 28 | normalise::{MediaScope, normalise_timeline, normalise_timeline_diffs}, |
| 29 | transport::{EventSender, Responder, SendEventError}, |
| 30 | }; |
| 31 | |
| 32 | const PAGINATION_QUEUE: usize = 32; |
| 33 | |
| 34 | /// long-lived tasks inside a room actor report panics here so the actor can die loudly |
| 35 | #[derive(Clone)] |
| 36 | pub(super) struct Supervisor(mpsc::UnboundedSender<&'static str>); |
| 37 | |
| 38 | impl Supervisor { |
| 39 | pub(super) fn new() -> (Self, mpsc::UnboundedReceiver<&'static str>) { |
| 40 | let (sender, receiver) = mpsc::unbounded_channel(); |
| 41 | (Self(sender), receiver) |
| 42 | } |
| 43 | |
| 44 | pub(super) fn spawn( |
| 45 | &self, |
| 46 | label: &'static str, |
| 47 | task: impl Future<Output = ()> + Send + 'static, |
| 48 | ) -> JoinHandle<()> { |
| 49 | let panics = self.0.clone(); |
| 50 | tokio::spawn(async move { |
| 51 | if AssertUnwindSafe(task).catch_unwind().await.is_err() { |
| 52 | let _ = panics.send(label); |
| 53 | } |
| 54 | }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// what a timeline session needs from the room that owns it |
| 59 | #[derive(Clone)] |
| 60 | pub(super) struct SessionContext { |
| 61 | pub(super) events: EventSender, |
| 62 | pub(super) media: Arc<MediaService>, |
| 63 | pub(super) current_user_id: Option<OwnedUserId>, |
| 64 | pub(super) initial_history_limit: u16, |
| 65 | pub(super) supervisor: Supervisor, |
| 66 | } |
| 67 | |
| 68 | pub(super) struct TimelineSession { |
| 69 | pub(super) id: TimelineId, |
| 70 | timeline: Arc<Timeline>, |
| 71 | context: SessionContext, |
| 72 | scope: MediaScope, |
| 73 | watcher: JoinHandle<()>, |
| 74 | pagination: mpsc::Sender<PaginationRequest>, |
| 75 | pagination_worker: JoinHandle<()>, |
| 76 | } |
| 77 | |
| 78 | struct PaginationRequest { |
| 79 | limit: u16, |
| 80 | reply: Option<Responder>, |
| 81 | } |
| 82 | |
| 83 | impl TimelineSession { |
| 84 | pub(super) async fn start( |
| 85 | id: TimelineId, |
| 86 | timeline: Timeline, |
| 87 | context: SessionContext, |
| 88 | ) -> Result<Self, SendEventError> { |
| 89 | let timeline = Arc::new(timeline); |
| 90 | let scope = MediaScope::new(); |
| 91 | let watcher = start_watcher(&id, &timeline, &context, &scope).await?; |
| 92 | let (pagination, requests) = mpsc::channel(PAGINATION_QUEUE); |
| 93 | let pagination_worker = context.supervisor.spawn( |
| 94 | "pagination worker", |
| 95 | run_pagination( |
| 96 | requests, |
| 97 | timeline.clone(), |
| 98 | context.events.clone(), |
| 99 | id.clone(), |
| 100 | ), |
| 101 | ); |
| 102 | let session = Self { |
| 103 | id, |
| 104 | timeline, |
| 105 | scope, |
| 106 | watcher, |
| 107 | pagination, |
| 108 | pagination_worker, |
| 109 | context, |
| 110 | }; |
| 111 | if session.context.initial_history_limit > 0 { |
| 112 | session.paginate(session.context.initial_history_limit, None); |
| 113 | } |
| 114 | Ok(session) |
| 115 | } |
| 116 | |
| 117 | /// swaps in a fresh watcher. the old one is dead before the reset goes out, |
| 118 | /// so no stale diff can land after it |
| 119 | pub(super) async fn resync(&mut self) -> Result<(), Error> { |
| 120 | self.watcher.abort(); |
| 121 | let _ = (&mut self.watcher).await; |
| 122 | self.watcher = start_watcher(&self.id, &self.timeline, &self.context, &self.scope) |
| 123 | .await |
| 124 | .map_err(|_| Error::new(ErrorKind::Timeline, "timeline reset could not be sent"))?; |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | pub(super) fn paginate(&self, limit: u16, reply: Option<Responder>) { |
| 129 | if let Err(error) = self.pagination.try_send(PaginationRequest { limit, reply }) { |
| 130 | let (request, error) = match error { |
| 131 | mpsc::error::TrySendError::Full(request) => ( |
| 132 | request, |
| 133 | Error::new(ErrorKind::QueueFull, "pagination queue is full"), |
| 134 | ), |
| 135 | mpsc::error::TrySendError::Closed(request) => ( |
| 136 | request, |
| 137 | Error::new(ErrorKind::TimelineNotOpen, "timeline is closing"), |
| 138 | ), |
| 139 | }; |
| 140 | if let Some(reply) = request.reply { |
| 141 | reply.done(Err(error)); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// pending paginations answer `Interrupted` as their responders drop |
| 147 | pub(super) async fn close(mut self) { |
| 148 | self.context.media.release(&self.scope).await; |
| 149 | self.pagination_worker.abort(); |
| 150 | let _ = (&mut self.pagination_worker).await; |
| 151 | self.watcher.abort(); |
| 152 | let _ = (&mut self.watcher).await; |
| 153 | } |
| 154 | |
| 155 | pub(super) async fn execute( |
| 156 | &self, |
| 157 | command: TimelineCommand, |
| 158 | reply: Responder, |
| 159 | work: &mut JoinSet<()>, |
| 160 | ) { |
| 161 | let timeline = self.timeline.clone(); |
| 162 | let thread_root = self.id.thread_root().cloned(); |
| 163 | let background: Pin<Box<dyn Future<Output = Result<(), Error>> + Send>> = match command { |
| 164 | TimelineCommand::Paginate { limit, .. } => return self.paginate(limit, Some(reply)), |
| 165 | // network-bound, so it runs beside the actor instead of queueing the room behind it |
| 166 | TimelineCommand::Redact { |
| 167 | event_id, reason, .. |
| 168 | } => Box::pin(async move { |
| 169 | timeline |
| 170 | .redact(&TimelineEventItemId::EventId(event_id), reason.as_deref()) |
| 171 | .await |
| 172 | .map_err(timeline_error) |
| 173 | }), |
| 174 | TimelineCommand::ToggleReaction { event_id, key, .. } => Box::pin(async move { |
| 175 | timeline |
| 176 | .toggle_reaction(&TimelineEventItemId::EventId(event_id), &key) |
| 177 | .await |
| 178 | .map(drop) |
| 179 | .map_err(timeline_error) |
| 180 | }), |
| 181 | TimelineCommand::MarkRead { event_id, .. } => Box::pin(async move { |
| 182 | let receipt_failed = |
| 183 | |source| Error::from_sdk("sending read receipt failed", source); |
| 184 | timeline |
| 185 | .send_single_receipt(ReceiptType::Read, event_id.clone()) |
| 186 | .await |
| 187 | .map_err(receipt_failed)?; |
| 188 | if thread_root.is_none() { |
| 189 | timeline |
| 190 | .send_single_receipt(ReceiptType::FullyRead, event_id) |
| 191 | .await |
| 192 | .map_err(receipt_failed)?; |
| 193 | } |
| 194 | Ok(()) |
| 195 | }), |
| 196 | command => return reply.done(self.execute_serial(command).await), |
| 197 | }; |
| 198 | work.spawn(async move { reply.done(background.await) }); |
| 199 | } |
| 200 | |
| 201 | /// sends stay on the actor so they hit the send queue in the order they were asked for |
| 202 | async fn execute_serial(&self, command: TimelineCommand) -> Result<(), Error> { |
| 203 | let timeline = &self.timeline; |
| 204 | match command { |
| 205 | TimelineCommand::Send { content, .. } => { |
| 206 | let body = match &content { |
| 207 | MessageContent::Text { content, .. } |
| 208 | | MessageContent::Emote { content, .. } |
| 209 | | MessageContent::Reply { content, .. } => &content.body, |
| 210 | }; |
| 211 | if body.trim().is_empty() { |
| 212 | return Err(Error::new(ErrorKind::EmptyBody, "message body is empty")); |
| 213 | } |
| 214 | let content = match content { |
| 215 | MessageContent::Text { content, mentions } => { |
| 216 | message_content(content, mentions, false).with_relation(None) |
| 217 | } |
| 218 | MessageContent::Emote { content, mentions } => { |
| 219 | message_content(content, mentions, true).with_relation(None) |
| 220 | } |
| 221 | MessageContent::Reply { |
| 222 | event_id, |
| 223 | content, |
| 224 | mentions, |
| 225 | notify_replied_to, |
| 226 | } => { |
| 227 | self.reply_content(event_id, content, mentions, notify_replied_to) |
| 228 | .await? |
| 229 | } |
| 230 | }; |
| 231 | timeline |
| 232 | .send(content.into()) |
| 233 | .await |
| 234 | .map(drop) |
| 235 | .map_err(timeline_error) |
| 236 | } |
| 237 | TimelineCommand::Edit { |
| 238 | event_id, content, .. |
| 239 | } => { |
| 240 | let (content, mentions, emote) = match content { |
| 241 | MessageEditContent::Text { content, mentions } => (content, mentions, false), |
| 242 | MessageEditContent::Emote { content, mentions } => (content, mentions, true), |
| 243 | }; |
| 244 | if content.body.trim().is_empty() { |
| 245 | return Err(Error::new(ErrorKind::EmptyBody, "message body is empty")); |
| 246 | } |
| 247 | timeline |
| 248 | .edit( |
| 249 | &TimelineEventItemId::EventId(event_id), |
| 250 | EditedContent::RoomMessage(message_content(content, mentions, emote)), |
| 251 | ) |
| 252 | .await |
| 253 | .map_err(timeline_error) |
| 254 | } |
| 255 | _ => Err(Error::new( |
| 256 | ErrorKind::Other, |
| 257 | "timeline command was misrouted", |
| 258 | )), |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | async fn reply_content( |
| 263 | &self, |
| 264 | event_id: OwnedEventId, |
| 265 | content: RichText, |
| 266 | mentions: MessageMentions, |
| 267 | notify_replied_to: bool, |
| 268 | ) -> Result<matrix_sdk::ruma::events::room::message::RoomMessageEventContent, Error> { |
| 269 | let thread_root = self.id.thread_root(); |
| 270 | let content = self |
| 271 | .timeline |
| 272 | .room() |
| 273 | .make_reply_event( |
| 274 | message_content(content, mentions, false), |
| 275 | SdkReply { |
| 276 | event_id, |
| 277 | enforce_thread: if thread_root.is_some() { |
| 278 | EnforceThread::Threaded(ReplyWithinThread::Yes) |
| 279 | } else { |
| 280 | EnforceThread::MaybeThreaded |
| 281 | }, |
| 282 | add_mentions: if notify_replied_to { |
| 283 | AddMentions::Yes |
| 284 | } else { |
| 285 | AddMentions::No |
| 286 | }, |
| 287 | }, |
| 288 | ) |
| 289 | .await |
| 290 | .map_err(|source| { |
| 291 | Error::with_source(ErrorKind::Timeline, "reply operation failed", source) |
| 292 | })?; |
| 293 | if let Some(thread_root) = thread_root |
| 294 | && !matches!( |
| 295 | content.relates_to.as_ref(), |
| 296 | Some(Relation::Thread(thread)) if &thread.event_id == thread_root |
| 297 | ) |
| 298 | { |
| 299 | return Err(Error::new( |
| 300 | ErrorKind::Invalid, |
| 301 | "reply target does not belong to the selected thread", |
| 302 | )); |
| 303 | } |
| 304 | Ok(content) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | impl Drop for TimelineSession { |
| 309 | fn drop(&mut self) { |
| 310 | self.watcher.abort(); |
| 311 | self.pagination_worker.abort(); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | async fn start_watcher( |
| 316 | id: &TimelineId, |
| 317 | timeline: &Arc<Timeline>, |
| 318 | context: &SessionContext, |
| 319 | scope: &MediaScope, |
| 320 | ) -> Result<JoinHandle<()>, SendEventError> { |
| 321 | let (items, mut stream) = timeline.subscribe().await; |
| 322 | let current_user_id = context.current_user_id.clone(); |
| 323 | let normalised = normalise_timeline(items.iter(), current_user_id.as_deref(), scope); |
| 324 | context.media.register(normalised.media).await; |
| 325 | context |
| 326 | .events |
| 327 | .send(Event::TimelineReset { |
| 328 | timeline_id: id.clone(), |
| 329 | items: normalised.items, |
| 330 | }) |
| 331 | .await?; |
| 332 | let id = id.clone(); |
| 333 | let events = context.events.clone(); |
| 334 | let media = context.media.clone(); |
| 335 | let scope = scope.clone(); |
| 336 | Ok(context.supervisor.spawn("timeline watcher", async move { |
| 337 | while let Some(diffs) = stream.next().await { |
| 338 | let normalised = normalise_timeline_diffs(diffs, current_user_id.as_deref(), &scope); |
| 339 | media.register(normalised.media).await; |
| 340 | let event = Event::TimelineChanged { |
| 341 | timeline_id: id.clone(), |
| 342 | diffs: normalised.diffs, |
| 343 | }; |
| 344 | if events.send(event).await.is_err() { |
| 345 | return; |
| 346 | } |
| 347 | } |
| 348 | })) |
| 349 | } |
| 350 | |
| 351 | async fn run_pagination( |
| 352 | mut requests: mpsc::Receiver<PaginationRequest>, |
| 353 | timeline: Arc<Timeline>, |
| 354 | events: EventSender, |
| 355 | timeline_id: TimelineId, |
| 356 | ) { |
| 357 | while let Some(PaginationRequest { limit, reply }) = requests.recv().await { |
| 358 | let history = |state| Event::HistoryChanged { |
| 359 | timeline_id: timeline_id.clone(), |
| 360 | state, |
| 361 | }; |
| 362 | if events.send(history(HistoryState::Loading)).await.is_err() { |
| 363 | return; |
| 364 | } |
| 365 | let result = timeline |
| 366 | .paginate_backwards(limit.max(1)) |
| 367 | .await |
| 368 | .map_err(timeline_error); |
| 369 | let state = match &result { |
| 370 | Ok(true) => HistoryState::StartReached, |
| 371 | Ok(false) => HistoryState::Idle, |
| 372 | Err(error) => HistoryState::Failed(error.to_string()), |
| 373 | }; |
| 374 | let _ = events.send(history(state)).await; |
| 375 | if let Some(reply) = reply { |
| 376 | reply.done(result.map(drop)); |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | fn message_content( |
| 382 | content: RichText, |
| 383 | mentions: MessageMentions, |
| 384 | emote: bool, |
| 385 | ) -> RoomMessageEventContentWithoutRelation { |
| 386 | let content = match content.formatted_body { |
| 387 | Some(formatted_body) if emote => { |
| 388 | RoomMessageEventContentWithoutRelation::emote_html(content.body, formatted_body) |
| 389 | } |
| 390 | Some(formatted_body) => { |
| 391 | RoomMessageEventContentWithoutRelation::text_html(content.body, formatted_body) |
| 392 | } |
| 393 | None if emote => RoomMessageEventContentWithoutRelation::emote_plain(content.body), |
| 394 | None => RoomMessageEventContentWithoutRelation::text_plain(content.body), |
| 395 | }; |
| 396 | let content = content.add_mentions(Mentions::with_user_ids(mentions.user_ids)); |
| 397 | if mentions.room { |
| 398 | content.add_mentions(Mentions::with_room_mention()) |
| 399 | } else { |
| 400 | content |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | pub(super) fn timeline_error(source: matrix_sdk_ui::timeline::Error) -> Error { |
| 405 | Error::with_source(ErrorKind::Timeline, "timeline operation failed", source) |
| 406 | } |