Skip to main content

matrix_sdk/event_cache/caches/room/
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
15pub mod pagination;
16mod state;
17mod updates;
18
19use std::{collections::BTreeMap, fmt, sync::Arc};
20
21use eyeball::SharedObservable;
22use matrix_sdk_base::{
23    deserialized_responses::{AmbiguityChange, ThreadSummary},
24    event_cache::Event,
25    sync::Timeline,
26};
27use ruma::{
28    EventId, OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedUserId, RoomId,
29    events::{AnyRoomAccountDataEvent, relation::RelationType},
30    serde::Raw,
31};
32use tokio::sync::{Notify, mpsc};
33use tracing::{instrument, trace, warn};
34
35use self::pagination::RoomPagination;
36pub use self::{
37    state::RoomEventCacheState,
38    updates::{
39        LinkedChunkUpdateSender, RoomEventCacheGenericUpdate, RoomEventCacheLinkedChunkUpdate,
40        RoomEventCacheUpdate, RoomEventCacheUpdateSender,
41    },
42};
43use super::{
44    super::{
45        EventsOrigin, Result,
46        states::{CacheStateLock, StateLockWriteGuard, selectors::RoomStateSelector},
47    },
48    TimelineVectorDiffs,
49    event_linked_chunk::sort_positions_descending,
50    pagination::SharedPaginationStatus,
51    read_receipts::MaybeReceiptEventContent,
52    subscriber::{AutoShrinkMessage, Subscriber},
53};
54use crate::room::WeakRoom;
55
56/// The outcome of [`RoomEventCache::rfind_map_event_until_gap_by`].
57#[derive(Debug)]
58pub(crate) enum RFindMapOutcome<O> {
59    /// An event matched the predicate.
60    Found(O),
61
62    /// No event matched before a gap: there may be more events to fetch.
63    ReachedGap,
64
65    /// No event matched, all the way to the start of the room.
66    ReachedStart,
67
68    /// No event matched within the maximum number of stored chunks to read.
69    ReachedLimit,
70}
71
72/// A subset of an event cache, for a room.
73///
74/// Cloning is shallow, and thus is cheap to do.
75#[derive(Clone)]
76pub struct RoomEventCache {
77    inner: Arc<RoomEventCacheInner>,
78}
79
80impl fmt::Debug for RoomEventCache {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.debug_struct("RoomEventCache").finish_non_exhaustive()
83    }
84}
85
86impl RoomEventCache {
87    /// Create a new [`RoomEventCache`] using the given room and store.
88    pub(super) fn new(
89        room_id: OwnedRoomId,
90        weak_room: WeakRoom,
91        own_user_id: OwnedUserId,
92        state: CacheStateLock<RoomStateSelector>,
93        shared_pagination_status: SharedObservable<SharedPaginationStatus>,
94        auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
95        update_sender: RoomEventCacheUpdateSender,
96    ) -> Self {
97        Self {
98            inner: Arc::new(RoomEventCacheInner {
99                room_id,
100                weak_room,
101                own_user_id,
102                state,
103                update_sender,
104                pagination_batch_token_notifier: Notify::new(),
105                auto_shrink_sender,
106                shared_pagination_status,
107            }),
108        }
109    }
110
111    /// Get the room ID for this [`RoomEventCache`].
112    pub fn room_id(&self) -> &RoomId {
113        &self.inner.room_id
114    }
115
116    /// Get the owner of this [`RoomEventCache`].
117    pub(super) fn own_user_id(&self) -> &OwnedUserId {
118        &self.inner.own_user_id
119    }
120
121    /// Get the weak room of this [`RoomEventCache`].
122    pub(super) fn weak_room(&self) -> &WeakRoom {
123        &self.inner.weak_room
124    }
125
126    /// Read all current events.
127    ///
128    /// Use [`RoomEventCache::subscribe`] to get all current events, plus a
129    /// subscriber.
130    pub async fn events(&self) -> Result<Vec<Event>> {
131        let state = self.inner.state.read().await?;
132
133        Ok(state.room_linked_chunk().events().map(|(_position, item)| item.clone()).collect())
134    }
135
136    /// Subscribe to this room updates, after getting the initial list of
137    /// events.
138    ///
139    /// Use [`RoomEventCache::events`] to get all current events without the
140    /// subscriber. Creating, and especially dropping, a [`Subscriber`] isn't
141    /// free, as it triggers side-effects.
142    pub async fn subscribe(&self) -> Result<(Vec<Event>, Subscriber<RoomEventCacheUpdate>)> {
143        let state = self.inner.state.read().await?;
144        let events =
145            state.room_linked_chunk().events().map(|(_position, item)| item.clone()).collect();
146
147        let subscribers_handle = state.subscribers_handle();
148
149        let subscriber = Subscriber::new(
150            self.inner.update_sender.new_room_receiver(),
151            AutoShrinkMessage::Room { room_id: self.inner.room_id.clone() },
152            self.inner.auto_shrink_sender.clone(),
153            subscribers_handle,
154        );
155
156        trace!("added a room event cache subscriber; new count: {}", subscribers_handle.count());
157
158        Ok((events, subscriber))
159    }
160
161    /// Return a [`RoomPagination`] type useful for running back-pagination
162    /// queries in the current room.
163    pub fn pagination(&self) -> RoomPagination {
164        RoomPagination::new(self.inner.clone())
165    }
166
167    /// Try to find a single event in this room, starting from the most recent
168    /// event.
169    ///
170    /// The `predicate` receives the current event as its single argument.
171    ///
172    /// **Warning**! It looks into the loaded events from the in-memory linked
173    /// chunk **only**. It doesn't look inside the storage.
174    pub async fn rfind_map_event_in_memory_by<O, P>(&self, predicate: P) -> Result<Option<O>>
175    where
176        P: FnMut(&Event) -> Option<O>,
177    {
178        Ok(self.inner.state.read().await?.rfind_map_event_in_memory_by(predicate))
179    }
180
181    /// Try to find a single event in this room, starting from the most recent
182    /// event, and carrying on in the storage until a gap or the start of the
183    /// room.
184    ///
185    /// Contrary to [`Self::rfind_map_event_in_memory_by`], it also reads up to
186    /// `max_stored_chunkds` stored chunks preceding the in-memory ones.
187    pub(crate) async fn rfind_map_event_until_gap_by<O, P>(
188        &self,
189        max_stored_chunks: usize,
190        predicate: P,
191    ) -> Result<RFindMapOutcome<O>>
192    where
193        P: FnMut(&Event) -> Option<O>,
194    {
195        self.inner
196            .state
197            .read()
198            .await?
199            .rfind_map_event_until_gap_by(max_stored_chunks, predicate)
200            .await
201    }
202
203    /// Try to find an event by ID in this room.
204    ///
205    /// It starts by looking into loaded events before looking inside the
206    /// storage.
207    pub async fn find_event(&self, event_id: &EventId) -> Result<Option<Event>> {
208        Ok(self
209            .inner
210            .state
211            .read()
212            .await?
213            .find_event(event_id)
214            .await
215            .ok()
216            .flatten()
217            .map(|(_loc, event)| event))
218    }
219
220    /// Try to find an event by ID in this room, along with its related events.
221    ///
222    /// You can filter which types of related events to retrieve using `filter`.
223    /// `None` will retrieve related events of any type.
224    ///
225    /// The related events are sorted like this:
226    ///
227    /// - events saved out-of-band (with `RoomEventCache::save_events`) will be
228    ///   located at the beginning of the array.
229    /// - events present in the linked chunk (be it in memory or in the storage)
230    ///   will be sorted according to their ordering in the linked chunk.
231    pub async fn find_event_with_relations(
232        &self,
233        event_id: &EventId,
234        filter: Option<Vec<RelationType>>,
235    ) -> Result<Option<(Event, Vec<Event>)>> {
236        // Search in all loaded or stored events.
237        Ok(self
238            .inner
239            .state
240            .read()
241            .await?
242            .find_event_with_relations(event_id, filter)
243            .await
244            .ok()
245            .flatten())
246    }
247
248    /// Try to find the related events for an event by ID in this room.
249    ///
250    /// You can filter which types of related events to retrieve using `filter`.
251    /// `None` will retrieve related events of any type.
252    ///
253    /// The related events are sorted like this:
254    ///
255    /// - events saved out-of-band (with `RoomEventCache::save_events`) will be
256    ///   located at the beginning of the array.
257    /// - events present in the linked chunk (be it in memory or in the storage)
258    ///   will be sorted according to their ordering in the linked chunk.
259    pub async fn find_event_relations(
260        &self,
261        event_id: &EventId,
262        filter: Option<Vec<RelationType>>,
263    ) -> Result<Vec<Event>> {
264        // Search in all loaded or stored events.
265        self.inner.state.read().await?.find_event_relations(event_id, filter.clone()).await
266    }
267
268    /// Return a reference to the state.
269    pub(in super::super) fn state(&self) -> &CacheStateLock<RoomStateSelector> {
270        &self.inner.state
271    }
272
273    /// Handle an update from a joined room.
274    #[instrument(skip_all, fields(room_id = %self.room_id()))]
275    pub(super) async fn handle_joined_room_update(
276        &self,
277        timeline: Timeline,
278        read_receipts: MaybeReceiptEventContent,
279        account_data: Vec<Raw<AnyRoomAccountDataEvent>>,
280        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
281        avatar_changes: Option<BTreeMap<OwnedUserId, Option<OwnedMxcUri>>>,
282    ) -> Result<()> {
283        self.inner
284            .handle_timeline(timeline, read_receipts, ambiguity_changes, avatar_changes)
285            .await?;
286        self.inner.handle_account_data(account_data);
287
288        Ok(())
289    }
290
291    /// Handle an update from a left room.
292    #[instrument(skip_all, fields(room_id = %self.room_id()))]
293    pub(super) async fn handle_left_room_update(
294        &self,
295        timeline: Timeline,
296        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
297    ) -> Result<()> {
298        self.inner
299            .handle_timeline(timeline, MaybeReceiptEventContent::none(), ambiguity_changes, None)
300            .await?;
301
302        Ok(())
303    }
304
305    pub(in super::super) fn update_thread_summary(
306        &self,
307        thread_id: &EventId,
308        new_thread_summary: ThreadSummary,
309    ) -> Result<()> {
310        // Nothing to do here apart of sending an update. The `ThreadSummary` is
311        // stored inside `ThreadInfo` already, this cache doesn't need
312        // to hold it.
313        self.inner.update_sender.send(
314            RoomEventCacheUpdate::UpdateThreadSummary {
315                thread_root: thread_id.to_owned(),
316                thread_summary: new_thread_summary,
317            },
318            Some(RoomEventCacheGenericUpdate { room_id: self.inner.room_id.clone() }),
319        );
320
321        Ok(())
322    }
323
324    /// Get a reference to the [`RoomEventCacheUpdateSender`].
325    pub(in super::super) fn update_sender(&self) -> &RoomEventCacheUpdateSender {
326        &self.inner.update_sender
327    }
328
329    /// Handle a single event from the `SendQueue`.
330    pub(crate) async fn insert_sent_event_from_send_queue(&self, event: Event) -> Result<()> {
331        self.inner.insert_sent_event_from_send_queue(event).await
332    }
333
334    /// Return a nice debug string (a vector of lines) for the linked chunk of
335    /// events for this room.
336    pub async fn debug_string(&self) -> Vec<String> {
337        match self.inner.state.read().await {
338            Ok(read_guard) => read_guard.room_linked_chunk().debug_string(),
339            Err(err) => {
340                warn!(?err, "Failed to obtain the read guard for the `RoomEventCache`");
341
342                vec![]
343            }
344        }
345    }
346}
347
348/// The (non-cloneable) details of the `RoomEventCache`.
349pub(super) struct RoomEventCacheInner {
350    /// The room id for this room.
351    room_id: OwnedRoomId,
352
353    weak_room: WeakRoom,
354
355    /// The user's own user id.
356    own_user_id: OwnedUserId,
357
358    /// State for this room's cache.
359    state: CacheStateLock<RoomStateSelector>,
360
361    /// A notifier that we received a new pagination token.
362    pagination_batch_token_notifier: Notify,
363
364    shared_pagination_status: SharedObservable<SharedPaginationStatus>,
365
366    /// Sender to the auto-shrink channel.
367    ///
368    /// See doc comment around [`EventCache::auto_shrink_linked_chunk_task`] for
369    /// more details.
370    auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
371
372    /// Update sender for this room.
373    update_sender: RoomEventCacheUpdateSender,
374}
375
376impl RoomEventCacheInner {
377    fn handle_account_data(&self, account_data: Vec<Raw<AnyRoomAccountDataEvent>>) {
378        if account_data.is_empty() {
379            return;
380        }
381
382        let mut handled_read_marker = false;
383
384        trace!("Handling account data");
385
386        for raw_event in account_data {
387            match raw_event.deserialize() {
388                Ok(AnyRoomAccountDataEvent::FullyRead(ev)) => {
389                    // If duplicated, do not forward read marker multiple times
390                    // to avoid clutter the update channel.
391                    if handled_read_marker {
392                        continue;
393                    }
394
395                    handled_read_marker = true;
396
397                    // Propagate to observers. (We ignore the error if there
398                    // aren't any.)
399                    self.update_sender.send(
400                        RoomEventCacheUpdate::MoveReadMarkerTo { event_id: ev.content.event_id },
401                        None,
402                    );
403                }
404
405                Ok(_) => {
406                    // We're not interested in other room account data updates,
407                    // at this point.
408                }
409
410                Err(e) => {
411                    let event_type = raw_event.get_field::<String>("type").ok().flatten();
412                    warn!(event_type, "Failed to deserialize account data: {e}");
413                }
414            }
415        }
416    }
417
418    /// Handle a [`Timeline`], i.e. new events received by a sync for this room.
419    async fn handle_timeline(
420        &self,
421        timeline: Timeline,
422        read_receipts: MaybeReceiptEventContent,
423        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
424        avatar_changes: Option<BTreeMap<OwnedUserId, Option<OwnedMxcUri>>>,
425    ) -> Result<()> {
426        self.handle_timeline_inner(
427            self.state.write().await?,
428            timeline,
429            read_receipts,
430            ambiguity_changes,
431            avatar_changes,
432        )
433        .await
434    }
435
436    /// Handle a single event from the `SendQueue`.
437    ///
438    /// The event is inserted if and only if the cache is not empty.
439    async fn insert_sent_event_from_send_queue(&self, event: Event) -> Result<()> {
440        let state = self.state.write().await?;
441
442        // Insert the event if the room is not empty, otherwise it can break the
443        // pagination logic when detecting the start of the timeline because no
444        // gap can be inserted properly: it is impossible to compute a
445        // `prev_batch` token here.
446        if state.room_linked_chunk().events().next().is_some() {
447            return self
448                .handle_timeline_inner(
449                    state,
450                    Timeline { limited: false, prev_batch: None, events: vec![event] },
451                    MaybeReceiptEventContent::none(),
452                    BTreeMap::new(),
453                    None,
454                )
455                .await;
456        }
457
458        Ok(())
459    }
460
461    async fn handle_timeline_inner(
462        &self,
463        mut state: StateLockWriteGuard<'_, RoomEventCacheState>,
464        timeline: Timeline,
465        read_receipts: MaybeReceiptEventContent,
466        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
467        avatar_changes: Option<BTreeMap<OwnedUserId, Option<OwnedMxcUri>>>,
468    ) -> Result<()> {
469        if timeline.events.is_empty()
470            && timeline.prev_batch.is_none()
471            && read_receipts.is_none()
472            && ambiguity_changes.is_empty()
473            && avatar_changes.as_ref().is_none_or(|avatars| avatars.is_empty())
474        {
475            return Ok(());
476        }
477
478        trace!("adding new events");
479
480        let (stored_prev_batch_token, timeline_event_diffs) =
481            state.handle_sync(timeline, &read_receipts).await?;
482
483        // Now that all events have been added, we can trigger the
484        // `pagination_token_notifier`.
485        if stored_prev_batch_token {
486            self.pagination_batch_token_notifier.notify_one();
487        }
488
489        // The order matters here: first send the timeline event diffs, then
490        // only the related events (members, etc.). Read receipts are broadcast
491        // by `Caches::handle_joined_room_update`, after this.
492        //
493        // The diffs must be sent while the state lock is still held: the
494        // indices they carry are only valid if no other change to the linked
495        // chunk is sent before them.
496        if !timeline_event_diffs.is_empty() {
497            state.update_sender.send(
498                RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs {
499                    diffs: timeline_event_diffs,
500                    origin: EventsOrigin::Sync,
501                }),
502                Some(RoomEventCacheGenericUpdate { room_id: self.room_id.clone() }),
503            );
504        }
505
506        if !ambiguity_changes.is_empty() || avatar_changes.as_ref().is_some_and(|c| !c.is_empty()) {
507            self.update_sender.send(
508                RoomEventCacheUpdate::UpdateMembers { ambiguity_changes, avatar_changes },
509                None,
510            );
511        }
512
513        Ok(())
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use matrix_sdk_base::{RoomState, event_cache::Event};
520    use matrix_sdk_test::{async_test, event_factory::EventFactory};
521    use ruma::{
522        RoomId, event_id,
523        events::{relation::RelationType, room::message::RoomMessageEventContentWithoutRelation},
524        room_id, user_id,
525    };
526
527    use crate::test_utils::logged_in_client;
528
529    #[async_test]
530    async fn test_find_event_by_id_with_edit_relation() {
531        let original_id = event_id!("$original");
532        let related_id = event_id!("$related");
533        let room_id = room_id!("!galette:saucisse.bzh");
534        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
535
536        assert_relations(
537            room_id,
538            f.text_msg("Original event").event_id(original_id).into(),
539            f.text_msg("* An edited event")
540                .edit(
541                    original_id,
542                    RoomMessageEventContentWithoutRelation::text_plain("And edited event"),
543                )
544                .event_id(related_id)
545                .into(),
546            f,
547        )
548        .await;
549    }
550
551    #[async_test]
552    async fn test_find_event_by_id_with_thread_reply_relation() {
553        let original_id = event_id!("$original");
554        let related_id = event_id!("$related");
555        let room_id = room_id!("!galette:saucisse.bzh");
556        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
557
558        assert_relations(
559            room_id,
560            f.text_msg("Original event").event_id(original_id).into(),
561            f.text_msg("A reply").in_thread(original_id, related_id).event_id(related_id).into(),
562            f,
563        )
564        .await;
565    }
566
567    #[async_test]
568    async fn test_find_event_by_id_with_reaction_relation() {
569        let original_id = event_id!("$original");
570        let related_id = event_id!("$related");
571        let room_id = room_id!("!galette:saucisse.bzh");
572        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
573
574        assert_relations(
575            room_id,
576            f.text_msg("Original event").event_id(original_id).into(),
577            f.reaction(original_id, ":D").event_id(related_id).into(),
578            f,
579        )
580        .await;
581    }
582
583    #[async_test]
584    async fn test_find_event_by_id_with_poll_response_relation() {
585        let original_id = event_id!("$original");
586        let related_id = event_id!("$related");
587        let room_id = room_id!("!galette:saucisse.bzh");
588        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
589
590        assert_relations(
591            room_id,
592            f.poll_start("Poll start event", "A poll question", vec!["An answer"])
593                .event_id(original_id)
594                .into(),
595            f.poll_response(vec!["1"], original_id).event_id(related_id).into(),
596            f,
597        )
598        .await;
599    }
600
601    #[async_test]
602    async fn test_find_event_by_id_with_poll_end_relation() {
603        let original_id = event_id!("$original");
604        let related_id = event_id!("$related");
605        let room_id = room_id!("!galette:saucisse.bzh");
606        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
607
608        assert_relations(
609            room_id,
610            f.poll_start("Poll start event", "A poll question", vec!["An answer"])
611                .event_id(original_id)
612                .into(),
613            f.poll_end("Poll ended", original_id).event_id(related_id).into(),
614            f,
615        )
616        .await;
617    }
618
619    #[async_test]
620    async fn test_find_event_by_id_with_filtered_relationships() {
621        let original_id = event_id!("$original");
622        let related_id = event_id!("$related");
623        let associated_related_id = event_id!("$recursive_related");
624        let room_id = room_id!("!galette:saucisse.bzh");
625        let event_factory = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
626
627        let original_event = event_factory.text_msg("Original event").event_id(original_id).into();
628        let related_event = event_factory
629            .text_msg("* Edited event")
630            .edit(original_id, RoomMessageEventContentWithoutRelation::text_plain("Edited event"))
631            .event_id(related_id)
632            .into();
633        let associated_related_event =
634            event_factory.reaction(related_id, "🤡").event_id(associated_related_id).into();
635
636        let client = logged_in_client(None).await;
637
638        client.base_client().get_or_create_room(room_id, RoomState::Joined);
639
640        let (room_event_cache, _drop_handles) =
641            client.event_cache().unwrap().room(room_id).await.unwrap();
642
643        {
644            let mut state = room_event_cache.inner.state.write().await.unwrap();
645
646            // Save the original event.
647            state.save_events([original_event]).await.unwrap();
648
649            // Save the related event.
650            state.save_events([related_event]).await.unwrap();
651
652            // Save the associated related event, which redacts the related
653            // event.
654            state.save_events([associated_related_event]).await.unwrap();
655        }
656
657        let filter = Some(vec![RelationType::Replacement]);
658        let (event, related_events) = room_event_cache
659            .find_event_with_relations(original_id, filter)
660            .await
661            .expect("Failed to find the event with relations")
662            .expect("Event has no relation");
663        // Fetched event is the right one.
664        let cached_event_id = event.event_id().unwrap();
665        assert_eq!(cached_event_id, original_id);
666
667        // There's only the edit event (an edit event can't have its own edit
668        // event).
669        assert_eq!(related_events.len(), 1);
670
671        let related_event_id = related_events[0].event_id().unwrap();
672        assert_eq!(related_event_id, related_id);
673
674        // Now we'll filter threads instead, there should be no related events
675        let filter = Some(vec![RelationType::Thread]);
676        let (event, related_events) = room_event_cache
677            .find_event_with_relations(original_id, filter)
678            .await
679            .expect("Failed to find the event with relations")
680            .expect("Event has no relation");
681
682        // Fetched event is the right one.
683        let cached_event_id = event.event_id().unwrap();
684        assert_eq!(cached_event_id, original_id);
685        // No Thread related events found
686        assert!(related_events.is_empty());
687    }
688
689    #[async_test]
690    async fn test_find_event_by_id_with_recursive_relation() {
691        let original_id = event_id!("$original");
692        let related_id = event_id!("$related");
693        let associated_related_id = event_id!("$recursive_related");
694        let room_id = room_id!("!galette:saucisse.bzh");
695        let event_factory = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
696
697        let original_event = event_factory.text_msg("Original event").event_id(original_id).into();
698        let related_event = event_factory
699            .text_msg("* Edited event")
700            .edit(original_id, RoomMessageEventContentWithoutRelation::text_plain("Edited event"))
701            .event_id(related_id)
702            .into();
703        let associated_related_event =
704            event_factory.reaction(related_id, "👍").event_id(associated_related_id).into();
705
706        let client = logged_in_client(None).await;
707
708        client.base_client().get_or_create_room(room_id, RoomState::Joined);
709
710        let (room_event_cache, _drop_handles) =
711            client.event_cache().unwrap().room(room_id).await.unwrap();
712
713        {
714            let mut state = room_event_cache.inner.state.write().await.unwrap();
715
716            // Save the original event.
717            state.save_events([original_event]).await.unwrap();
718
719            // Save the related event.
720            state.save_events([related_event]).await.unwrap();
721
722            // Save the associated related event, which redacts the related
723            // event.
724            state.save_events([associated_related_event]).await.unwrap();
725        }
726
727        let (event, related_events) = room_event_cache
728            .find_event_with_relations(original_id, None)
729            .await
730            .expect("Failed to find the event with relations")
731            .expect("Event has no relation");
732        // Fetched event is the right one.
733        let cached_event_id = event.event_id().unwrap();
734        assert_eq!(cached_event_id, original_id);
735
736        // There are both the related id and the associatively related id
737        assert_eq!(related_events.len(), 2);
738
739        let related_event_id = related_events[0].event_id().unwrap();
740        assert_eq!(related_event_id, related_id);
741        let related_event_id = related_events[1].event_id().unwrap();
742        assert_eq!(related_event_id, associated_related_id);
743    }
744
745    async fn assert_relations(
746        room_id: &RoomId,
747        original_event: Event,
748        related_event: Event,
749        event_factory: EventFactory,
750    ) {
751        let client = logged_in_client(None).await;
752
753        client.base_client().get_or_create_room(room_id, RoomState::Joined);
754
755        let (room_event_cache, _drop_handles) =
756            client.event_cache().unwrap().room(room_id).await.unwrap();
757
758        let original_event_id = original_event.event_id().unwrap().to_owned();
759        let related_id = related_event.event_id().unwrap().to_owned();
760
761        {
762            let mut state = room_event_cache.inner.state.write().await.unwrap();
763
764            // Save the original event.
765            state.save_events([original_event]).await.unwrap();
766
767            // Save an unrelated event to check it's not in the related events
768            // list.
769            let unrelated_id = event_id!("$2");
770            state
771                .save_events([event_factory
772                    .text_msg("An unrelated event")
773                    .event_id(unrelated_id)
774                    .into()])
775                .await
776                .unwrap();
777
778            // Save the related event.
779            state.save_events([related_event]).await.unwrap();
780        }
781
782        let (event, related_events) = room_event_cache
783            .find_event_with_relations(&original_event_id, None)
784            .await
785            .expect("Failed to find the event with relations")
786            .expect("Event has no relation");
787        // Fetched event is the right one.
788        let cached_event_id = event.event_id().unwrap();
789        assert_eq!(cached_event_id, original_event_id);
790
791        // There is only the actually related event in the related ones
792        let related_event_id = related_events[0].event_id().unwrap();
793        assert_eq!(related_event_id, related_id);
794    }
795}
796
797#[cfg(all(test, not(target_family = "wasm")))] // This uses the cross-process lock, so needs time support.
798mod timed_tests {
799    use std::{ops::Not, sync::Arc};
800
801    use assert_matches::assert_matches;
802    use eyeball_im::VectorDiff;
803    use futures_util::FutureExt;
804    use matrix_sdk_base::{
805        RoomState,
806        event_cache::{
807            Gap,
808            store::{ControlledMemoryStore, EventCacheStore as _, MemoryStore},
809        },
810        linked_chunk::{
811            ChunkContent, ChunkIdentifier, LinkedChunkId, Position, Update,
812            lazy_loader::from_all_chunks,
813        },
814        store::StoreConfig,
815        sync::Timeline,
816    };
817    use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
818    use matrix_sdk_test::{User, async_test, event_factory::EventFactory};
819    use ruma::{
820        EventId, event_id,
821        events::{AnySyncMessageLikeEvent, AnySyncTimelineEvent},
822        room_id,
823        serde::Raw,
824        user_id,
825    };
826    use serde_json::json;
827    use strass::assert_let;
828    use tokio::task::yield_now;
829
830    use super::{
831        super::{super::TimelineVectorDiffs, pagination::LoadMoreEventsBackwardsOutcome},
832        MaybeReceiptEventContent, RoomEventCache, RoomEventCacheGenericUpdate,
833        RoomEventCacheUpdate,
834    };
835    use crate::{assert_let_timeout, test_utils::client::MockClientBuilder};
836
837    #[async_test]
838    async fn test_write_to_storage() {
839        let room_id = room_id!("!galette:saucisse.bzh");
840        let event_id_0 = event_id!("$ev0");
841        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
842
843        let event_cache_store = Arc::new(MemoryStore::new());
844
845        let client = MockClientBuilder::new(None)
846            .on_builder(|builder| {
847                builder.store_config(
848                    StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
849                        .event_cache_store(event_cache_store.clone()),
850                )
851            })
852            .build()
853            .await;
854
855        let event_cache = client.event_cache().unwrap();
856
857        client.base_client().get_or_create_room(room_id, RoomState::Joined);
858
859        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
860        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
861
862        // Propagate an update for a message and a prev-batch token.
863        let timeline = Timeline {
864            limited: true,
865            prev_batch: Some("raclette".to_owned()),
866            events: vec![f.text_msg("hey yo").event_id(event_id_0).into_event()],
867        };
868
869        room_event_cache
870            .handle_joined_room_update(
871                timeline,
872                MaybeReceiptEventContent::none(),
873                Default::default(),
874                Default::default(),
875                Default::default(),
876            )
877            .await
878            .unwrap();
879
880        // Just checking the generic update is correct.
881        assert_matches!(
882            generic_stream.recv().await,
883            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
884                assert_eq!(expected_room_id, room_id);
885            }
886        );
887        assert!(generic_stream.is_empty());
888
889        // Check the storage.
890        let linked_chunk = from_all_chunks::<3, _, _>(
891            event_cache_store.load_all_chunks(LinkedChunkId::Room(room_id)).await.unwrap(),
892        )
893        .unwrap()
894        .unwrap();
895
896        assert_eq!(linked_chunk.chunks().count(), 2);
897
898        let mut chunks = linked_chunk.chunks();
899
900        // We start with the gap.
901        assert_matches!(chunks.next().unwrap().content(), ChunkContent::Gap(gap) => {
902            assert_eq!(gap.token, "raclette");
903        });
904
905        // Then we have the stored event.
906        assert_matches!(chunks.next().unwrap().content(), ChunkContent::Items(events) => {
907            assert_eq!(events.len(), 1);
908            assert_eq!(events[0].event_id(), Some(event_id_0));
909        });
910
911        // That's all, folks!
912        assert!(chunks.next().is_none());
913    }
914
915    #[async_test]
916    async fn test_write_to_storage_strips_bundled_relations() {
917        let room_id = room_id!("!galette:saucisse.bzh");
918        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
919
920        let event_cache_store = Arc::new(MemoryStore::new());
921
922        let client = MockClientBuilder::new(None)
923            .on_builder(|builder| {
924                builder.store_config(
925                    StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
926                        .event_cache_store(event_cache_store.clone()),
927                )
928            })
929            .build()
930            .await;
931
932        let event_cache = client.event_cache().unwrap();
933
934        client.base_client().get_or_create_room(room_id, RoomState::Joined);
935
936        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
937        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
938
939        // Propagate an update for a message with bundled relations.
940        let ev = f
941            .text_msg("hey yo")
942            .sender(User::Alice)
943            .with_bundled_edit(f.text_msg("Hello, Kind Sir").sender(User::Alice))
944            .into_event();
945
946        let timeline = Timeline { limited: false, prev_batch: None, events: vec![ev] };
947
948        room_event_cache
949            .handle_joined_room_update(
950                timeline,
951                MaybeReceiptEventContent::none(),
952                Default::default(),
953                Default::default(),
954                Default::default(),
955            )
956            .await
957            .unwrap();
958
959        // Just checking the generic update is correct.
960        assert_matches!(
961            generic_stream.recv().await,
962            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
963                assert_eq!(expected_room_id, room_id);
964            }
965        );
966        assert!(generic_stream.is_empty());
967
968        // The in-memory linked chunk keeps the bundled relation.
969        {
970            let events = room_event_cache.events().await.unwrap();
971
972            assert_eq!(events.len(), 1);
973
974            let ev = events[0].raw().deserialize().unwrap();
975            assert_let!(
976                AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(msg)) = ev
977            );
978
979            let original = msg.as_original().unwrap();
980            assert_eq!(original.content.body(), "hey yo");
981            assert!(original.unsigned.relations.replace.is_some());
982        }
983
984        // The one in storage does not.
985        let linked_chunk = from_all_chunks::<3, _, _>(
986            event_cache_store.load_all_chunks(LinkedChunkId::Room(room_id)).await.unwrap(),
987        )
988        .unwrap()
989        .unwrap();
990
991        assert_eq!(linked_chunk.chunks().count(), 1);
992
993        let mut chunks = linked_chunk.chunks();
994        assert_matches!(chunks.next().unwrap().content(), ChunkContent::Items(events) => {
995            assert_eq!(events.len(), 1);
996
997            let ev = events[0].raw().deserialize().unwrap();
998            assert_let!(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(msg)) = ev);
999
1000            let original = msg.as_original().unwrap();
1001            assert_eq!(original.content.body(), "hey yo");
1002            assert!(original.unsigned.relations.replace.is_none());
1003        });
1004
1005        // That's all, folks!
1006        assert!(chunks.next().is_none());
1007    }
1008
1009    #[async_test]
1010    async fn test_clear() {
1011        let room_id = room_id!("!galette:saucisse.bzh");
1012        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
1013
1014        let event_id1 = event_id!("$1");
1015        let event_id2 = event_id!("$2");
1016
1017        let ev1 = f.text_msg("hello world").event_id(event_id1).into_event();
1018        let ev2 = f.text_msg("how's it going").event_id(event_id2).into_event();
1019
1020        // Prefill the store with some data.
1021        let event_cache_store = Arc::new(MemoryStore::new());
1022        event_cache_store
1023            .handle_linked_chunk_updates(
1024                LinkedChunkId::Room(room_id),
1025                vec![
1026                    // An empty items chunk.
1027                    Update::NewItemsChunk {
1028                        previous: None,
1029                        new: ChunkIdentifier::new(0),
1030                        next: None,
1031                    },
1032                    // A gap chunk.
1033                    Update::NewGapChunk {
1034                        previous: Some(ChunkIdentifier::new(0)),
1035                        // Chunk IDs aren't supposed to be ordered, so use a random value here.
1036                        new: ChunkIdentifier::new(42),
1037                        next: None,
1038                        gap: Gap { token: "comté".to_owned() },
1039                    },
1040                    // Another items chunk, non-empty this time.
1041                    Update::NewItemsChunk {
1042                        previous: Some(ChunkIdentifier::new(42)),
1043                        new: ChunkIdentifier::new(1),
1044                        next: None,
1045                    },
1046                    Update::PushItems {
1047                        at: Position::new(ChunkIdentifier::new(1), 0),
1048                        items: vec![ev1.clone()],
1049                    },
1050                    // And another items chunk, non-empty again.
1051                    Update::NewItemsChunk {
1052                        previous: Some(ChunkIdentifier::new(1)),
1053                        new: ChunkIdentifier::new(2),
1054                        next: None,
1055                    },
1056                    Update::PushItems {
1057                        at: Position::new(ChunkIdentifier::new(2), 0),
1058                        items: vec![ev2.clone()],
1059                    },
1060                ],
1061            )
1062            .await
1063            .unwrap();
1064
1065        let client = MockClientBuilder::new(None)
1066            .on_builder(|builder| {
1067                builder.store_config(
1068                    StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
1069                        .event_cache_store(event_cache_store.clone()),
1070                )
1071            })
1072            .build()
1073            .await;
1074
1075        let event_cache = client.event_cache().unwrap();
1076
1077        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1078
1079        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1080
1081        let (items, mut stream) = room_event_cache.subscribe().await.unwrap();
1082        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1083
1084        // The room knows about all cached events.
1085        {
1086            assert!(room_event_cache.find_event(event_id1).await.unwrap().is_some());
1087            assert!(room_event_cache.find_event(event_id2).await.unwrap().is_some());
1088        }
1089
1090        // But only part of events are loaded from the store
1091        {
1092            // The room must contain only one event because only one chunk has
1093            // been loaded.
1094            assert_eq!(items.len(), 1);
1095            assert_eq!(items[0].event_id().unwrap(), event_id2);
1096
1097            assert!(stream.is_empty());
1098        }
1099
1100        // Let's load more chunks to load all events.
1101        {
1102            room_event_cache.pagination().run_backwards_once(20).await.unwrap();
1103
1104            assert_let_timeout!(
1105                Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1106                    stream.recv()
1107            );
1108            assert_eq!(diffs.len(), 1);
1109            assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value: event } => {
1110                // Here you are `event_id1`!
1111                assert_eq!(event.event_id().unwrap(), event_id1);
1112            });
1113
1114            assert!(stream.is_empty());
1115
1116            assert_let_timeout!(
1117                Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) =
1118                    generic_stream.recv()
1119            );
1120            assert_eq!(room_id, expected_room_id);
1121            assert!(generic_stream.is_empty());
1122        }
1123
1124        // After clearing,…
1125        event_cache.clear_all_rooms().await.unwrap();
1126
1127        //… we get an update that the content has been cleared.
1128        assert_let_timeout!(
1129            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1130                stream.recv()
1131        );
1132        assert_eq!(diffs.len(), 1);
1133        assert_let!(VectorDiff::Clear = &diffs[0]);
1134
1135        // … same with a generic update.
1136        assert_let_timeout!(
1137            Ok(RoomEventCacheGenericUpdate { room_id: received_room_id }) = generic_stream.recv()
1138        );
1139        assert_eq!(received_room_id, room_id);
1140        assert!(generic_stream.is_empty());
1141
1142        // Events are forgotten by the event cache, after clearing a room.
1143        assert!(room_event_cache.find_event(event_id1).await.unwrap().is_none());
1144
1145        // And their presence in a linked chunk is forgotten.
1146        let items = room_event_cache.events().await.unwrap();
1147        assert!(items.is_empty());
1148
1149        // The event cache store is fully empty.
1150        assert!(
1151            event_cache_store
1152                .load_all_chunks(LinkedChunkId::Room(room_id))
1153                .await
1154                .unwrap()
1155                .is_empty()
1156        );
1157    }
1158
1159    #[async_test]
1160    async fn test_load_from_storage() {
1161        let room_id = room_id!("!galette:saucisse.bzh");
1162        let f = EventFactory::new().room(room_id).sender(user_id!("@ben:saucisse.bzh"));
1163
1164        let event_id1 = event_id!("$1");
1165        let event_id2 = event_id!("$2");
1166
1167        let ev1 = f.text_msg("hello world").sender(User::Alice).event_id(event_id1).into_event();
1168        let ev2 = f.text_msg("how's it going").sender(User::Bob).event_id(event_id2).into_event();
1169
1170        // Prefill the store with some data.
1171        let event_cache_store = Arc::new(MemoryStore::new());
1172        event_cache_store
1173            .handle_linked_chunk_updates(
1174                LinkedChunkId::Room(room_id),
1175                vec![
1176                    // An empty items chunk.
1177                    Update::NewItemsChunk {
1178                        previous: None,
1179                        new: ChunkIdentifier::new(0),
1180                        next: None,
1181                    },
1182                    // A gap chunk.
1183                    Update::NewGapChunk {
1184                        previous: Some(ChunkIdentifier::new(0)),
1185                        // Chunk IDs aren't supposed to be ordered, so use a random value here.
1186                        new: ChunkIdentifier::new(42),
1187                        next: None,
1188                        gap: Gap { token: "cheddar".to_owned() },
1189                    },
1190                    // Another items chunk, non-empty this time.
1191                    Update::NewItemsChunk {
1192                        previous: Some(ChunkIdentifier::new(42)),
1193                        new: ChunkIdentifier::new(1),
1194                        next: None,
1195                    },
1196                    Update::PushItems {
1197                        at: Position::new(ChunkIdentifier::new(1), 0),
1198                        items: vec![ev1.clone()],
1199                    },
1200                    // And another items chunk, non-empty again.
1201                    Update::NewItemsChunk {
1202                        previous: Some(ChunkIdentifier::new(1)),
1203                        new: ChunkIdentifier::new(2),
1204                        next: None,
1205                    },
1206                    Update::PushItems {
1207                        at: Position::new(ChunkIdentifier::new(2), 0),
1208                        items: vec![ev2.clone()],
1209                    },
1210                ],
1211            )
1212            .await
1213            .unwrap();
1214
1215        let client = MockClientBuilder::new(None)
1216            .on_builder(|builder| {
1217                builder.store_config(
1218                    StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
1219                        .event_cache_store(event_cache_store.clone()),
1220                )
1221            })
1222            .build()
1223            .await;
1224
1225        let event_cache = client.event_cache().unwrap();
1226
1227        // Let's check whether the generic updates are received for the
1228        // initialisation.
1229        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1230
1231        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1232
1233        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1234
1235        // The room event cache has been loaded. A generic update must have been
1236        // triggered.
1237        assert_matches!(
1238            generic_stream.recv().await,
1239            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
1240                assert_eq!(room_id, expected_room_id);
1241            }
1242        );
1243        assert!(generic_stream.is_empty());
1244
1245        let (items, mut stream) = room_event_cache.subscribe().await.unwrap();
1246
1247        // The initial items contain one event because only the last chunk is
1248        // loaded by default.
1249        assert_eq!(items.len(), 1);
1250        assert_eq!(items[0].event_id().unwrap(), event_id2);
1251        assert!(stream.is_empty());
1252
1253        // The event cache knows only all events though, even if they aren't
1254        // loaded.
1255        assert!(room_event_cache.find_event(event_id1).await.unwrap().is_some());
1256        assert!(room_event_cache.find_event(event_id2).await.unwrap().is_some());
1257
1258        // Let's paginate to load more events.
1259        room_event_cache.pagination().run_backwards_once(20).await.unwrap();
1260
1261        assert_let_timeout!(
1262            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1263                stream.recv()
1264        );
1265        assert_eq!(diffs.len(), 1);
1266        assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value: event } => {
1267            assert_eq!(event.event_id().unwrap(), event_id1);
1268        });
1269
1270        assert!(stream.is_empty());
1271
1272        // A generic update is triggered too.
1273        assert_matches!(
1274            generic_stream.recv().await,
1275            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
1276                assert_eq!(expected_room_id, room_id);
1277            }
1278        );
1279        assert!(generic_stream.is_empty());
1280
1281        // A new update with one of these events leads to deduplication.
1282        let timeline = Timeline { limited: false, prev_batch: None, events: vec![ev2] };
1283
1284        room_event_cache
1285            .handle_joined_room_update(
1286                timeline,
1287                MaybeReceiptEventContent::none(),
1288                Default::default(),
1289                Default::default(),
1290                Default::default(),
1291            )
1292            .await
1293            .unwrap();
1294
1295        // Just checking the generic update is correct. There is a duplicate
1296        // event, so no generic changes whatsoever!
1297        assert!(generic_stream.recv().now_or_never().is_none());
1298
1299        // The stream doesn't report these changes _yet_. Use the items vector
1300        // given when subscribing, to check that the items correspond to their
1301        // new positions. The duplicated item is removed (so it's not the first
1302        // element anymore), and it's added to the back of the list.
1303        let items = room_event_cache.events().await.unwrap();
1304        assert_eq!(items.len(), 2);
1305        assert_eq!(items[0].event_id().unwrap(), event_id1);
1306        assert_eq!(items[1].event_id().unwrap(), event_id2);
1307    }
1308
1309    #[async_test]
1310    async fn test_load_from_storage_resilient_to_failure() {
1311        let room_id = room_id!("!fondue:patate.ch");
1312
1313        let event = EventFactory::new()
1314            .room(room_id)
1315            .sender(user_id!("@ben:saucisse.bzh"))
1316            .text_msg("foo")
1317            .event_id(event_id!("$42"))
1318            .into_event();
1319
1320        // Prefill the store with invalid data: two chunks that form a cycle.
1321        let event_cache_store = Arc::new(MemoryStore::new());
1322        event_cache_store
1323            .handle_linked_chunk_updates(
1324                LinkedChunkId::Room(room_id),
1325                vec![
1326                    Update::NewItemsChunk {
1327                        previous: None,
1328                        new: ChunkIdentifier::new(0),
1329                        next: None,
1330                    },
1331                    Update::PushItems {
1332                        at: Position::new(ChunkIdentifier::new(0), 0),
1333                        items: vec![event],
1334                    },
1335                    Update::NewItemsChunk {
1336                        previous: Some(ChunkIdentifier::new(0)),
1337                        new: ChunkIdentifier::new(1),
1338                        next: Some(ChunkIdentifier::new(0)),
1339                    },
1340                ],
1341            )
1342            .await
1343            .unwrap();
1344
1345        let client = MockClientBuilder::new(None)
1346            .on_builder(|builder| {
1347                builder.store_config(
1348                    StoreConfig::new(CrossProcessLockConfig::multi_process("holder"))
1349                        .event_cache_store(event_cache_store.clone()),
1350                )
1351            })
1352            .build()
1353            .await;
1354
1355        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1356        let event_cache = client.event_cache().unwrap();
1357
1358        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1359
1360        let items = room_event_cache.events().await.unwrap();
1361
1362        // Because the persisted content was invalid, the room store is reset:
1363        // there are no events in the cache.
1364        assert!(items.is_empty());
1365
1366        // Storage doesn't contain anything. It would also be valid that it
1367        // contains a single initial empty items chunk.
1368        let raw_chunks =
1369            event_cache_store.load_all_chunks(LinkedChunkId::Room(room_id)).await.unwrap();
1370        assert!(raw_chunks.is_empty());
1371    }
1372
1373    #[async_test]
1374    async fn test_no_useless_gaps() {
1375        let room_id = room_id!("!galette:saucisse.bzh");
1376
1377        let client = MockClientBuilder::new(None).build().await;
1378
1379        let event_cache = client.event_cache().unwrap();
1380
1381        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1382        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1383        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1384
1385        let f = EventFactory::new().room(room_id).sender(User::Alice);
1386
1387        // Propagate an update including a limited timeline with one message and
1388        // a prev-batch token.
1389        room_event_cache
1390            .handle_joined_room_update(
1391                Timeline {
1392                    limited: true,
1393                    prev_batch: Some("raclette".to_owned()),
1394                    events: vec![f.text_msg("hey yo").into_event()],
1395                },
1396                MaybeReceiptEventContent::none(),
1397                Default::default(),
1398                Default::default(),
1399                Default::default(),
1400            )
1401            .await
1402            .unwrap();
1403
1404        // Just checking the generic update is correct.
1405        assert_matches!(
1406            generic_stream.recv().await,
1407            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
1408                assert_eq!(expected_room_id, room_id);
1409            }
1410        );
1411        assert!(generic_stream.is_empty());
1412
1413        {
1414            let state = room_event_cache.inner.state.read().await.unwrap();
1415
1416            let mut num_gaps = 0;
1417            let mut num_events = 0;
1418
1419            for c in state.room_linked_chunk().chunks() {
1420                match c.content() {
1421                    ChunkContent::Items(items) => num_events += items.len(),
1422                    ChunkContent::Gap(_) => num_gaps += 1,
1423                }
1424            }
1425
1426            // The limited sync unloads the chunk, so it will appear as if there
1427            // are only the events.
1428            assert_eq!(num_gaps, 0);
1429            assert_eq!(num_events, 1);
1430        }
1431
1432        // But if I manually reload more of the chunk, the gap will be present.
1433        assert_matches!(
1434            room_event_cache.pagination().load_more_events_backwards().await.unwrap(),
1435            LoadMoreEventsBackwardsOutcome::Gap { .. }
1436        );
1437
1438        {
1439            let state = room_event_cache.inner.state.read().await.unwrap();
1440
1441            let mut num_gaps = 0;
1442            let mut num_events = 0;
1443
1444            for c in state.room_linked_chunk().chunks() {
1445                match c.content() {
1446                    ChunkContent::Items(items) => num_events += items.len(),
1447                    ChunkContent::Gap(_) => num_gaps += 1,
1448                }
1449            }
1450
1451            // The gap must have been stored.
1452            assert_eq!(num_gaps, 1);
1453            assert_eq!(num_events, 1);
1454        }
1455
1456        // Now, propagate an update for another message, but the timeline isn't
1457        // limited this time.
1458        room_event_cache
1459            .handle_joined_room_update(
1460                Timeline {
1461                    limited: false,
1462                    prev_batch: Some("fondue".to_owned()),
1463                    events: vec![f.text_msg("sup").into_event()],
1464                },
1465                MaybeReceiptEventContent::none(),
1466                Default::default(),
1467                Default::default(),
1468                Default::default(),
1469            )
1470            .await
1471            .unwrap();
1472
1473        // Just checking the generic update is correct.
1474        assert_matches!(
1475            generic_stream.recv().await,
1476            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
1477                assert_eq!(expected_room_id, room_id);
1478            }
1479        );
1480        assert!(generic_stream.is_empty());
1481
1482        {
1483            let state = room_event_cache.inner.state.read().await.unwrap();
1484
1485            let mut num_gaps = 0;
1486            let mut num_events = 0;
1487
1488            for c in state.room_linked_chunk().chunks() {
1489                match c.content() {
1490                    ChunkContent::Items(items) => num_events += items.len(),
1491                    ChunkContent::Gap(gap) => {
1492                        assert_eq!(gap.token, "raclette");
1493                        num_gaps += 1;
1494                    }
1495                }
1496            }
1497
1498            // There's only the previous gap, no new ones.
1499            assert_eq!(num_gaps, 1);
1500            assert_eq!(num_events, 2);
1501        }
1502    }
1503
1504    #[async_test]
1505    async fn test_shrink_to_last_chunk() {
1506        let room_id = room_id!("!galette:saucisse.bzh");
1507
1508        let f = EventFactory::new().room(room_id);
1509
1510        let evid1 = event_id!("$1");
1511        let evid2 = event_id!("$2");
1512
1513        let ev1 = f.text_msg("hello world").sender(User::Alice).event_id(evid1).into_event();
1514        let ev2 = f.text_msg("howdy").sender(User::Bob).event_id(evid2).into_event();
1515
1516        // Fill the event cache store with an initial linked chunk with 2 events
1517        // chunks.
1518        let event_cache_store = MemoryStore::new();
1519        event_cache_store
1520            .handle_linked_chunk_updates(
1521                LinkedChunkId::Room(room_id),
1522                vec![
1523                    Update::NewItemsChunk {
1524                        previous: None,
1525                        new: ChunkIdentifier::new(0),
1526                        next: None,
1527                    },
1528                    Update::PushItems {
1529                        at: Position::new(ChunkIdentifier::new(0), 0),
1530                        items: vec![ev1],
1531                    },
1532                    Update::NewItemsChunk {
1533                        previous: Some(ChunkIdentifier::new(0)),
1534                        new: ChunkIdentifier::new(1),
1535                        next: None,
1536                    },
1537                    Update::PushItems {
1538                        at: Position::new(ChunkIdentifier::new(1), 0),
1539                        items: vec![ev2],
1540                    },
1541                ],
1542            )
1543            .await
1544            .unwrap();
1545
1546        let client = MockClientBuilder::new(None)
1547            .on_builder(move |builder| {
1548                builder.store_config(
1549                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
1550                        holder_name: "foo".to_owned(),
1551                    })
1552                    .event_cache_store(event_cache_store),
1553                )
1554            })
1555            .build()
1556            .await;
1557
1558        let event_cache = client.event_cache().unwrap();
1559
1560        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1561        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1562
1563        // Sanity check: lazily loaded, so only includes one item at start.
1564        let (events, mut stream) = room_event_cache.subscribe().await.unwrap();
1565        assert_eq!(events.len(), 1);
1566        assert_eq!(events[0].event_id(), Some(evid2));
1567        assert!(stream.is_empty());
1568
1569        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1570
1571        // Force loading the full linked chunk by back-paginating.
1572        let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap();
1573        assert_eq!(outcome.events.len(), 1);
1574        assert_eq!(outcome.events[0].event_id(), Some(evid1));
1575        assert!(outcome.reached_start);
1576
1577        // We also get an update about the loading from the store.
1578        assert_let_timeout!(
1579            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1580                stream.recv()
1581        );
1582        assert_eq!(diffs.len(), 1);
1583        assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value } => {
1584            assert_eq!(value.event_id(), Some(evid1));
1585        });
1586
1587        assert!(stream.is_empty());
1588
1589        // Same for the generic update.
1590        assert_let_timeout!(
1591            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1592        );
1593        assert_eq!(expected_room_id, room_id);
1594        assert!(generic_stream.is_empty());
1595
1596        // Shrink the linked chunk to the last chunk.
1597        room_event_cache
1598            .inner
1599            .state
1600            .reload_no_preprocessing()
1601            .await
1602            .expect("shrinking should succeed");
1603
1604        // We receive updates about the changes to the linked chunk.
1605        assert_let_timeout!(
1606            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1607                stream.recv()
1608        );
1609        assert_eq!(diffs.len(), 2);
1610        assert_matches!(&diffs[0], VectorDiff::Clear);
1611        assert_matches!(&diffs[1], VectorDiff::Append { values} => {
1612            assert_eq!(values.len(), 1);
1613            assert_eq!(values[0].event_id(), Some(evid2));
1614        });
1615
1616        assert!(stream.is_empty());
1617
1618        // A generic update has been received.
1619        assert_let_timeout!(Ok(RoomEventCacheGenericUpdate { .. }) = generic_stream.recv());
1620        assert!(generic_stream.is_empty());
1621
1622        // When reading the events, we do get only the last one.
1623        let events = room_event_cache.events().await.unwrap();
1624        assert_eq!(events.len(), 1);
1625        assert_eq!(events[0].event_id(), Some(evid2));
1626
1627        // But if we back-paginate, we don't need access to network to find out
1628        // about the previous event.
1629        let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap();
1630        assert_eq!(outcome.events.len(), 1);
1631        assert_eq!(outcome.events[0].event_id(), Some(evid1));
1632        assert!(outcome.reached_start);
1633    }
1634
1635    #[async_test]
1636    async fn test_shrink_when_loading_the_last_chunk_fails() {
1637        let room_id = room_id!("!galette:saucisse.bzh");
1638
1639        let f = EventFactory::new().room(room_id);
1640
1641        let ev1 =
1642            f.text_msg("hello world").sender(User::Alice).event_id(event_id!("$1")).into_event();
1643        let ev2 = f.text_msg("howdy").sender(User::Bob).event_id(event_id!("$2")).into_event();
1644
1645        // Fill the event cache store with an initial linked chunk with 2 events
1646        // chunks.
1647        let event_cache_store = ControlledMemoryStore::new();
1648        event_cache_store
1649            .handle_linked_chunk_updates(
1650                LinkedChunkId::Room(room_id),
1651                vec![
1652                    Update::NewItemsChunk {
1653                        previous: None,
1654                        new: ChunkIdentifier::new(0),
1655                        next: None,
1656                    },
1657                    Update::PushItems {
1658                        at: Position::new(ChunkIdentifier::new(0), 0),
1659                        items: vec![ev1],
1660                    },
1661                    Update::NewItemsChunk {
1662                        previous: Some(ChunkIdentifier::new(0)),
1663                        new: ChunkIdentifier::new(1),
1664                        next: None,
1665                    },
1666                    Update::PushItems {
1667                        at: Position::new(ChunkIdentifier::new(1), 0),
1668                        items: vec![ev2],
1669                    },
1670                ],
1671            )
1672            .await
1673            .unwrap();
1674
1675        let client = MockClientBuilder::new(None)
1676            .on_builder({
1677                let event_cache_store = event_cache_store.clone();
1678
1679                move |builder| {
1680                    builder.store_config(
1681                        StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
1682                            .event_cache_store(event_cache_store),
1683                    )
1684                }
1685            })
1686            .build()
1687            .await;
1688
1689        let event_cache = client.event_cache().unwrap();
1690
1691        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1692        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1693
1694        let events = room_event_cache.events().await.unwrap();
1695        assert_eq!(events.len(), 1);
1696
1697        // Shrink while loading the last chunk fails: the chunks' metadata are
1698        // loaded, but the storage is then cleared.
1699        event_cache_store.fail_next_last_chunk_load();
1700        room_event_cache
1701            .inner
1702            .state
1703            .reload_no_preprocessing()
1704            .await
1705            .expect("shrinking should succeed");
1706
1707        // Reading the events lazily creates a new first chunk.
1708        assert!(room_event_cache.events().await.unwrap().is_empty());
1709
1710        event_cache_store.stop_failing_next_last_chunk_load();
1711
1712        // Shrinking again must not panic: the order tracker must not have kept
1713        // the metadata of the chunks that have been cleared.
1714        room_event_cache
1715            .inner
1716            .state
1717            .reload_no_preprocessing()
1718            .await
1719            .expect("shrinking should succeed");
1720
1721        assert!(room_event_cache.events().await.unwrap().is_empty());
1722    }
1723
1724    #[async_test]
1725    async fn test_room_ordering() {
1726        let room_id = room_id!("!galette:saucisse.bzh");
1727
1728        let f = EventFactory::new().room(room_id).sender(User::Alice);
1729
1730        let evid1 = event_id!("$1");
1731        let evid2 = event_id!("$2");
1732        let evid3 = event_id!("$3");
1733
1734        let ev1 = f.text_msg("hello world").event_id(evid1).into_event();
1735        let ev2 = f.text_msg("howdy").sender(User::Bob).event_id(evid2).into_event();
1736        let ev3 = f.text_msg("yo").event_id(evid3).into_event();
1737
1738        // Fill the event cache store with an initial linked chunk with 2 events
1739        // chunks.
1740        let event_cache_store = MemoryStore::new();
1741        event_cache_store
1742            .handle_linked_chunk_updates(
1743                LinkedChunkId::Room(room_id),
1744                vec![
1745                    Update::NewItemsChunk {
1746                        previous: None,
1747                        new: ChunkIdentifier::new(0),
1748                        next: None,
1749                    },
1750                    Update::PushItems {
1751                        at: Position::new(ChunkIdentifier::new(0), 0),
1752                        items: vec![ev1, ev2],
1753                    },
1754                    Update::NewItemsChunk {
1755                        previous: Some(ChunkIdentifier::new(0)),
1756                        new: ChunkIdentifier::new(1),
1757                        next: None,
1758                    },
1759                    Update::PushItems {
1760                        at: Position::new(ChunkIdentifier::new(1), 0),
1761                        items: vec![ev3.clone()],
1762                    },
1763                ],
1764            )
1765            .await
1766            .unwrap();
1767
1768        let client = MockClientBuilder::new(None)
1769            .on_builder(move |builder| {
1770                builder.store_config(
1771                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
1772                        holder_name: "foo".to_owned(),
1773                    })
1774                    .event_cache_store(event_cache_store),
1775                )
1776            })
1777            .build()
1778            .await;
1779
1780        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1781        let event_cache = client.event_cache().unwrap();
1782
1783        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1784
1785        // Initially, the linked chunk only contains the last chunk, so only ev3
1786        // is loaded.
1787        {
1788            let state = room_event_cache.inner.state.read().await.unwrap();
1789            let room_linked_chunk = state.room_linked_chunk();
1790
1791            // But we can get the order of ev1.
1792            assert_eq!(
1793                room_linked_chunk.event_order(Position::new(ChunkIdentifier::new(0), 0)),
1794                Some(0)
1795            );
1796
1797            // And that of ev2 as well.
1798            assert_eq!(
1799                room_linked_chunk.event_order(Position::new(ChunkIdentifier::new(0), 1)),
1800                Some(1)
1801            );
1802
1803            // ev3, which is loaded, also has a known ordering.
1804            let mut events = room_linked_chunk.events();
1805            let (pos, ev) = events.next().unwrap();
1806            assert_eq!(pos, Position::new(ChunkIdentifier::new(1), 0));
1807            assert_eq!(ev.event_id(), Some(evid3));
1808            assert_eq!(room_linked_chunk.event_order(pos), Some(2));
1809
1810            // No other loaded events.
1811            assert!(events.next().is_none());
1812        }
1813
1814        // Force loading the full linked chunk by back-paginating.
1815        let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap();
1816        assert!(outcome.reached_start);
1817
1818        // All events are now loaded, so their order is precisely their
1819        // enumerated index in a linear iteration.
1820        {
1821            let state = room_event_cache.inner.state.read().await.unwrap();
1822            let room_linked_chunk = state.room_linked_chunk();
1823
1824            for (i, (pos, _)) in room_linked_chunk.events().enumerate() {
1825                assert_eq!(room_linked_chunk.event_order(pos), Some(i));
1826            }
1827        }
1828
1829        // Handle a gappy sync with two events (including one duplicate, so
1830        // deduplication kicks in), so that the linked chunk is shrunk to the
1831        // last chunk, and that the linked chunk only contains the last two
1832        // events.
1833        let evid4 = event_id!("$4");
1834        room_event_cache
1835            .handle_joined_room_update(
1836                Timeline {
1837                    limited: true,
1838                    prev_batch: Some("fondue".to_owned()),
1839                    events: vec![ev3, f.text_msg("sup").event_id(evid4).into_event()],
1840                },
1841                MaybeReceiptEventContent::none(),
1842                Default::default(),
1843                Default::default(),
1844                Default::default(),
1845            )
1846            .await
1847            .unwrap();
1848
1849        {
1850            let state = room_event_cache.inner.state.read().await.unwrap();
1851            let room_linked_chunk = state.room_linked_chunk();
1852
1853            // After the shrink, only evid3 and evid4 are loaded.
1854            let mut events = room_linked_chunk.events();
1855
1856            let (pos, ev) = events.next().unwrap();
1857            assert_eq!(ev.event_id(), Some(evid3));
1858            assert_eq!(room_linked_chunk.event_order(pos), Some(2));
1859
1860            let (pos, ev) = events.next().unwrap();
1861            assert_eq!(ev.event_id(), Some(evid4));
1862            assert_eq!(room_linked_chunk.event_order(pos), Some(3));
1863
1864            // No other loaded events.
1865            assert!(events.next().is_none());
1866
1867            // But we can still get the order of previous events.
1868            assert_eq!(
1869                room_linked_chunk.event_order(Position::new(ChunkIdentifier::new(0), 0)),
1870                Some(0)
1871            );
1872            assert_eq!(
1873                room_linked_chunk.event_order(Position::new(ChunkIdentifier::new(0), 1)),
1874                Some(1)
1875            );
1876
1877            // ev3 doesn't have an order with its previous position, since it's
1878            // been deduplicated.
1879            assert_eq!(
1880                room_linked_chunk.event_order(Position::new(ChunkIdentifier::new(1), 0)),
1881                None
1882            );
1883        }
1884    }
1885
1886    #[async_test]
1887    async fn test_auto_shrink_after_all_subscribers_are_gone() {
1888        let room_id = room_id!("!galette:saucisse.bzh");
1889
1890        let f = EventFactory::new().room(room_id);
1891
1892        let evid1 = event_id!("$1");
1893        let evid2 = event_id!("$2");
1894
1895        let ev1 = f.text_msg("hello world").sender(User::Alice).event_id(evid1).into_event();
1896        let ev2 = f.text_msg("howdy").sender(User::Bob).event_id(evid2).into_event();
1897
1898        // Fill the event cache store with an initial linked chunk with 2 events
1899        // chunks.
1900        let event_cache_store = MemoryStore::new();
1901        event_cache_store
1902            .handle_linked_chunk_updates(
1903                LinkedChunkId::Room(room_id),
1904                vec![
1905                    Update::NewItemsChunk {
1906                        previous: None,
1907                        new: ChunkIdentifier::new(0),
1908                        next: None,
1909                    },
1910                    Update::PushItems {
1911                        at: Position::new(ChunkIdentifier::new(0), 0),
1912                        items: vec![ev1],
1913                    },
1914                    Update::NewItemsChunk {
1915                        previous: Some(ChunkIdentifier::new(0)),
1916                        new: ChunkIdentifier::new(1),
1917                        next: None,
1918                    },
1919                    Update::PushItems {
1920                        at: Position::new(ChunkIdentifier::new(1), 0),
1921                        items: vec![ev2],
1922                    },
1923                ],
1924            )
1925            .await
1926            .unwrap();
1927
1928        let client = MockClientBuilder::new(None)
1929            .on_builder(move |builder| {
1930                builder.store_config(
1931                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
1932                        holder_name: "foo".to_owned(),
1933                    })
1934                    .event_cache_store(event_cache_store),
1935                )
1936            })
1937            .build()
1938            .await;
1939
1940        let event_cache = client.event_cache().unwrap();
1941
1942        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1943        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
1944
1945        // Sanity check: lazily loaded, so only includes one item at start.
1946        let (events1, mut stream1) = room_event_cache.subscribe().await.unwrap();
1947        assert_eq!(events1.len(), 1);
1948        assert_eq!(events1[0].event_id(), Some(evid2));
1949        assert!(stream1.is_empty());
1950
1951        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1952
1953        // Force loading the full linked chunk by back-paginating.
1954        let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap();
1955        assert_eq!(outcome.events.len(), 1);
1956        assert_eq!(outcome.events[0].event_id(), Some(evid1));
1957        assert!(outcome.reached_start);
1958
1959        // We also get an update about the loading from the store. Ignore it,
1960        // for this test's sake.
1961        assert_let_timeout!(
1962            Ok(RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1963                stream1.recv()
1964        );
1965        assert_eq!(diffs.len(), 1);
1966        assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value } => {
1967            assert_eq!(value.event_id(), Some(evid1));
1968        });
1969
1970        assert!(stream1.is_empty());
1971
1972        assert_let_timeout!(
1973            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1974        );
1975        assert_eq!(expected_room_id, room_id);
1976        assert!(generic_stream.is_empty());
1977
1978        // Have another subscriber. Since it's not the first one, and the
1979        // previous one loaded some more events, the second subscribers sees
1980        // them all.
1981        let (events2, stream2) = room_event_cache.subscribe().await.unwrap();
1982        assert_eq!(events2.len(), 2);
1983        assert_eq!(events2[0].event_id(), Some(evid1));
1984        assert_eq!(events2[1].event_id(), Some(evid2));
1985        assert!(stream2.is_empty());
1986
1987        // Grab a receiver for testing no diffs is sent.
1988        let subscriber = {
1989            let state = room_event_cache.inner.state.read().await.unwrap();
1990            state.update_sender.new_room_receiver()
1991        };
1992
1993        // Drop the first stream, and wait a bit.
1994        drop(stream1);
1995        yield_now().await;
1996
1997        // The second stream remains undisturbed.
1998        assert!(stream2.is_empty());
1999
2000        // Now drop the second stream, and wait a bit.
2001        drop(stream2);
2002        yield_now().await;
2003
2004        // The linked chunk must have auto-shrunk by now.
2005
2006        {
2007            // Check the inner state: there's no more shared auto-shrinker.
2008            let state = room_event_cache.inner.state.read().await.unwrap();
2009            assert_eq!(state.subscribers_handle().count(), 0);
2010
2011            // No diff is sent when the linked chunk has auto-shrunk.
2012            assert!(subscriber.is_empty());
2013            assert!(generic_stream.is_empty());
2014        }
2015
2016        // Getting the events will only give us the latest chunk.
2017        let events3 = room_event_cache.events().await.unwrap();
2018        assert_eq!(events3.len(), 1);
2019        assert_eq!(events3[0].event_id(), Some(evid2));
2020    }
2021
2022    #[async_test]
2023    async fn test_rfind_map_event_in_memory_by() {
2024        let user_id = user_id!("@mnt_io:matrix.org");
2025        let room_id = room_id!("!raclette:patate.ch");
2026
2027        let event_factory = EventFactory::new().room(room_id);
2028
2029        let event_id_0 = event_id!("$ev0");
2030        let event_id_1 = event_id!("$ev1");
2031        let event_id_2 = event_id!("$ev2");
2032        let event_id_3 = event_id!("$ev3");
2033
2034        let event_0 =
2035            event_factory.text_msg("hello").sender(User::Bob).event_id(event_id_0).into_event();
2036        let event_1 =
2037            event_factory.text_msg("world").sender(User::Alice).event_id(event_id_1).into_event();
2038        let event_2 =
2039            event_factory.text_msg("!").sender(User::Alice).event_id(event_id_2).into_event();
2040        let event_3 =
2041            event_factory.text_msg("eh!").sender(user_id).event_id(event_id_3).into_event();
2042
2043        // Fill the event cache store with an initial linked chunk of 2 chunks,
2044        // and 4 events.
2045        let event_cache_store = MemoryStore::new();
2046        event_cache_store
2047            .handle_linked_chunk_updates(
2048                LinkedChunkId::Room(room_id),
2049                vec![
2050                    Update::NewItemsChunk {
2051                        previous: None,
2052                        new: ChunkIdentifier::new(0),
2053                        next: None,
2054                    },
2055                    Update::PushItems {
2056                        at: Position::new(ChunkIdentifier::new(0), 0),
2057                        items: vec![event_3],
2058                    },
2059                    Update::NewItemsChunk {
2060                        previous: Some(ChunkIdentifier::new(0)),
2061                        new: ChunkIdentifier::new(1),
2062                        next: None,
2063                    },
2064                    Update::PushItems {
2065                        at: Position::new(ChunkIdentifier::new(1), 0),
2066                        items: vec![event_0, event_1, event_2],
2067                    },
2068                ],
2069            )
2070            .await
2071            .unwrap();
2072
2073        let client = MockClientBuilder::new(None)
2074            .on_builder(move |builder| {
2075                builder.store_config(
2076                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
2077                        holder_name: "foo".to_owned(),
2078                    })
2079                    .event_cache_store(event_cache_store),
2080                )
2081            })
2082            .build()
2083            .await;
2084
2085        client.base_client().get_or_create_room(room_id, RoomState::Joined);
2086        let event_cache = client.event_cache().unwrap();
2087        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
2088
2089        // Look for an event from Bob: it must be `event_0`.
2090        assert_matches!(
2091            room_event_cache
2092                .rfind_map_event_in_memory_by(|event| {
2093                    (event.sender().is_some_and(|sender| sender == User::Bob)).then(|| event.event_id().map(ToOwned::to_owned))
2094                })
2095                .await,
2096            Ok(Some(event_id)) => {
2097                assert_eq!(event_id.as_deref(), Some(event_id_0));
2098            }
2099        );
2100
2101        // Look for an event from Alice: it must be `event_2`, right before
2102        // `event_1` because events are looked for in reverse order.
2103        assert_matches!(
2104            room_event_cache
2105                .rfind_map_event_in_memory_by(|event| {
2106                    (event.sender().is_some_and(|sender| sender == User::Alice)).then(|| event.event_id().map(ToOwned::to_owned))
2107                })
2108                .await,
2109            Ok(Some(event_id)) => {
2110                assert_eq!(event_id.as_deref(), Some(event_id_2));
2111            }
2112        );
2113
2114        // Look for an event that is inside the storage, but not loaded.
2115        assert!(
2116            room_event_cache
2117                .rfind_map_event_in_memory_by(|event| {
2118                    (event.sender().as_deref() == Some(user_id))
2119                        .then(|| event.event_id().map(ToOwned::to_owned))
2120                })
2121                .await
2122                .unwrap()
2123                .is_none()
2124        );
2125
2126        // Look for an event that doesn't exist.
2127        assert!(
2128            room_event_cache.rfind_map_event_in_memory_by(|_| None::<()>).await.unwrap().is_none()
2129        );
2130    }
2131
2132    #[async_test]
2133    async fn test_reload_when_dirty() {
2134        let user_id = user_id!("@mnt_io:matrix.org");
2135        let room_id = room_id!("!raclette:patate.ch");
2136
2137        let event_factory = EventFactory::new().room(room_id).sender(user_id);
2138
2139        let ev_id_0 = event_id!("$ev_0");
2140        let ev_id_1 = event_id!("$ev_1");
2141
2142        let ev_0 = event_factory.text_msg("comté").event_id(ev_id_0).into_event();
2143        let ev_1 = event_factory.text_msg("morbier").event_id(ev_id_1).into_event();
2144
2145        // Add events to the storage (shared by the two clients!).
2146        let event_cache_store = MemoryStore::new();
2147        event_cache_store
2148            .handle_linked_chunk_updates(
2149                LinkedChunkId::Room(room_id),
2150                vec![
2151                    Update::NewItemsChunk {
2152                        previous: None,
2153                        new: ChunkIdentifier::new(0),
2154                        next: None,
2155                    },
2156                    Update::PushItems {
2157                        at: Position::new(ChunkIdentifier::new(0), 0),
2158                        items: vec![ev_0],
2159                    },
2160                    Update::NewItemsChunk {
2161                        previous: Some(ChunkIdentifier::new(0)),
2162                        new: ChunkIdentifier::new(1),
2163                        next: None,
2164                    },
2165                    Update::PushItems {
2166                        at: Position::new(ChunkIdentifier::new(1), 0),
2167                        items: vec![ev_1],
2168                    },
2169                ],
2170            )
2171            .await
2172            .unwrap();
2173
2174        // Client for the process 0.
2175        let client_p0 = MockClientBuilder::new(None)
2176            .on_builder(|builder| {
2177                builder.store_config(
2178                    StoreConfig::new(CrossProcessLockConfig::multi_process("process #0"))
2179                        .event_cache_store(event_cache_store.clone()),
2180                )
2181            })
2182            .build()
2183            .await;
2184
2185        // Client for the process 1.
2186        let client_p1 = MockClientBuilder::new(None)
2187            .on_builder(|builder| {
2188                builder.store_config(
2189                    StoreConfig::new(CrossProcessLockConfig::multi_process("process #1"))
2190                        .event_cache_store(event_cache_store),
2191                )
2192            })
2193            .build()
2194            .await;
2195
2196        // Subscribe the event caches, and create the room.
2197        let (room_event_cache_p0, room_event_cache_p1) = {
2198            client_p0.base_client().get_or_create_room(room_id, RoomState::Joined);
2199            client_p1.base_client().get_or_create_room(room_id, RoomState::Joined);
2200
2201            let (room_event_cache_p0, _drop_handles) =
2202                client_p0.event_cache().unwrap().room(room_id).await.unwrap();
2203            let (room_event_cache_p1, _drop_handles) =
2204                client_p1.event_cache().unwrap().room(room_id).await.unwrap();
2205
2206            (room_event_cache_p0, room_event_cache_p1)
2207        };
2208
2209        // Okay. We are ready for the test!
2210        //
2211        // First off, let's check `room_event_cache_p0` has access to the first
2212        // event loaded in-memory, then do a pagination, and see more events.
2213        let mut updates_stream_p0 = {
2214            let room_event_cache = &room_event_cache_p0;
2215
2216            let (initial_updates, mut updates_stream) =
2217                room_event_cache_p0.subscribe().await.unwrap();
2218
2219            // Initial updates contain `ev_id_1` only.
2220            assert_eq!(initial_updates.len(), 1);
2221            assert_eq!(initial_updates[0].event_id(), Some(ev_id_1));
2222            assert!(updates_stream.is_empty());
2223
2224            // `ev_id_1` must be loaded in memory.
2225            assert!(event_loaded(room_event_cache, ev_id_1).await);
2226
2227            // `ev_id_0` must NOT be loaded in memory.
2228            assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2229
2230            // Load one more event with a backpagination.
2231            room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2232
2233            // A new update for `ev_id_0` must be present.
2234            assert_matches!(
2235                updates_stream.recv().await.unwrap(),
2236                RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2237                    assert_eq!(diffs.len(), 1, "{diffs:#?}");
2238                    assert_matches!(
2239                        &diffs[0],
2240                        VectorDiff::Insert { index: 0, value: event } => {
2241                            assert_eq!(event.event_id(), Some(ev_id_0));
2242                        }
2243                    );
2244                }
2245            );
2246
2247            // `ev_id_0` must now be loaded in memory.
2248            assert!(event_loaded(room_event_cache, ev_id_0).await);
2249
2250            updates_stream
2251        };
2252
2253        // Second, let's check `room_event_cache_p1` has the same accesses.
2254        let mut updates_stream_p1 = {
2255            let room_event_cache = &room_event_cache_p1;
2256            let (initial_updates, mut updates_stream) =
2257                room_event_cache_p1.subscribe().await.unwrap();
2258
2259            // Initial updates contain `ev_id_1` only.
2260            assert_eq!(initial_updates.len(), 1);
2261            assert_eq!(initial_updates[0].event_id(), Some(ev_id_1));
2262            assert!(updates_stream.is_empty());
2263
2264            // `ev_id_1` must be loaded in memory.
2265            assert!(event_loaded(room_event_cache, ev_id_1).await);
2266
2267            // `ev_id_0` must NOT be loaded in memory.
2268            assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2269
2270            // Load one more event with a backpagination.
2271            room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2272
2273            // A new update for `ev_id_0` must be present.
2274            assert_matches!(
2275                updates_stream.recv().await.unwrap(),
2276                RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2277                    assert_eq!(diffs.len(), 1, "{diffs:#?}");
2278                    assert_matches!(
2279                        &diffs[0],
2280                        VectorDiff::Insert { index: 0, value: event } => {
2281                            assert_eq!(event.event_id(), Some(ev_id_0));
2282                        }
2283                    );
2284                }
2285            );
2286
2287            // `ev_id_0` must now be loaded in memory.
2288            assert!(event_loaded(room_event_cache, ev_id_0).await);
2289
2290            updates_stream
2291        };
2292
2293        // Do this a couple times, for the fun.
2294        for _ in 0..3 {
2295            // Third, because `room_event_cache_p1` has locked the store, the
2296            // lock is dirty for `room_event_cache_p0`, so it will shrink to its
2297            // last chunk!
2298            {
2299                let room_event_cache = &room_event_cache_p0;
2300                let updates_stream = &mut updates_stream_p0;
2301
2302                // `ev_id_1` must be loaded in memory, just like before.
2303                assert!(event_loaded(room_event_cache, ev_id_1).await);
2304
2305                // However, `ev_id_0` must NOT be loaded in memory. It WAS
2306                // loaded, but the state has been reloaded to its last chunk.
2307                assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2308
2309                // The reload can be observed via the updates too.
2310                assert_matches!(
2311                    updates_stream.recv().await.unwrap(),
2312                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2313                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
2314                        assert_matches!(&diffs[0], VectorDiff::Clear);
2315                        assert_matches!(
2316                            &diffs[1],
2317                            VectorDiff::Append { values: events } => {
2318                                assert_eq!(events.len(), 1);
2319                                assert_eq!(events[0].event_id(), Some(ev_id_1));
2320                            }
2321                        );
2322                    }
2323                );
2324
2325                // Load one more event with a backpagination.
2326                room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2327
2328                // `ev_id_0` must now be loaded in memory.
2329                assert!(event_loaded(room_event_cache, ev_id_0).await);
2330
2331                // The pagination can be observed via the updates too.
2332                assert_matches!(
2333                    updates_stream.recv().await.unwrap(),
2334                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2335                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
2336                        assert_matches!(
2337                            &diffs[0],
2338                            VectorDiff::Insert { index: 0, value: event } => {
2339                                assert_eq!(event.event_id(), Some(ev_id_0));
2340                            }
2341                        );
2342                    }
2343                );
2344            }
2345
2346            // Fourth, because `room_event_cache_p0` has locked the store again,
2347            // the lock is dirty for `room_event_cache_p1` too!, so it will
2348            // shrink to its last chunk!
2349            {
2350                let room_event_cache = &room_event_cache_p1;
2351                let updates_stream = &mut updates_stream_p1;
2352
2353                // `ev_id_1` must be loaded in memory, just like before.
2354                assert!(event_loaded(room_event_cache, ev_id_1).await);
2355
2356                // However, `ev_id_0` must NOT be loaded in memory. It WAS
2357                // loaded, but the state has shrunk to its last chunk.
2358                assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2359
2360                // The reload can be observed via the updates too.
2361                assert_matches!(
2362                    updates_stream.recv().await.unwrap(),
2363                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2364                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
2365                        assert_matches!(&diffs[0], VectorDiff::Clear);
2366                        assert_matches!(
2367                            &diffs[1],
2368                            VectorDiff::Append { values: events } => {
2369                                assert_eq!(events.len(), 1);
2370                                assert_eq!(events[0].event_id(), Some(ev_id_1));
2371                            }
2372                        );
2373                    }
2374                );
2375
2376                // Load one more event with a backpagination.
2377                room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2378
2379                // `ev_id_0` must now be loaded in memory.
2380                assert!(event_loaded(room_event_cache, ev_id_0).await);
2381
2382                // The pagination can be observed via the updates too.
2383                assert_matches!(
2384                    updates_stream.recv().await.unwrap(),
2385                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2386                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
2387                        assert_matches!(
2388                            &diffs[0],
2389                            VectorDiff::Insert { index: 0, value: event } => {
2390                                assert_eq!(event.event_id(), Some(ev_id_0));
2391                            }
2392                        );
2393                    }
2394                );
2395            }
2396        }
2397
2398        // Repeat that with an explicit read lock (so that we don't rely on
2399        // `event_loaded` to trigger the dirty detection).
2400        for _ in 0..3 {
2401            {
2402                let room_event_cache = &room_event_cache_p0;
2403                let updates_stream = &mut updates_stream_p0;
2404
2405                let guard = room_event_cache.inner.state.read().await.unwrap();
2406
2407                // Guard is kept alive, to ensure we can have multiple read
2408                // guards alive with a shared access. See
2409                // `RoomEventCacheStateLock::read` to learn more.
2410
2411                // The lock is no longer marked as dirty, it's been cleaned.
2412                assert!(guard.is_dirty().not());
2413
2414                // The reload can be observed via the updates too.
2415                assert_matches!(
2416                    updates_stream.recv().await.unwrap(),
2417                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2418                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
2419                        assert_matches!(&diffs[0], VectorDiff::Clear);
2420                        assert_matches!(
2421                            &diffs[1],
2422                            VectorDiff::Append { values: events } => {
2423                                assert_eq!(events.len(), 1);
2424                                assert_eq!(events[0].event_id(), Some(ev_id_1));
2425                            }
2426                        );
2427                    }
2428                );
2429
2430                assert!(event_loaded(room_event_cache, ev_id_1).await);
2431                assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2432
2433                // Ensure `guard` is alive up to this point (in case this test
2434                // is refactored, I want to make this super explicit).
2435                //
2436                // We drop need to drop it before the pagination because the
2437                // pagination needs to obtain a write lock.
2438                drop(guard);
2439
2440                room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2441                assert!(event_loaded(room_event_cache, ev_id_0).await);
2442
2443                // The pagination can be observed via the updates too.
2444                assert_matches!(
2445                    updates_stream.recv().await.unwrap(),
2446                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2447                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
2448                        assert_matches!(
2449                            &diffs[0],
2450                            VectorDiff::Insert { index: 0, value: event } => {
2451                                assert_eq!(event.event_id(), Some(ev_id_0));
2452                            }
2453                        );
2454                    }
2455                );
2456            }
2457
2458            {
2459                let room_event_cache = &room_event_cache_p1;
2460                let updates_stream = &mut updates_stream_p1;
2461
2462                let guard = room_event_cache.inner.state.read().await.unwrap();
2463
2464                // Guard is kept alive, to ensure we can have multiple read
2465                // guards alive with a shared access.
2466
2467                // The lock is no longer marked as dirty, it's been cleaned.
2468                assert!(guard.is_dirty().not());
2469
2470                // The reload can be observed via the updates too.
2471                assert_matches!(
2472                    updates_stream.recv().await.unwrap(),
2473                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2474                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
2475                        assert_matches!(&diffs[0], VectorDiff::Clear);
2476                        assert_matches!(
2477                            &diffs[1],
2478                            VectorDiff::Append { values: events } => {
2479                                assert_eq!(events.len(), 1);
2480                                assert_eq!(events[0].event_id(), Some(ev_id_1));
2481                            }
2482                        );
2483                    }
2484                );
2485
2486                assert!(event_loaded(room_event_cache, ev_id_1).await);
2487                assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2488
2489                // Ensure `guard` is alive up to this point (in case this test
2490                // is refactored, I want to make this super explicit).
2491                //
2492                // We drop need to drop it before the pagination because the
2493                // pagination needs to obtain a write lock.
2494                drop(guard);
2495
2496                room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2497                assert!(event_loaded(room_event_cache, ev_id_0).await);
2498
2499                // The pagination can be observed via the updates too.
2500                assert_matches!(
2501                    updates_stream.recv().await.unwrap(),
2502                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2503                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
2504                        assert_matches!(
2505                            &diffs[0],
2506                            VectorDiff::Insert { index: 0, value: event } => {
2507                                assert_eq!(event.event_id(), Some(ev_id_0));
2508                            }
2509                        );
2510                    }
2511                );
2512            }
2513        }
2514
2515        // Repeat that with an explicit write lock.
2516        for _ in 0..3 {
2517            {
2518                let room_event_cache = &room_event_cache_p0;
2519                let updates_stream = &mut updates_stream_p0;
2520
2521                let guard = room_event_cache.inner.state.write().await.unwrap();
2522
2523                // The lock is no longer marked as dirty, it's been cleaned.
2524                assert!(guard.is_dirty().not());
2525
2526                // The reload can be observed via the updates too.
2527                assert_matches!(
2528                    updates_stream.recv().await.unwrap(),
2529                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2530                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
2531                        assert_matches!(&diffs[0], VectorDiff::Clear);
2532                        assert_matches!(
2533                            &diffs[1],
2534                            VectorDiff::Append { values: events } => {
2535                                assert_eq!(events.len(), 1);
2536                                assert_eq!(events[0].event_id(), Some(ev_id_1));
2537                            }
2538                        );
2539                    }
2540                );
2541
2542                // Guard isn't kept alive, otherwise `event_loaded` couldn't run
2543                // because it needs to obtain a read lock.
2544                drop(guard);
2545
2546                assert!(event_loaded(room_event_cache, ev_id_1).await);
2547                assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2548
2549                room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2550                assert!(event_loaded(room_event_cache, ev_id_0).await);
2551
2552                // The pagination can be observed via the updates too.
2553                assert_matches!(
2554                    updates_stream.recv().await.unwrap(),
2555                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2556                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
2557                        assert_matches!(
2558                            &diffs[0],
2559                            VectorDiff::Insert { index: 0, value: event } => {
2560                                assert_eq!(event.event_id(), Some(ev_id_0));
2561                            }
2562                        );
2563                    }
2564                );
2565            }
2566
2567            {
2568                let room_event_cache = &room_event_cache_p1;
2569                let updates_stream = &mut updates_stream_p1;
2570
2571                let guard = room_event_cache.inner.state.write().await.unwrap();
2572
2573                // The lock is no longer marked as dirty, it's been cleaned.
2574                assert!(guard.is_dirty().not());
2575
2576                // The reload can be observed via the updates too.
2577                assert_matches!(
2578                    updates_stream.recv().await.unwrap(),
2579                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2580                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
2581                        assert_matches!(&diffs[0], VectorDiff::Clear);
2582                        assert_matches!(
2583                            &diffs[1],
2584                            VectorDiff::Append { values: events } => {
2585                                assert_eq!(events.len(), 1);
2586                                assert_eq!(events[0].event_id(), Some(ev_id_1));
2587                            }
2588                        );
2589                    }
2590                );
2591
2592                // Guard isn't kept alive, otherwise `event_loaded` couldn't run
2593                // because it needs to obtain a read lock.
2594                drop(guard);
2595
2596                assert!(event_loaded(room_event_cache, ev_id_1).await);
2597                assert!(event_loaded(room_event_cache, ev_id_0).await.not());
2598
2599                room_event_cache.pagination().run_backwards_once(1).await.unwrap();
2600                assert!(event_loaded(room_event_cache, ev_id_0).await);
2601
2602                // The pagination can be observed via the updates too.
2603                assert_matches!(
2604                    updates_stream.recv().await.unwrap(),
2605                    RoomEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
2606                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
2607                        assert_matches!(
2608                            &diffs[0],
2609                            VectorDiff::Insert { index: 0, value: event } => {
2610                                assert_eq!(event.event_id(), Some(ev_id_0));
2611                            }
2612                        );
2613                    }
2614                );
2615            }
2616        }
2617    }
2618
2619    #[async_test]
2620    async fn test_load_when_dirty() {
2621        let room_id_0 = room_id!("!raclette:patate.ch");
2622        let room_id_1 = room_id!("!morbiflette:patate.ch");
2623
2624        // The storage shared by the two clients.
2625        let event_cache_store = MemoryStore::new();
2626
2627        // Client for the process 0.
2628        let client_p0 = MockClientBuilder::new(None)
2629            .on_builder(|builder| {
2630                builder.store_config(
2631                    StoreConfig::new(CrossProcessLockConfig::multi_process("process #0"))
2632                        .event_cache_store(event_cache_store.clone()),
2633                )
2634            })
2635            .build()
2636            .await;
2637
2638        // Client for the process 1.
2639        let client_p1 = MockClientBuilder::new(None)
2640            .on_builder(|builder| {
2641                builder.store_config(
2642                    StoreConfig::new(CrossProcessLockConfig::multi_process("process #1"))
2643                        .event_cache_store(event_cache_store),
2644                )
2645            })
2646            .build()
2647            .await;
2648
2649        // Subscribe the event caches, and create the room.
2650        let (room_event_cache_0_p0, room_event_cache_0_p1) = {
2651            client_p0.base_client().get_or_create_room(room_id_0, RoomState::Joined);
2652            client_p0.base_client().get_or_create_room(room_id_1, RoomState::Joined);
2653
2654            client_p1.base_client().get_or_create_room(room_id_0, RoomState::Joined);
2655            client_p1.base_client().get_or_create_room(room_id_1, RoomState::Joined);
2656
2657            let (room_event_cache_0_p0, _drop_handles) =
2658                client_p0.event_cache().unwrap().room(room_id_0).await.unwrap();
2659            let (room_event_cache_0_p1, _drop_handles) =
2660                client_p1.event_cache().unwrap().room(room_id_0).await.unwrap();
2661
2662            (room_event_cache_0_p0, room_event_cache_0_p1)
2663        };
2664
2665        // Let's make the cross-process lock over the store dirty.
2666        {
2667            drop(room_event_cache_0_p0.inner.state.read().await.unwrap());
2668            drop(room_event_cache_0_p1.inner.state.read().await.unwrap());
2669        }
2670
2671        // Create the `RoomEventCache` for `room_id_1`. During its creation, the
2672        // cross-process lock over the store MUST be dirty, which makes no
2673        // difference as a clean one: the state is just loaded, not reloaded.
2674        let (room_event_cache_1_p0, _) =
2675            client_p0.event_cache().unwrap().room(room_id_1).await.unwrap();
2676
2677        // Check the lock isn't dirty because it's been cleared.
2678        {
2679            let guard = room_event_cache_1_p0.inner.state.read().await.unwrap();
2680            assert!(guard.is_dirty().not());
2681        }
2682
2683        // The only way to test this behaviour is to see that the dirty block in
2684        // `RoomEventCacheStateLock` is covered by this test.
2685    }
2686
2687    #[async_test]
2688    async fn test_uniq_read_marker() {
2689        let client = MockClientBuilder::new(None).build().await;
2690        let room_id = room_id!("!galette:saucisse.bzh");
2691        client.base_client().get_or_create_room(room_id, RoomState::Joined);
2692
2693        let event_cache = client.event_cache().unwrap();
2694
2695        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
2696        let (room_event_cache, _drop_handles) = event_cache.room(room_id).await.unwrap();
2697        let (events, mut stream) = room_event_cache.subscribe().await.unwrap();
2698
2699        assert!(events.is_empty());
2700
2701        // When sending multiple times the same read marker event,…
2702        let read_marker_event = Raw::from_json_string(
2703            json!({
2704                "content": {
2705                    "event_id": "$crepe:saucisse.bzh"
2706                },
2707                "room_id": "!galette:saucisse.bzh",
2708                "type": "m.fully_read"
2709            })
2710            .to_string(),
2711        )
2712        .unwrap();
2713        let account_data = vec![read_marker_event; 100];
2714
2715        room_event_cache
2716            .handle_joined_room_update(
2717                Default::default(),
2718                MaybeReceiptEventContent::none(),
2719                account_data,
2720                Default::default(),
2721                Default::default(),
2722            )
2723            .await
2724            .unwrap();
2725
2726        // … there's only one read marker update.
2727        assert_matches!(
2728            stream.recv().await.unwrap(),
2729            RoomEventCacheUpdate::MoveReadMarkerTo { .. }
2730        );
2731
2732        assert!(stream.recv().now_or_never().is_none());
2733
2734        // None, because an account data doesn't trigger a generic update.
2735        assert!(generic_stream.recv().now_or_never().is_none());
2736    }
2737
2738    async fn event_loaded(room_event_cache: &RoomEventCache, event_id: &EventId) -> bool {
2739        room_event_cache
2740            .rfind_map_event_in_memory_by(|event| {
2741                (event.event_id() == Some(event_id)).then_some(())
2742            })
2743            .await
2744            .unwrap()
2745            .is_some()
2746    }
2747}