/* Copyright 2026 Element Creations Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { MatrixEvent } from "../models/event.ts"; import { RoomEvent, type Room } from "./room.ts"; import { RoomStateEvent } from "./room-state.ts"; import { type Logger, logger as rootLogger } from "../logger.ts"; import { EventType } from "../@types/event.ts"; import type { RetentionPolicyService } from "../retentionPolicy.ts"; import type { IStore } from "../store/index.ts"; import { ROOM_RETENTION_TYPE, type RoomRetentionContent } from "../@types/retention.ts"; /** * The largest delay `setTimeout` accepts (2^31 - 1 ms, ~24.8 days). Larger values overflow * and cause the callback to fire immediately. */ const MAX_TIMEOUT_MS = 2 ** 31 - 1; /** * Whether a retention policy with the given maximum lifetime keeps an event. * * Only messages expire. Dropping an old state event as it loads would leave it out of the room * state, and the room would show an outdated name, topic or membership. Redactions are kept too, * as the expiry sweep in {@link RoomRetentionPolicy} already did. */ function isRetainedUnder(ev: MatrixEvent, maxRetention: number | null): boolean { if (!maxRetention || ev.isState() || ev.isRedaction()) return true; return ev.getTs() > Date.now() - maxRetention; } /** * Applies https://github.com/matrix-org/matrix-spec-proposals/pull/1763 by checking the current * state of the room and applying the *latest* retention policy to all preceeding events. * Currently does not: * - Apply global server policies (requires Synapse work) * - React at all to `min_retention` configs. * - Loop */ export class RoomRetentionPolicy { // minRetention is not implemented. private maxRetention: number | null = null; private retentionTimeout?: ReturnType; private disposed = false; private readonly logger: Logger; public constructor( private readonly room: Room, private readonly retentionService: RetentionPolicyService, private readonly store: IStore, ) { this.logger = rootLogger.getChild(`RetentionPolicy ${room.roomId}`); // Recalculate on room state update. room.on(RoomStateEvent.Events, this.onRoomStateEvent); // Recalculate our retention whenever the global policy changes. this.retentionService.on("update", this.onRetentionServiceUpdate); // Do an initial check on construction. This also binds RoomEvent.Timeline if there is a policy. this.handleRetentionUpdate(); } /** * Stop applying the retention policy: cancels any pending expiry check and removes all listeners. * The instance must not be used after this is called. */ public dispose(): void { this.disposed = true; this.room.off(RoomStateEvent.Events, this.onRoomStateEvent); this.room.off(RoomEvent.Timeline, this.timelineUpdated); this.retentionService.off("update", this.onRetentionServiceUpdate); clearTimeout(this.retentionTimeout); this.retentionTimeout = undefined; } private readonly onRoomStateEvent = (event: MatrixEvent): void => { if ( event.getStateKey() !== "" || (event.getType() !== "org.matrix.msc1763.retention" && event.getType() !== "m.room.retention") ) { return; } this.handleRetentionUpdate(); }; private readonly onRetentionServiceUpdate = (): void => { this.logger.info("Got global retention policy update!"); this.handleRetentionUpdate(); }; /** * Whether the room's current retention policy keeps an event. State events and redactions are * always kept: only messages expire. */ public shouldEventBeRetained(ev: MatrixEvent): boolean { return isRetainedUnder(ev, this.maxRetention); } private readonly handleRetentionUpdate = (): void => { if (this.disposed) return; // First store if we currently have a retention period. const hadRetentionPeriod = this.maxRetention !== null; try { this.maxRetention = this.computeMaxRetention(this.getRoomStatePolicy()); } catch (err) { this.logger.warn("Failed to recalculate retention policy", err); return; } // Bind/unbind the Timeline event handler based on whether we should be running retention. // This must not wait: a sync applies the room state and adds the timeline events straight // after, and those events are what schedule the next expiry. Binding later left messages on // screen past their lifetime after a reload, until some other event arrived in the room. if (hadRetentionPeriod !== (this.maxRetention !== null)) { this.logger.info("retention recalculated to be", this.maxRetention); if (this.maxRetention) { this.room.on(RoomEvent.Timeline, this.timelineUpdated); } else { this.room.off(RoomEvent.Timeline, this.timelineUpdated); } } this.processTimeline(); }; /** * The retention policy set in the room state, preferring `m.room.retention` over the unstable type. */ private getRoomStatePolicy(): RoomRetentionContent | undefined { const policyEvent = this.room.currentState.getStateEvents(ROOM_RETENTION_TYPE.name, "") ?? this.room.currentState.getStateEvents(ROOM_RETENTION_TYPE.altName, ""); return policyEvent?.getContent(); } /** * Work out the effective maximum lifetime of messages in the room, in milliseconds, or `null` when * messages are kept forever. * * @param roomStatePolicy - The policy set in the room state, if any. * @throws If the policy's `max_lifetime` is not a non-negative integer. */ private computeMaxRetention(roomStatePolicy: RoomRetentionContent | undefined): number | null { const serverPolicy = this.retentionService.getCached(); const serverRoomPolicy = serverPolicy?.policies?.[this.room.roomId]; const content = // * if the homeserver defines a specific retention policy for this room, then use this policy as the effective retention policy of the room. serverRoomPolicy ?? // * otherwise, if the state of the room includes a `m.room.retention` event with an empty state key: roomStatePolicy ?? // * otherwise, if the state of the room does not include a m.room.retention event with an empty state key: serverPolicy?.policies?.["*"]; if (!content) { // * otherwise, don't apply a retention policy in this room. return null; } const validatePolicy = !serverRoomPolicy && roomStatePolicy; // Parse it let { max_lifetime: maxLifetime } = content; if (!maxLifetime && validatePolicy) { // if there is no value specified in the room's state, use the limit's min value for the effective retention policy of the room (which can be null or absent). maxLifetime = serverPolicy?.limits?.max_lifetime?.min; if (!maxLifetime) { return null; } } if (typeof maxLifetime !== "number") { throw Error(`max_lifetime must be a number, got "${maxLifetime}"`); } if (maxLifetime < 0 || !Number.isInteger(maxLifetime)) { throw Error(`max_lifetime must be >= 0, got ${maxLifetime}`); } if (validatePolicy && serverPolicy?.limits?.max_lifetime) { // We're using room state so we need to validate this policy matches the server. /** if the value specified in the room's state complies with the limit, use this value for the effective retention policy of the room. if the value specified in the room's state is lower than the limit's min value, use the min value for the effective retention policy of the room. if the value specified in the room's state is greater than the limit's max value, use the max value for the effective retention policy of the room. */ maxLifetime = Math.max(maxLifetime, serverPolicy.limits.max_lifetime.min ?? 0); maxLifetime = Math.min(maxLifetime, serverPolicy.limits.max_lifetime.max ?? Number.MAX_SAFE_INTEGER); } return maxLifetime; } private readonly timelineUpdated = (): void => { this.logger.info("timelineUpdated"); this.scheduleTimelineCheck(200); }; private readonly scheduleTimelineCheck = (nextTs: number): void => { if (this.retentionTimeout) { clearTimeout(this.retentionTimeout); } this.retentionTimeout = setTimeout( () => { this.retentionTimeout = undefined; this.processTimeline(); }, Math.min(nextTs, MAX_TIMEOUT_MS), ); }; /** * Every event the room has loaded: all timelines of every timeline set, including the ones * left behind by a permalink jump, and every thread's timelines. Thread replies only live in * their thread's timelines, so looking at the live timeline alone would never expire them. */ private getLoadedEvents(): MatrixEvent[] { const timelineSets = [ ...this.room.getTimelineSets(), ...this.room.getThreads().map((thread) => thread.timelineSet), ]; const events = new Set(); for (const timelineSet of timelineSets) { for (const timeline of timelineSet.getTimelines()) { for (const event of timeline.getEvents()) events.add(event); } } return [...events]; } private processTimeline(): void { if (this.disposed || !this.maxRetention) { return; // No policy, skip. } this.logger.info(`Running processTimeline`); const expireBefore = Date.now() - this.maxRetention; const events = this.getLoadedEvents().filter( (ev) => ev.getStateKey() === undefined && !ev.isRedacted() && ev.getType() !== "m.room.redaction", ); const expiredEvents = events.filter((ev) => ev.getTs() < expireBefore); const [earliestExpiringEvent] = events .filter((ev) => ev.getTs() >= expireBefore) .sort((a, b) => a.getTs() - b.getTs()); if (earliestExpiringEvent) { const nextTs = earliestExpiringEvent.getTs() + this.maxRetention - Date.now(); this.logger.info(`Next expiry scheduled for ${nextTs}`); this.scheduleTimelineCheck(nextTs); } if (expiredEvents.length === 0) { this.logger.info("Found no expired events"); return; } this.logger.info(`Found ${expiredEvents.length} expired events`); for (const event of expiredEvents) { this.room.tryApplyRedaction( new MatrixEvent({ type: EventType.RoomRedaction, sender: event.getSender(), event_id: "$synthetic_redaction", room_id: this.room.roomId, redacts: event.getId(), content: { reason: "Retention policy", }, origin_server_ts: Date.now(), unsigned: {}, }), ); } void this.store .removeEventsFromRoom( this.room.roomId, expiredEvents.map((e) => e.getId()!), ) .catch((ex) => { this.logger.warn(`Failed to remove events from store`, ex); }); } }