feat: persist room timeline to IndexedDB before pruning from memory

This commit is contained in:
Evie Gauthier committed 2026-03-17 18:22:14 -04:00
1 parent 67c626c6b2
commit 023bf2a325
2 files changed
+109 -12

No files matched your search

+43 -6
View File
@@ -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<void> =>
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<string, unknown> = {}) {
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<typeof vi.fn>; save: ReturnType<typeof vi.fn> };
};
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<string, { timeline: { limited: boolean } }> } },
];
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) });
+66 -6
View File
@@ -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<void> {
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);
}