Skip to main content

matrix_sdk/event_cache/caches/thread/
mod.rs

1// Copyright 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Threads-related data structures.
16
17pub mod pagination;
18mod state;
19mod updates;
20
21use std::{fmt, sync::Arc};
22
23use eyeball::AsyncLock;
24use matrix_sdk_base::{
25    deserialized_responses::ThreadSummary,
26    event_cache::{Event, thread::ThreadInfo},
27    read_receipts::ReadReceipts,
28    sync::Timeline,
29};
30use ruma::{
31    EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, events::relation::RelationType,
32    room_version_rules::RoomVersionRules,
33};
34use tokio::sync::{Notify, broadcast::Sender, mpsc};
35use tracing::{instrument, trace};
36
37pub(in super::super) use self::state::ThreadEventCacheState;
38pub(super) use self::updates::ThreadEventCacheUpdateSender;
39pub use self::{pagination::ThreadPagination, updates::ThreadEventCacheUpdate};
40#[cfg(feature = "e2e-encryption")]
41use super::super::redecryptor::MaybeResolvedEvent;
42use super::{
43    super::{
44        Result,
45        states::{CacheStateLock, StateLock, selectors::ThreadStateSelector},
46    },
47    EventsOrigin, TimelineVectorDiffs,
48    read_receipts::MaybeReceiptEventContent,
49    room::RoomEventCacheGenericUpdate,
50    subscriber::{AutoShrinkMessage, Subscriber},
51};
52use crate::{event_cache::caches::room::LinkedChunkUpdateSender, room::WeakRoom};
53
54/// All the information related to a single thread.
55///
56/// Cloning is shallow, and thus is cheap to do.
57#[derive(Clone)]
58pub struct ThreadEventCache {
59    inner: Arc<ThreadEventCacheInner>,
60}
61
62/// The (non-cloneable) details of the `ThreadEventCache`.
63struct ThreadEventCacheInner {
64    /// The room ID.
65    room_id: OwnedRoomId,
66
67    /// The thread root ID.
68    thread_id: OwnedEventId,
69
70    /// The room where this thread belongs to.
71    weak_room: WeakRoom,
72
73    /// State for this thread's event cache.
74    state: CacheStateLock<ThreadStateSelector>,
75
76    /// A notifier that we received a new pagination token.
77    pagination_batch_token_notifier: Notify,
78
79    /// Sender to the auto-shrink channel.
80    ///
81    /// See doc comment around [`EventCache::auto_shrink_linked_chunk_task`] for
82    /// more details.
83    auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
84
85    /// Update sender for this thread.
86    update_sender: ThreadEventCacheUpdateSender,
87}
88
89impl fmt::Debug for ThreadEventCache {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.debug_struct("ThreadEventCache").finish_non_exhaustive()
92    }
93}
94
95impl ThreadEventCache {
96    /// Create a new empty thread event cache.
97    #[allow(clippy::too_many_arguments)]
98    pub(super) async fn new(
99        room_id: OwnedRoomId,
100        thread_id: OwnedEventId,
101        own_user_id: OwnedUserId,
102        room_version_rules: RoomVersionRules,
103        weak_room: WeakRoom,
104        state: &StateLock,
105        auto_shrink_sender: mpsc::Sender<AutoShrinkMessage>,
106        generic_update_sender: Sender<RoomEventCacheGenericUpdate>,
107        linked_chunk_update_sender: LinkedChunkUpdateSender,
108    ) -> Result<Self> {
109        let update_sender = ThreadEventCacheUpdateSender::new(generic_update_sender.clone());
110
111        // Computed while building the state: nothing may await once the state
112        // is inserted, or a cancellation or error would leave it
113        // inserted without its cache, making every later attempt fail.
114        let mut timeline_is_not_empty = false;
115
116        let cache_state = state
117            .try_insert_once_with(
118                ThreadStateSelector::new(room_id.clone(), thread_id.clone()),
119                async |store_guard| {
120                    let cache_state = ThreadEventCacheState::new(
121                        room_id.clone(),
122                        thread_id.clone(),
123                        weak_room.clone(),
124                        own_user_id,
125                        room_version_rules,
126                        store_guard,
127                        update_sender.clone(),
128                        linked_chunk_update_sender,
129                    )
130                    .await?;
131
132                    timeline_is_not_empty =
133                        cache_state.thread_linked_chunk.revents().next().is_some();
134
135                    Ok(cache_state)
136                },
137            )
138            .await?;
139
140        let cache = Self {
141            inner: Arc::new(ThreadEventCacheInner {
142                room_id: room_id.clone(),
143                thread_id,
144                weak_room,
145                state: cache_state,
146                pagination_batch_token_notifier: Notify::new(),
147                auto_shrink_sender,
148                update_sender,
149            }),
150        };
151
152        // If at least one event has been loaded, it means there is a timeline.
153        // Let's emit a generic update.
154        if timeline_is_not_empty {
155            let _ = generic_update_sender
156                .send(RoomEventCacheGenericUpdate { room_id: room_id.to_owned() });
157        }
158
159        Ok(cache)
160    }
161
162    /// Get the room ID for this room.
163    pub fn room_id(&self) -> &RoomId {
164        &self.inner.room_id
165    }
166
167    /// Get the thread ID for this thread.
168    pub fn thread_id(&self) -> &EventId {
169        &self.inner.thread_id
170    }
171
172    /// Get the number of unread messages.
173    ///
174    /// To get multiple information about the read receipts, use
175    /// [`Self::read_receipts`] as it involves a single lock.
176    pub async fn num_unread_messages(&self) -> Result<u64> {
177        Ok(self.inner.state.read().await?.thread_info.read().await.read_receipts.num_unread)
178    }
179
180    /// Get the number of unread notifications.
181    ///
182    /// To get multiple information about the read receipts, use
183    /// [`Self::read_receipts`] as it involves a single lock.
184    pub async fn num_unread_notifications(&self) -> Result<u64> {
185        Ok(self.inner.state.read().await?.thread_info.read().await.read_receipts.num_notifications)
186    }
187
188    /// Get the number of unread mentions, that is, messages causing a highlight
189    /// in a room.
190    ///
191    /// To get multiple information about the read receipts, use
192    /// [`Self::read_receipts`] as it involves a single lock.
193    pub async fn num_unread_mentions(&self) -> Result<u64> {
194        Ok(self.inner.state.read().await?.thread_info.read().await.read_receipts.num_mentions)
195    }
196
197    /// Get the detailed information about read receipts for this thread.
198    pub async fn read_receipts(&self) -> Result<ReadReceipts> {
199        Ok(self.inner.state.read().await?.thread_info.read().await.read_receipts.clone())
200    }
201
202    /// Subscribe to update of the [`ThreadInfo`].
203    pub async fn subscribe_to_thread_info(
204        &self,
205    ) -> Result<eyeball::Subscriber<ThreadInfo, AsyncLock>> {
206        Ok(self.inner.state.read().await?.thread_info.subscribe().await)
207    }
208
209    /// Subscribe to this thread updates, after getting the initial list of
210    /// events.
211    ///
212    /// Creating, and especially dropping, a [`Subscriber`] isn't free, as it
213    /// triggers side-effects.
214    pub async fn subscribe(&self) -> Result<(Vec<Event>, Subscriber<ThreadEventCacheUpdate>)> {
215        let state = self.inner.state.read().await?;
216        let events =
217            state.thread_linked_chunk().events().map(|(_position, item)| item.clone()).collect();
218
219        let subscribers_handle = state.subscribers_handle();
220
221        let subscriber = Subscriber::new(
222            self.inner.update_sender.new_thread_receiver(),
223            AutoShrinkMessage::Thread {
224                room_id: self.inner.room_id.clone(),
225                thread_id: self.inner.thread_id.clone(),
226            },
227            self.inner.auto_shrink_sender.clone(),
228            subscribers_handle,
229        );
230
231        trace!("added a thread event cache subscriber; new count: {}", subscribers_handle.count());
232
233        Ok((events, subscriber))
234    }
235
236    /// Return a [`ThreadPagination`] useful for running back-pagination queries
237    /// in this thread.
238    pub fn pagination(&self) -> ThreadPagination {
239        ThreadPagination::new(self.inner.clone())
240    }
241
242    /// Return a reference to the state.
243    pub(in super::super) fn state(&self) -> &CacheStateLock<ThreadStateSelector> {
244        &self.inner.state
245    }
246
247    /// Return a reference to the update sender.
248    pub(in super::super) fn update_sender(&self) -> &ThreadEventCacheUpdateSender {
249        &self.inner.update_sender
250    }
251
252    /// Handle an update from a joined room.
253    #[instrument(skip_all, fields(room_id = %self.inner.room_id, thread_root = %self.inner.thread_id))]
254    pub(super) async fn handle_joined_room_update(
255        &self,
256        timeline: Timeline,
257        read_receipts: MaybeReceiptEventContent,
258    ) -> Result<()> {
259        self.handle_timeline(timeline, read_receipts).await
260    }
261
262    /// Handle an update from a left room.
263    #[instrument(skip_all, fields(room_id = %self.inner.room_id, thread_root = %self.inner.thread_id))]
264    pub(super) async fn handle_left_room_update(&self, timeline: Timeline) -> Result<()> {
265        self.handle_timeline(timeline, MaybeReceiptEventContent::none()).await
266    }
267
268    /// Handle a [`Timeline`], i.e. new events received by a sync for this
269    /// thread.
270    async fn handle_timeline(
271        &self,
272        timeline: Timeline,
273        read_receipts: MaybeReceiptEventContent,
274    ) -> Result<()> {
275        if timeline.events.is_empty() && timeline.prev_batch.is_none() && read_receipts.is_none() {
276            return Ok(());
277        }
278
279        trace!("adding new events");
280
281        let mut state = self.inner.state.write().await?;
282
283        let (stored_prev_batch_token, timeline_event_diffs) =
284            state.handle_sync(timeline, &read_receipts).await?;
285
286        // Now that all events have been added, we can trigger the
287        // `pagination_token_notifier`.
288        if stored_prev_batch_token {
289            self.inner.pagination_batch_token_notifier.notify_one();
290        }
291
292        if !timeline_event_diffs.is_empty() {
293            state.update_sender.send(
294                ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs {
295                    diffs: timeline_event_diffs,
296                    origin: EventsOrigin::Sync,
297                }),
298                // This function is part of the `RoomEventCache` flow. The
299                // generic update is handled by it.
300                None,
301            );
302        }
303
304        Ok(())
305    }
306
307    /// Update the [`ThreadSummary`] for this thread, and return a copy of it.
308    pub(in super::super) async fn update_thread_summary(&self) -> Result<ThreadSummary> {
309        let mut state = self.inner.state.write().await?;
310
311        let thread_summary = state.update_thread_summary().await?;
312
313        state
314            .update_sender
315            .send(ThreadEventCacheUpdate::UpdateSummary(thread_summary.clone()), None);
316
317        Ok(thread_summary)
318    }
319
320    /// Find a single event in this thread.
321    ///
322    /// It starts by looking into loaded events in `EventLinkedChunk` before
323    /// looking inside the storage.
324    #[cfg(test)]
325    async fn find_event(
326        &self,
327        event_id: &EventId,
328    ) -> Result<Option<(super::EventLocation, Event)>> {
329        self.inner.state.read().await?.find_event(event_id).await
330    }
331
332    /// Try to find an event by ID in this thread, along with its related
333    /// events.
334    ///
335    /// You can filter which types of related events to retrieve using `filter`.
336    /// `None` will retrieve related events of any type.
337    ///
338    /// The related events are sorted like this:
339    ///
340    /// - events saved out-of-band (with `RoomEventCache::save_events`) will be
341    ///   located at the beginning of the array.
342    /// - events present in the linked chunk (be it in memory or in the storage)
343    ///   will be sorted according to their ordering in the linked chunk.
344    pub async fn find_event_with_relations(
345        &self,
346        event_id: &EventId,
347        filter: Option<Vec<RelationType>>,
348    ) -> Result<Option<(Event, Vec<Event>)>> {
349        // Search in all loaded or stored events.
350        Ok(self
351            .inner
352            .state
353            .read()
354            .await?
355            .find_event_with_relations(event_id, filter)
356            .await
357            .ok()
358            .flatten())
359    }
360
361    /// Try to locate the events in the linked chunk corresponding to the given
362    /// list of resolved events, and replace them, while alerting observers
363    /// about the update.
364    ///
365    /// Return `true` if at least one event has been updated.
366    #[cfg(feature = "e2e-encryption")]
367    pub(in super::super) async fn replace_in_memory_utds(
368        &self,
369        resolved_events: &[MaybeResolvedEvent],
370    ) -> Result<bool> {
371        let mut state = self.inner.state.write().await?;
372        let timeline_event_diffs = state.replace_in_memory_utds(resolved_events)?;
373
374        // Drain the updates to the store, events have already been updated
375        // before calling this method.
376        let _ = state.thread_linked_chunk_mut().store_updates().take();
377
378        state
379            .post_process_upserted_events(
380                resolved_events.iter().filter_map(|resolved_event| resolved_event.as_resolved()),
381                // Read receipt events aren't encrypted, so we can't have
382                // decrypted a new one here. As a result, we don't have any new
383                // receipt events to post-process, so we can just pass `None`
384                // here.
385                //
386                // Note: read receipts may be updated anyhow in the
387                // post-processing step, as the redecryption may have decrypted
388                // some events that don't count as unreads.
389                None,
390            )
391            .await?;
392
393        let timeline_event_diffs = timeline_event_diffs
394            .into_iter()
395            .flatten()
396            .chain(state.thread_linked_chunk_mut().updates_as_vector_diffs())
397            .collect::<Vec<_>>();
398
399        Ok(if !timeline_event_diffs.is_empty() {
400            state.update_sender.send(
401                ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs {
402                    diffs: timeline_event_diffs,
403                    origin: EventsOrigin::Cache,
404                }),
405                Some(RoomEventCacheGenericUpdate { room_id: self.inner.room_id.clone() }),
406            );
407
408            true
409        } else {
410            false
411        })
412    }
413}
414
415#[cfg(all(test, not(target_family = "wasm")))] // This uses the cross-process lock, so needs time support.
416mod timed_tests {
417    use std::sync::Arc;
418
419    use assert_matches::assert_matches;
420    use eyeball_im::VectorDiff;
421    use futures_util::FutureExt as _;
422    use matrix_sdk_base::{
423        RoomState, ThreadingSupport,
424        cross_process_lock::CrossProcessLockConfig,
425        event_cache::{
426            Gap,
427            store::{EventCacheStore as _, MemoryStore},
428        },
429        linked_chunk::{
430            ChunkContent, ChunkIdentifier, LinkedChunkId, Position, Update,
431            lazy_loader::from_all_chunks,
432        },
433        store::StoreConfig,
434        sync::Timeline,
435    };
436    use matrix_sdk_test::{User, async_test, event_factory::EventFactory};
437    use ruma::{
438        event_id,
439        events::{AnySyncMessageLikeEvent, AnySyncTimelineEvent},
440        room_id, user_id,
441    };
442    use strass::assert_let;
443    use tokio::task::yield_now;
444
445    use super::{
446        super::{super::RoomEventCacheGenericUpdate, TimelineVectorDiffs},
447        MaybeReceiptEventContent, ThreadEventCacheUpdate,
448    };
449    use crate::{assert_let_timeout, test_utils::client::MockClientBuilder};
450
451    #[async_test]
452    async fn test_write_to_storage() {
453        let room_id = room_id!("!r0");
454        let thread_root = event_id!("$t0_ev0");
455        let thread_event_id_0 = event_id!("$t0_ev1");
456
457        let f = EventFactory::new().room(room_id).sender(user_id!("@mnt_io:matrix.org"));
458
459        let event_cache_store = Arc::new(MemoryStore::new());
460
461        let client = MockClientBuilder::new(None)
462            .on_builder(|builder| {
463                builder
464                    .store_config(
465                        StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
466                            .event_cache_store(event_cache_store.clone()),
467                    )
468                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
469            })
470            .build()
471            .await;
472
473        let event_cache = client.event_cache().unwrap();
474
475        client.base_client().get_or_create_room(room_id, RoomState::Joined);
476
477        let (thread_event_cache, _drop_handles) =
478            event_cache.thread(room_id, thread_root).await.unwrap();
479        let (thread_events, mut thread_stream) = thread_event_cache.subscribe().await.unwrap();
480
481        assert!(thread_events.is_empty());
482
483        // Propagate an update for a message and a prev-batch token.
484        let timeline = Timeline {
485            limited: true,
486            prev_batch: Some("raclette".to_owned()),
487            events: vec![
488                f.text_msg("salut")
489                    .event_id(thread_event_id_0)
490                    .in_thread(thread_root, thread_root)
491                    .into_event(),
492            ],
493        };
494
495        thread_event_cache
496            .handle_joined_room_update(timeline, MaybeReceiptEventContent::none())
497            .await
498            .unwrap();
499
500        assert_matches!(
501            thread_stream.recv().await,
502            Ok(ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) => {
503                assert_eq!(diffs.len(), 2);
504                assert_matches!(&diffs[0], VectorDiff::Clear);
505                assert_matches!(&diffs[1], VectorDiff::Append { values: events } => {
506                    assert_eq!(events.len(), 1);
507                    assert_eq!(events[0].event_id(), Some(thread_event_id_0));
508                });
509            }
510        );
511        assert!(thread_stream.is_empty());
512
513        // Check the storage.
514        let linked_chunk = from_all_chunks::<3, _, _>(
515            event_cache_store
516                .load_all_chunks(LinkedChunkId::Thread(room_id, thread_root))
517                .await
518                .unwrap(),
519        )
520        .unwrap()
521        .unwrap();
522
523        assert_eq!(linked_chunk.chunks().count(), 2);
524
525        let mut chunks = linked_chunk.chunks();
526
527        // We start with the gap.
528        assert_matches!(chunks.next().unwrap().content(), ChunkContent::Gap(gap) => {
529            assert_eq!(gap.token, "raclette");
530        });
531
532        // Then we have the stored event.
533        assert_matches!(chunks.next().unwrap().content(), ChunkContent::Items(events) => {
534            assert_eq!(events.len(), 1);
535            assert_eq!(events[0].event_id(), Some(thread_event_id_0));
536        });
537
538        // That's all, folks!
539        assert!(chunks.next().is_none());
540    }
541
542    #[async_test]
543    async fn test_write_to_storage_strips_bundled_relations() {
544        let sender = user_id!("@mnt_io:matrix.org");
545        let room_id = room_id!("!r0");
546        let thread_root = event_id!("$t0_ev0");
547        let thread_event_id_0 = event_id!("$t0_ev1");
548
549        let f = EventFactory::new().room(room_id).sender(sender);
550
551        let event_cache_store = Arc::new(MemoryStore::new());
552
553        let client = MockClientBuilder::new(None)
554            .on_builder(|builder| {
555                builder
556                    .store_config(
557                        StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
558                            .event_cache_store(event_cache_store.clone()),
559                    )
560                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
561            })
562            .build()
563            .await;
564
565        let event_cache = client.event_cache().unwrap();
566
567        client.base_client().get_or_create_room(room_id, RoomState::Joined);
568
569        let (thread_event_cache, _drop_handles) =
570            event_cache.thread(room_id, thread_root).await.unwrap();
571
572        // Propagate an update for a message with bundled relations.
573        let timeline = Timeline {
574            limited: false,
575            prev_batch: None,
576            events: vec![
577                f.text_msg("s 'up")
578                    .event_id(thread_event_id_0)
579                    .with_bundled_edit(f.text_msg("Hello, Kind Sir").sender(sender))
580                    .in_thread(thread_root, thread_root)
581                    .into_event(),
582            ],
583        };
584
585        thread_event_cache
586            .handle_joined_room_update(timeline, MaybeReceiptEventContent::none())
587            .await
588            .unwrap();
589
590        // The in-memory linked chunk keeps the bundled relation.
591        {
592            let (events, _) = thread_event_cache.subscribe().await.unwrap();
593
594            assert_eq!(events.len(), 1);
595
596            let event = events[0].raw().deserialize().unwrap();
597            assert_eq!(event.event_id(), thread_event_id_0);
598            assert_let!(
599                AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(msg)) =
600                    event
601            );
602            assert!(msg.as_original().unwrap().unsigned.relations.replace.is_some());
603        }
604
605        // The one in storage does not.
606        let linked_chunk = from_all_chunks::<3, _, _>(
607            event_cache_store
608                .load_all_chunks(LinkedChunkId::Thread(room_id, thread_root))
609                .await
610                .unwrap(),
611        )
612        .unwrap()
613        .unwrap();
614
615        assert_eq!(linked_chunk.chunks().count(), 1);
616
617        let mut chunks = linked_chunk.chunks();
618        assert_matches!(chunks.next().unwrap().content(), ChunkContent::Items(events) => {
619            assert_eq!(events.len(), 1);
620
621            let event = events[0].raw().deserialize().unwrap();
622            assert_eq!(event.event_id(), thread_event_id_0);
623
624            assert_let!(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage(msg)) = event);
625            assert!(msg.as_original().unwrap().unsigned.relations.replace.is_none());
626        });
627
628        // That's all, folks!
629        assert!(chunks.next().is_none());
630    }
631
632    #[async_test]
633    async fn test_clear() {
634        let room_id = room_id!("!r0");
635        let f = EventFactory::new().room(room_id).sender(user_id!("@mnt_io:matrix.org"));
636
637        let thread_root = event_id!("$t0_ev0");
638        let thread_event_id_0 = event_id!("$t0_ev1");
639        let thread_event_id_1 = event_id!("$t0_ev2");
640
641        let thread_event_0 = f
642            .text_msg("foo")
643            .event_id(thread_event_id_0)
644            .in_thread(thread_root, thread_root)
645            .into_event();
646        let thread_event_1 = f
647            .text_msg("bar")
648            .event_id(thread_event_id_1)
649            .in_thread(thread_root, thread_event_id_0)
650            .into_event();
651
652        // Prefill the store with some data.
653        let event_cache_store = Arc::new(MemoryStore::new());
654        event_cache_store
655            .handle_linked_chunk_updates(
656                LinkedChunkId::Thread(room_id, thread_root),
657                vec![
658                    // An empty items chunk.
659                    Update::NewItemsChunk {
660                        previous: None,
661                        new: ChunkIdentifier::new(0),
662                        next: None,
663                    },
664                    // A gap chunk.
665                    Update::NewGapChunk {
666                        previous: Some(ChunkIdentifier::new(0)),
667                        // Chunk IDs aren't supposed to be ordered, so use a random value here.
668                        new: ChunkIdentifier::new(42),
669                        next: None,
670                        gap: Gap { token: "comté".to_owned() },
671                    },
672                    // Another items chunk, non-empty this time.
673                    Update::NewItemsChunk {
674                        previous: Some(ChunkIdentifier::new(42)),
675                        new: ChunkIdentifier::new(1),
676                        next: None,
677                    },
678                    Update::PushItems {
679                        at: Position::new(ChunkIdentifier::new(1), 0),
680                        items: vec![thread_event_0.clone()],
681                    },
682                    // And another items chunk, non-empty again.
683                    Update::NewItemsChunk {
684                        previous: Some(ChunkIdentifier::new(1)),
685                        new: ChunkIdentifier::new(2),
686                        next: None,
687                    },
688                    Update::PushItems {
689                        at: Position::new(ChunkIdentifier::new(2), 0),
690                        items: vec![thread_event_1.clone()],
691                    },
692                ],
693            )
694            .await
695            .unwrap();
696
697        let client = MockClientBuilder::new(None)
698            .on_builder(|builder| {
699                builder
700                    .store_config(
701                        StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
702                            .event_cache_store(event_cache_store.clone()),
703                    )
704                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
705            })
706            .build()
707            .await;
708
709        let event_cache = client.event_cache().unwrap();
710
711        client.base_client().get_or_create_room(room_id, RoomState::Joined);
712
713        let (thread_event_cache, _drop_handles) =
714            event_cache.thread(room_id, thread_root).await.unwrap();
715        let (thread_events, mut thread_stream) = thread_event_cache.subscribe().await.unwrap();
716
717        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
718
719        // The thread knows about all cached events.
720        {
721            assert!(thread_event_cache.find_event(thread_event_id_0).await.unwrap().is_some());
722            assert!(thread_event_cache.find_event(thread_event_id_1).await.unwrap().is_some());
723        }
724
725        // But only part of events are loaded from the store.
726        {
727            // The thread must contain only one event because only one chunk has
728            // been loaded.
729            assert_eq!(thread_events.len(), 1);
730            assert_eq!(thread_events[0].event_id().unwrap(), thread_event_id_1);
731
732            assert!(thread_stream.is_empty());
733        }
734
735        // Let's load more chunks to load all events.
736        {
737            thread_event_cache.pagination().run_backwards_once(20).await.unwrap();
738
739            assert_matches!(
740                thread_stream.recv().await,
741                Ok(ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) => {
742                    assert_eq!(diffs.len(), 1);
743                    assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value: event } => {
744                        // Here you are `thread_event_0`!
745                        assert_eq!(event.event_id(), Some(thread_event_id_0));
746                    });
747                }
748            );
749            assert!(thread_stream.is_empty());
750
751            assert_matches!(
752                generic_stream.recv().await,
753                Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
754                    assert_eq!(room_id, expected_room_id);
755                }
756            );
757            assert!(generic_stream.is_empty());
758        }
759
760        // After clearing,…
761        event_cache.clear_all_rooms().await.unwrap();
762
763        //… we get an update that the content has been cleared.
764        assert_matches!(
765            thread_stream.recv().await,
766            Ok(ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) => {
767                assert_eq!(diffs.len(), 1);
768                assert_matches!(&diffs[0], VectorDiff::Clear);
769            }
770        );
771
772        // … same with a generic update. (update for the clearing of the room)
773        assert_matches!(
774            generic_stream.recv().await,
775            Ok(RoomEventCacheGenericUpdate { room_id: received_room_id }) => {
776                assert_eq!(received_room_id, room_id);
777            }
778        );
779        // (update for the clearing of the thread)
780        assert_matches!(
781            generic_stream.recv().await,
782            Ok(RoomEventCacheGenericUpdate { room_id: received_room_id }) => {
783                assert_eq!(received_room_id, room_id);
784            }
785        );
786        assert!(generic_stream.is_empty());
787
788        // Events individually are forgotten by the event cache, after clearing
789        // the threads.
790        assert!(thread_event_cache.find_event(thread_event_id_0).await.unwrap().is_none());
791        assert!(thread_event_cache.find_event(thread_event_id_1).await.unwrap().is_none());
792
793        // And their presence in a linked chunk is forgotten.
794        let (thread_events, _) = thread_event_cache.subscribe().await.unwrap();
795        assert!(thread_events.is_empty());
796
797        // The event cache store is totally empty.
798        assert!(
799            event_cache_store
800                .load_all_chunks(LinkedChunkId::Thread(room_id, thread_root))
801                .await
802                .unwrap()
803                .is_empty()
804        );
805    }
806
807    #[async_test]
808    async fn test_load_from_storage() {
809        let room_id = room_id!("!r0");
810        let f = EventFactory::new().room(room_id).sender(user_id!("@mnt_io:matrix.org"));
811
812        let event_cache_store = Arc::new(MemoryStore::new());
813
814        let thread_root = event_id!("$t0");
815        let thread_event_id_0 = event_id!("$t0_ev0");
816        let thread_event_id_1 = event_id!("$t0_ev1");
817
818        let thread_event_0 = f
819            .text_msg("hello world")
820            .event_id(thread_event_id_0)
821            .in_thread(thread_root, thread_root)
822            .into_event();
823        let thread_event_1 = f
824            .text_msg("how's it going")
825            .event_id(thread_event_id_1)
826            .in_thread(thread_root, thread_event_id_1)
827            .into_event();
828
829        // Prefill the store with some data. The room usually has all events
830        // duplicated from the threads. It's important to make the test pass
831        // when checking the generic update.
832        let updates = vec![
833            // An empty items chunk.
834            Update::NewItemsChunk { previous: None, new: ChunkIdentifier::new(0), next: None },
835            // A gap chunk.
836            Update::NewGapChunk {
837                previous: Some(ChunkIdentifier::new(0)),
838                // Chunk IDs aren't supposed to be ordered, so use a random value here.
839                new: ChunkIdentifier::new(42),
840                next: None,
841                gap: Gap { token: "gruyère".to_owned() },
842            },
843            // Another items chunk, non-empty this time.
844            Update::NewItemsChunk {
845                previous: Some(ChunkIdentifier::new(42)),
846                new: ChunkIdentifier::new(1),
847                next: None,
848            },
849            Update::PushItems {
850                at: Position::new(ChunkIdentifier::new(1), 0),
851                items: vec![thread_event_0.clone()],
852            },
853            // And another items chunk, non-empty again.
854            Update::NewItemsChunk {
855                previous: Some(ChunkIdentifier::new(1)),
856                new: ChunkIdentifier::new(2),
857                next: None,
858            },
859            Update::PushItems {
860                at: Position::new(ChunkIdentifier::new(2), 0),
861                items: vec![thread_event_1.clone()],
862            },
863        ];
864        event_cache_store
865            .handle_linked_chunk_updates(LinkedChunkId::Room(room_id), updates.clone())
866            .await
867            .unwrap();
868        event_cache_store
869            .handle_linked_chunk_updates(LinkedChunkId::Thread(room_id, thread_root), updates)
870            .await
871            .unwrap();
872
873        let client = MockClientBuilder::new(None)
874            .on_builder(|builder| {
875                builder
876                    .store_config(
877                        StoreConfig::new(CrossProcessLockConfig::multi_process("hodor"))
878                            .event_cache_store(event_cache_store.clone()),
879                    )
880                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
881            })
882            .build()
883            .await;
884
885        let event_cache = client.event_cache().unwrap();
886
887        client.base_client().get_or_create_room(room_id, RoomState::Joined);
888
889        // Let's check whether the generic updates are received for the
890        // initialisation.
891        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
892        let (thread_event_cache, _drop_handles) =
893            event_cache.thread(room_id, thread_root).await.unwrap();
894        let (thread_events, mut thread_stream) = thread_event_cache.subscribe().await.unwrap();
895
896        // The room **and** the thread have been loaded. Two generic updates
897        // must have been triggered.
898        for _ in 0..2 {
899            assert_matches!(
900                generic_stream.recv().await,
901                Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
902                    assert_eq!(room_id, expected_room_id);
903                }
904            );
905        }
906        assert!(generic_stream.is_empty());
907
908        // The initial events contain one event because only the last chunk is
909        // loaded by default.
910        assert_eq!(thread_events.len(), 1);
911        assert_eq!(thread_events[0].event_id().unwrap(), thread_event_id_1);
912        assert!(thread_stream.is_empty());
913
914        // The thread knows all events in the storage though, even if they
915        // aren't loaded.
916        assert!(thread_event_cache.find_event(thread_event_id_0).await.unwrap().is_some());
917        assert!(thread_event_cache.find_event(thread_event_id_1).await.unwrap().is_some());
918
919        // Let's paginate to load more events.
920        thread_event_cache.pagination().run_backwards_once(20).await.unwrap();
921
922        assert_matches!(
923            thread_stream.recv().await,
924            Ok(ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) => {
925                assert_eq!(diffs.len(), 1);
926                assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value: event } => {
927                    assert_eq!(event.event_id(), Some(thread_event_id_0));
928                });
929            }
930        );
931        assert!(thread_stream.is_empty());
932
933        // A generic update is triggered too.
934        assert_matches!(
935            generic_stream.recv().await,
936            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) => {
937                assert_eq!(expected_room_id, room_id);
938            }
939        );
940        assert!(generic_stream.is_empty());
941
942        // A new update with one of these events leads to deduplication.
943        let timeline = Timeline { limited: false, prev_batch: None, events: vec![thread_event_1] };
944
945        thread_event_cache
946            .handle_joined_room_update(timeline, MaybeReceiptEventContent::none())
947            .await
948            .unwrap();
949
950        // Just checking the generic update is correct. There is a duplicate
951        // event, so no generic changes whatsoever!
952        assert!(generic_stream.recv().now_or_never().is_none());
953
954        // The stream doesn't report these changes _yet_. Use the events vector
955        // given when subscribing, to check that the events correspond to their
956        // new positions. The duplicated item is removed (so it's not the first
957        // element anymore), and it's added to the back of the list.
958        let (thread_events, _) = thread_event_cache.subscribe().await.unwrap();
959        assert_eq!(thread_events.len(), 2);
960        assert_eq!(thread_events[0].event_id(), Some(thread_event_id_0));
961        assert_eq!(thread_events[1].event_id(), Some(thread_event_id_1));
962    }
963
964    #[async_test]
965    async fn test_load_from_storage_resilient_to_failure() {
966        let room_id = room_id!("!r0");
967        let f = EventFactory::new().room(room_id).sender(user_id!("@mnt_io:matrix.org"));
968
969        let thread_root = event_id!("$t0");
970        let thread_event_id_0 = event_id!("$t0_ev0");
971
972        let thread_event_0 = f
973            .text_msg("hello world")
974            .event_id(thread_event_id_0)
975            .in_thread(thread_root, thread_root)
976            .into_event();
977
978        // Prefill the store with invalid data: two chunks that form a cycle.
979        let event_cache_store = Arc::new(MemoryStore::new());
980        event_cache_store
981            .handle_linked_chunk_updates(
982                LinkedChunkId::Thread(room_id, thread_root),
983                vec![
984                    Update::NewItemsChunk {
985                        previous: None,
986                        new: ChunkIdentifier::new(0),
987                        next: None,
988                    },
989                    Update::PushItems {
990                        at: Position::new(ChunkIdentifier::new(0), 0),
991                        items: vec![thread_event_0],
992                    },
993                    Update::NewItemsChunk {
994                        previous: Some(ChunkIdentifier::new(0)),
995                        new: ChunkIdentifier::new(1),
996                        next: Some(ChunkIdentifier::new(0)),
997                    },
998                ],
999            )
1000            .await
1001            .unwrap();
1002
1003        let client = MockClientBuilder::new(None)
1004            .on_builder(|builder| {
1005                builder
1006                    .store_config(
1007                        StoreConfig::new(CrossProcessLockConfig::multi_process("holder"))
1008                            .event_cache_store(event_cache_store.clone()),
1009                    )
1010                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
1011            })
1012            .build()
1013            .await;
1014
1015        let event_cache = client.event_cache().unwrap();
1016
1017        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1018
1019        let (thread_event_cache, _drop_handles) =
1020            event_cache.thread(room_id, thread_root).await.unwrap();
1021        let (thread_events, _) = thread_event_cache.subscribe().await.unwrap();
1022
1023        // Because the persisted content was invalid, the thread store is reset:
1024        // there are no events in the cache.
1025        assert!(thread_events.is_empty());
1026
1027        // Storage doesn't contain anything. It would also be valid that it
1028        // contains a single initial empty items chunk.
1029        let raw_chunks = event_cache_store
1030            .load_all_chunks(LinkedChunkId::Thread(room_id, thread_root))
1031            .await
1032            .unwrap();
1033        assert!(raw_chunks.is_empty());
1034    }
1035
1036    #[async_test]
1037    async fn test_reload_when_dirty() {
1038        let user_id = user_id!("@mnt_io:matrix.org");
1039        let room_id = room_id!("!raclette:patate.ch");
1040
1041        let event_factory = EventFactory::new().room(room_id).sender(user_id);
1042
1043        let thread_root = event_id!("$t0");
1044        let thread_event_id_0 = event_id!("$t0_ev0");
1045        let thread_event_id_1 = event_id!("$t0_ev1");
1046
1047        let thread_event_0 = event_factory
1048            .text_msg("comté")
1049            .event_id(thread_event_id_0)
1050            .in_thread(thread_root, thread_root)
1051            .into_event();
1052        let thread_event_1 = event_factory
1053            .text_msg("morbier")
1054            .event_id(thread_event_id_1)
1055            .in_thread(thread_root, thread_event_id_0)
1056            .into_event();
1057
1058        // The storage shared by the two clients.
1059        let event_cache_store = MemoryStore::new();
1060        event_cache_store
1061            .handle_linked_chunk_updates(
1062                LinkedChunkId::Thread(room_id, thread_root),
1063                vec![
1064                    Update::NewItemsChunk {
1065                        previous: None,
1066                        new: ChunkIdentifier::new(0),
1067                        next: None,
1068                    },
1069                    Update::PushItems {
1070                        at: Position::new(ChunkIdentifier::new(0), 0),
1071                        items: vec![thread_event_0],
1072                    },
1073                    Update::NewItemsChunk {
1074                        previous: Some(ChunkIdentifier::new(0)),
1075                        new: ChunkIdentifier::new(1),
1076                        next: None,
1077                    },
1078                    Update::PushItems {
1079                        at: Position::new(ChunkIdentifier::new(1), 0),
1080                        items: vec![thread_event_1],
1081                    },
1082                ],
1083            )
1084            .await
1085            .unwrap();
1086
1087        // Client for the process 0.
1088        let client_p0 = MockClientBuilder::new(None)
1089            .on_builder(|builder| {
1090                builder
1091                    .store_config(
1092                        StoreConfig::new(CrossProcessLockConfig::multi_process("process #0"))
1093                            .event_cache_store(event_cache_store.clone()),
1094                    )
1095                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
1096            })
1097            .build()
1098            .await;
1099
1100        // Client for the process 1.
1101        let client_p1 = MockClientBuilder::new(None)
1102            .on_builder(|builder| {
1103                builder
1104                    .store_config(
1105                        StoreConfig::new(CrossProcessLockConfig::multi_process("process #1"))
1106                            .event_cache_store(event_cache_store),
1107                    )
1108                    .with_threading_support(ThreadingSupport::Enabled { with_subscriptions: true })
1109            })
1110            .build()
1111            .await;
1112
1113        // Subscribe the event caches, and create the room.
1114        let (thread_event_cache_p0, thread_event_cache_p1) = {
1115            let event_cache_p0 = client_p0.event_cache().unwrap();
1116            let event_cache_p1 = client_p1.event_cache().unwrap();
1117
1118            client_p0.base_client().get_or_create_room(room_id, RoomState::Joined);
1119            client_p1.base_client().get_or_create_room(room_id, RoomState::Joined);
1120
1121            let (thread_event_cache_p0, _drop_handles) =
1122                event_cache_p0.thread(room_id, thread_root).await.unwrap();
1123            let (thread_event_cache_p1, _drop_handles) =
1124                event_cache_p1.thread(room_id, thread_root).await.unwrap();
1125
1126            (thread_event_cache_p0, thread_event_cache_p1)
1127        };
1128
1129        // Okay. We are ready for the test!
1130        //
1131        // First off, let's check `thread_event_cache_p0` has access to the
1132        // first event loaded in-memory, then do a pagination, and see more
1133        // events.
1134        let mut updates_stream_p0 = {
1135            let thread_event_cache = &thread_event_cache_p0;
1136
1137            let (initial_updates, mut updates_stream) =
1138                thread_event_cache_p0.subscribe().await.unwrap();
1139
1140            // Initial updates contain `thread_event_id_1` only.
1141            assert_eq!(initial_updates.len(), 1);
1142            assert_eq!(initial_updates[0].event_id(), Some(thread_event_id_1));
1143            assert!(updates_stream.is_empty());
1144
1145            // Load one more event with a backpagination.
1146            thread_event_cache.pagination().run_backwards_once(1).await.unwrap();
1147
1148            // A new update for `ev_id_0` must be present.
1149            assert_matches!(
1150                updates_stream.recv().await.unwrap(),
1151                ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
1152                    assert_eq!(diffs.len(), 1, "{diffs:#?}");
1153                    assert_matches!(
1154                        &diffs[0],
1155                        VectorDiff::Insert { index: 0, value: event } => {
1156                            assert_eq!(event.event_id(), Some(thread_event_id_0));
1157                        }
1158                    );
1159                }
1160            );
1161
1162            updates_stream
1163        };
1164
1165        // Second, let's check `thread_event_cache_p1` has the same accesses.
1166        let mut updates_stream_p1 = {
1167            let thread_event_cache = &thread_event_cache_p1;
1168            let (initial_updates, mut updates_stream) =
1169                thread_event_cache_p1.subscribe().await.unwrap();
1170
1171            // Initial updates contain `thread_event_id_1` only.
1172            assert_eq!(initial_updates.len(), 1);
1173            assert_eq!(initial_updates[0].event_id(), Some(thread_event_id_1));
1174            assert!(updates_stream.is_empty());
1175
1176            // Load one more event with a backpagination.
1177            thread_event_cache.pagination().run_backwards_once(1).await.unwrap();
1178
1179            // A new update for `thread_event_id_0` must be present.
1180            assert_matches!(
1181                updates_stream.recv().await.unwrap(),
1182                ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
1183                    assert_eq!(diffs.len(), 1, "{diffs:#?}");
1184                    assert_matches!(
1185                        &diffs[0],
1186                        VectorDiff::Insert { index: 0, value: event } => {
1187                            assert_eq!(event.event_id(), Some(thread_event_id_0));
1188                        }
1189                    );
1190                }
1191            );
1192
1193            updates_stream
1194        };
1195
1196        // Do this a couple times, for the fun.
1197        for _ in 0..3 {
1198            // Third, because `thread_event_cache_p1` has locked the store, the
1199            // lock is dirty for `thread_event_cache_p0`, so it will shrink to
1200            // its last chunk for the thread!
1201            {
1202                let thread_event_cache = &thread_event_cache_p0;
1203                let updates_stream = &mut updates_stream_p0;
1204
1205                // `thread_event_id_1` must be loaded in memory, just like
1206                // before. However, `thread_event_id_0` must NOT be loaded in
1207                // memory. It WAS loaded, but the state has been reloaded to its
1208                // last chunk.
1209                let (initial_updates, _) = thread_event_cache.subscribe().await.unwrap();
1210
1211                assert_eq!(initial_updates.len(), 1);
1212                assert_eq!(initial_updates[0].event_id(), Some(thread_event_id_1));
1213
1214                // The reload can be observed via the updates too.
1215                assert_matches!(
1216                    updates_stream.recv().await.unwrap(),
1217                    ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
1218                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
1219                        assert_matches!(&diffs[0], VectorDiff::Clear);
1220                        assert_matches!(
1221                            &diffs[1],
1222                            VectorDiff::Append { values: events } => {
1223                                assert_eq!(events.len(), 1);
1224                                assert_eq!(events[0].event_id(), Some(thread_event_id_1));
1225                            }
1226                        );
1227                    }
1228                );
1229                assert_matches!(
1230                    updates_stream.recv().await.unwrap(),
1231                    ThreadEventCacheUpdate::UpdateSummary(summary) => {
1232                        assert_eq!(summary.latest_reply.as_deref(), Some(thread_event_id_1));
1233                        assert_eq!(summary.num_replies, 2);
1234                    }
1235                );
1236
1237                // Load one more event with a backpagination.
1238                thread_event_cache.pagination().run_backwards_once(1).await.unwrap();
1239
1240                // `thread_event_id_0` must now be loaded in memory. The
1241                // pagination can be observed via the updates.
1242                assert_matches!(
1243                    updates_stream.recv().await.unwrap(),
1244                    ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
1245                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
1246                        assert_matches!(
1247                            &diffs[0],
1248                            VectorDiff::Insert { index: 0, value: event } => {
1249                                assert_eq!(event.event_id(), Some(thread_event_id_0));
1250                            }
1251                        );
1252                    }
1253                );
1254
1255                assert!(updates_stream.is_empty());
1256            }
1257
1258            // Fourth, because `thread_event_cache_p0` has locked the store
1259            // again, the lock is dirty for `thread_event_cache_p1` too!, so it
1260            // will shrink to its last chunk for the thread!
1261            {
1262                let thread_event_cache = &thread_event_cache_p1;
1263                let updates_stream = &mut updates_stream_p1;
1264
1265                // `thread_event_id_1` must be loaded in memory, just like
1266                // before. However, `thread_event_id_0` must NOT be loaded in
1267                // memory. It WAS loaded, but the state has shrunk to its last
1268                // chunk.
1269                let (initial_updates, _) = thread_event_cache.subscribe().await.unwrap();
1270
1271                assert_eq!(initial_updates.len(), 1);
1272                assert_eq!(initial_updates[0].event_id(), Some(thread_event_id_1));
1273
1274                // The reload can be observed via the updates too.
1275                assert_matches!(
1276                    updates_stream.recv().await.unwrap(),
1277                    ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
1278                        assert_eq!(diffs.len(), 2, "{diffs:#?}");
1279                        assert_matches!(&diffs[0], VectorDiff::Clear);
1280                        assert_matches!(
1281                            &diffs[1],
1282                            VectorDiff::Append { values: events } => {
1283                                assert_eq!(events.len(), 1);
1284                                assert_eq!(events[0].event_id(), Some(thread_event_id_1));
1285                            }
1286                        );
1287                    }
1288                );
1289                assert_matches!(
1290                    updates_stream.recv().await.unwrap(),
1291                    ThreadEventCacheUpdate::UpdateSummary(summary) => {
1292                        assert_eq!(summary.latest_reply.as_deref(), Some(thread_event_id_1));
1293                        assert_eq!(summary.num_replies, 2);
1294                    }
1295                );
1296
1297                // Load one more event with a backpagination.
1298                thread_event_cache.pagination().run_backwards_once(1).await.unwrap();
1299
1300                // `thread_event_id_0` must now be loaded in memory. The
1301                // pagination can be observed via the updates.
1302                assert_matches!(
1303                    updates_stream.recv().await.unwrap(),
1304                    ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. }) => {
1305                        assert_eq!(diffs.len(), 1, "{diffs:#?}");
1306                        assert_matches!(
1307                            &diffs[0],
1308                            VectorDiff::Insert { index: 0, value: event } => {
1309                                assert_eq!(event.event_id(), Some(thread_event_id_0));
1310                            }
1311                        );
1312                    }
1313                );
1314            }
1315        }
1316    }
1317
1318    #[async_test]
1319    async fn test_auto_shrink_after_all_subscribers_are_gone() {
1320        let room_id = room_id!("!r0");
1321        let thread_id = event_id!("$t0");
1322
1323        let f = EventFactory::new().room(room_id).sender(User::Alice);
1324
1325        let event_id_0 = event_id!("$ev0");
1326        let event_id_1 = event_id!("$ev1");
1327
1328        let thread_root =
1329            f.text_msg("gr00t").event_id(thread_id).in_thread(thread_id, thread_id).into_event();
1330        let event_0 =
1331            f.text_msg("hello").event_id(event_id_0).in_thread(thread_id, event_id_0).into_event();
1332        let event_1 =
1333            f.text_msg("world").event_id(event_id_1).in_thread(thread_id, event_id_1).into_event();
1334
1335        // Fill the event cache store with an initial linked chunk with 2 events
1336        // chunks.
1337        let event_cache_store = MemoryStore::new();
1338        event_cache_store
1339            .handle_linked_chunk_updates(
1340                LinkedChunkId::Thread(room_id, thread_id),
1341                vec![
1342                    Update::NewItemsChunk {
1343                        previous: None,
1344                        new: ChunkIdentifier::new(0),
1345                        next: None,
1346                    },
1347                    Update::PushItems {
1348                        at: Position::new(ChunkIdentifier::new(0), 0),
1349                        items: vec![thread_root, event_0],
1350                    },
1351                    Update::NewItemsChunk {
1352                        previous: Some(ChunkIdentifier::new(0)),
1353                        new: ChunkIdentifier::new(1),
1354                        next: None,
1355                    },
1356                    Update::PushItems {
1357                        at: Position::new(ChunkIdentifier::new(1), 0),
1358                        items: vec![event_1],
1359                    },
1360                ],
1361            )
1362            .await
1363            .unwrap();
1364
1365        let client = MockClientBuilder::new(None)
1366            .on_builder(move |builder| {
1367                builder.store_config(
1368                    StoreConfig::new(CrossProcessLockConfig::MultiProcess {
1369                        holder_name: "foo".to_owned(),
1370                    })
1371                    .event_cache_store(event_cache_store),
1372                )
1373            })
1374            .build()
1375            .await;
1376
1377        let event_cache = client.event_cache().unwrap();
1378
1379        client.base_client().get_or_create_room(room_id, RoomState::Joined);
1380
1381        let (thread_event_cache, _drop_handles) =
1382            event_cache.thread(room_id, thread_id).await.unwrap();
1383
1384        // Sanity check: lazily loaded, so only includes one item at start.
1385        let (events1, mut stream1) = thread_event_cache.subscribe().await.unwrap();
1386        assert_eq!(events1.len(), 1);
1387        assert_eq!(events1[0].event_id(), Some(event_id_1));
1388        assert!(stream1.is_empty());
1389
1390        let mut generic_stream = event_cache.subscribe_to_room_generic_updates();
1391
1392        // Force loading the full linked chunk by back-paginating.
1393        let outcome = thread_event_cache.pagination().run_backwards_once(20).await.unwrap();
1394        assert_eq!(outcome.events.len(), 2);
1395        assert_eq!(outcome.events[0].event_id(), Some(event_id_0));
1396        assert_eq!(outcome.events[1].event_id(), Some(thread_id));
1397        assert!(outcome.reached_start);
1398
1399        // We also get an update about the loading from the store. Ignore it,
1400        // for this test's sake.
1401        assert_let_timeout!(
1402            Ok(ThreadEventCacheUpdate::UpdateTimelineEvents(TimelineVectorDiffs { diffs, .. })) =
1403                stream1.recv()
1404        );
1405        assert_eq!(diffs.len(), 2);
1406        assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value } => {
1407            assert_eq!(value.event_id(), Some(thread_id));
1408        });
1409        assert_matches!(&diffs[1], VectorDiff::Insert { index: 1, value } => {
1410            assert_eq!(value.event_id(), Some(event_id_0));
1411        });
1412
1413        assert!(stream1.is_empty());
1414
1415        assert_let_timeout!(
1416            Ok(RoomEventCacheGenericUpdate { room_id: expected_room_id }) = generic_stream.recv()
1417        );
1418        assert_eq!(expected_room_id, room_id);
1419        assert!(generic_stream.is_empty());
1420
1421        // Have another subscriber. Since it's not the first one, and the
1422        // previous one loaded some more events, the second subscribers sees
1423        // them all.
1424        let (events2, stream2) = thread_event_cache.subscribe().await.unwrap();
1425        assert_eq!(events2.len(), 3);
1426        assert_eq!(events2[0].event_id(), Some(thread_id));
1427        assert_eq!(events2[1].event_id(), Some(event_id_0));
1428        assert_eq!(events2[2].event_id(), Some(event_id_1));
1429        assert!(stream2.is_empty());
1430
1431        // Grab a receiver for testing no diffs is sent.
1432        let subscriber = {
1433            let state = thread_event_cache.inner.state.read().await.unwrap();
1434            state.update_sender.new_thread_receiver()
1435        };
1436
1437        // Drop the first stream, and wait a bit.
1438        drop(stream1);
1439        yield_now().await;
1440
1441        // The second stream remains undisturbed.
1442        assert!(stream2.is_empty());
1443
1444        // Now drop the second stream, and wait a bit.
1445        drop(stream2);
1446        yield_now().await;
1447
1448        // The linked chunk must have auto-shrunk by now.
1449
1450        {
1451            // Check the inner state: there's no more shared auto-shrinker.
1452            let state = thread_event_cache.inner.state.read().await.unwrap();
1453            assert_eq!(state.subscribers_handle().count(), 0);
1454
1455            // No diff is sent when the linked chunk has auto-shrunk.
1456            assert!(subscriber.is_empty());
1457            assert!(generic_stream.is_empty());
1458        }
1459
1460        // Getting the events will only give us the latest chunk.
1461        let events3 = thread_event_cache
1462            .inner
1463            .state
1464            .read()
1465            .await
1466            .unwrap()
1467            .thread_linked_chunk()
1468            .events()
1469            .map(|(_position, item)| item.clone())
1470            .collect::<Vec<_>>();
1471        assert_eq!(events3.len(), 1);
1472        assert_eq!(events3[0].event_id(), Some(event_id_1));
1473    }
1474}