Skip to main content

matrix_sdk_base/sticky/
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//! Sticky events ([MSC4354]), received over sliding sync through the
16//! [MSC4480] extension.
17//!
18//! A sticky event is a message-like event that the server keeps delivering to
19//! clients for a bounded duration (at most one hour), regardless of the
20//! timeline limit. Clients fold the sticky events of a room into a map keyed by
21//! `(sender, type, content.sticky_key)`, in which the event that is last to
22//! expire wins, and from which entries disappear once they expire. MatrixRTC
23//! uses this to track who is in a call.
24//!
25//! The map of a room is reachable through [`Room::sticky_events`]. It is fed
26//! from the sync response, expires its entries in the background, and
27//! broadcasts every visible change to its subscribers. Encrypted sticky events
28//! that cannot be decrypted yet are kept aside and retried when their room key
29//! arrives. Nothing is persisted: the server re-sends every sticky event that
30//! is still live when the sliding sync connection starts over.
31//!
32//! [MSC4354]: https://github.com/matrix-org/matrix-spec-proposals/pull/4354
33//! [MSC4480]: https://github.com/matrix-org/matrix-spec-proposals/pull/4480
34//! [`Room::sticky_events`]: crate::Room::sticky_events
35
36#[cfg(feature = "e2e-encryption")]
37mod decrypt;
38mod extract;
39mod map;
40mod task;
41
42#[cfg(feature = "e2e-encryption")]
43use std::collections::BTreeSet;
44use std::sync::{Arc, Mutex, OnceLock, Weak};
45
46use matrix_sdk_common::{
47    deserialized_responses::{EncryptionInfo, TimelineEventKind},
48    executor::AbortOnDrop,
49};
50use ruma::{
51    MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
52    events::{AnySyncTimelineEvent, TimelineEventType},
53    serde::Raw,
54};
55use tokio::sync::{Notify, broadcast};
56use tracing::{debug, warn};
57
58#[cfg(feature = "e2e-encryption")]
59pub(crate) use self::decrypt::{Decryption, decrypt, spawn_redecryptor};
60use self::map::EphemeralMap;
61pub(crate) use self::{
62    extract::{Payload, StickyMeta, classify, resolve},
63    map::Candidate,
64};
65
66/// The maximum number of encrypted sticky events kept aside per room while
67/// waiting for their room keys. Beyond that, the oldest (which are the closest
68/// to expiring) make way for new ones.
69const MAX_PENDING: usize = 5000;
70
71/// The capacity of the broadcast channel behind [`StickyEvents::subscribe`].
72const UPDATES_CHANNEL_CAPACITY: usize = 32;
73
74/// Whether `raw`, received now, is a sticky event that the map of its room
75/// tracks.
76pub fn is_tracked(raw: &Raw<AnySyncTimelineEvent>) -> bool {
77    classify(now_ms(), raw).is_some()
78}
79
80/// The key of a sticky event in the map of a room.
81///
82/// MSC4354 keys the map by `(room_id, sender, type, content.sticky_key)`; the
83/// room is implied by the map this key belongs to.
84#[derive(Clone, Debug, PartialEq, Eq, Hash)]
85pub struct StickyKey {
86    /// The sender of the event.
87    pub sender: OwnedUserId,
88    /// The type of the event, e.g. `m.rtc.member`.
89    pub event_type: TimelineEventType,
90    /// The `content.sticky_key` of the event.
91    pub sticky_key: String,
92}
93
94/// A sticky event that is currently live in the map of a room.
95#[derive(Clone, Debug)]
96pub struct StickyEvent {
97    /// The key of the event in the map.
98    pub key: StickyKey,
99    /// The event ID.
100    pub event_id: OwnedEventId,
101    /// The event, decrypted if it was encrypted, along with its encryption
102    /// info.
103    pub kind: TimelineEventKind,
104    /// When the event stops being sticky.
105    pub expires_at: MilliSecondsSinceUnixEpoch,
106}
107
108impl StickyEvent {
109    /// The event, decrypted if it was encrypted.
110    pub fn raw(&self) -> &Raw<AnySyncTimelineEvent> {
111        self.kind.raw()
112    }
113
114    /// The encryption info of the event, if it was encrypted.
115    pub fn encryption_info(&self) -> Option<&Arc<EncryptionInfo>> {
116        self.kind.encryption_info()
117    }
118}
119
120/// Why a sticky event disappeared from the map of a room.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
123pub enum RemovalReason {
124    /// The event stopped being sticky.
125    Expired,
126    /// A newer event with the same key and an empty content (a removal, in
127    /// MSC4354 terms) replaced it.
128    Replaced,
129    /// We left the room.
130    RoomLeft,
131}
132
133/// A sticky event that is no longer live in the map of a room.
134#[derive(Clone, Debug)]
135pub struct StickyEventRemoval {
136    /// The key the event was tracked under.
137    pub key: StickyKey,
138    /// Why it is no longer live.
139    pub reason: RemovalReason,
140    /// The event that removed it, when the reason is
141    /// [`RemovalReason::Replaced`] which is the newer event with the same key
142    /// and an empty content. This empty tombstone event is not live and, thus,
143    /// never part of [`StickyEvents::live`].
144    pub tombstone: Option<StickyEvent>,
145}
146
147/// A batch of visible changes to the map of a room.
148///
149/// One update is broadcast per processed sync response, and one per expiry
150/// pass, so that subscribers see the net effect of each at once.
151#[derive(Clone, Debug, Default)]
152pub struct StickyEventsUpdate {
153    /// The events that appeared under a key that had no live event.
154    pub added: Vec<StickyEvent>,
155    /// The events that replaced the live event of their key.
156    pub updated: Vec<StickyEvent>,
157    /// The keys whose live event disappeared, and why.
158    pub removed: Vec<StickyEventRemoval>,
159}
160
161impl StickyEventsUpdate {
162    /// Whether this update carries no change at all.
163    pub fn is_empty(&self) -> bool {
164        self.added.is_empty() && self.updated.is_empty() && self.removed.is_empty()
165    }
166}
167
168/// An encrypted sticky event that couldn't be decrypted yet.
169///
170/// Without encryption support nothing ever reads the event back: it is kept
171/// until it expires, like any other, for the sake of a single code path.
172#[derive(Debug)]
173pub(crate) struct PendingEvent {
174    /// The sticky metadata of the event, with a [`Payload::Encrypted`].
175    pub meta: StickyMeta,
176    /// The encrypted event.
177    #[cfg_attr(not(feature = "e2e-encryption"), allow(dead_code))]
178    pub event: Raw<AnySyncTimelineEvent>,
179}
180
181impl PendingEvent {
182    /// Return the Megolm session the event was encrypted with (if any).
183    fn session_id(&self) -> Option<&str> {
184        match &self.meta.payload {
185            Payload::Encrypted { session_id } => session_id.as_deref(),
186            Payload::Plain { .. } => None,
187        }
188    }
189}
190
191/// The sticky events of a room.
192///
193/// This is a cheap-to-clone handle over the map of a room, which every clone
194/// (and every clone of the [`Room`](crate::Room) it belongs to) shares.
195#[derive(Clone, Debug)]
196pub struct StickyEvents {
197    inner: Arc<StickyEventsInner>,
198}
199
200#[derive(Debug)]
201struct StickyEventsInner {
202    /// The ID of the room these sticky events belong to.
203    room_id: OwnedRoomId,
204    /// The mutable state of the room's sticky events.
205    state: Mutex<State>,
206    /// Broadcasts the visible changes of the map to subscribers.
207    updates: broadcast::Sender<StickyEventsUpdate>,
208    /// Notified whenever the state changed in a way that may require the
209    /// maintenance task to wake up earlier than planned.
210    changed: Arc<Notify>,
211    /// The background task expiring entries and pending events. Spawned the
212    /// first time there is something to expire, so that a room without sticky
213    /// events costs nothing, and aborted when the last handle is dropped.
214    task: OnceLock<AbortOnDrop<()>>,
215}
216
217/// The mutable state of a room's sticky events.
218#[derive(Debug, Default)]
219struct State {
220    /// The map of live (and tombstoned) sticky events.
221    map: EphemeralMap,
222    /// Encrypted sticky events awaiting their room key, oldest first.
223    pending: Vec<PendingEvent>,
224}
225
226impl StickyEvents {
227    pub(crate) fn new(room_id: OwnedRoomId) -> Self {
228        let (updates, _) = broadcast::channel(UPDATES_CHANNEL_CAPACITY);
229
230        Self {
231            inner: Arc::new(StickyEventsInner {
232                room_id,
233                state: Default::default(),
234                updates,
235                changed: Default::default(),
236                task: OnceLock::new(),
237            }),
238        }
239    }
240
241    /// The room these sticky events belong to.
242    pub fn room_id(&self) -> &RoomId {
243        &self.inner.room_id
244    }
245
246    /// The sticky events that are currently live, in no particular order.
247    pub fn live(&self) -> Vec<StickyEvent> {
248        self.inner.state.lock().unwrap().map.live(now_ms()).collect()
249    }
250
251    /// The sticky events that have not expired, in no particular order.
252    /// Includes live events plus removals (tombstones).
253    pub fn unexpired(&self) -> Vec<StickyEvent> {
254        self.inner.state.lock().unwrap().map.unexpired(now_ms()).collect()
255    }
256
257    /// Subscribe to the changes of the map.
258    ///
259    /// A subscriber that falls behind receives a
260    /// [`Lagged`](broadcast::error::RecvError::Lagged) error, after which it
261    /// should reconcile with [`live`](Self::live) (or
262    /// [`unexpired`](Self::unexpired) when relaying the events).
263    pub fn subscribe(&self) -> broadcast::Receiver<StickyEventsUpdate> {
264        self.inner.updates.subscribe()
265    }
266
267    /// Apply resolved sticky events received at `now` to the map.
268    pub(crate) fn ingest(&self, now: u64, candidates: Vec<Candidate>) {
269        if candidates.is_empty() {
270            return;
271        }
272
273        self.ensure_task();
274
275        let update = self.inner.state.lock().unwrap().map.apply(now, candidates);
276        self.inner.changed.notify_one();
277        self.publish(update);
278    }
279
280    /// Keep encrypted sticky events aside until their room key arrives.
281    pub(crate) fn park(&self, pending: Vec<PendingEvent>) {
282        if pending.is_empty() {
283            return;
284        }
285
286        self.ensure_task();
287
288        {
289            let mut state = self.inner.state.lock().unwrap();
290
291            for event in pending {
292                if event.session_id().is_none() {
293                    debug!(
294                        room_id = %self.inner.room_id,
295                        event_id = %event.meta.event_id,
296                        "Dropping an encrypted sticky event without a session ID"
297                    );
298                    continue;
299                }
300
301                state.pending.push(event);
302            }
303
304            if state.pending.len() > MAX_PENDING {
305                warn!(
306                    room_id = %self.inner.room_id,
307                    "Too many encrypted sticky events await their room key, dropping the oldest"
308                );
309                let excess = state.pending.len() - MAX_PENDING;
310                state.pending.drain(..excess);
311            }
312        }
313
314        self.inner.changed.notify_one();
315    }
316
317    /// Take the pending encrypted sticky events that were encrypted with one of
318    /// `session_ids`, or all of them if `None`.
319    #[cfg(feature = "e2e-encryption")]
320    pub(crate) fn take_pending(&self, session_ids: Option<&BTreeSet<String>>) -> Vec<PendingEvent> {
321        let mut state = self.inner.state.lock().unwrap();
322
323        match session_ids {
324            None => std::mem::take(&mut state.pending),
325            Some(session_ids) => {
326                let (taken, kept) =
327                    std::mem::take(&mut state.pending).into_iter().partition(|event| {
328                        event.session_id().is_some_and(|id| session_ids.contains(id))
329                    });
330                state.pending = kept;
331                taken
332            }
333        }
334    }
335
336    /// Whether any encrypted sticky event awaits its room key.
337    #[cfg(feature = "e2e-encryption")]
338    pub(crate) fn has_pending(&self) -> bool {
339        !self.inner.state.lock().unwrap().pending.is_empty()
340    }
341
342    /// Forget every sticky event, e.g. because we left the room.
343    pub(crate) fn clear(&self) {
344        let removed = {
345            let mut state = self.inner.state.lock().unwrap();
346            state.pending.clear();
347            state.map.clear(now_ms())
348        };
349
350        self.publish(StickyEventsUpdate {
351            removed: removed
352                .into_iter()
353                .map(|key| StickyEventRemoval {
354                    key,
355                    reason: RemovalReason::RoomLeft,
356                    tombstone: None,
357                })
358                .collect(),
359            ..Default::default()
360        });
361    }
362
363    fn publish(&self, update: StickyEventsUpdate) {
364        if !update.is_empty() {
365            // Failing to send only means there is no subscriber.
366            let _ = self.inner.updates.send(update);
367        }
368    }
369
370    fn ensure_task(&self) {
371        self.inner
372            .task
373            .get_or_init(|| task::spawn(Arc::downgrade(&self.inner), self.inner.changed.clone()));
374    }
375}
376
377impl StickyEventsInner {
378    /// Drop what has expired at `now`, broadcast the visible removals, and
379    /// return when the next entry is due to expire, if any.
380    fn expire(&self, now: u64) -> Option<u64> {
381        let (removed, next) = {
382            let mut state = self.state.lock().unwrap();
383
384            let removed = state.map.evict_expired(now);
385            state.pending.retain(|event| event.meta.expires_at > now);
386
387            let next_pending = state.pending.iter().map(|event| event.meta.expires_at).min();
388            let next = match (state.map.next_expiry(), next_pending) {
389                (Some(a), Some(b)) => Some(a.min(b)),
390                (a, b) => a.or(b),
391            };
392
393            (removed, next)
394        };
395
396        if !removed.is_empty() {
397            let _ = self.updates.send(StickyEventsUpdate {
398                removed: removed
399                    .into_iter()
400                    .map(|key| StickyEventRemoval {
401                        key,
402                        reason: RemovalReason::Expired,
403                        tombstone: None,
404                    })
405                    .collect(),
406                ..Default::default()
407            });
408        }
409
410        next
411    }
412}
413
414/// The current time, in milliseconds since the Unix epoch.
415pub(crate) fn now_ms() -> u64 {
416    MilliSecondsSinceUnixEpoch::now().get().into()
417}
418
419/// A weak handle to the state of a room's sticky events, for background
420/// tasks.
421type WeakStickyEvents = Weak<StickyEventsInner>;
422
423#[cfg(test)]
424mod tests {
425    use std::time::Duration;
426
427    use matrix_sdk_common::deserialized_responses::TimelineEventKind;
428    use matrix_sdk_test::async_test;
429    use ruma::{
430        events::{AnySyncTimelineEvent, TimelineEventType},
431        owned_event_id, owned_user_id, room_id,
432        serde::Raw,
433    };
434    use serde_json::json;
435    use strass::assert_let;
436    use tokio::sync::broadcast::error::TryRecvError;
437
438    use super::{
439        Candidate, PendingEvent, RemovalReason, StickyEventRemoval, StickyEvents, StickyKey,
440        StickyMeta, now_ms,
441    };
442    use crate::sticky::Payload;
443
444    fn raw_event() -> Raw<AnySyncTimelineEvent> {
445        serde_json::from_value(json!({
446            "type": "m.rtc.member",
447            "sender": "@alice:localhost",
448            "event_id": "$a:localhost",
449            "origin_server_ts": 1,
450            "content": { "msc4354_sticky_key": "slot" },
451        }))
452        .unwrap()
453    }
454
455    fn candidate(sticky_key: &str, expires_at: u64) -> Candidate {
456        Candidate {
457            key: StickyKey {
458                sender: owned_user_id!("@alice:localhost"),
459                event_type: TimelineEventType::from("m.rtc.member"),
460                sticky_key: sticky_key.to_owned(),
461            },
462            event_id: owned_event_id!("$a:localhost"),
463            order_ts: expires_at,
464            expires_at,
465            is_tombstone: false,
466            kind: TimelineEventKind::PlainText { event: raw_event() },
467        }
468    }
469
470    fn pending(session_id: Option<&str>, expires_at: u64) -> PendingEvent {
471        PendingEvent {
472            meta: StickyMeta {
473                sender: owned_user_id!("@alice:localhost"),
474                event_id: owned_event_id!("$a:localhost"),
475                order_ts: expires_at,
476                expires_at,
477                payload: Payload::Encrypted { session_id: session_id.map(ToOwned::to_owned) },
478            },
479            event: raw_event(),
480        }
481    }
482
483    #[async_test]
484    async fn test_ingest_broadcasts_and_exposes_live_events() {
485        let sticky = StickyEvents::new(room_id!("!room:localhost").to_owned());
486        let mut subscriber = sticky.subscribe();
487
488        let now = now_ms();
489        sticky.ingest(now, vec![candidate("slot", now + 60_000)]);
490
491        let live = sticky.live();
492        assert_eq!(live.len(), 1);
493        assert_eq!(live[0].key.sticky_key, "slot");
494        assert!(live[0].encryption_info().is_none());
495
496        let update = subscriber.try_recv().unwrap();
497        assert_eq!(update.added.len(), 1);
498        assert_eq!(update.added[0].key.sticky_key, "slot");
499    }
500
501    #[async_test]
502    async fn test_expired_events_are_evicted_in_the_background() {
503        let sticky = StickyEvents::new(room_id!("!room:localhost").to_owned());
504        let mut subscriber = sticky.subscribe();
505
506        let now = now_ms();
507        sticky.ingest(now, vec![candidate("slot", now + 50)]);
508        assert_let!(Ok(update) = subscriber.try_recv());
509        assert_eq!(update.added.len(), 1);
510
511        // No further action on our side: the maintenance task must notice the
512        // expiry and tell us.
513        let update = tokio::time::timeout(Duration::from_secs(5), subscriber.recv())
514            .await
515            .expect("the expiry should be broadcast in time")
516            .unwrap();
517        assert_let!(
518            [StickyEventRemoval { key, reason: RemovalReason::Expired, tombstone: None }] =
519                update.removed.as_slice()
520        );
521        assert_eq!(key.sticky_key, "slot");
522
523        assert!(sticky.live().is_empty());
524    }
525
526    #[async_test]
527    async fn test_clear_broadcasts_removals() {
528        let sticky = StickyEvents::new(room_id!("!room:localhost").to_owned());
529        let mut subscriber = sticky.subscribe();
530
531        let now = now_ms();
532        sticky.ingest(now, vec![candidate("slot", now + 60_000)]);
533        sticky.park(vec![pending(Some("session"), now + 60_000)]);
534        let _ = subscriber.try_recv().unwrap();
535
536        sticky.clear();
537
538        let update = subscriber.try_recv().unwrap();
539        assert_let!(
540            [StickyEventRemoval { key, reason: RemovalReason::RoomLeft, tombstone: None }] =
541                update.removed.as_slice()
542        );
543        assert_eq!(key.sticky_key, "slot");
544        assert!(sticky.live().is_empty());
545        assert_let!(Err(TryRecvError::Empty) = subscriber.try_recv());
546    }
547
548    #[cfg(feature = "e2e-encryption")]
549    #[async_test]
550    async fn test_pending_events_are_taken_by_session_id() {
551        use std::collections::BTreeSet;
552
553        let sticky = StickyEvents::new(room_id!("!room:localhost").to_owned());
554
555        let now = now_ms();
556        sticky.park(vec![
557            pending(Some("session1"), now + 60_000),
558            pending(Some("session2"), now + 60_000),
559            // Nothing could ever decrypt this one: it isn't kept.
560            pending(None, now + 60_000),
561        ]);
562
563        let taken = sticky.take_pending(Some(&BTreeSet::from(["session2".to_owned()])));
564        assert_eq!(taken.len(), 1);
565        assert_let!(Payload::Encrypted { session_id } = &taken[0].meta.payload);
566        assert_eq!(session_id.as_deref(), Some("session2"));
567
568        assert!(sticky.has_pending());
569        let taken = sticky.take_pending(None);
570        assert_eq!(taken.len(), 1);
571        assert!(!sticky.has_pending());
572    }
573
574    #[cfg(feature = "e2e-encryption")]
575    #[async_test]
576    async fn test_pending_events_are_capped() {
577        use std::collections::BTreeSet;
578
579        use super::MAX_PENDING;
580
581        let sticky = StickyEvents::new(room_id!("!room:localhost").to_owned());
582
583        let now = now_ms();
584        // One more than the cap, the oldest first.
585        let mut events = vec![pending(Some("oldest"), now + 60_000)];
586        events.extend((0..MAX_PENDING).map(|_| pending(Some("newer"), now + 60_000)));
587        sticky.park(events);
588
589        // The oldest made way.
590        assert!(sticky.take_pending(Some(&BTreeSet::from(["oldest".to_owned()]))).is_empty());
591        assert_eq!(sticky.take_pending(None).len(), MAX_PENDING);
592    }
593
594    #[cfg(feature = "e2e-encryption")]
595    #[async_test]
596    async fn test_expired_pending_events_are_pruned_in_the_background() {
597        let sticky = StickyEvents::new(room_id!("!room:localhost").to_owned());
598
599        sticky.park(vec![pending(Some("session"), now_ms() + 50)]);
600        assert!(sticky.has_pending());
601
602        tokio::time::timeout(Duration::from_secs(5), async {
603            while sticky.has_pending() {
604                tokio::time::sleep(Duration::from_millis(20)).await;
605            }
606        })
607        .await
608        .expect("the pending event should be pruned in time");
609    }
610}