From 4fb1c5a66a7cf6cd85d71bc0d39cb3653eb7724e Mon Sep 17 00:00:00 2001 From: Olivier 'reivilibre Date: Fri, 19 Dec 2025 17:40:40 +0000 Subject: [PATCH] Don't duplicate clamping logic --- synapse/events/__init__.py | 7 ++++++ .../storage/databases/main/sticky_events.py | 23 ++++++++----------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/synapse/events/__init__.py b/synapse/events/__init__.py index d723fa0847..83916211af 100644 --- a/synapse/events/__init__.py +++ b/synapse/events/__init__.py @@ -324,6 +324,13 @@ class EventBase(metaclass=abc.ABCMeta): self._dict = freeze(self._dict) def sticky_duration(self) -> int | None: + """ + Returns the effective sticky duration of this event, or None + if the event does not have a sticky duration. + (Sticky Events are a MSC4354 feature.) + + Clamps the sticky duration to the maximum allowed duration. + """ sticky_obj = self.get_dict().get(StickyEvent.FIELD_NAME, None) if type(sticky_obj) is not dict: return None diff --git a/synapse/storage/databases/main/sticky_events.py b/synapse/storage/databases/main/sticky_events.py index 092b897f8b..03c79f544b 100644 --- a/synapse/storage/databases/main/sticky_events.py +++ b/synapse/storage/databases/main/sticky_events.py @@ -21,7 +21,7 @@ from typing import ( from twisted.internet.defer import Deferred from synapse import event_auth -from synapse.api.constants import EventTypes, StickyEvent +from synapse.api.constants import EventTypes from synapse.api.errors import AuthError from synapse.events import EventBase from synapse.events.snapshot import EventPersistencePair @@ -315,21 +315,16 @@ class StickyEventsWorkerStore(StateGroupWorkerStore, CacheInvalidationWorkerStor # We can't persist outlier sticky events as we don't know the room state at that event if ev.internal_metadata.is_outlier(): continue - # MSC: The presence of sticky.duration_ms with a valid value makes the event “sticky” sticky_duration = ev.sticky_duration() - if sticky_duration: - # MSC: The start time is min(now, origin_server_ts). - # This ensures that malicious origin timestamps cannot specify start times in the future. - # Calculate the end time as start_time + min(sticky.duration_ms, MAX_DURATION_MS). - expires_at = min(ev.origin_server_ts, now_ms) + min( - ev.get_dict()[StickyEvent.FIELD_NAME]["duration_ms"], - StickyEvent.MAX_DURATION_MS, + if sticky_duration is None: + continue + # Calculate the end time as start_time + effecitve sticky duration + expires_at = min(ev.origin_server_ts, now_ms) + sticky_duration + # Filter out already expired sticky events + if expires_at > now_ms: + sticky_events.append( + (ev, expires_at, self._sticky_events_id_gen.get_next_txn(txn)) ) - # filter out already expired sticky events - if expires_at > now_ms: - sticky_events.append( - (ev, expires_at, self._sticky_events_id_gen.get_next_txn(txn)) - ) if len(sticky_events) == 0: return logger.info(