Skip to main content

matrix_sdk/event_cache/
mod.rs

1// Copyright 2024 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//! The event cache is an abstraction layer, sitting between the Rust SDK and a
16//! final client, that acts as a global observer of all the rooms, gathering and
17//! inferring some extra useful information about each room. In particular, this
18//! doesn't require subscribing to a specific room to get access to this
19//! information.
20//!
21//! It's intended to be fast, robust and easy to maintain, having learned from
22//! previous endeavours at implementing middle to high level features elsewhere
23//! in the SDK, notably in the UI's Timeline object.
24//!
25//! See the [github issue](https://github.com/matrix-org/matrix-rust-sdk/issues/3058) for more
26//! details about the historical reasons that led us to start writing this.
27
28#![forbid(missing_docs)]
29
30use std::{
31    collections::HashMap,
32    fmt,
33    num::NonZeroUsize,
34    ops::Deref,
35    sync::{
36        Arc, OnceLock, RwLock as StdRwLock, RwLockReadGuard, RwLockWriteGuard,
37        atomic::{AtomicBool, Ordering},
38    },
39};
40
41use matrix_sdk_base::{
42    cross_process_lock::{CrossProcessLockError, MappedCrossProcessLockState},
43    event_cache::{
44        store::{EventCacheStoreError, EventCacheStoreLock},
45        thread::ThreadInfo,
46    },
47    linked_chunk::lazy_loader::LazyLoaderError,
48    sync::RoomUpdates,
49    task_monitor::BackgroundTaskHandle,
50};
51use ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId};
52use tokio::sync::{
53    OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock,
54    broadcast::{Receiver, Sender, channel},
55    mpsc,
56};
57use tracing::{info, instrument, trace};
58
59use crate::{
60    Client,
61    client::{ClientInner, WeakClient},
62    event_cache::caches::room::LinkedChunkUpdateSender,
63    paginators::PaginatorError,
64};
65
66pub(crate) mod back_pagination_queue;
67mod caches;
68mod deduplicator;
69mod persistence;
70#[cfg(feature = "e2e-encryption")]
71mod redecryptor;
72mod search_backfill;
73mod states;
74mod tasks;
75
76#[cfg(feature = "e2e-encryption")]
77pub use redecryptor::{DecryptionRetryRequest, RedecryptorReport};
78
79pub(crate) use self::caches::room::RFindMapOutcome;
80pub use self::{
81    back_pagination_queue::BackPaginationQueue,
82    caches::{
83        TimelineVectorDiffs,
84        event_focused::{EventFocusThreadMode, EventFocusedCache, EventFocusedCacheKey},
85        pagination::{BackPaginationOutcome, PaginationStatus},
86        pinned_events::PinnedEventsCache,
87        room::{
88            RoomEventCache, RoomEventCacheGenericUpdate, RoomEventCacheUpdate,
89            pagination::RoomPagination,
90        },
91        subscriber::Subscriber,
92        thread::{ThreadEventCache, ThreadEventCacheUpdate, pagination::ThreadPagination},
93    },
94    search_backfill::SearchBackfillStrategy,
95};
96use self::{
97    caches::{Caches, room::RoomEventCacheLinkedChunkUpdate, subscriber::AutoShrinkMessage},
98    states::StateLock,
99};
100
101/// An error observed in the [`EventCache`].
102#[derive(thiserror::Error, Clone, Debug)]
103pub enum EventCacheError {
104    /// Room cache is not found.
105    #[error("Room cache `{room_id}` is not found.")]
106    RoomNotFound {
107        /// The room ID.
108        room_id: OwnedRoomId,
109    },
110
111    /// Thread cache is not found.
112    #[error("Thread cache `{thread_id}` of room `{room_id}` is not found.")]
113    ThreadNotFound {
114        /// The room ID of the thread.
115        room_id: OwnedRoomId,
116
117        /// The thread root event ID.
118        thread_id: OwnedEventId,
119    },
120
121    /// Pinned-events cache are not found.
122    #[error("Pinned-events cache for room `{room_id}` are not found.")]
123    PinnedEventsNotFound {
124        /// The room ID of the pinned-events.
125        room_id: OwnedRoomId,
126    },
127
128    /// Event-focused cache is not found.
129    #[error("Event-focused cache `{event_focused_id:?}` of room `{room_id}` is not found.")]
130    EventFocusedNotFound {
131        /// The room ID of the thread.
132        room_id: OwnedRoomId,
133
134        /// The thread root event ID.
135        event_focused_id: EventFocusedCacheKey,
136    },
137
138    /// A new cache was inserted at an occupied place, i.e. where an existing
139    /// cache state was present.
140    #[error("The state of a cache is not found")]
141    CacheStateAlreadyExists,
142
143    /// An error has been observed while back- or forward- paginating.
144    #[error(transparent)]
145    PaginationError(Arc<crate::Error>),
146
147    /// An error has been observed while initiating an event-focused timeline.
148    #[error(transparent)]
149    InitialPaginationError(#[from] PaginatorError),
150
151    /// An error happening when interacting with storage.
152    #[error(transparent)]
153    Storage(#[from] EventCacheStoreError),
154
155    /// An error happening when attempting to (cross-process) lock storage.
156    #[error(transparent)]
157    LockingStorage(#[from] CrossProcessLockError),
158
159    /// The [`EventCache`] owns a weak reference to the [`Client`] it pertains
160    /// to. It's possible this weak reference points to nothing anymore, at
161    /// times where we try to use the client.
162    #[error("The owning client of the event cache has been dropped.")]
163    ClientDropped,
164
165    /// An error happening when interacting with the [`LinkedChunk`]'s lazy
166    /// loader.
167    ///
168    /// [`LinkedChunk`]: matrix_sdk_common::linked_chunk::LinkedChunk
169    #[error(transparent)]
170    LinkedChunkLoader(#[from] LazyLoaderError),
171
172    /// An error happened when trying to load pinned events; none of them could
173    /// be loaded, which would otherwise result in an empty pinned events list,
174    /// incorrectly.
175    #[error("Unable to load any of the pinned events.")]
176    UnableToLoadPinnedEvents,
177
178    /// An error happened when reading the metadata of a linked chunk, upon
179    /// reload.
180    #[error("the linked chunk metadata is invalid: {details}")]
181    InvalidLinkedChunkMetadata {
182        /// A string containing details about the error.
183        details: String,
184    },
185}
186
187/// A result using the [`EventCacheError`].
188pub type Result<T> = std::result::Result<T, EventCacheError>;
189
190/// Hold handles to the tasks spawn by a [`EventCache`].
191pub struct EventCacheDropHandles {
192    /// Task that listens to updates to the user's ignored list.
193    ignore_user_list_update_task: BackgroundTaskHandle,
194
195    /// The task used to automatically shrink the linked chunks.
196    auto_shrink_linked_chunk_task: BackgroundTaskHandle,
197
198    /// A background task listening to room and send queue updates, and
199    /// automatically subscribing the user to threads when needed, based on the
200    /// semantics of MSC4306.
201    ///
202    /// One important constraint is that there is only one such task per
203    /// [`EventCache`], so it does listen to _all_ rooms at the same time.
204    thread_subscriber_task: BackgroundTaskHandle,
205
206    /// A background task listening to room updates, and automatically handling
207    /// search index operations add/remove/edit depending on the event type.
208    ///
209    /// One important constraint is that there is only one such task per
210    /// [`EventCache`], so it does listen to _all_ rooms at the same time.
211    #[cfg(feature = "experimental-search")]
212    search_indexing_task: BackgroundTaskHandle,
213
214    /// The task used to automatically redecrypt UTDs.
215    #[cfg(feature = "e2e-encryption")]
216    redecryptor: OnceLock<redecryptor::Redecryptor>,
217
218    /// Whether [`EventCacheDropHandles::abort_all`] has been called, in which
219    /// case no task must be spawned anymore.
220    is_shut_down: AtomicBool,
221}
222
223impl EventCacheDropHandles {
224    fn new(
225        event_cache_inner: &Arc<EventCacheInner>,
226        event_cache_config: RwLockReadGuard<'_, EventCacheConfig>,
227        auto_shrink_receiver: mpsc::Receiver<AutoShrinkMessage>,
228        #[cfg(feature = "experimental-search")] search_index_receiver: mpsc::UnboundedReceiver<(
229            OwnedRoomId,
230            Vec<matrix_sdk_base::event_cache::Event>,
231        )>,
232        client: Client,
233    ) -> Self {
234        let task_monitor = client.task_monitor();
235
236        let ignore_user_list_update_task = task_monitor
237            .spawn_infinite_task(
238                "event_cache::ignore_user_list_update_task",
239                tasks::ignore_user_list_update_task(
240                    event_cache_inner.clone(),
241                    client.subscribe_to_ignore_user_list_changes(),
242                ),
243            )
244            .abort_on_drop();
245
246        let auto_shrink_linked_chunk_task = task_monitor
247            .spawn_infinite_task(
248                "event_cache::auto_shrink_linked_chunk_task",
249                tasks::auto_shrink_linked_chunk_task(
250                    Arc::downgrade(event_cache_inner),
251                    auto_shrink_receiver,
252                ),
253            )
254            .abort_on_drop();
255
256        let thread_subscriber_task = client
257            .task_monitor()
258            .spawn_infinite_task(
259                "event_cache::thread_subscriber",
260                tasks::thread_subscriber_task(
261                    event_cache_inner.client.clone(),
262                    event_cache_inner.linked_chunk_update_sender.clone(),
263                    event_cache_inner.thread_subscriber_sender.clone(),
264                ),
265            )
266            .abort_on_drop();
267
268        #[cfg(feature = "experimental-search")]
269        let search_indexing_task = client
270            .task_monitor()
271            .spawn_infinite_task(
272                "event_cache::search_indexing",
273                tasks::search_indexing_task(
274                    event_cache_inner.client.clone(),
275                    search_index_receiver,
276                ),
277            )
278            .abort_on_drop();
279
280        if event_cache_inner.enable_automatic_back_pagination {
281            // Deferred initialization of the shared back-pagination queue.
282            trace!("spawning the back-pagination queue");
283            let max_concurrent = event_cache_config.max_concurrent_back_paginations;
284
285            event_cache_inner.back_pagination_queue.get_or_init(|| {
286                BackPaginationQueue::new(
287                    Arc::downgrade(event_cache_inner),
288                    max_concurrent,
289                    task_monitor,
290                )
291            });
292        } else {
293            trace!("back-pagination queue is disabled");
294        }
295
296        Self {
297            ignore_user_list_update_task,
298            auto_shrink_linked_chunk_task,
299            // It is initialised with `EventCache::initialise_redecryptor`. See this method to learn
300            // more.
301            #[cfg(feature = "e2e-encryption")]
302            redecryptor: OnceLock::new(),
303            thread_subscriber_task,
304            #[cfg(feature = "experimental-search")]
305            search_indexing_task,
306            is_shut_down: AtomicBool::new(false),
307        }
308    }
309
310    /// Abort all the tasks, and prevent new ones from being spawned.
311    fn abort_all(&self) {
312        self.is_shut_down.store(true, Ordering::SeqCst);
313
314        self.ignore_user_list_update_task.abort();
315        self.auto_shrink_linked_chunk_task.abort();
316        self.thread_subscriber_task.abort();
317
318        #[cfg(feature = "experimental-search")]
319        self.search_indexing_task.abort();
320
321        #[cfg(feature = "e2e-encryption")]
322        if let Some(redecryptor) = self.redecryptor.get() {
323            redecryptor.abort();
324        }
325    }
326}
327
328impl fmt::Debug for EventCacheDropHandles {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        f.debug_struct("EventCacheDropHandles").finish_non_exhaustive()
331    }
332}
333
334/// An event cache, providing lots of useful functionality for clients.
335///
336/// Cloning is shallow, and thus is cheap to do.
337///
338/// See also the module-level comment.
339#[derive(Clone)]
340pub struct EventCache {
341    /// Reference to the inner cache.
342    //
343    // It's behind an `Arc` to provide a cheap clone.
344    inner: Arc<EventCacheInner>,
345
346    /// Handles to keep alive the tasks listening to updates.
347    //
348    // It's behind an `Arc` because this value is cloned and returned to callers
349    // of some methods.
350    drop_handles: Arc<EventCacheDropHandles>,
351}
352
353impl fmt::Debug for EventCache {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        f.debug_struct("EventCache").finish_non_exhaustive()
356    }
357}
358
359impl EventCache {
360    /// Create a new [`EventCache`] for the given client.
361    pub(crate) fn new(
362        client: &Arc<ClientInner>,
363        event_cache_store: EventCacheStoreLock,
364        enable_automatic_back_pagination: bool,
365    ) -> Self {
366        let (generic_update_sender, _) = channel(128);
367        #[cfg(feature = "experimental-search")]
368        let (search_index_sender, search_index_receiver) = mpsc::unbounded_channel();
369        let linked_chunk_update_sender = LinkedChunkUpdateSender::new(
370            #[cfg(feature = "experimental-search")]
371            search_index_sender,
372        );
373
374        let weak_client = WeakClient::from_inner(client);
375        let client =
376            weak_client.get().expect("Unreachable: `client` is still alive, it can be upgraded");
377
378        let (auto_shrink_sender, auto_shrink_receiver) = mpsc::channel(32);
379
380        let (thread_subscriber_sender, _thread_subscriber_receiver) = channel(128);
381
382        #[cfg(feature = "e2e-encryption")]
383        let redecryption_channels = redecryptor::RedecryptorChannels::new();
384
385        let inner = Arc::new(EventCacheInner {
386            client: weak_client,
387            config: StdRwLock::new(EventCacheConfig::default()),
388            state: StateLock::new(event_cache_store),
389            by_room: Default::default(),
390            auto_shrink_sender,
391            generic_update_sender,
392            linked_chunk_update_sender,
393            #[cfg(feature = "e2e-encryption")]
394            redecryption_channels,
395            enable_automatic_back_pagination,
396            back_pagination_queue: OnceLock::new(),
397            thread_subscriber_sender,
398        });
399
400        let drop_handles = Arc::new(EventCacheDropHandles::new(
401            &inner,
402            inner.config.read().unwrap(),
403            auto_shrink_receiver,
404            #[cfg(feature = "experimental-search")]
405            search_index_receiver,
406            client,
407        ));
408
409        Self { inner, drop_handles }
410    }
411
412    /// Get a read-only handle to the global configuration of the
413    /// [`EventCache`].
414    pub fn config(&self) -> RwLockReadGuard<'_, EventCacheConfig> {
415        self.inner.config.read().unwrap()
416    }
417
418    /// Get a writable handle to the global configuration of the [`EventCache`].
419    pub fn config_mut(&self) -> RwLockWriteGuard<'_, EventCacheConfig> {
420        self.inner.config.write().unwrap()
421    }
422
423    /// Initialise `Redecryptor`, aka R2D2.
424    ///
425    /// The `EventCache` is built when the `Client` is built. When a `Client` is
426    /// built, the `OlmMachine` does not exist. Thus, `Redecryptor` will fail to
427    /// start because it needs an `OlmMachine`. That's why this method exists:
428    /// once the `OlmMachine` is created, this method is called to build
429    /// `Redecryptor`. This usually happens in [`Client::activate`].
430    ///
431    /// This method initialises `Redecryptor` only once. Calling it several
432    /// times will have no effect.
433    ///
434    /// It returns an error if the `Client` has been dropped.
435    #[cfg(feature = "e2e-encryption")]
436    pub(crate) fn initialise_redecryptor(&self) -> Result<()> {
437        if self.drop_handles.is_shut_down.load(Ordering::SeqCst) {
438            tracing::debug!("The event cache has been shut down, not starting the redecryptor");
439            return Ok(());
440        }
441
442        let client = self.inner.client()?;
443        let receiver =
444            self.inner.redecryption_channels.decryption_request_receiver.lock().take().expect(
445                "We should have initialized the channel an subscribing should happen only once",
446            );
447
448        self.drop_handles.redecryptor.get_or_init(|| {
449            redecryptor::Redecryptor::new(
450                &client,
451                Arc::downgrade(&self.inner),
452                receiver,
453                &self.inner.linked_chunk_update_sender,
454            )
455        });
456
457        Ok(())
458    }
459
460    /// Stop all the background work of the event cache, for good.
461    ///
462    /// This is meant to be called once the session has ended, e.g. after a
463    /// logout: the automatic back-paginations, the redecryption of UTDs, the
464    /// search indexing and the other background tasks would otherwise keep
465    /// running, and keep the [`Client`] alive, for a session that can't make
466    /// any request anymore.
467    ///
468    /// The event cache can still be read, but nothing will update it in the
469    /// background anymore.
470    pub(crate) fn shut_down(&self) {
471        info!("Shutting down the event cache");
472
473        if let Some(back_pagination_queue) = self.inner.back_pagination_queue.get() {
474            back_pagination_queue.shut_down();
475        }
476
477        self.drop_handles.abort_all();
478    }
479
480    /// Subscribes to updates that a thread subscription has been sent.
481    ///
482    /// For testing purposes only.
483    #[cfg(feature = "testing")]
484    pub fn subscribe_thread_subscriber_updates(&self) -> Receiver<()> {
485        self.inner.thread_subscriber_sender.subscribe()
486    }
487
488    /// Handle [`RoomUpdates`], i.e. the entry point of the `EventCache` for
489    /// receiving new updates.
490    ///
491    /// This method is `pub` because the `testing` feature is turned on.
492    #[cfg(feature = "testing")]
493    pub async fn handle_room_updates(&self, updates: RoomUpdates) -> Result<()> {
494        self.inner.handle_room_updates(updates).await
495    }
496
497    /// Handle [`RoomUpdates`], i.e. the entry point of the `EventCache` for
498    /// receiving new updates.
499    ///
500    /// This method is `pub(crate)` because the `testing` feature is turned off.
501    #[cfg(not(feature = "testing"))]
502    pub(crate) async fn handle_room_updates(&self, updates: RoomUpdates) -> Result<()> {
503        self.inner.handle_room_updates(updates).await
504    }
505
506    /// Return a room-specific view over the [`EventCache`].
507    pub async fn room(
508        &self,
509        room_id: &RoomId,
510    ) -> Result<(RoomEventCache, Arc<EventCacheDropHandles>)> {
511        let drop_handles = self.drop_handles.clone();
512
513        let caches_for_room = self.inner.all_caches_for_room(room_id).await?;
514
515        Ok((caches_for_room.room().clone(), drop_handles))
516    }
517
518    /// Return a thread-specific view over the [`EventCache`].
519    ///
520    /// Note: it is impossible to know if `thread_id` represents a valid thread
521    /// identifier. It means it's possible to create a [`ThreadEventCache`] for
522    /// an event that is not a thread root.
523    pub async fn thread(
524        &self,
525        room_id: &RoomId,
526        thread_id: &EventId,
527    ) -> Result<(ThreadEventCache, Arc<EventCacheDropHandles>)> {
528        let drop_handles = self.drop_handles.clone();
529
530        let caches_for_room = self.inner.all_caches_for_room(room_id).await?;
531
532        Ok((caches_for_room.thread(thread_id.to_owned()).await?.deref().clone(), drop_handles))
533    }
534
535    /// Return a pinned-events-specific view over the [`EventCache`].
536    pub async fn pinned_events(
537        &self,
538        room_id: &RoomId,
539    ) -> Result<(PinnedEventsCache, Arc<EventCacheDropHandles>)> {
540        let drop_handles = self.drop_handles.clone();
541
542        let caches_for_room = self.inner.all_caches_for_room(room_id).await?;
543
544        Ok((caches_for_room.pinned_events().await?.clone(), drop_handles))
545    }
546
547    /// Return an event-focused view over the [`EventCache`].
548    pub async fn event_focused(
549        &self,
550        room_id: &RoomId,
551        event_id: &EventId,
552        thread_mode: EventFocusThreadMode,
553        number_of_initial_events: u16,
554    ) -> Result<(EventFocusedCache, Arc<EventCacheDropHandles>)> {
555        let drop_handles = self.drop_handles.clone();
556
557        let caches_for_room = self.inner.all_caches_for_room(room_id).await?;
558
559        Ok((
560            caches_for_room
561                .event_focused(event_id.to_owned(), thread_mode, number_of_initial_events)
562                .await?
563                .deref()
564                .clone(),
565            drop_handles,
566        ))
567    }
568
569    /// Get the [`ThreadInfo`] of a thread, if any.
570    pub async fn thread_info(
571        &self,
572        room_id: &RoomId,
573        thread_id: &EventId,
574    ) -> Result<Option<ThreadInfo>> {
575        let Some(client) = self.inner.client.get() else {
576            return Ok(None);
577        };
578
579        // We can go directly on the store. I don't think we need to go through
580        // the `State`, as the data cannot be outdated/dirty: the store
581        // is the source of truth.
582        let store = match client.event_cache_store().lock().await? {
583            MappedCrossProcessLockState::Clean(store)
584            | MappedCrossProcessLockState::Dirty(store) => store,
585        };
586
587        Ok(store.load_thread_info(room_id, thread_id, false).await?)
588    }
589
590    /// Forget all caches related to a single room.
591    ///
592    /// This will notify any live observers that the room has been cleared.
593    pub async fn forget_room(&self, room_id: &RoomId) -> Result<()> {
594        self.inner.forget_room(room_id).await
595    }
596
597    /// Cleanly clear all the rooms' event caches.
598    ///
599    /// This will notify any live observers that the room has been cleared.
600    pub async fn clear_all_rooms(&self) -> Result<()> {
601        self.inner.clear_all_rooms().await
602    }
603
604    /// Subscribe to room _generic_ updates.
605    ///
606    /// If one wants to listen what has changed in a specific room for example,
607    /// the [`RoomEventCache::subscribe`] is recommended. However, the
608    /// [`Subscriber`] type triggers side-effects.
609    ///
610    /// If one wants to get a high-overview, generic, updates for rooms, and
611    /// without side-effects, this method is recommended. Also, dropping the
612    /// receiver of this channel will not trigger any side-effect.
613    pub fn subscribe_to_room_generic_updates(&self) -> Receiver<RoomEventCacheGenericUpdate> {
614        self.inner.generic_update_sender.subscribe()
615    }
616
617    /// Returns the shared [`BackPaginationQueue`], if enabled at construction
618    /// with [`ClientBuilder::with_enable_automatic_back_pagination`].
619    ///
620    /// [`ClientBuilder::with_enable_automatic_back_pagination`]: crate::ClientBuilder::with_enable_automatic_back_pagination
621    pub fn back_pagination_queue(&self) -> Option<BackPaginationQueue> {
622        self.inner.back_pagination_queue.get().cloned()
623    }
624}
625
626/// Global configuration for the [`EventCache`], applied to every single room.
627#[derive(Clone, Copy, Debug)]
628pub struct EventCacheConfig {
629    /// Maximum number of concurrent /event requests when loading pinned events.
630    pub max_pinned_events_concurrent_requests: usize,
631
632    /// Maximum number of pinned events to load, for any room.
633    pub max_pinned_events_to_load: usize,
634
635    /// The maximum number of back-paginations the background queue runs at
636    /// once, across all rooms and use cases. Bounds server load.
637    ///
638    /// Defaults to
639    /// [`EventCacheConfig::DEFAULT_MAX_CONCURRENT_BACK_PAGINATIONS`].
640    pub max_concurrent_back_paginations: NonZeroUsize,
641}
642
643impl EventCacheConfig {
644    /// The default maximum number of pinned events to load.
645    pub const DEFAULT_MAX_EVENTS_TO_LOAD: usize = 128;
646
647    /// The default maximum number of concurrent requests to perform when
648    /// loading the pinned events.
649    pub const DEFAULT_MAX_CONCURRENT_REQUESTS: usize = 8;
650
651    /// The default maximum number of concurrent background back-paginations
652    /// (see also [`EventCacheConfig::max_concurrent_back_paginations`]).
653    pub const DEFAULT_MAX_CONCURRENT_BACK_PAGINATIONS: NonZeroUsize = NonZeroUsize::new(3).unwrap();
654}
655
656impl Default for EventCacheConfig {
657    fn default() -> Self {
658        Self {
659            max_pinned_events_concurrent_requests: Self::DEFAULT_MAX_CONCURRENT_REQUESTS,
660            max_pinned_events_to_load: Self::DEFAULT_MAX_EVENTS_TO_LOAD,
661            max_concurrent_back_paginations: Self::DEFAULT_MAX_CONCURRENT_BACK_PAGINATIONS,
662        }
663    }
664}
665
666type CachesByRoom = HashMap<OwnedRoomId, Caches>;
667
668struct EventCacheInner {
669    /// A weak reference to the inner client, useful when trying to get a handle
670    /// on the owning client.
671    client: WeakClient,
672
673    /// Global configuration for the event cache.
674    config: StdRwLock<EventCacheConfig>,
675
676    /// Lock around the state of the Event Cache, containing all the cache
677    /// states.
678    state: StateLock,
679
680    /// Lazily-filled cache of live [`RoomEventCache`], once per room.
681    //
682    // It's behind an `Arc` to get owned locks.
683    by_room: Arc<RwLock<CachesByRoom>>,
684
685    /// A sender for notifications that a room _may_ need to be auto-shrunk.
686    ///
687    /// Needs to live here, so it may be passed to each [`RoomEventCache`]
688    /// instance.
689    ///
690    /// See doc comment of [`tasks::auto_shrink_linked_chunk_task`].
691    auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
692
693    /// A sender for room generic update.
694    ///
695    /// See doc comment of [`RoomEventCacheGenericUpdate`] and
696    /// [`EventCache::subscribe_to_room_generic_updates`].
697    generic_update_sender: Sender<RoomEventCacheGenericUpdate>,
698
699    /// A sender for a persisted linked chunk update.
700    ///
701    /// This is used to notify that some linked chunk has persisted some updates
702    /// to a store, during sync or a back-pagination of _any_ linked chunk. This
703    /// can be used by observers to look for new events.
704    ///
705    /// See doc comment of [`RoomEventCacheLinkedChunkUpdate`].
706    linked_chunk_update_sender: LinkedChunkUpdateSender,
707
708    /// A test helper receiver that will be emitted every time the thread
709    /// subscriber task subscribed to a new thread.
710    ///
711    /// This is helpful for tests to coordinate that a new thread subscription
712    /// has been sent or not.
713    thread_subscriber_sender: Sender<()>,
714
715    #[cfg(feature = "e2e-encryption")]
716    redecryption_channels: redecryptor::RedecryptorChannels,
717
718    /// Whether to spawn the [`BackPaginationQueue`] at subscription time; set
719    /// once, at construction, via
720    /// [`ClientBuilder::with_enable_automatic_back_pagination`].
721    ///
722    /// [`ClientBuilder::with_enable_automatic_back_pagination`]: crate::ClientBuilder::with_enable_automatic_back_pagination
723    enable_automatic_back_pagination: bool,
724
725    /// State for the automatic pagination mechanism.
726    ///
727    /// Deferred initialization: spawned at subscription time, if
728    /// `enable_automatic_back_pagination` is set.
729    back_pagination_queue: OnceLock<BackPaginationQueue>,
730}
731
732impl EventCacheInner {
733    fn client(&self) -> Result<Client> {
734        self.client.get().ok_or(EventCacheError::ClientDropped)
735    }
736
737    /// Clear a single room's data.
738    async fn forget_room(&self, room_id: &RoomId) -> Result<()> {
739        // The constraints are very similar to what we do in `clear_all_rooms`.
740        // See this information to understand them.
741
742        let mut caches_for_all_rooms = self.by_room.write().await;
743
744        // Clear the room's stored events and remove its underlying state
745        self.state.clear_and_remove(&caches_for_all_rooms, room_id).await?;
746
747        // Finally, we forget the corresponding caches.
748        caches_for_all_rooms.remove(room_id);
749
750        Ok(())
751    }
752
753    /// Clears all the rooms' data.
754    async fn clear_all_rooms(&self) -> Result<()> {
755        // Okay, here's where things get delicate.
756        //
757        // On the one hand, `by_room` may include storage for _some_ caches that
758        // we know about, but not _all_ of them. Any cache that hasn't been
759        // loaded in the client, or touched by a sync, will remain unloaded in
760        // memory, so it will be missing from `self.by_room`. As a result, we
761        // need to make sure that we're hitting the storage backend to _really_
762        // clear all the caches, including those that haven't been loaded yet.
763        //
764        // On the other hand, one must NOT clear the `by_room` map, because if
765        // someone subscribed to a cache update, they would never get any new
766        // update for that cache, since re-creating the cache would create a
767        // new, unrelated sender.
768        //
769        // So we need to _keep_ the caches in `by_room` alive, while clearing
770        // them in the store backend.
771        //
772        // As a result, for a short while, the in-memory linked chunks will be
773        // desynchronised from the storage. We need to be careful then. During
774        // that short while, we don't want _anyone_ to touch the linked chunks
775        // (be it in memory or in the storage).
776        //
777        // And since that requirement applies to _any_ cache in `by_room` at the
778        // same time, we'll have to take the lock for _all_ the live caches and
779        // for the states, so as to properly clear the underlying storage.
780
781        // We acquire an exclusive access to `by_room`.
782        let caches_for_all_rooms = self.by_room.write().await;
783
784        // Then, we can clear and reload the states for all the rooms.
785        self.state.clear_and_reload(&caches_for_all_rooms, None).await?;
786
787        Ok(())
788    }
789
790    /// Handles a single set of room updates at once.
791    #[instrument(skip(self, updates))]
792    async fn handle_room_updates(&self, updates: RoomUpdates) -> Result<()> {
793        // NOTE: We tried to make this concurrent at some point, but it turned
794        // out to be a performance regression, even for large sync updates.
795        // Lacking time to investigate, this code remains sequential for now.
796        // See also https://github.com/matrix-org/matrix-rust-sdk/pull/5426.
797
798        // Left rooms.
799        for (room_id, left_room_update) in updates.left {
800            trace!(?room_id, "Handling a `LeftRoomUpdate`");
801
802            self.all_caches_for_room(&room_id)
803                .await?
804                .handle_left_room_update(left_room_update)
805                .await?;
806        }
807
808        // Joined rooms.
809        for (room_id, joined_room_update) in updates.joined {
810            trace!(?room_id, "Handling a `JoinedRoomUpdate`");
811
812            self.all_caches_for_room(&room_id)
813                .await?
814                .handle_joined_room_update(joined_room_update)
815                .await?;
816        }
817
818        // Invited rooms.
819        //
820        // We don't handle `updates.invite` because they contain stripped-state
821        // events, which is not handled by the Event Cache for the moment.
822
823        Ok(())
824    }
825
826    /// Return all the event caches associated to a specific room.
827    async fn all_caches_for_room(
828        &self,
829        room_id: &RoomId,
830    ) -> Result<OwnedRwLockReadGuard<CachesByRoom, Caches>> {
831        // Fast path: the entry exists; let's acquire a read lock, it's cheaper
832        // than a write lock.
833        match OwnedRwLockReadGuard::try_map(self.by_room.clone().read_owned().await, |by_room| {
834            by_room.get(room_id)
835        }) {
836            Ok(caches) => Ok(caches),
837
838            Err(by_room_guard) => {
839                // Slow-path: the entry doesn't exist; let's acquire a write
840                // lock.
841                drop(by_room_guard);
842                let by_room_guard = self.by_room.clone().write_owned().await;
843
844                // In the meanwhile, some other caller might have obtained write
845                // access and done the same, so check for existence again.
846                let mut by_room_guard =
847                    match OwnedRwLockWriteGuard::try_downgrade_map(by_room_guard, |by_room| {
848                        by_room.get(room_id)
849                    }) {
850                        Ok(caches) => return Ok(caches),
851                        Err(by_room_guard) => by_room_guard,
852                    };
853
854                let caches = Caches::new(
855                    &self.client,
856                    room_id,
857                    self.generic_update_sender.clone(),
858                    self.linked_chunk_update_sender.clone(),
859                    self.auto_shrink_sender.clone(),
860                    &self.state,
861                    self.back_pagination_queue.get().cloned(),
862                )
863                .await?;
864
865                by_room_guard.insert(room_id.to_owned(), caches);
866
867                Ok(OwnedRwLockWriteGuard::try_downgrade_map(by_room_guard, |by_room| {
868                    by_room.get(room_id)
869                })
870                .expect("`Caches` has just been inserted"))
871            }
872        }
873    }
874}
875
876/// Indicate where events are coming from.
877#[derive(Debug, Clone)]
878pub enum EventsOrigin {
879    /// Events are coming from a sync.
880    Sync,
881
882    /// Events are coming from pagination.
883    Pagination,
884
885    /// The cause of the change is purely internal to the cache.
886    Cache,
887}
888
889#[cfg(test)]
890mod tests {
891    use std::{ops::Not, sync::Arc, time::Duration};
892
893    use assert_matches::assert_matches;
894    use futures_util::FutureExt as _;
895    use matrix_sdk_base::{
896        RoomState,
897        cross_process_lock::CrossProcessLockConfig,
898        event_cache::store::{EventCacheStore, MemoryStore},
899        linked_chunk::{ChunkIdentifier, LinkedChunkId, Position, Update},
900        store::StoreConfig,
901        sync::{JoinedRoomUpdate, RoomUpdates, Timeline},
902    };
903    use matrix_sdk_test::{
904        JoinedRoomBuilder, SyncResponseBuilder, async_test, event_factory::EventFactory,
905    };
906    use ruma::{event_id, room_id, user_id};
907    use tokio::time::sleep;
908
909    use super::{EventCacheError, RoomEventCacheGenericUpdate};
910    use crate::test_utils::{
911        assert_event_matches_msg, client::MockClientBuilder, logged_in_client,
912    };
913
914    #[cfg(not(target_family = "wasm"))]
915    #[async_test]
916    async fn test_logout_shuts_down_the_event_cache() {
917        use std::ops::ControlFlow;
918
919        use matrix_sdk_common::timeout::timeout;
920
921        use super::back_pagination_queue::{
922            BackPaginationQueueError, BackPaginationRequest, Priority,
923        };
924        use crate::test_utils::mocks::MatrixMockServer;
925
926        let server = MatrixMockServer::new().await;
927        let client = server
928            .client_builder()
929            .on_builder(|builder| builder.with_enable_automatic_back_pagination(true))
930            .build()
931            .await;
932
933        server.mock_logout().ok().mock_once().mount().await;
934
935        let event_cache = client.event_cache().unwrap();
936        let back_pagination_queue = event_cache
937            .back_pagination_queue()
938            .expect("the back-pagination queue should be enabled");
939        let drop_handles = event_cache.drop_handles.clone();
940
941        assert!(drop_handles.ignore_user_list_update_task.is_finished().not());
942
943        client.logout().await.unwrap();
944
945        // All the background tasks are aborted…
946        timeout(
947            async {
948                while !(drop_handles.ignore_user_list_update_task.is_finished()
949                    && drop_handles.auto_shrink_linked_chunk_task.is_finished()
950                    && drop_handles.thread_subscriber_task.is_finished())
951                {
952                    sleep(Duration::from_millis(10)).await;
953                }
954            },
955            Duration::from_secs(5),
956        )
957        .await
958        .expect("the event cache tasks should be aborted after a logout");
959
960        #[cfg(feature = "experimental-search")]
961        assert!(drop_handles.search_indexing_task.is_finished());
962
963        // … and the back-pagination queue doesn't accept new requests anymore.
964        timeout(
965            async {
966                loop {
967                    let request = BackPaginationRequest {
968                        room_id: room_id!("!galette:saucisse.bzh").to_owned(),
969                        priority: Priority::Normal,
970                        stop: Box::new(|_| ControlFlow::Continue(())),
971                        batch_size: 10,
972                        max_batches: None,
973                    };
974
975                    if let Err(BackPaginationQueueError::ShutDown) =
976                        back_pagination_queue.enqueue(request)
977                    {
978                        break;
979                    }
980
981                    sleep(Duration::from_millis(10)).await;
982                }
983            },
984            Duration::from_secs(5),
985        )
986        .await
987        .expect("the back-pagination queue should be shut down after a logout");
988    }
989
990    #[async_test]
991    async fn test_get_event_by_id() {
992        let client = logged_in_client(None).await;
993        let room_id1 = room_id!("!galette:saucisse.bzh");
994        let room_id2 = room_id!("!crepe:saucisse.bzh");
995
996        client.base_client().get_or_create_room(room_id1, RoomState::Joined);
997        client.base_client().get_or_create_room(room_id2, RoomState::Joined);
998
999        let event_cache = client.event_cache().unwrap();
1000
1001        // Insert two rooms with a few events.
1002        let f = EventFactory::new().room(room_id1).sender(user_id!("@ben:saucisse.bzh"));
1003
1004        let eid1 = event_id!("$1");
1005        let eid2 = event_id!("$2");
1006        let eid3 = event_id!("$3");
1007
1008        let joined_room_update1 = JoinedRoomUpdate {
1009            timeline: Timeline {
1010                events: vec![
1011                    f.text_msg("hey").event_id(eid1).into(),
1012                    f.text_msg("you").event_id(eid2).into(),
1013                ],
1014                ..Default::default()
1015            },
1016            ..Default::default()
1017        };
1018
1019        let joined_room_update2 = JoinedRoomUpdate {
1020            timeline: Timeline {
1021                events: vec![f.text_msg("bjr").event_id(eid3).into()],
1022                ..Default::default()
1023            },
1024            ..Default::default()
1025        };
1026
1027        let mut updates = RoomUpdates::default();
1028        updates.joined.insert(room_id1.to_owned(), joined_room_update1);
1029        updates.joined.insert(room_id2.to_owned(), joined_room_update2);
1030
1031        // Have the event cache handle them.
1032        event_cache.inner.handle_room_updates(updates).await.unwrap();
1033
1034        // We can find the events in a single room.
1035        let (room_event_cache, _drop_handles) = event_cache.room(room_id1).await.unwrap();
1036
1037        let found1 = room_event_cache.find_event(eid1).await.unwrap().unwrap();
1038        assert_event_matches_msg(&found1, "hey");
1039
1040        let found2 = room_event_cache.find_event(eid2).await.unwrap().unwrap();
1041        assert_event_matches_msg(&found2, "you");
1042
1043        // Retrieving the event with id3 from the room which doesn't contain it
1044        // will fail…
1045        assert!(room_event_cache.find_event(eid3).await.unwrap().is_none());
1046    }
1047
1048    #[async_test]
1049    async fn test_generic_update_when_loading_rooms() {
1050        // Create 2 rooms. One of them has data in the event cache storage.
1051        let user = user_id!("@mnt_io:matrix.org");
1052
1053        let room_id_0 = room_id!("!raclette:patate.ch");
1054        let room_id_1 = room_id!("!fondue:patate.ch");
1055
1056        let event_factory = EventFactory::new().room(room_id_0).sender(user);
1057
1058        let event_cache_store = MemoryStore::new();
1059        event_cache_store
1060            .handle_linked_chunk_updates(
1061                LinkedChunkId::Room(room_id_0),
1062                vec![
1063                    // Non-empty items chunk.
1064                    Update::NewItemsChunk {
1065                        previous: None,
1066                        new: ChunkIdentifier::new(0),
1067                        next: None,
1068                    },
1069                    Update::PushItems {
1070                        at: Position::new(ChunkIdentifier::new(0), 0),
1071                        items: vec![
1072                            event_factory
1073                                .text_msg("hello")
1074                                .sender(user)
1075                                .event_id(event_id!("$ev0"))
1076                                .into_event(),
1077                        ],
1078                    },
1079                ],
1080            )
1081            .await
1082            .unwrap();
1083
1084        let client = MockClientBuilder::new(None)
1085            .on_builder(move |builder| {
1086                builder.store_config(
1087                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
1088                        holder_name: "foo".to_owned(),
1089                    })
1090                    .event_cache_store(event_cache_store),
1091                )
1092            })
1093            .build()
1094            .await;
1095
1096        let event_cache = client.event_cache().unwrap();
1097
1098        client.base_client().get_or_create_room(room_id_0, RoomState::Joined);
1099        client.base_client().get_or_create_room(room_id_1, RoomState::Joined);
1100
1101        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1102
1103        // Room 0 has initial data, so it must trigger a generic update.
1104        {
1105            let _room_event_cache = event_cache.room(room_id_0).await.unwrap();
1106
1107            assert_matches!(
1108                generic_stream.recv().await,
1109                Ok(RoomEventCacheGenericUpdate { room_id }) => {
1110                    assert_eq!(room_id, room_id_0);
1111                }
1112            );
1113        }
1114
1115        // Room 1 has NO initial data, so nothing should happen.
1116        {
1117            let _room_event_cache = event_cache.room(room_id_1).await.unwrap();
1118
1119            assert!(generic_stream.recv().now_or_never().is_none());
1120        }
1121    }
1122
1123    #[async_test]
1124    async fn test_generic_update_when_paginating_room() {
1125        // Create 1 room, with 4 chunks in the event cache storage.
1126        let user = user_id!("@mnt_io:matrix.org");
1127        let room_id = room_id!("!raclette:patate.ch");
1128
1129        let event_factory = EventFactory::new().room(room_id).sender(user);
1130
1131        let event_cache_store = MemoryStore::new();
1132        event_cache_store
1133            .handle_linked_chunk_updates(
1134                LinkedChunkId::Room(room_id),
1135                vec![
1136                    // Empty chunk.
1137                    Update::NewItemsChunk {
1138                        previous: None,
1139                        new: ChunkIdentifier::new(0),
1140                        next: None,
1141                    },
1142                    // Empty chunk.
1143                    Update::NewItemsChunk {
1144                        previous: Some(ChunkIdentifier::new(0)),
1145                        new: ChunkIdentifier::new(1),
1146                        next: None,
1147                    },
1148                    // Non-empty items chunk.
1149                    Update::NewItemsChunk {
1150                        previous: Some(ChunkIdentifier::new(1)),
1151                        new: ChunkIdentifier::new(2),
1152                        next: None,
1153                    },
1154                    Update::PushItems {
1155                        at: Position::new(ChunkIdentifier::new(2), 0),
1156                        items: vec![
1157                            event_factory
1158                                .text_msg("hello")
1159                                .sender(user)
1160                                .event_id(event_id!("$ev0"))
1161                                .into_event(),
1162                        ],
1163                    },
1164                    // Non-empty items chunk.
1165                    Update::NewItemsChunk {
1166                        previous: Some(ChunkIdentifier::new(2)),
1167                        new: ChunkIdentifier::new(3),
1168                        next: None,
1169                    },
1170                    Update::PushItems {
1171                        at: Position::new(ChunkIdentifier::new(3), 0),
1172                        items: vec![
1173                            event_factory
1174                                .text_msg("world")
1175                                .sender(user)
1176                                .event_id(event_id!("$ev1"))
1177                                .into_event(),
1178                        ],
1179                    },
1180                ],
1181            )
1182            .await
1183            .unwrap();
1184
1185        let client = MockClientBuilder::new(None)
1186            .on_builder(move |builder| {
1187                builder.store_config(
1188                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
1189                        holder_name: "foo".to_owned(),
1190                    })
1191                    .event_cache_store(event_cache_store),
1192                )
1193            })
1194            .build()
1195            .await;
1196
1197        let event_cache = client.event_cache().unwrap();
1198
1199        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1200
1201        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1202
1203        // Room is initialised, it gets one event in the timeline.
1204        let (room_event_cache, _) = event_cache.room(room_id).await.unwrap();
1205
1206        assert_matches!(
1207            generic_stream.recv().await,
1208            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
1209                assert_eq!(room_id, expected_room_id);
1210            }
1211        );
1212
1213        let pagination = room_event_cache.pagination();
1214
1215        // Paginate, it gets one new event in the timeline.
1216        let pagination_outcome = pagination.run_backwards_once(1).await.unwrap();
1217
1218        assert_eq!(pagination_outcome.events.len(), 1);
1219        assert!(pagination_outcome.reached_start.not());
1220        assert_matches!(
1221            generic_stream.recv().await,
1222            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
1223                assert_eq!(room_id, expected_room_id);
1224            }
1225        );
1226
1227        // Paginate, it gets zero new event in the timeline.
1228        let pagination_outcome = pagination.run_backwards_once(1).await.unwrap();
1229
1230        assert!(pagination_outcome.events.is_empty());
1231        assert!(pagination_outcome.reached_start.not());
1232        assert!(generic_stream.recv().now_or_never().is_none());
1233
1234        // Paginate once more. Just checking our scenario is correct.
1235        let pagination_outcome = pagination.run_backwards_once(1).await.unwrap();
1236
1237        assert!(pagination_outcome.reached_start);
1238        assert!(generic_stream.recv().now_or_never().is_none());
1239    }
1240
1241    #[async_test]
1242    async fn test_for_room_when_room_is_not_found() {
1243        let client = logged_in_client(None).await;
1244        let room_id = room_id!("!raclette:patate.ch");
1245
1246        let event_cache = client.event_cache().unwrap();
1247
1248        // Room doesn't exist. It returns an error.
1249        assert_matches!(
1250            event_cache.room(room_id).await,
1251            Err(EventCacheError::RoomNotFound { room_id: not_found_room_id }) => {
1252                assert_eq!(room_id, not_found_room_id);
1253            }
1254        );
1255
1256        // Now create the room.
1257        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1258
1259        // Room exists. Everything fine.
1260        assert!(event_cache.room(room_id).await.is_ok());
1261    }
1262
1263    /// Test that the event cache does not create reference cycles or tasks that
1264    /// retain its reference indefinitely, preventing it from being deallocated.
1265    #[cfg(not(target_family = "wasm"))]
1266    #[async_test]
1267    async fn test_no_refcycle_event_cache_tasks() {
1268        let client = MockClientBuilder::new(None).build().await;
1269
1270        // Wait for the init tasks to die.
1271        sleep(Duration::from_secs(1)).await;
1272
1273        let event_cache_weak = Arc::downgrade(&client.event_cache().unwrap().inner);
1274        assert_eq!(event_cache_weak.strong_count(), 2);
1275
1276        {
1277            let room_id = room_id!("!room:example.org");
1278
1279            // Have the client know the room.
1280            let response = SyncResponseBuilder::default()
1281                .add_joined_room(JoinedRoomBuilder::new(room_id))
1282                .build_sync_response();
1283            client.inner.base_client.receive_sync_response(response).await.unwrap();
1284
1285            let (_room_event_cache, _drop_handles) =
1286                client.event_cache().unwrap().room(room_id).await.unwrap();
1287        }
1288
1289        drop(client);
1290
1291        // Give a bit of time for background tasks to die.
1292        sleep(Duration::from_secs(1)).await;
1293
1294        // No strong counts should exist now that the Client has been dropped.
1295        assert_eq!(
1296            event_cache_weak.strong_count(),
1297            0,
1298            "Too many strong references to the event cache {}",
1299            event_cache_weak.strong_count()
1300        );
1301    }
1302
1303    /// Dropping the future creating a room's caches must not leave the room
1304    /// state half-created, which would make every later attempt fail.
1305    #[async_test]
1306    async fn test_cancelled_caches_creation_can_be_retried() {
1307        let client = logged_in_client(None).await;
1308        let room_id_a = room_id!("!a:saucisse.bzh");
1309        let room_id_b = room_id!("!b:saucisse.bzh");
1310
1311        client.base_client().get_or_create_room(room_id_a, RoomState::Joined);
1312        client.base_client().get_or_create_room(room_id_b, RoomState::Joined);
1313
1314        let event_cache = client.event_cache().unwrap();
1315
1316        let (room_a, _drop_handles) = event_cache.room(room_id_a).await.unwrap();
1317
1318        // Hold the state write lock so that creating room B's caches waits on
1319        // it.
1320        let guard = room_a.state().write().await.unwrap();
1321
1322        let mut create_b = Box::pin(event_cache.room(room_id_b));
1323        assert!(create_b.as_mut().now_or_never().is_none());
1324
1325        // Queue another writer behind room B's creation.
1326        let mut other_writer = Box::pin(room_a.state().write());
1327        assert!(other_writer.as_mut().now_or_never().is_none());
1328
1329        // Room B's creation gets the lock and inserts its state. If anything
1330        // still has to wait after that (behind the other writer), cancel it
1331        // there.
1332        drop(guard);
1333        let _ = create_b.as_mut().now_or_never();
1334        drop(create_b);
1335        drop(other_writer);
1336
1337        // Creating room B's caches again works.
1338        event_cache.room(room_id_b).await.unwrap();
1339    }
1340}