Skip to main content

matrix_sdk/event_cache/caches/
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
15use std::{
16    collections::{BTreeMap, HashMap},
17    ops::Not,
18    sync::Arc,
19};
20
21use aggregator::EphemeralEvents;
22use eyeball::SharedObservable;
23use eyeball_im::VectorDiff;
24use matrix_sdk_base::{
25    ThreadingSupport,
26    event_cache::Event,
27    linked_chunk::Position,
28    sync::{JoinedRoomUpdate, LeftRoomUpdate},
29};
30use ruma::{OwnedEventId, RoomId, room_version_rules::RoomVersionRules};
31use tokio::sync::{
32    OnceCell, OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock, broadcast::Sender, mpsc,
33};
34
35use self::{
36    room::RoomEventCacheUpdate, subscriber::AutoShrinkMessage, thread::ThreadEventCacheUpdate,
37};
38use super::{
39    EventCacheError, EventsOrigin, Result, back_pagination_queue::BackPaginationQueue, states,
40};
41use crate::{client::WeakClient, room::WeakRoom};
42
43mod aggregator;
44pub mod event_focused;
45pub mod event_linked_chunk;
46pub mod pagination;
47pub mod pinned_events;
48mod read_receipts;
49pub mod room;
50pub mod subscriber;
51pub mod thread;
52
53/// A type to hold all the caches for a given room.
54#[derive(Debug)]
55pub(super) struct Caches {
56    /// The one and only [`RoomEventCache`].
57    ///
58    /// [`RoomEventCache`]: room::RoomEventCache
59    pub room: room::RoomEventCache,
60
61    /// All the lazily-loaded [`ThreadEventCache`].
62    ///
63    /// [`ThreadEventCache`]: thread::ThreadEventCache
64    // An `Arc` is used to get an owned lock.
65    pub threads: Arc<RwLock<HashMap<OwnedEventId, thread::ThreadEventCache>>>,
66
67    /// The one and only [`PinnedEventsCache`].
68    ///
69    /// [`PinnedEventsCache`]: pinned_events::PinnedEventsCache
70    pub pinned_events: OnceCell<pinned_events::PinnedEventsCache>,
71
72    /// All the lazily-loaded [`EventFocusedCache`].
73    ///
74    /// [`EventFocusedCache`]: event_focused::EventFocusedCache
75    // An `Arc` is used to get an owned lock.
76    pub event_focused:
77        Arc<RwLock<HashMap<event_focused::EventFocusedCacheKey, event_focused::EventFocusedCache>>>,
78
79    /// Internals data, used to lazily create caches.
80    internals: CachesInternals,
81}
82
83#[derive(Debug)]
84struct CachesInternals {
85    state: states::StateLock,
86    auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
87    linked_chunk_update_sender: room::LinkedChunkUpdateSender,
88    room_version_rules: RoomVersionRules,
89}
90
91impl Caches {
92    /// Create a new [`Caches`].
93    pub async fn new(
94        weak_client: &WeakClient,
95        room_id: &RoomId,
96        generic_update_sender: Sender<room::RoomEventCacheGenericUpdate>,
97        linked_chunk_update_sender: room::LinkedChunkUpdateSender,
98        auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
99        state: &states::StateLock,
100        back_pagination_queue: Option<BackPaginationQueue>,
101    ) -> Result<Self> {
102        let Some(client) = weak_client.get() else {
103            return Err(EventCacheError::ClientDropped);
104        };
105
106        let weak_room = WeakRoom::new(weak_client.clone(), room_id.to_owned());
107
108        let room = client
109            .get_room(room_id)
110            .ok_or_else(|| EventCacheError::RoomNotFound { room_id: room_id.to_owned() })?;
111        let room_version_rules = room.clone_info().room_version_rules_or_default();
112
113        let pagination_status = SharedObservable::new(pagination::SharedPaginationStatus::Idle {
114            hit_timeline_start: false,
115        });
116
117        let enabled_thread_support =
118            matches!(client.base_client().threading_support, ThreadingSupport::Enabled { .. });
119
120        let update_sender = room::RoomEventCacheUpdateSender::new(generic_update_sender.clone());
121
122        let own_user_id =
123            client.user_id().expect("the user must be logged in, at this point").to_owned();
124
125        // Computed while building the state: nothing may await once the state
126        // is inserted, or a cancellation or error would leave it
127        // inserted without its `Caches`, making every later attempt
128        // fail.
129        let mut timeline_is_not_empty = false;
130
131        let room_state = state
132            .try_insert_once_with(
133                states::selectors::RoomStateSelector::new(room_id.to_owned()),
134                async |store_guard| {
135                    let room_state = room::RoomEventCacheState::new(
136                        own_user_id.clone(),
137                        room_id.to_owned(),
138                        weak_room.clone(),
139                        room_version_rules.clone(),
140                        enabled_thread_support,
141                        update_sender.clone(),
142                        linked_chunk_update_sender.clone(),
143                        store_guard,
144                        pagination_status.clone(),
145                        back_pagination_queue,
146                    )
147                    .await?;
148
149                    timeline_is_not_empty =
150                        room_state.room_linked_chunk().revents().next().is_some();
151
152                    Ok(room_state)
153                },
154            )
155            .await?;
156
157        let room_event_cache = room::RoomEventCache::new(
158            room_id.to_owned(),
159            weak_room,
160            own_user_id,
161            room_state,
162            pagination_status,
163            auto_shrink_sender.clone(),
164            update_sender,
165        );
166
167        // If at least one event has been loaded, it means there is a timeline.
168        // Let's emit a generic update.
169        if timeline_is_not_empty {
170            let _ = generic_update_sender
171                .send(room::RoomEventCacheGenericUpdate { room_id: room_id.to_owned() });
172        }
173
174        Ok(Self {
175            room: room_event_cache,
176            threads: Arc::new(RwLock::new(HashMap::new())),
177            pinned_events: OnceCell::new(),
178            event_focused: Arc::new(RwLock::new(HashMap::new())),
179            internals: CachesInternals {
180                state: state.clone(),
181                auto_shrink_sender,
182                linked_chunk_update_sender,
183                room_version_rules,
184            },
185        })
186    }
187
188    /// Get the [`RoomEventCache`].
189    ///
190    /// [`RoomEventCache`]: room::RoomEventCache
191    pub fn room(&self) -> &room::RoomEventCache {
192        &self.room
193    }
194
195    /// Get or create a [`ThreadEventCache`].
196    ///
197    /// Note: it is impossible to know if `thread_id` represents a valid thread
198    /// identifier. It means it's possible to create a [`ThreadEventCache`] for
199    /// an event that is not a thread root.
200    ///
201    /// [`ThreadEventCache`]: thread::ThreadEventCache
202    pub async fn thread(
203        &self,
204        thread_id: OwnedEventId,
205    ) -> Result<
206        OwnedRwLockReadGuard<
207            HashMap<OwnedEventId, thread::ThreadEventCache>,
208            thread::ThreadEventCache,
209        >,
210    > {
211        Ok(
212            match OwnedRwLockWriteGuard::try_downgrade_map(
213                self.threads.clone().write_owned().await,
214                |threads| threads.get(&thread_id),
215            ) {
216                // Thread exists.
217                Ok(locked_cache) => locked_cache,
218                // Thread does not exist, let's create it.
219                Err(mut threads) => {
220                    let room = &self.room;
221                    let cache = thread::ThreadEventCache::new(
222                        room.room_id().to_owned(),
223                        thread_id.clone(),
224                        room.own_user_id().to_owned(),
225                        self.internals.room_version_rules.clone(),
226                        room.weak_room().to_owned(),
227                        &self.internals.state,
228                        self.internals.auto_shrink_sender.clone(),
229                        room.update_sender().generic_update_sender().clone(),
230                        self.internals.linked_chunk_update_sender.clone(),
231                    )
232                    .await?;
233
234                    threads.insert(thread_id.clone(), cache);
235
236                    OwnedRwLockWriteGuard::downgrade_map(threads, |threads| {
237                        threads.get(&thread_id).unwrap()
238                    })
239                }
240            },
241        )
242    }
243
244    /// Get or create a [`PinnedEventsCache`].
245    ///
246    /// [`PinnedEventsCache`]: pinned_events::PinnedEventsCache
247    pub async fn pinned_events(&self) -> Result<&pinned_events::PinnedEventsCache> {
248        self.pinned_events
249            .get_or_try_init(|| {
250                pinned_events::PinnedEventsCache::new(
251                    self.room.weak_room(),
252                    self.room.own_user_id().clone(),
253                    self.internals.room_version_rules.clone(),
254                    self.internals.linked_chunk_update_sender.clone(),
255                    &self.internals.state,
256                )
257            })
258            .await
259    }
260
261    /// Get or create a [`EventFocusedCache`].
262    ///
263    /// [`EventFocusedCache`]: event_focused::EventFocusedCache
264    pub async fn event_focused(
265        &self,
266        event_id: OwnedEventId,
267        thread_mode: event_focused::EventFocusThreadMode,
268        number_of_initial_events: u16,
269    ) -> Result<
270        OwnedRwLockReadGuard<
271            HashMap<event_focused::EventFocusedCacheKey, event_focused::EventFocusedCache>,
272            event_focused::EventFocusedCache,
273        >,
274    > {
275        let key = event_focused::EventFocusedCacheKey { focused_event_id: event_id, thread_mode };
276
277        Ok(
278            match OwnedRwLockWriteGuard::try_downgrade_map(
279                self.event_focused.clone().write_owned().await,
280                |event_focused_caches| event_focused_caches.get(&key),
281            ) {
282                // Event-focused cache exists.
283                Ok(locked_cache) => locked_cache,
284                // Event-focused cache does not exist, let's create it.
285                Err(mut event_focused_caches) => {
286                    let cache = event_focused::EventFocusedCache::new(
287                        self.room.weak_room().clone(),
288                        key.clone(),
289                        &self.internals.state,
290                        self.internals.linked_chunk_update_sender.clone(),
291                    )
292                    .await?;
293                    cache.start_from(number_of_initial_events, thread_mode).await?;
294
295                    event_focused_caches.insert(key.clone(), cache);
296
297                    OwnedRwLockWriteGuard::downgrade_map(
298                        event_focused_caches,
299                        |event_focused_caches| event_focused_caches.get(&key).unwrap(),
300                    )
301                }
302            },
303        )
304    }
305
306    /// Update all the event caches with a [`JoinedRoomUpdate`].
307    pub(super) async fn handle_joined_room_update(&self, updates: JoinedRoomUpdate) -> Result<()> {
308        let Self { room, threads: _, pinned_events, event_focused, internals } = &self;
309
310        // This method will compute a `JoinedRoomUpdate` for each cache. The
311        // game is to avoid cloning useless data or to clone as few data as
312        // possible. That's a fun game.
313        let JoinedRoomUpdate {
314            // Read receipts are computed by the Event Cache, see
315            // [`read_receipts`], we don't need the server value.
316            unread_notifications: _,
317            // State-events are not stored in the Event Cache.
318            state: _,
319
320            // Extract the original timeline and ephemeral events as timeline
321            // will be used by all caches, and ephemeral events by the room and
322            // thread caches.
323            timeline: original_timeline,
324            ephemeral: original_ephemeral,
325
326            // Extract other data, only useful for the room cache.
327            account_data,
328            ambiguity_changes,
329            avatar_changes,
330        } = updates;
331
332        // Deserialize ephemeral events and group their read receipts, in a
333        // single pass.
334        let EphemeralEvents {
335            room_read_receipts,
336            own_room_read_receipts,
337            thread_read_receipts,
338            own_thread_read_receipts,
339        } = EphemeralEvents::from_sync(room.own_user_id(), original_ephemeral);
340
341        // Room.
342        {
343            room.handle_joined_room_update(
344                original_timeline.clone(),
345                own_room_read_receipts,
346                account_data,
347                ambiguity_changes,
348                avatar_changes,
349            )
350            .await?;
351
352            // Broadcast the read receipts, regardless of their user ids. These
353            // will be later handled by other components, like the timeline.
354            if let Some(event) = room_read_receipts {
355                room.update_sender()
356                    .send(RoomEventCacheUpdate::AddReadReceiptEvent { event }, None);
357            }
358        }
359
360        // Threads.
361        {
362            let timeline_and_read_receipts_for_threads = {
363                // To aggregate the timelines for threads, we need to lookup in
364                // the room cache and the thread caches. We acquire a read lock
365                // over all the caches, and select the room cache and thread
366                // cache' states.
367                let all_states_lock = states::CacheStateLock::new(
368                    states::selectors::AllStatesSelector::new(room.room_id().to_owned()),
369                    self.internals.state.clone(),
370                );
371                let all_states = all_states_lock.read().await?;
372
373                aggregator::aggregate_timeline_and_read_receipts_for_threads(
374                    &original_timeline,
375                    own_thread_read_receipts,
376                    all_states.threads(),
377                    all_states.room(),
378                    &internals.room_version_rules.redaction,
379                )
380                .await?
381            };
382
383            for (thread_id, (timeline, read_receipts)) in timeline_and_read_receipts_for_threads {
384                // Update the thread summary if and only if there are new
385                // events.
386                let has_new_timeline_events = timeline.events.is_empty().not();
387
388                if has_new_timeline_events.not() && read_receipts.is_none() {
389                    // There are no timeline or own read receipt updates, so
390                    // there is nothing to do.
391                    continue;
392                }
393
394                let thread = self.thread(thread_id).await?;
395                thread.handle_joined_room_update(timeline, read_receipts).await?;
396
397                if has_new_timeline_events {
398                    let new_thread_summary = thread.update_thread_summary().await?;
399
400                    room.update_thread_summary(thread.thread_id(), new_thread_summary)?;
401                }
402            }
403
404            // Broadcast the thread read receipts unconditionally, after the
405            // timeline updates have been sent. A thread without a
406            // cache has no subscribers, so there is no need to
407            // create one.
408            if !thread_read_receipts.is_empty() {
409                let threads = self.threads.read().await;
410
411                for (thread_id, event) in thread_read_receipts {
412                    if let Some(thread) = threads.get(&thread_id) {
413                        thread
414                            .update_sender()
415                            .send(ThreadEventCacheUpdate::AddReadReceiptEvent { event }, None);
416                    }
417                }
418            }
419        }
420
421        // Pinned-events.
422        if let Some(pinned_events) = pinned_events.get() {
423            let timeline = aggregator::aggregate_timeline_for_pinned_events(
424                &original_timeline,
425                &pinned_events.state().read().await?.current_event_ids(),
426                &internals.room_version_rules.redaction,
427            );
428
429            pinned_events.handle_joined_room_update(timeline).await?;
430        }
431
432        // Event-focused.
433        {
434            // An event-focused cache isn't listening to live update.
435            // Consequently, it is not interested by this kind of update.
436            let _ = event_focused;
437        }
438
439        Ok(())
440    }
441
442    /// Update all the event caches with a [`LeftRoomUpdate`].
443    pub(super) async fn handle_left_room_update(&self, updates: LeftRoomUpdate) -> Result<()> {
444        let Self { room, threads: _, pinned_events, event_focused, internals } = &self;
445
446        // This method will compute a `JoinedRoomUpdate` for each cache. The
447        // game is to avoid cloning useless data or to clone as few data as
448        // possible. That's a fun game.
449        let LeftRoomUpdate {
450            // State-events are not stored in the Event Cache.
451            state: _,
452            // Account data are not used by any cache.
453            account_data: _,
454
455            // Extract the original timeline as it's going to be used by all caches.
456            timeline: original_timeline,
457
458            // Extract other data, only useful for the room cache.
459            ambiguity_changes,
460        } = updates;
461
462        // Room.
463        {
464            room.handle_left_room_update(original_timeline.clone(), ambiguity_changes).await?;
465        }
466
467        // Threads.
468        {
469            let timeline_and_read_receipts_for_threads = {
470                // To aggregate the timelines for threads, we need to lookup in
471                // the room cache and the thread caches. We acquire a read lock
472                // over all the caches, and select the room cache and thread
473                // cache' states.
474                let all_caches_states_lock = states::CacheStateLock::new(
475                    states::selectors::AllStatesSelector::new(room.room_id().to_owned()),
476                    self.internals.state.clone(),
477                );
478                let all_caches_states = all_caches_states_lock.read().await?;
479
480                aggregator::aggregate_timeline_and_read_receipts_for_threads(
481                    &original_timeline,
482                    BTreeMap::new(),
483                    all_caches_states.threads(),
484                    all_caches_states.room(),
485                    &internals.room_version_rules.redaction,
486                )
487                .await?
488            };
489
490            for (thread_id, (timeline, _read_receipts)) in timeline_and_read_receipts_for_threads {
491                let thread = self.thread(thread_id).await?;
492                thread.handle_left_room_update(timeline).await?;
493            }
494        }
495
496        // Pinned-events.
497        if let Some(pinned_events) = pinned_events.get() {
498            let timeline = aggregator::aggregate_timeline_for_pinned_events(
499                &original_timeline,
500                &pinned_events.state().read().await?.current_event_ids(),
501                &internals.room_version_rules.redaction,
502            );
503
504            pinned_events.handle_left_room_update(timeline).await?;
505        }
506
507        // Event-focused.
508        {
509            // An event-focused cache isn't listening to live update.
510            // Consequently, it is not interested by this kind of update.
511            let _ = event_focused;
512        }
513
514        Ok(())
515    }
516
517    /// Get all in-memory events from all the event caches managed by this
518    /// [`Caches`].
519    ///
520    /// Events can be duplicated if present in different event caches.
521    #[cfg(feature = "e2e-encryption")]
522    pub async fn all_in_memory_events(&self) -> Result<impl Iterator<Item = Event>> {
523        // We have to fetch events from all the caches.
524        //
525        // The room cache contains all the room events + the thread events + the
526        // pinned-events.
527        let mut events = self.room.events().await?;
528
529        // The last cache is the events from the event-focused cache.
530        {
531            let event_focused = self.event_focused.read().await;
532
533            for event_focused in event_focused.values() {
534                events.extend(event_focused.events().await?);
535            }
536        }
537
538        Ok(events.into_iter())
539    }
540
541    /// Get all the events of this room saved in the store.
542    #[cfg(feature = "experimental-search")]
543    pub async fn stored_events(&self) -> Result<Vec<Event>> {
544        let state = self.internals.state.read().await?;
545        Ok(state.store.get_room_events(self.room.room_id(), None, None).await?)
546    }
547
548    /// Get all encrypted events from all the event caches managed by this
549    /// [`Caches`].
550    ///
551    /// The `event_type` represents the type of the event to filter by. The
552    /// `session_id` represents the unique ID of the room key that was used to
553    /// encrypt the event
554    ///
555    /// Events can be duplicated if present in different event caches.
556    #[cfg(feature = "e2e-encryption")]
557    pub async fn all_events_of_type(
558        &self,
559        event_type: Option<&str>,
560        session_id: Option<&str>,
561    ) -> Result<impl Iterator<Item = Event>> {
562        // All caches store their events in the store except one. Let's start by
563        // looking inside the store.
564        let mut events = {
565            let state = self.internals.state.read().await?;
566
567            state.store.get_room_events(self.room.room_id(), event_type, session_id).await?
568        };
569
570        // The only cache to not store its events is the event-focused cache.
571        // Its events only live in memory.
572        {
573            let event_focused = self.event_focused.read().await;
574
575            for event_focused in event_focused.values() {
576                events.extend(
577                    event_focused
578                        .events()
579                        .await?
580                        .into_iter()
581                        .filter(|event| event_type == event.kind.event_type().as_deref())
582                        .filter(|event| session_id == event.kind.session_id()),
583                );
584            }
585        }
586
587        Ok(events.into_iter())
588    }
589}
590
591/// A diff update for an event cache timeline represented as a vector.
592#[derive(Clone, Debug)]
593pub struct TimelineVectorDiffs {
594    /// New vector diff for the thread timeline.
595    pub diffs: Vec<VectorDiff<Event>>,
596    /// The origin that triggered this update.
597    pub origin: EventsOrigin,
598}
599
600/// An enum representing where an event has been found.
601#[derive(Debug)]
602pub(super) enum EventLocation {
603    /// Event lives in memory (and likely in the store!).
604    Memory(Position),
605
606    /// Event lives in the store only, it has not been loaded in memory yet.
607    Store,
608}