1use std::{
40 cmp::Ordering,
41 collections::{BinaryHeap, HashMap},
42 num::NonZeroUsize,
43 ops::ControlFlow,
44 sync::{Arc, Weak},
45};
46
47use matrix_sdk_base::{RoomState, locks::Mutex, task_monitor::TaskMonitor};
48use matrix_sdk_common::executor::{AbortOnDrop, JoinHandleExt as _, spawn};
49use ruma::OwnedRoomId;
50use tokio::sync::{mpsc, oneshot};
51use tokio_util::sync::{CancellationToken, DropGuard};
52use tracing::{debug, info, instrument, trace, warn};
53
54use super::{EventCacheInner, caches::pagination::BackPaginationOutcome};
55
56pub(crate) const BATCH_SIZE: u16 = 30;
58
59#[allow(dead_code)]
62#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
63pub(crate) enum Priority {
64 Low,
67 Normal,
70 High,
72}
73
74pub(crate) type StopCondition = Box<dyn FnMut(&BackPaginationOutcome) -> ControlFlow<()> + Send>;
82
83pub(crate) struct BackPaginationRequest {
86 pub room_id: OwnedRoomId,
88 pub priority: Priority,
90 pub stop: StopCondition,
92 pub batch_size: u16,
94 pub max_batches: Option<usize>,
96}
97
98#[cfg(not(tarpaulin_include))]
99impl std::fmt::Debug for BackPaginationRequest {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 f.debug_struct("BackPaginationRequest")
102 .field("room_id", &self.room_id)
103 .field("priority", &self.priority)
104 .field("batch_size", &self.batch_size)
105 .field("max_batches", &self.max_batches)
106 .finish_non_exhaustive()
107 }
108}
109
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub(crate) enum BackPaginationStopReason {
113 ReachedTimelineStart,
115 StopConditionMet,
117 BatchLimitReached,
120 NoDataAvailable,
123 Failed,
125 Cancelled,
127 Skipped,
130}
131
132#[allow(dead_code)]
134#[derive(Clone, Copy, Debug)]
135pub(crate) struct BackPaginationRunResult {
136 pub reason: BackPaginationStopReason,
138}
139
140type RequestCoalescingKey = (OwnedRoomId, Priority);
142
143pub(crate) struct BackPaginationHandle {
146 guard: Arc<DropGuard>,
149 #[allow(dead_code)]
151 completion: Option<oneshot::Receiver<BackPaginationRunResult>>,
152}
153
154#[cfg(not(tarpaulin_include))]
155impl std::fmt::Debug for BackPaginationHandle {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 f.debug_struct("BackPaginationHandle").finish_non_exhaustive()
158 }
159}
160
161impl BackPaginationHandle {
162 pub(crate) fn detach(self) {
168 if let Some(guard) = Arc::into_inner(self.guard) {
169 guard.disarm();
170 }
171 }
172
173 #[allow(dead_code)]
175 pub(crate) async fn join(mut self) -> BackPaginationRunResult {
176 let cancelled = BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
177 match self.completion.take() {
178 Some(completion) => completion.await.unwrap_or(cancelled),
179 None => cancelled,
180 }
181 }
182}
183
184#[derive(Clone)]
186pub struct BackPaginationQueue {
187 inner: Arc<BackPaginationQueueInner>,
188}
189
190struct BackPaginationQueueInner {
191 sender: mpsc::UnboundedSender<SchedulerEvent>,
192 cancellations: Mutex<HashMap<RequestCoalescingKey, SharedCancellation>>,
199 task: matrix_sdk_base::task_monitor::BackgroundTaskHandle,
200}
201
202struct SharedCancellation {
204 token: CancellationToken,
206 guard: Weak<DropGuard>,
209}
210
211#[cfg(not(tarpaulin_include))]
212impl std::fmt::Debug for BackPaginationQueue {
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 f.debug_struct("BackPaginationQueue").finish_non_exhaustive()
215 }
216}
217
218impl BackPaginationQueue {
219 pub(super) fn new(
221 event_cache: Weak<EventCacheInner>,
222 max_concurrent: NonZeroUsize,
223 task_monitor: &TaskMonitor,
224 ) -> Self {
225 let (sender, receiver) = mpsc::unbounded_channel();
226
227 let task = task_monitor
231 .spawn_infinite_task(
232 "event_cache::back_pagination_queue",
233 scheduler(event_cache, receiver, sender.clone(), max_concurrent.get()),
234 )
235 .abort_on_drop();
236
237 Self {
238 inner: Arc::new(BackPaginationQueueInner {
239 sender,
240 cancellations: Mutex::new(HashMap::new()),
241 task,
242 }),
243 }
244 }
245
246 pub(crate) fn enqueue(
250 &self,
251 request: BackPaginationRequest,
252 ) -> Result<BackPaginationHandle, BackPaginationQueueError> {
253 let key = (request.room_id.clone(), request.priority);
254 let (token, guard) = cancellation_for(&self.inner.cancellations, key);
255
256 let (completion_tx, completion_rx) = oneshot::channel();
257 let submitted = SubmittedRequest { request, token, completion: completion_tx };
258
259 self.inner
260 .sender
261 .send(SchedulerEvent::Submitted(submitted))
262 .map_err(|_| BackPaginationQueueError::ShutDown)?;
263
264 Ok(BackPaginationHandle { guard, completion: Some(completion_rx) })
265 }
266
267 pub(super) fn shut_down(&self) {
273 self.inner.task.abort();
274 }
275}
276
277fn cancellation_for(
284 cancellations: &Mutex<HashMap<RequestCoalescingKey, SharedCancellation>>,
285 key: RequestCoalescingKey,
286) -> (CancellationToken, Arc<DropGuard>) {
287 let mut cancellations = cancellations.lock();
288
289 if let Some(existing) = cancellations.get(&key)
290 && let Some(guard) = existing.guard.upgrade()
291 {
292 return (existing.token.clone(), guard);
293 }
294
295 cancellations.retain(|_, cancellation| cancellation.guard.strong_count() > 0);
297
298 let token = CancellationToken::new();
299 let guard = Arc::new(token.clone().drop_guard());
300 cancellations
301 .insert(key, SharedCancellation { token: token.clone(), guard: Arc::downgrade(&guard) });
302
303 (token, guard)
304}
305
306#[derive(Debug, thiserror::Error)]
308pub(crate) enum BackPaginationQueueError {
309 #[error("the back-pagination queue executor is not running")]
312 ShutDown,
313}
314
315enum SchedulerEvent {
318 Submitted(SubmittedRequest),
320 Finished(RequestCoalescingKey, BackPaginationRunResult),
322}
323
324struct SubmittedRequest {
327 request: BackPaginationRequest,
328 token: CancellationToken,
329 completion: oneshot::Sender<BackPaginationRunResult>,
330}
331
332struct PendingRequest {
335 request: BackPaginationRequest,
336 seq: u64,
338 token: CancellationToken,
339}
340
341impl PartialEq for PendingRequest {
342 fn eq(&self, other: &Self) -> bool {
343 self.request.priority == other.request.priority && self.seq == other.seq
344 }
345}
346
347impl Eq for PendingRequest {}
348
349impl PartialOrd for PendingRequest {
350 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
351 Some(self.cmp(other))
352 }
353}
354
355impl Ord for PendingRequest {
356 fn cmp(&self, other: &Self) -> Ordering {
357 self.request.priority.cmp(&other.request.priority).then_with(|| other.seq.cmp(&self.seq))
359 }
360}
361
362#[instrument(skip_all)]
365async fn scheduler(
366 event_cache: Weak<EventCacheInner>,
367 mut receiver: mpsc::UnboundedReceiver<SchedulerEvent>,
368 sender: mpsc::UnboundedSender<SchedulerEvent>,
369 max_concurrent: usize,
370) {
371 trace!("Spawning the back-pagination queue executor");
372
373 let mut pending_requests: BinaryHeap<PendingRequest> = BinaryHeap::new();
374 let mut active_requests: HashMap<OwnedRoomId, AbortOnDrop<()>> = HashMap::new();
378 let mut next_seq: u64 = 0;
379
380 let mut waiters: HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>> =
386 HashMap::new();
387
388 let mut events = Vec::with_capacity(max_concurrent);
391
392 loop {
393 schedule(
396 &event_cache,
397 &mut pending_requests,
398 &mut active_requests,
399 max_concurrent,
400 &sender,
401 );
402
403 if receiver.recv_many(&mut events, max_concurrent).await == 0 {
406 info!("Back-pagination queue channel closed, exiting");
407 break;
408 }
409
410 for event in events.drain(..) {
411 match event {
412 SchedulerEvent::Submitted(submitted) => {
413 let key = (submitted.request.room_id.clone(), submitted.request.priority);
414
415 if try_coalesce(&mut waiters, &key, submitted.completion) {
416 trace!(
417 room_id = %key.0,
418 priority = ?key.1,
419 "coalesced back-pagination request onto an existing run"
420 );
421 continue;
422 }
423
424 pending_requests.push(PendingRequest {
425 request: submitted.request,
426 seq: next_seq,
427 token: submitted.token,
428 });
429 next_seq += 1;
430 }
431
432 SchedulerEvent::Finished(key, result) => {
433 active_requests.remove(&key.0);
434 if let Some(senders) = waiters.remove(&key) {
437 for waiter in senders {
438 let _ = waiter.send(result);
439 }
440 }
441 }
442 }
443 }
444 }
445}
446
447fn try_coalesce(
456 waiters: &mut HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>>,
457 key: &RequestCoalescingKey,
458 completion: oneshot::Sender<BackPaginationRunResult>,
459) -> bool {
460 match waiters.get_mut(key) {
461 Some(existing) => {
462 existing.push(completion);
463 true
464 }
465 None => {
466 waiters.insert(key.to_owned(), vec![completion]);
467 false
468 }
469 }
470}
471
472fn schedule(
474 event_cache: &Weak<EventCacheInner>,
475 pending_requests: &mut BinaryHeap<PendingRequest>,
476 active_requests: &mut HashMap<OwnedRoomId, AbortOnDrop<()>>,
477 max_concurrent: usize,
478 sender: &mpsc::UnboundedSender<SchedulerEvent>,
479) {
480 for request in next_runnable(pending_requests, active_requests, max_concurrent) {
481 let key = (request.request.room_id.clone(), request.request.priority);
482
483 trace!(
484 room_id = %key.0,
485 priority = ?key.1,
486 active = active_requests.len(),
487 queued = pending_requests.len(),
488 "back-pagination scheduled"
489 );
490
491 let room_id = key.0.clone();
492 let event_cache = event_cache.clone();
493 let sender = sender.clone();
494 let task = spawn(async move {
495 let result = run_request(&event_cache, request.request, &request.token).await;
496 let _ = sender.send(SchedulerEvent::Finished(key, result));
499 });
500
501 active_requests.insert(room_id, task.abort_on_drop());
502 }
503}
504
505fn next_runnable<T>(
513 pending_requests: &mut BinaryHeap<PendingRequest>,
514 active_requests: &HashMap<OwnedRoomId, T>,
515 max_concurrent: usize,
516) -> Vec<PendingRequest> {
517 let mut picked: Vec<PendingRequest> = Vec::new();
518 let mut skipped = Vec::new();
519
520 while active_requests.len() + picked.len() < max_concurrent {
521 let Some(request) = pending_requests.pop() else {
522 break;
523 };
524
525 let room_id = &request.request.room_id;
526 if active_requests.contains_key(room_id)
527 || picked.iter().any(|other| other.request.room_id == *room_id)
528 {
529 skipped.push(request);
531 continue;
532 }
533
534 picked.push(request);
535 }
536
537 pending_requests.extend(skipped);
538
539 picked
540}
541
542#[instrument(skip_all, fields(room_id = %request.room_id, priority = ?request.priority))]
545async fn run_request(
546 event_cache: &Weak<EventCacheInner>,
547 mut request: BackPaginationRequest,
548 token: &CancellationToken,
549) -> BackPaginationRunResult {
550 if token.is_cancelled() {
552 return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
553 }
554
555 let (pagination, _subscriber) = {
563 let Some(inner) = event_cache.upgrade() else {
564 return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
565 };
566 if let Ok(client) = inner.client()
567 && let Some(room) = client.get_room(&request.room_id)
568 && (room.is_space() || room.state() != RoomState::Joined)
569 {
570 debug!("skipping back-pagination for a space or a non-joined room");
571 return BackPaginationRunResult { reason: BackPaginationStopReason::Skipped };
572 }
573 let room = match inner.all_caches_for_room(&request.room_id).await {
574 Ok(caches) => caches.room().clone(),
575 Err(err) => {
576 warn!("no caches for room while back-paginating: {err}");
577 return BackPaginationRunResult { reason: BackPaginationStopReason::Failed };
578 }
579 };
580 let subscriber = match room.subscribe().await {
581 Ok((_events, subscriber)) => subscriber,
582 Err(err) => {
583 warn!("couldn't subscribe to the room while back-paginating: {err}");
584 return BackPaginationRunResult { reason: BackPaginationStopReason::Failed };
585 }
586 };
587 (room.pagination(), subscriber)
588 };
589
590 let mut batches = 0usize;
591
592 let reason = loop {
593 if token.is_cancelled() {
594 break BackPaginationStopReason::Cancelled;
595 }
596
597 let outcome = match pagination.run_backwards_once(request.batch_size).await {
598 Ok(outcome) => outcome,
599 Err(err) => {
600 warn!("back-pagination failed: {err}");
601 break BackPaginationStopReason::Failed;
602 }
603 };
604
605 if (request.stop)(&outcome).is_break() {
608 break BackPaginationStopReason::StopConditionMet;
609 }
610
611 if outcome.reached_start {
612 break BackPaginationStopReason::ReachedTimelineStart;
613 }
614
615 if outcome.events.is_empty() {
616 break BackPaginationStopReason::NoDataAvailable;
617 }
618
619 batches += 1;
620 if let Some(max) = request.max_batches
621 && batches >= max
622 {
623 break BackPaginationStopReason::BatchLimitReached;
624 }
625 };
626
627 debug!(?reason, "back-pagination run finished");
628
629 BackPaginationRunResult { reason }
630}
631
632#[cfg(all(test, not(target_arch = "wasm32")))]
633mod tests {
634 use std::{collections::HashMap, ops::ControlFlow};
635
636 use matrix_sdk_base::locks::Mutex;
637 use ruma::room_id;
638
639 use super::{
640 BackPaginationRequest, PendingRequest, Priority, cancellation_for, next_runnable,
641 try_coalesce,
642 };
643
644 fn queued(room_id: ruma::OwnedRoomId, priority: Priority, seq: u64) -> PendingRequest {
646 PendingRequest {
647 request: BackPaginationRequest {
648 room_id,
649 priority,
650 stop: Box::new(|_| ControlFlow::Continue(())),
652 batch_size: 10,
653 max_batches: None,
654 },
655 seq,
656 token: tokio_util::sync::CancellationToken::new(),
657 }
658 }
659
660 #[test]
663 fn test_scheduling_priority_and_fifo() {
664 use std::collections::BinaryHeap;
665
666 let (a, b, c, d) = (room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e"), room_id!("!d:e"));
667
668 let mut pending_requests = BinaryHeap::new();
669 pending_requests.push(queued(a.to_owned(), Priority::Low, 0));
671 pending_requests.push(queued(b.to_owned(), Priority::High, 1));
672 pending_requests.push(queued(c.to_owned(), Priority::Normal, 2));
673 pending_requests.push(queued(d.to_owned(), Priority::High, 3));
674
675 let active_requests: HashMap<_, ()> = HashMap::new();
676 let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
677 .into_iter()
678 .map(|r| r.request.room_id)
679 .collect();
680
681 assert_eq!(picked, vec![b.to_owned(), d.to_owned(), c.to_owned(), a.to_owned()]);
683 }
684
685 #[test]
687 fn test_scheduling_respects_concurrency_cap() {
688 use std::collections::BinaryHeap;
689
690 let mut pending_requests = BinaryHeap::new();
691 for (i, room) in [room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e")].iter().enumerate() {
692 pending_requests.push(queued((*room).to_owned(), Priority::Normal, i as u64));
693 }
694
695 let active_requests: HashMap<_, ()> = HashMap::new();
696 let picked = next_runnable(&mut pending_requests, &active_requests, 2);
697
698 assert_eq!(picked.len(), 2);
699 assert_eq!(pending_requests.len(), 1);
701 }
702
703 #[test]
706 fn test_scheduling_per_room_single_flight() {
707 use std::collections::BinaryHeap;
708
709 let (a, b) = (room_id!("!a:e"), room_id!("!b:e"));
710
711 let active_requests = HashMap::from([(a.to_owned(), ())]);
713
714 let mut pending_requests = BinaryHeap::new();
715 pending_requests.push(queued(a.to_owned(), Priority::High, 0)); pending_requests.push(queued(a.to_owned(), Priority::High, 1)); pending_requests.push(queued(b.to_owned(), Priority::Low, 2)); let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
720 .into_iter()
721 .map(|r| r.request.room_id)
722 .collect();
723
724 assert_eq!(picked, vec![b.to_owned()]);
726 assert_eq!(pending_requests.len(), 2);
727 }
728
729 #[test]
732 fn test_cancellation_is_shared_per_key() {
733 let cancellations = Mutex::new(HashMap::new());
734 let key = (room_id!("!a:e").to_owned(), Priority::Normal);
735
736 let (first_token, first_guard) = cancellation_for(&cancellations, key.clone());
737 let (second_token, second_guard) = cancellation_for(&cancellations, key.clone());
738
739 assert!(!first_token.is_cancelled());
741 drop(first_guard);
742 assert!(!first_token.is_cancelled());
743 assert!(!second_token.is_cancelled());
744
745 drop(second_guard);
747 assert!(first_token.is_cancelled());
748 assert!(second_token.is_cancelled());
749
750 let (third_token, _third_guard) = cancellation_for(&cancellations, key);
753 assert!(!third_token.is_cancelled());
754
755 let other = (room_id!("!a:e").to_owned(), Priority::High);
757 let (other_token, other_guard) = cancellation_for(&cancellations, other);
758 drop(other_guard);
759 assert!(other_token.is_cancelled());
760 assert!(!third_token.is_cancelled());
761 }
762
763 #[test]
767 fn test_coalescing() {
768 let a = room_id!("!a:e");
769 let mut waiters = HashMap::new();
770
771 let completion = || tokio::sync::oneshot::channel().0;
772 let normal = (a.to_owned(), Priority::Normal);
773 let high = (a.to_owned(), Priority::High);
774
775 assert!(!try_coalesce(&mut waiters, &normal, completion()));
777 assert_eq!(waiters[&normal].len(), 1);
778
779 assert!(try_coalesce(&mut waiters, &normal, completion()));
781 assert_eq!(waiters[&normal].len(), 2);
782
783 assert!(!try_coalesce(&mut waiters, &high, completion()));
785 assert_eq!(waiters.len(), 2);
786 assert_eq!(waiters[&high].len(), 1);
787 }
788}