Skip to main content

matrix_sdk/event_cache/caches/room/
updates.rs

1// Copyright 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16
17use matrix_sdk_base::{
18    deserialized_responses::AmbiguityChange,
19    event_cache::{Event, Gap},
20    linked_chunk::{self, OwnedLinkedChunkId},
21};
22use ruma::{
23    OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedUserId, events::receipt::ReceiptEventContent,
24};
25use tokio::sync::broadcast::{Receiver, Sender};
26
27use super::super::TimelineVectorDiffs;
28
29/// An update related to events happened in a room.
30#[derive(Debug, Clone)]
31pub enum RoomEventCacheUpdate {
32    /// The fully read marker has moved to a different event.
33    MoveReadMarkerTo {
34        /// Event at which the read marker is now pointing.
35        event_id: OwnedEventId,
36    },
37
38    /// The members have changed.
39    UpdateMembers {
40        /// Collection of ambiguity changes that room member events trigger.
41        ///
42        /// This is a map of event ID of the `m.room.member` event to the
43        /// details of the ambiguity change.
44        ambiguity_changes: BTreeMap<OwnedEventId, AmbiguityChange>,
45
46        /// Collection of avatar changes that room member events trigger.
47        avatar_changes: Option<BTreeMap<OwnedUserId, Option<OwnedMxcUri>>>,
48    },
49
50    /// The room has received updates for the timeline as _diffs_.
51    UpdateTimelineEvents(TimelineVectorDiffs),
52
53    /// The room has received a new read receipt event.
54    AddReadReceiptEvent {
55        /// The event containing the receipts.
56        event: ReceiptEventContent,
57    },
58}
59
60/// Represents a timeline update of a room. It hides the details of
61/// [`RoomEventCacheUpdate`] by being more generic.
62///
63/// This is used by [`EventCache::subscribe_to_room_generic_updates`][0]. Please
64/// read it to learn more about the motivation behind this type.
65///
66/// [0]: super::super::super::EventCache::subscribe_to_room_generic_updates
67#[derive(Clone, Debug)]
68pub struct RoomEventCacheGenericUpdate {
69    /// The room ID owning the timeline.
70    pub room_id: OwnedRoomId,
71}
72
73/// An update being triggered when events change in the persisted event cache
74/// for any room.
75#[derive(Clone, Debug)]
76pub struct RoomEventCacheLinkedChunkUpdate {
77    /// The linked chunk affected by the update.
78    pub linked_chunk_id: OwnedLinkedChunkId,
79
80    /// A vector of all the linked chunk updates that happened during this event
81    /// cache update.
82    pub updates: Vec<linked_chunk::Update<Event, Gap>>,
83}
84
85impl RoomEventCacheLinkedChunkUpdate {
86    /// Return all the new events propagated by this update, in topological
87    /// order.
88    pub fn events(self) -> impl DoubleEndedIterator<Item = Event> {
89        use itertools::Either;
90        self.updates.into_iter().flat_map(|update| match update {
91            linked_chunk::Update::PushItems { items, .. } => {
92                Either::Left(Either::Left(items.into_iter()))
93            }
94            linked_chunk::Update::ReplaceItem { item, .. } => {
95                Either::Left(Either::Right(std::iter::once(item)))
96            }
97            linked_chunk::Update::RemoveItem { .. }
98            | linked_chunk::Update::DetachLastItems { .. }
99            | linked_chunk::Update::StartReattachItems
100            | linked_chunk::Update::EndReattachItems
101            | linked_chunk::Update::NewItemsChunk { .. }
102            | linked_chunk::Update::NewGapChunk { .. }
103            | linked_chunk::Update::RemoveChunk(..)
104            | linked_chunk::Update::Clear => {
105                // All these updates don't contain any new event.
106                Either::Right(std::iter::empty())
107            }
108        })
109    }
110}
111
112/// A small type to send updates in all channels.
113#[derive(Clone)]
114pub struct RoomEventCacheUpdateSender {
115    room_sender: Sender<RoomEventCacheUpdate>,
116    generic_sender: Sender<RoomEventCacheGenericUpdate>,
117}
118
119impl RoomEventCacheUpdateSender {
120    /// Create a new [`RoomEventCacheUpdateSender`].
121    pub fn new(generic_sender: Sender<RoomEventCacheGenericUpdate>) -> Self {
122        Self { room_sender: Sender::new(32), generic_sender }
123    }
124
125    /// Send a [`RoomEventCacheUpdate`] and an optional
126    /// [`RoomEventCacheGenericUpdate`].
127    pub fn send(
128        &self,
129        room_update: RoomEventCacheUpdate,
130        generic_update: Option<RoomEventCacheGenericUpdate>,
131    ) {
132        let _ = self.room_sender.send(room_update);
133
134        if let Some(generic_update) = generic_update {
135            let _ = self.generic_sender.send(generic_update);
136        }
137    }
138
139    /// Get the generic update sender.
140    pub(in super::super) fn generic_update_sender(&self) -> &Sender<RoomEventCacheGenericUpdate> {
141        &self.generic_sender
142    }
143
144    /// Create a new [`Receiver`] of [`RoomEventCacheUpdate`].
145    pub(super) fn new_room_receiver(&self) -> Receiver<RoomEventCacheUpdate> {
146        self.room_sender.subscribe()
147    }
148}