Skip to main content

matrix_sdk/event_cache/caches/event_focused/
mod.rs

1// Copyright 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Event-focused timeline cache.
16//!
17//! This module provides [`EventFocusedCache`], a cache for an event-focused
18//! timeline (e.g., for permalinks). It handles:
19//! - Initialization from a focused event via `/context`.
20//! - Thread detection (if the focused event is in a thread).
21//! - Forward and backward pagination.
22//! - In-memory storage, as these linked chunks are meant to be short-lived.
23//!
24//! Pagination tokens are stored as Gap items in the linked chunk:
25//! - Backward token: Gap at the front of the linked chunk.
26//! - Forward token: Gap at the back of the linked chunk.
27//!
28//! This allows pagination to resume at any point, and supports a future use
29//! case where we'd want to persist these caches on disk (e.g., for permalinks
30//! to work across sessions).
31
32use std::sync::Arc;
33
34use matrix_sdk_base::{
35    deserialized_responses::TimelineEvent,
36    event_cache::{Event, Gap},
37    linked_chunk::OwnedLinkedChunkId,
38};
39use matrix_sdk_common::{linked_chunk::ChunkIdentifier, serde_helpers::extract_thread_root};
40use ruma::{OwnedEventId, UInt, api::Direction};
41use tokio::sync::{
42    RwLock,
43    broadcast::{Receiver, Sender},
44};
45use tracing::{instrument, trace};
46
47#[cfg(feature = "e2e-encryption")]
48use crate::event_cache::redecryptor::ResolvedUtd;
49use crate::{
50    Room,
51    event_cache::{
52        EventCacheError, EventsOrigin, Result, RoomEventCacheLinkedChunkUpdate,
53        caches::{TimelineVectorDiffs, event_linked_chunk::EventLinkedChunk},
54    },
55    paginators::{PaginationResult, Paginator, StartFromResult, thread::PaginableThread},
56    room::{IncludeRelations, MessagesOptions, RelationsOptions, WeakRoom},
57};
58
59/// Options for controlling the behaviour of an `EventFocusedCache` when the
60/// focused event may be part of a thread, or a thread's root.
61#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
62pub enum EventFocusThreadMode {
63    /// Force the timeline represented by the linked chunk to only include
64    /// threaded events.
65    ///
66    /// When the focused event is part of a thread, the linked chunk will be
67    /// focused on that thread's root. Otherwise, the linked chunk will
68    /// treat the target event itself as the thread root. Threaded events
69    /// will never be hidden.
70    ForceThread,
71
72    /// Automatically determine if the target event is part of a thread or not.
73    ///
74    /// If the event is part of a thread, the linked chunk will be filtered to
75    /// on-thread events.
76    Automatic,
77}
78
79/// The mode of pagination for an event-focused linked chunk.
80#[derive(Debug, Clone)]
81pub(crate) enum EventFocusedPaginationMode {
82    /// Standard room pagination (for all events as for an unthreaded/main room
83    /// linked chunk).
84    Room,
85
86    /// Threaded pagination (the focused event is part of a thread).
87    Thread {
88        /// The root event ID of the thread.
89        thread_root: OwnedEventId,
90    },
91}
92
93struct EventFocusedCacheInner {
94    /// The room owning this event-focused cache.
95    room: WeakRoom,
96
97    /// The focused event ID.
98    focused_event_id: OwnedEventId,
99
100    /// The pagination mode (room or thread).
101    pagination_mode: EventFocusedPaginationMode,
102
103    /// The linked chunk for this event-focused cache.
104    chunk: EventLinkedChunk,
105
106    /// A sender of timeline updates.
107    sender: Sender<TimelineVectorDiffs>,
108
109    /// A sender for globally observable linked chunk updates.
110    linked_chunk_update_sender: Sender<RoomEventCacheLinkedChunkUpdate>,
111}
112
113impl EventFocusedCacheInner {
114    /// Initialize the cache from a focused event.
115    ///
116    /// This uses `/context` to fetch the event with surrounding context.
117    ///
118    /// This detects if the event is part of a thread and sets up the
119    /// appropriate pagination mode.
120    ///
121    /// Pagination tokens are stored as gaps in the linked chunk:
122    /// - Backward token (start): Gap at the front of the linked chunk.
123    /// - Forward token (end): Gap at the back of the linked chunk.
124    #[instrument(skip(self, room), fields(room_id = %self.room.room_id(), event_id = %self.focused_event_id))]
125    async fn start_from(
126        &mut self,
127        room: Room,
128        num_context_events: u16,
129        thread_mode: EventFocusThreadMode,
130    ) -> Result<StartFromResult> {
131        trace!(num_context_events, "fetching event with context via /context");
132
133        let paginator = Paginator::new(room);
134
135        let result =
136            paginator.start_from(&self.focused_event_id, UInt::from(num_context_events)).await?;
137
138        // Detect if the focused event is part of a thread.
139        let thread_root = match thread_mode {
140            EventFocusThreadMode::ForceThread => {
141                // Try to extract a thread root from the focused event, first.
142                let focused_event = result
143                    .events
144                    .iter()
145                    .find(|event| event.event_id().as_ref() == Some(&self.focused_event_id));
146
147                // If the focused event has a thread root, use it.
148                let mut thread_root =
149                    focused_event.and_then(|event| extract_thread_root(event.raw()));
150
151                // If there's no thread root, consider that the focused event itself is the
152                // thread root.
153                if thread_root.is_none() {
154                    thread_root = Some(self.focused_event_id.clone());
155                }
156
157                trace!("force thread mode enabled, treating focused event as thread root");
158                thread_root
159            }
160
161            EventFocusThreadMode::Automatic => {
162                trace!(
163                    "automatic thread mode enabled, checking if focused event is part of a thread"
164                );
165                result
166                    .events
167                    .iter()
168                    .find(|event| event.event_id().as_ref() == Some(&self.focused_event_id))
169                    .and_then(|event| extract_thread_root(event.raw()))
170            }
171        };
172
173        // Get pagination tokens from the paginator.
174        let tokens = paginator.tokens();
175
176        if let Some(root_id) = thread_root {
177            trace!(thread_root = %root_id, "focused event is part of a thread, setting up thread pagination");
178
179            // Check if the thread root is included in the response. Start from the
180            // beginning, since it's more likely to be around there, in that
181            // case.
182            let includes_root =
183                result.events.iter().any(|event| event.event_id().as_ref() == Some(&root_id));
184
185            self.pagination_mode =
186                EventFocusedPaginationMode::Thread { thread_root: root_id.clone() };
187
188            // Filter events to only include those in the thread.
189            let thread_events = result
190                .events
191                .iter()
192                .filter(|event| {
193                    extract_thread_root(event.raw()).as_ref() == Some(&root_id)
194                        || event.event_id().as_ref() == Some(&root_id)
195                })
196                .cloned()
197                .collect();
198
199            // Determine backward token (only if we don't have the thread root).
200            let backward_token = if includes_root {
201                // We have the root, no need for backward pagination.
202                None
203            } else {
204                tokens.previous.into_token()
205            };
206
207            // Forward token.
208            let forward_token = tokens.next.into_token();
209
210            self.add_initial_events_with_gaps(thread_events, backward_token, forward_token);
211        } else {
212            trace!("focused event is not part of a thread, setting up room pagination");
213            self.pagination_mode = EventFocusedPaginationMode::Room;
214
215            let backward_token = tokens.previous.into_token();
216            let forward_token = tokens.next.into_token();
217
218            self.add_initial_events_with_gaps(result.events.clone(), backward_token, forward_token);
219        }
220
221        self.propagate_changes();
222
223        // Empty the updates_as_vector_diffs(), since it's impossible for an observer to
224        // have subscribed to this cache yet, since this code is part of the constructor
225        // flow.
226        //
227        // If we didn't empty those, such initial updates would be duplicated, since the
228        // subscriber would get the full initial list of events as diffs and as a set of
229        // initial events.
230        let _ = self.chunk.updates_as_vector_diffs();
231
232        Ok(result)
233    }
234
235    /// Add initial events to the chunk, with gaps for pagination tokens.
236    fn add_initial_events_with_gaps(
237        &mut self,
238        events: Vec<TimelineEvent>,
239        prev_gap_token: Option<String>,
240        next_gap_token: Option<String>,
241    ) {
242        // Insert backward gap at the back if we have a token, and the events
243        // themselves.
244        self.chunk
245            .push_live_events(prev_gap_token.map(|prev_token| Gap { token: prev_token }), &events);
246
247        // Insert forward gap at back if we have a token.
248        if let Some(next_token) = next_gap_token {
249            trace!("inserting forward pagination gap at back");
250            self.chunk.push_gap(Gap { token: next_token });
251        }
252    }
253
254    /// Propagate changes to the linked chunk update sender.
255    fn propagate_changes(&mut self) {
256        let updates = self.chunk.store_updates().take();
257        if !updates.is_empty() {
258            let _ = self.linked_chunk_update_sender.send(RoomEventCacheLinkedChunkUpdate {
259                updates,
260                linked_chunk_id: OwnedLinkedChunkId::EventFocused(
261                    self.room.room_id().to_owned(),
262                    self.focused_event_id.clone(),
263                ),
264            });
265        }
266    }
267
268    /// Notify subscribers of timeline updates.
269    fn notify_subscribers(&mut self, origin: EventsOrigin) {
270        let diffs = self.chunk.updates_as_vector_diffs();
271        if !diffs.is_empty() {
272            let _ = self.sender.send(TimelineVectorDiffs { diffs, origin });
273        }
274    }
275
276    /// Return the first chunk as a gap, if it's one.
277    fn first_chunk_as_gap(&self) -> Option<(ChunkIdentifier, Gap)> {
278        self.chunk.first_chunk_as_gap()
279    }
280
281    /// Return the last chunk as a gap, if it's one.
282    fn last_chunk_as_gap(&self) -> Option<(ChunkIdentifier, Gap)> {
283        self.chunk.last_chunk_as_gap()
284    }
285
286    /// Paginate backwards in this event-focused linked chunk.
287    ///
288    /// This finds the gap at the front of the linked chunk, fetches older
289    /// events, replaces the gap with the events, and inserts a new gap if
290    /// there are more events to fetch.
291    #[instrument(skip(self), fields(room_id = %self.room.room_id()))]
292    async fn paginate_backwards(&mut self, num_events: u16) -> Result<PaginationResult> {
293        let room = self.room.get().ok_or(EventCacheError::ClientDropped)?;
294
295        // Find the gap at the front (backward pagination token).
296        let Some((gap_id, gap)) = self.first_chunk_as_gap() else {
297            // No gap at front means we've already hit the start of the timeline.
298            trace!("no front gap found, already at timeline start");
299            return Ok(PaginationResult { events: Vec::new(), hit_end_of_timeline: true });
300        };
301
302        let token = gap.token;
303        trace!(?token, "paginating backwards with token from front gap");
304
305        // Fetch events based on pagination mode.
306        let (mut events, new_token) = match &self.pagination_mode {
307            EventFocusedPaginationMode::Room => {
308                Self::fetch_room_backwards(&room, num_events, &token).await?
309            }
310            EventFocusedPaginationMode::Thread { thread_root } => {
311                Self::fetch_thread_backwards(&room, num_events, &token, thread_root.clone()).await?
312            }
313        };
314
315        // Events are in the reverse order, per the API contracts defined in the two
316        // fetch methods.
317        events.reverse();
318
319        let hit_end = new_token.is_none();
320        let new_gap = new_token.map(|t| Gap { token: t });
321
322        // Replace the gap and insert the new events.
323        self.chunk.push_backwards_pagination_events(Some(gap_id), new_gap, &events);
324
325        self.propagate_changes();
326        self.notify_subscribers(EventsOrigin::Pagination);
327
328        Ok(PaginationResult { events, hit_end_of_timeline: hit_end })
329    }
330
331    /// Fetch events for backward room pagination (returns events and optional
332    /// next token).
333    ///
334    /// Returns the events in the same ordering as the one received by the
335    /// server, i.e., newest to oldest.
336    async fn fetch_room_backwards(
337        room: &Room,
338        num_events: u16,
339        token: &str,
340    ) -> Result<(Vec<Event>, Option<String>)> {
341        let mut options = MessagesOptions::backward().from(token);
342        options.limit = UInt::from(num_events);
343
344        let messages = room
345            .messages(options)
346            .await
347            .map_err(|err| EventCacheError::PaginationError(Box::new(err)))?;
348
349        Ok((messages.chunk, messages.end))
350    }
351
352    /// Fetch events for backward thread pagination.
353    ///
354    /// Returns the events in the same ordering as the one received by the
355    /// server, i.e., newest to oldest.
356    async fn fetch_thread_backwards(
357        room: &Room,
358        num_events: u16,
359        token: &str,
360        thread_root: OwnedEventId,
361    ) -> Result<(Vec<Event>, Option<String>)> {
362        let options = RelationsOptions {
363            from: Some(token.to_owned()),
364            dir: Direction::Backward,
365            limit: Some(UInt::from(num_events)),
366            include_relations: IncludeRelations::AllRelations,
367            recurse: true,
368        };
369
370        let mut result = room
371            .relations(thread_root.clone(), options)
372            .await
373            .map_err(|err| EventCacheError::PaginationError(Box::new(err)))?;
374
375        // If we hit the end (no more token), load the thread root event.
376        if result.next_batch_token.is_none() {
377            let root_event = room
378                .load_event(&thread_root)
379                .await
380                .map_err(|err| EventCacheError::PaginationError(Box::new(err)))?;
381            result.chunk.push(root_event);
382        }
383
384        Ok((result.chunk, result.next_batch_token))
385    }
386
387    /// Paginate forwards in this event-focused timeline.
388    ///
389    /// This finds the gap at the back of the linked chunk, fetches newer
390    /// events, replaces the gap with the events, and inserts a new gap if
391    /// there are more events to fetch.
392    #[instrument(skip(self), fields(room_id = %self.room.room_id()))]
393    async fn paginate_forwards(&mut self, num_events: u16) -> Result<PaginationResult> {
394        let room = self.room.get().ok_or(EventCacheError::ClientDropped)?;
395
396        // Find the gap at the back (forward pagination token).
397        let Some((gap_id, gap)) = self.last_chunk_as_gap() else {
398            // No gap at back means we've already hit the end of the timeline.
399            trace!("no back gap found, already at timeline end");
400            return Ok(PaginationResult { events: Vec::new(), hit_end_of_timeline: true });
401        };
402
403        let token = gap.token;
404        trace!(?token, "paginating forwards with token from back gap");
405
406        // Fetch events based on pagination mode.
407        let (events, new_token) = match &self.pagination_mode {
408            EventFocusedPaginationMode::Room => {
409                Self::fetch_room_forwards(&room, num_events, &token).await?
410            }
411            EventFocusedPaginationMode::Thread { thread_root } => {
412                Self::fetch_thread_forwards(&room, num_events, &token, thread_root.clone()).await?
413            }
414        };
415
416        let hit_end = new_token.is_none();
417        let new_gap = new_token.map(|t| Gap { token: t });
418
419        // Replace the gap and insert new events.
420        self.chunk.push_forwards_pagination_events(Some(gap_id), new_gap, &events);
421
422        self.propagate_changes();
423        self.notify_subscribers(EventsOrigin::Pagination);
424
425        Ok(PaginationResult { events, hit_end_of_timeline: hit_end })
426    }
427
428    /// Fetch events for forward room pagination.
429    async fn fetch_room_forwards(
430        room: &Room,
431        num_events: u16,
432        token: &str,
433    ) -> Result<(Vec<Event>, Option<String>)> {
434        let mut options = MessagesOptions::new(Direction::Forward);
435        options = options.from(Some(token));
436        options.limit = UInt::from(num_events);
437
438        let messages = room
439            .messages(options)
440            .await
441            .map_err(|err| EventCacheError::PaginationError(Box::new(err)))?;
442
443        Ok((messages.chunk, messages.end))
444    }
445
446    /// Fetch events for forward thread pagination.
447    async fn fetch_thread_forwards(
448        room: &Room,
449        num_events: u16,
450        token: &str,
451        thread_root: OwnedEventId,
452    ) -> Result<(Vec<Event>, Option<String>)> {
453        let options = RelationsOptions {
454            from: Some(token.to_owned()),
455            dir: Direction::Forward,
456            limit: Some(UInt::from(num_events)),
457            include_relations: IncludeRelations::AllRelations,
458            recurse: true,
459        };
460
461        let result = room
462            .relations(thread_root, options)
463            .await
464            .map_err(|err| EventCacheError::PaginationError(Box::new(err)))?;
465
466        Ok((result.chunk, result.next_batch_token))
467    }
468}
469
470/// A cache for an event-focused timeline.
471///
472/// This represents a timeline centered around a specific event (e.g., from a
473/// permalink), supporting both forward and backward pagination. The focused
474/// event may be part of a thread, in which case pagination will use the
475/// `/relations` API instead of `/messages`.
476///
477/// Pagination tokens are stored as Gap items in the linked chunk itself:
478/// - A gap at the **front** (first position) contains the backward pagination
479///   token.
480/// - A gap at the **back** (last position) contains the forward pagination
481///   token.
482///
483/// This is a shallow data structure, and can be cloned cheaply.
484#[derive(Clone)]
485pub struct EventFocusedCache {
486    inner: Arc<RwLock<EventFocusedCacheInner>>,
487}
488
489impl EventFocusedCache {
490    /// Create a new empty event-focused cache.
491    pub(super) fn new(
492        room: WeakRoom,
493        focused_event_id: OwnedEventId,
494        linked_chunk_update_sender: Sender<RoomEventCacheLinkedChunkUpdate>,
495    ) -> Self {
496        Self {
497            inner: Arc::new(RwLock::new(EventFocusedCacheInner {
498                room,
499                focused_event_id,
500                pagination_mode: EventFocusedPaginationMode::Room,
501                chunk: EventLinkedChunk::new(),
502                sender: Sender::new(32),
503                linked_chunk_update_sender,
504            })),
505        }
506    }
507
508    /// Subscribe to updates from this event-focused timeline.
509    pub async fn subscribe(&self) -> (Vec<Event>, Receiver<TimelineVectorDiffs>) {
510        let inner = self.inner.read().await;
511        let events = inner.chunk.events().map(|(_position, item)| item.clone()).collect();
512        let recv = inner.sender.subscribe();
513        (events, recv)
514    }
515
516    /// Check if we've hit the start of the timeline (no more backward
517    /// pagination possible).
518    pub async fn hit_timeline_start(&self) -> bool {
519        self.inner.read().await.first_chunk_as_gap().is_none()
520    }
521
522    /// Check if we've hit the end of the timeline (no more forward pagination
523    /// possible).
524    pub async fn hit_timeline_end(&self) -> bool {
525        self.inner.read().await.last_chunk_as_gap().is_none()
526    }
527
528    /// Start the event-focused timeline from the focused event, fetching
529    /// context events and detecting thread membership.
530    pub(super) async fn start_from(
531        &self,
532        room: Room,
533        num_context_events: u16,
534        thread_mode: EventFocusThreadMode,
535    ) -> Result<StartFromResult> {
536        self.inner.write().await.start_from(room, num_context_events, thread_mode).await
537    }
538
539    /// Paginate backwards in this event-focused timeline, be it room or thread
540    /// pagination depending on the mode.
541    pub async fn paginate_backwards(&self, num_events: u16) -> Result<PaginationResult> {
542        self.inner.write().await.paginate_backwards(num_events).await
543    }
544
545    /// Paginate forwards in this event-focused timeline, be it room or thread
546    /// pagination depending on the mode.
547    pub async fn paginate_forwards(&self, num_events: u16) -> Result<PaginationResult> {
548        self.inner.write().await.paginate_forwards(num_events).await
549    }
550
551    /// Get the thread root event ID if this linked chunk is in thread mode.
552    pub async fn thread_root(&self) -> Option<OwnedEventId> {
553        match &self.inner.read().await.pagination_mode {
554            EventFocusedPaginationMode::Thread { thread_root } => Some(thread_root.clone()),
555            _ => None,
556        }
557    }
558
559    /// Try to locate the events in the linked chunk corresponding to the given
560    /// list of decrypted events, and replace them, while alerting observers
561    /// about the update.
562    #[cfg(feature = "e2e-encryption")]
563    pub async fn replace_utds(&self, events: &[ResolvedUtd]) {
564        let mut guard = self.inner.write().await;
565        if guard.chunk.replace_utds(events) {
566            guard.propagate_changes();
567            guard.notify_subscribers(EventsOrigin::Cache);
568        }
569    }
570}
571
572#[cfg(not(tarpaulin_include))]
573impl std::fmt::Debug for EventFocusedCache {
574    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
575        f.debug_struct("EventFocusedCache").finish_non_exhaustive()
576    }
577}