From 023bf2a325744ea98f517e93e834d5c7802ec52e Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 18:22:14 -0400 Subject: [PATCH] feat: persist room timeline to IndexedDB before pruning from memory --- src/client/slidingSync.test.ts | 49 ++++++++++++++++++++--- src/client/slidingSync.ts | 72 +++++++++++++++++++++++++++++++--- 2 files changed, 109 insertions(+), 12 deletions(-) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 27f267cf..01560d14 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -8,14 +8,19 @@ * * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room transitions * from active to background, its in-memory event chain is released if it - * exceeds PRUNE_TIMELINE_THRESHOLD. Sliding sync does not persist timeline - * events to IndexedDB, so the pruned events are gone from memory. On next - * open the active-room subscription re-fetches the latest events from the - * server. + * exceeds PRUNE_TIMELINE_THRESHOLD. The recent tail is persisted to + * IndexedDB (via store.setSyncData + store.save) so the events survive an + * app reload; the full history is always available from the server. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; +/** Flush all pending Promise microtasks. */ +const flushPromises = (): Promise => + new Promise((r) => { + setTimeout(r, 0); + }); + // ── vi.hoisted mocks ───────────────────────────────────────────────────────── // Must be defined via vi.hoisted so they're available before vi.mock runs // (vi.mock calls are hoisted above all imports by vitest's transformer). @@ -72,16 +77,26 @@ function makeMockMx(overrides: Record = {}) { getRoom: vi.fn().mockReturnValue(null), on: vi.fn(), off: vi.fn(), + store: { + setSyncData: vi.fn().mockResolvedValue(undefined), + save: vi.fn().mockResolvedValue(undefined), + }, ...overrides, } as unknown as import('$types/matrix-sdk').MatrixClient; } function makeMockRoom(eventCount: number) { - const events = Array.from({ length: eventCount }, (_, i) => ({ getId: () => `$ev${i}` })); + const events = Array.from({ length: eventCount }, (_, i) => ({ + getId: () => `$ev${i}`, + event: { event_id: `$ev${i}`, type: 'm.room.message', content: {} }, + })); const resetLiveTimeline = vi.fn(); return { getUnfilteredTimelineSet: vi.fn().mockReturnValue({ - getLiveTimeline: vi.fn().mockReturnValue({ getEvents: vi.fn().mockReturnValue(events) }), + getLiveTimeline: vi.fn().mockReturnValue({ + getEvents: vi.fn().mockReturnValue(events), + getPaginationToken: vi.fn().mockReturnValue('t123'), + }), resetLiveTimeline, }), _resetLiveTimeline: resetLiveTimeline, @@ -123,6 +138,28 @@ describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); }); + it('persists events to store.setSyncData and store.save after pruning', async () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + + manager.unsubscribeFromRoom('!room:example.com'); + await flushPromises(); + + const { store } = mx as unknown as { + store: { setSyncData: ReturnType; save: ReturnType }; + }; + expect(store.setSyncData).toHaveBeenCalledOnce(); + expect(store.save).toHaveBeenCalledWith(true); + + // The payload must target the correct room and use limited:true so the + // accumulator replaces any stale timeline rather than appending. + const [payload] = store.setSyncData.mock.calls[0] as [ + { rooms: { join: Record } }, + ]; + expect(payload.rooms.join['!room:example.com'].timeline.limited).toBe(true); + }); + it('does not reset when event count equals the threshold exactly', () => { const room = makeMockRoom(PRUNE_THRESHOLD); const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 8f1f2158..0c7c86bc 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -1,8 +1,12 @@ /* eslint-disable max-classes-per-file */ import { ClientEvent, + EventTimeline, Extension, ExtensionState, + IJoinedRoom, + IRoomEvent, + ISyncResponse, MatrixClient, MSC3575List, MSC3575RoomData, @@ -54,7 +58,6 @@ const ACTIVE_ROOM_TIMELINE_LIMIT_LOW = 50; const ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM = 100; const ACTIVE_ROOM_TIMELINE_LIMIT_HIGH = 150; // Rooms with more than this many events in memory are pruned when they go inactive. -// The full history remains on disk (IndexedDBStore); it is re-loaded on next open. const PRUNE_TIMELINE_THRESHOLD = ACTIVE_ROOM_TIMELINE_LIMIT_HIGH; export type PartialSlidingSyncRequest = { @@ -625,23 +628,80 @@ export class SlidingSyncManager { * freeing its in-memory event chain. Only fires when the room has accumulated * more than PRUNE_TIMELINE_THRESHOLD events. * - * Note: sliding sync does not write timeline events to IndexedDBStore, so - * there is no on-disk copy of the pruned events. The full history is still - * available on the server; on next open the active-room subscription - * re-fetches the latest timeline_limit events. + * The timeline is reset synchronously so memory is freed immediately. Then, + * as a best-effort fire-and-forget step, the snapshot of recent events is + * fed into the SyncAccumulator and flushed to IndexedDB so they survive an + * app reload (the accumulator caps storage at ~50 events per room; the full + * history is always available from the server). */ private pruneRoomTimeline(roomId: string): void { const room = this.mx.getRoom(roomId); if (!room) return; const tl = room.getUnfilteredTimelineSet().getLiveTimeline(); - if (tl.getEvents().length <= PRUNE_TIMELINE_THRESHOLD) return; + const events = tl.getEvents(); + if (events.length <= PRUNE_TIMELINE_THRESHOLD) return; + + // Capture the back-pagination token before resetting the timeline. + const prevBatch = tl.getPaginationToken(EventTimeline.BACKWARDS); + + // Free the in-memory event chain immediately. room.getUnfilteredTimelineSet().resetLiveTimeline(); + + // Persist the tail of the timeline to IndexedDB asynchronously. + // If it fails, the events are still available from the server. + this.persistRoomTimeline( + roomId, + events.map((e) => e.event as IRoomEvent), + prevBatch + ).catch((err: unknown) => { + debugLog.warn('timeline', 'Failed to persist pruned room timeline', { roomId, err }); + }); + debugLog.info('timeline', 'Pruned room timeline from memory', { roomId, threshold: PRUNE_TIMELINE_THRESHOLD, }); } + /** + * Persist a snapshot of room timeline events to the IndexedDB store via a + * synthetic /sync payload. This feeds the SyncAccumulator (which the SDK + * uses for both start-up replay and classic sync persistence) so that the + * last ~50 events are available on the next app load without a server round- + * trip. The sliding sync layer never calls setSyncData itself, so this is + * the only path by which sliding-sync rooms get on-disk history. + */ + private async persistRoomTimeline( + roomId: string, + rawEvents: IRoomEvent[], + prevBatch: string | null + ): Promise { + const payload: ISyncResponse = { + next_batch: '', + account_data: { events: [] }, + rooms: { + join: { + [roomId]: { + summary: {}, + timeline: { + events: rawEvents, + limited: true, + prev_batch: prevBatch, + }, + ephemeral: { events: [] }, + account_data: { events: [] }, + unread_notifications: {}, + } as unknown as IJoinedRoom, + }, + invite: {}, + leave: {}, + knock: {}, + }, + }; + await this.mx.store.setSyncData(payload); + await this.mx.store.save(true); + } + public setPresenceEnabled(enabled: boolean): void { this.presenceExtension.setEnabled(enabled); }