fix(unread): flush the sync store when the app is hidden or closed

This commit is contained in:
Erwan Leboucher committed 2026-08-17 22:14:27 +02:00
1 parent 5c94cef1ac
commit f7117e7eaa
6 files changed
+477

No files matched your search

+1
View File
@@ -157,6 +157,7 @@
"@vitest/ui": "^4.1.10",
"buffer": "^6.0.3",
"cloudflared": "^0.7.1",
"fake-indexeddb": "^6.2.5",
"jsdom": "^29.1.1",
"knip": "6.32.1",
"oxfmt": "^0.57.0",
+9
View File
@@ -362,6 +362,9 @@ importers:
cloudflared:
specifier: ^0.7.1
version: 0.7.1
fake-indexeddb:
specifier: ^6.2.5
version: 6.2.5
jsdom:
specifier: ^29.1.1
version: 29.1.1(@noble/[email protected])
@@ -3961,6 +3964,10 @@ packages:
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
engines: {node: '>=12.0.0'}
[email protected]:
resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
@@ -9273,6 +9280,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
+3
View File
@@ -41,6 +41,7 @@ import {
} from './slidingSync';
import { PresenceSyncManager } from './presenceSync';
import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache';
import { disposeSyncStorePersistence, installSyncStorePersistence } from './syncStorePersistence';
import { clearCachedUserProfiles } from './userProfileCache';
import {
clearLocalNotificationCache,
@@ -570,6 +571,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig):
}),
{ transport: useSliding ? 'sliding' : 'classic' }
);
if (!useSliding) installSyncStorePersistence(mx);
if (manager && (await manager.waitForSidebarCacheHydration())) {
config?.onCachedRoomsLoaded?.();
}
@@ -592,6 +594,7 @@ export const stopClient = (mx: MatrixClient): void => {
log.log('stopClient', mx.getUserId());
debugLog.info('sync', 'Stopping client', { userId: mx.getUserId() });
slidingSyncRequestCleanupByClient.get(mx)?.();
disposeSyncStorePersistence(mx);
disposeSlidingSync(mx);
disposePresenceSync(mx);
mx.stopClient();
@@ -0,0 +1,140 @@
import 'fake-indexeddb/auto';
import { EventEmitter } from 'events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { MatrixClient } from '$types/matrix-sdk';
import { IndexedDBStore, RoomEvent } from '$types/matrix-sdk';
import { disposeSyncStorePersistence, installSyncStorePersistence } from './syncStorePersistence';
const USER_ID = '@me:example.org';
const ROOM_ID = '!room:example.org';
type SyncOptions = { nextBatch: string; notificationCount: number; readReceiptFor?: string };
const syncResponse = ({ nextBatch, notificationCount, readReceiptFor }: SyncOptions) => ({
next_batch: nextBatch,
account_data: { events: [] },
presence: { events: [] },
rooms: {
join: {
[ROOM_ID]: {
timeline: {
events: [
{
event_id: '$msg',
type: 'm.room.message',
sender: '@them:example.org',
content: { msgtype: 'm.text', body: 'hi' },
origin_server_ts: 1000,
},
],
prev_batch: 'p1',
limited: false,
},
state: { events: [] },
account_data: { events: [] },
ephemeral: {
events: readReceiptFor
? [
{
type: 'm.receipt',
content: { [readReceiptFor]: { 'm.read': { [USER_ID]: { ts: 2000 } } } },
},
]
: [],
},
unread_notifications: { notification_count: notificationCount, highlight_count: 0 },
},
},
invite: {},
leave: {},
},
});
const openStore = (dbName: string) =>
new IndexedDBStore({ indexedDB: globalThis.indexedDB, localStorage, dbName });
const readBackSnapshot = async (dbName: string) => {
const store = openStore(dbName);
await store.startup();
const saved = await store.getSavedSync();
const room = saved?.roomsData.join[ROOM_ID];
await store.destroy();
return {
notificationCount: room?.unread_notifications?.notification_count,
receipts: room?.ephemeral?.events ?? [],
};
};
const fakeClient = (store: IndexedDBStore) =>
Object.assign(new EventEmitter(), {
store,
getUserId: () => USER_ID,
}) as unknown as MatrixClient;
let dbName = '';
let liveStore: IndexedDBStore | undefined;
let liveClient: MatrixClient | undefined;
beforeEach(async () => {
dbName = `sync-store-${Math.random().toString(16).slice(2)}`;
liveStore = openStore(dbName);
await liveStore.startup();
liveClient = fakeClient(liveStore);
installSyncStorePersistence(liveClient);
// The state a running client already had on disk before the room was read.
await liveStore.setSyncData(syncResponse({ nextBatch: 's1', notificationCount: 3 }) as never);
await liveStore.save(true);
// Reading the room: the server echoes the receipt and a cleared count, but
// the sync loop will not write it for another five minutes.
await liveStore.setSyncData(
syncResponse({ nextBatch: 's2', notificationCount: 0, readReceiptFor: '$msg' }) as never
);
});
afterEach(async () => {
if (liveClient) disposeSyncStorePersistence(liveClient);
await liveStore?.destroy();
liveStore = undefined;
liveClient = undefined;
});
describe('sync store persistence across a restart', () => {
it('restores the pre-read snapshot when nothing flushes the store', async () => {
const snapshot = await readBackSnapshot(dbName);
expect(snapshot.notificationCount).toBe(3);
expect(snapshot.receipts).toEqual([]);
});
it('restores the read state after the app is hidden', async () => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: () => 'hidden',
});
document.dispatchEvent(new Event('visibilitychange'));
await vi.waitFor(async () => {
expect((await readBackSnapshot(dbName)).notificationCount).toBe(0);
});
const snapshot = await readBackSnapshot(dbName);
expect(snapshot.receipts).toHaveLength(1);
});
it('restores the read state once our own receipt settles, without any hide', async () => {
vi.useFakeTimers();
try {
(liveClient as unknown as EventEmitter).emit(RoomEvent.Receipt, {
getContent: () => ({ $msg: { 'm.read': { [USER_ID]: { ts: 2000 } } } }),
});
await vi.advanceTimersByTimeAsync(60000);
} finally {
vi.useRealTimers();
}
await vi.waitFor(async () => {
expect((await readBackSnapshot(dbName)).notificationCount).toBe(0);
});
});
});
+237
View File
@@ -0,0 +1,237 @@
import { EventEmitter } from 'events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk';
import { RoomEvent } from '$types/matrix-sdk';
import { disposeSyncStorePersistence, installSyncStorePersistence } from './syncStorePersistence';
const USER_ID = '@me:example.org';
const receipt = (userId: string): MatrixEvent =>
({
getContent: () => ({
$event: { 'm.read': { [userId]: { ts: 1 } } },
}),
}) as unknown as MatrixEvent;
const setVisibility = (state: DocumentVisibilityState) => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: () => state,
});
};
const hide = () => {
setVisibility('hidden');
document.dispatchEvent(new Event('visibilitychange'));
};
const show = () => {
setVisibility('visible');
document.dispatchEvent(new Event('visibilitychange'));
};
const saveMock = () => vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
const fakeClient = (save = saveMock(), userId: string | null = USER_ID) => {
const emitter = new EventEmitter();
return Object.assign(emitter, {
store: { save },
getUserId: () => userId,
}) as unknown as MatrixClient;
};
const emitReceipt = (mx: MatrixClient, userId = USER_ID) => {
(mx as unknown as EventEmitter).emit(RoomEvent.Receipt, receipt(userId));
};
const clients: MatrixClient[] = [];
const install = (mx: MatrixClient) => {
clients.push(mx);
installSyncStorePersistence(mx);
};
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
setVisibility('visible');
});
afterEach(() => {
clients.splice(0).forEach(disposeSyncStorePersistence);
vi.useRealTimers();
});
describe('installSyncStorePersistence', () => {
it('forces a store write when the app is hidden', () => {
const save = saveMock();
install(fakeClient(save));
hide();
expect(save).toHaveBeenCalledExactlyOnceWith(true);
});
it('forces a store write when the page goes away', () => {
const save = saveMock();
install(fakeClient(save));
window.dispatchEvent(new Event('pagehide'));
expect(save).toHaveBeenCalledExactlyOnceWith(true);
});
it('does not write while the app stays visible', () => {
const save = saveMock();
install(fakeClient(save));
show();
expect(save).not.toHaveBeenCalled();
});
it('throttles bursts of hide events', async () => {
const save = saveMock();
install(fakeClient(save));
hide();
await vi.advanceTimersByTimeAsync(0);
show();
hide();
expect(save).toHaveBeenCalledTimes(1);
});
it('writes again once the throttle window has passed', async () => {
const save = saveMock();
install(fakeClient(save));
hide();
await vi.advanceTimersByTimeAsync(5000);
show();
hide();
expect(save).toHaveBeenCalledTimes(2);
});
it('does not stack writes while one is in flight', async () => {
let release: (() => void) | undefined;
const save = vi.fn<() => Promise<void>>().mockReturnValue(
new Promise<void>((resolve) => {
release = resolve;
})
);
install(fakeClient(save));
hide();
await vi.advanceTimersByTimeAsync(6000);
show();
hide();
expect(save).toHaveBeenCalledTimes(1);
release?.();
await vi.advanceTimersByTimeAsync(6000);
show();
hide();
expect(save).toHaveBeenCalledTimes(2);
});
it('swallows a failed write', async () => {
const save = vi.fn<() => Promise<void>>().mockRejectedValue(new Error('quota exceeded'));
install(fakeClient(save));
hide();
await vi.advanceTimersByTimeAsync(6000);
show();
hide();
expect(save).toHaveBeenCalledTimes(2);
});
it('stops writing after dispose', () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
disposeSyncStorePersistence(mx);
hide();
window.dispatchEvent(new Event('pagehide'));
expect(save).not.toHaveBeenCalled();
});
it('writes after our own receipt settles', async () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
emitReceipt(mx);
expect(save).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(60000);
expect(save).toHaveBeenCalledExactlyOnceWith(true);
});
it('coalesces a burst of receipts into one write', async () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
emitReceipt(mx);
await vi.advanceTimersByTimeAsync(30000);
emitReceipt(mx);
await vi.advanceTimersByTimeAsync(30000);
expect(save).toHaveBeenCalledTimes(1);
});
it('ignores receipts from other users', async () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
emitReceipt(mx, '@someone:example.org');
await vi.advanceTimersByTimeAsync(60000);
expect(save).not.toHaveBeenCalled();
});
it('retries when the receipt write lands inside the throttle window', async () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
emitReceipt(mx);
await vi.advanceTimersByTimeAsync(59000);
hide();
expect(save).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1000);
expect(save).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(60000);
expect(save).toHaveBeenCalledTimes(2);
});
it('drops a pending receipt write after dispose', async () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
emitReceipt(mx);
disposeSyncStorePersistence(mx);
await vi.advanceTimersByTimeAsync(60000);
expect(save).not.toHaveBeenCalled();
});
it('does not double-register when installed twice', () => {
const save = saveMock();
const mx = fakeClient(save);
install(mx);
install(mx);
hide();
expect(save).toHaveBeenCalledTimes(1);
});
});
+87
View File
@@ -0,0 +1,87 @@
import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk';
import { RoomEvent } from '$types/matrix-sdk';
import { createDebugLogger } from '$utils/debugLogger';
const debugLog = createDebugLogger('syncStorePersistence');
// The sync loop writes the store at most once every five minutes, so read
// receipts, m.fully_read and refreshed notification counts learned since the
// last write are lost on close and the next startup restores a snapshot from
// before those rooms were read.
const MIN_FLUSH_INTERVAL_MS = 5000;
// Our receipt only reaches the store once /sync echoes it back, and a write
// serialises the whole accumulator, so trail it.
const RECEIPT_FLUSH_DELAY_MS = 60000;
const cleanupByClient = new WeakMap<MatrixClient, () => void>();
type ReceiptContent = Record<string, Record<string, Record<string, unknown>>>;
const hasOwnReceipt = (event: MatrixEvent, userId: string): boolean =>
Object.values(event.getContent<ReceiptContent>()).some((byReceiptType) =>
Object.values(byReceiptType).some((byUser) => userId in byUser)
);
export const installSyncStorePersistence = (mx: MatrixClient): void => {
cleanupByClient.get(mx)?.();
let lastFlushTs = 0;
let flushing = false;
let receiptTimer: ReturnType<typeof globalThis.setTimeout> | undefined;
const flush = (): boolean => {
const now = Date.now();
if (flushing || now - lastFlushTs < MIN_FLUSH_INTERVAL_MS) return false;
flushing = true;
lastFlushTs = now;
void mx.store
.save(true)
.catch((error: unknown) => {
debugLog.warn('sync', 'Failed to flush sync store', {
error: error instanceof Error ? error.message : String(error),
});
})
.finally(() => {
flushing = false;
});
return true;
};
const scheduleReceiptFlush = () => {
if (receiptTimer !== undefined) return;
receiptTimer = globalThis.setTimeout(() => {
receiptTimer = undefined;
if (!flush()) scheduleReceiptFlush();
}, RECEIPT_FLUSH_DELAY_MS);
};
const onVisibilityChange = () => {
if (document.visibilityState === 'hidden') flush();
};
const onPageHide = () => {
flush();
};
const onReceipt = (event: MatrixEvent) => {
const userId = mx.getUserId();
if (!userId || !hasOwnReceipt(event, userId)) return;
scheduleReceiptFlush();
};
document.addEventListener('visibilitychange', onVisibilityChange);
window.addEventListener('pagehide', onPageHide);
mx.on(RoomEvent.Receipt, onReceipt);
cleanupByClient.set(mx, () => {
if (receiptTimer !== undefined) globalThis.clearTimeout(receiptTimer);
document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('pagehide', onPageHide);
mx.removeListener(RoomEvent.Receipt, onReceipt);
cleanupByClient.delete(mx);
});
};
export const disposeSyncStorePersistence = (mx: MatrixClient): void => {
cleanupByClient.get(mx)?.();
};