diff --git a/src/app/features/room/RoomOutbox.test.ts b/src/app/features/room/RoomOutbox.test.ts index b2c29b14..55597694 100644 --- a/src/app/features/room/RoomOutbox.test.ts +++ b/src/app/features/room/RoomOutbox.test.ts @@ -8,7 +8,7 @@ describe('outboxView', () => { canResend: false, }); expect(outboxView({ status: 'pending', ts: 100 }, 100 + SLOW_SEND_MS, 0)).toMatchObject({ - label: 'Still sending: slow connection', + label: expect.stringMatching(/^Still sending/), canResend: true, }); expect(outboxView({ status: 'failed', ts: 100, error: 'x' }, 100, 0)).toMatchObject({ @@ -21,4 +21,3 @@ describe('outboxView', () => { expect(outboxView({ status: 'pending', ts: 5 }, 6, 10).label).toMatch(/Interrupted/); }); }); - diff --git a/src/app/features/room/RoomOutbox.tsx b/src/app/features/room/RoomOutbox.tsx index 21c3e224..1e77df43 100644 --- a/src/app/features/room/RoomOutbox.tsx +++ b/src/app/features/room/RoomOutbox.tsx @@ -34,7 +34,11 @@ export const outboxView = ( }; } if (now - entry.ts >= SLOW_SEND_MS) { - return { label: 'Still sending: slow connection', failed: false, canResend: true }; + return { + label: 'Still sending: slow connection (Resend may duplicate it if it lands later)', + failed: false, + canResend: true, + }; } return { label: 'Sending…', failed: false, canResend: false }; }; diff --git a/src/app/state/room/composerStore.test.ts b/src/app/state/room/composerStore.test.ts index 0c4f8ac8..f5a0f35b 100644 --- a/src/app/state/room/composerStore.test.ts +++ b/src/app/state/room/composerStore.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { Descendant } from 'slate'; import { + PAGE_ID, clearDraft, enqueueOutbox, failOutbox, @@ -77,7 +78,7 @@ describe('outbox', () => { const store = memoryStore(); enqueueOutbox('@a:x', entry, 5, store); const after = loadOutbox('@a:x', store); - expect(after).toEqual([{ ...entry, status: 'pending', ts: 5 }]); + expect(after).toEqual([{ ...entry, status: 'pending', ts: 5, tab: PAGE_ID }]); removeOutbox('@a:x', 't1', store); expect(loadOutbox('@a:x', store)).toEqual([]); expect(store.size()).toBe(0); diff --git a/src/app/state/room/composerStore.ts b/src/app/state/room/composerStore.ts index ca1f6bcb..91933d72 100644 --- a/src/app/state/room/composerStore.ts +++ b/src/app/state/room/composerStore.ts @@ -21,8 +21,12 @@ export type OutboxEntry = { status: OutboxStatus; error?: string; ts: number; + /** The page that last sent it: only that page's watchdog may judge it stalled. */ + tab?: string; }; +export const PAGE_ID = Math.random().toString(36).slice(2); + type Store = Pick; const defaultStore = (): Store | undefined => { @@ -92,7 +96,8 @@ export const saveDraft = ( removeKey(store, draftKey(userId, roomId)); return; } - if (!writeJson(store, draftKey(userId, roomId), draft)) removeKey(store, draftKey(userId, roomId)); + if (!writeJson(store, draftKey(userId, roomId), draft)) + removeKey(store, draftKey(userId, roomId)); }; export const clearDraft = ( @@ -139,7 +144,7 @@ export const enqueueOutbox = ( store: Store | undefined = defaultStore() ): void => { const rest = loadOutbox(userId, store).filter((e) => e.txnId !== entry.txnId); - saveOutbox(userId, [...rest, { ...entry, status: 'pending', ts: now }], store); + saveOutbox(userId, [...rest, { ...entry, status: 'pending', ts: now, tab: PAGE_ID }], store); }; export const failOutbox = ( @@ -172,7 +177,7 @@ export const retryOutbox = ( userId, loadOutbox(userId, store).map((e) => e.txnId === txnId - ? { ...e, txnId: newTxnId, status: 'pending', error: undefined, ts: now } + ? { ...e, txnId: newTxnId, status: 'pending', error: undefined, ts: now, tab: PAGE_ID } : e ), store diff --git a/src/app/state/room/outboxSend.ts b/src/app/state/room/outboxSend.ts index 2bea0de7..845e64a0 100644 --- a/src/app/state/room/outboxSend.ts +++ b/src/app/state/room/outboxSend.ts @@ -13,7 +13,12 @@ export const PAGE_START = Date.now(); const attempt = async (mx: MatrixClient, userId: string, entry: OutboxEntry): Promise => { try { - await mx.sendEvent(entry.roomId, (entry.type ?? 'm.room.message') as never, entry.content as never, entry.txnId); + await mx.sendEvent( + entry.roomId, + (entry.type ?? 'm.room.message') as never, + entry.content as never, + entry.txnId + ); removeOutbox(userId, entry.txnId); } catch (e) { // sendEvent can also throw synchronously (e.g. a txn id the SDK already holds) @@ -50,13 +55,15 @@ export const resendTracked = (mx: MatrixClient, entry: OutboxEntry): Promise => { +export const resendInterrupted = ( + mx: MatrixClient, + since: number = PAGE_START +): Promise => { const userId = mx.getUserId() ?? ''; return Promise.all( loadOutbox(userId) diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index 5d8ec8c7..f3bf9e1c 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -20,9 +20,7 @@ export type TUploadItem = { export type TUploadListAtom = ReturnType>; -export const roomIdToUploadItemsAtomFamily = atomFamily( - createListAtom -); +export const roomIdToUploadItemsAtomFamily = atomFamily(createListAtom); export const roomUploadAtomFamily = createUploadAtomFamily(); diff --git a/src/client/initMatrix.test.ts b/src/client/initMatrix.test.ts index 193aa0cb..8db257ea 100644 --- a/src/client/initMatrix.test.ts +++ b/src/client/initMatrix.test.ts @@ -3,9 +3,12 @@ import { RECOVER_RELOAD_MIN_GAP_MS, reloadToRecoverSync } from './initMatrix'; const memory = () => { const m = new Map(); - return { getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => { + return { + getItem: (k: string) => m.get(k) ?? null, + setItem: (k: string, v: string) => { m.set(k, v); - } }; + }, + }; }; describe('reloadToRecoverSync', () => { @@ -13,8 +16,24 @@ describe('reloadToRecoverSync', () => { const store = memory(); const reload = vi.fn(); expect(reloadToRecoverSync(1_000_000, store, reload)).toBe(true); - expect(reloadToRecoverSync(1_000_000 + RECOVER_RELOAD_MIN_GAP_MS - 1, store, reload)).toBe(false); + expect(reloadToRecoverSync(1_000_000 + RECOVER_RELOAD_MIN_GAP_MS - 1, store, reload)).toBe( + false + ); expect(reloadToRecoverSync(1_000_000 + RECOVER_RELOAD_MIN_GAP_MS, store, reload)).toBe(true); expect(reload).toHaveBeenCalledTimes(2); }); }); + +describe('reloadToRecoverSync with unusable storage', () => { + it('refuses instead of throwing when sessionStorage throws', () => { + const reload = vi.fn(); + const broken = { + getItem: () => { + throw new Error('denied'); + }, + setItem: () => undefined, + }; + expect(reloadToRecoverSync(1, broken, reload)).toBe(false); + expect(reload).not.toHaveBeenCalled(); + }); +}); diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 2cb6a203..6c7886ac 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -12,7 +12,7 @@ import { clearNavToActivePathStore } from '../app/state/navToActivePath'; import { pushSessionToSW } from '../sw-session'; import { startResumeSync } from './resumeSync'; import { startWatchdog } from './watchdog'; -import { loadOutbox } from '../app/state/room/composerStore'; +import { PAGE_ID, loadOutbox } from '../app/state/room/composerStore'; import { resendInterrupted } from '../app/state/room/outboxSend'; type Session = { @@ -59,31 +59,38 @@ const startSync = (mx: MatrixClient) => const RECOVER_RELOAD_KEY = 'ratatoskr.recoverReloadAt'; export const RECOVER_RELOAD_MIN_GAP_MS = 60_000; -/** Reload to bring a dead sync back, at most once a minute, so a server that is down cannot loop us. */ +/** Reload to bring a dead connection back, at most once a minute, so a server that is down cannot loop us. */ export const reloadToRecoverSync = ( now: number = Date.now(), store: Pick = sessionStorage, reload: () => void = () => window.location.reload() ): boolean => { - const last = Number(store.getItem(RECOVER_RELOAD_KEY) ?? 0); - if (now - last < RECOVER_RELOAD_MIN_GAP_MS) return false; - store.setItem(RECOVER_RELOAD_KEY, String(now)); + try { + const last = Number(store.getItem(RECOVER_RELOAD_KEY) ?? 0); + if (now - last < RECOVER_RELOAD_MIN_GAP_MS) return false; + store.setItem(RECOVER_RELOAD_KEY, String(now)); + } catch { + return false; + } reload(); return true; }; +const started = new WeakSet(); + export const startClient = async (mx: MatrixClient) => { await startSync(mx); - const recover = () => reloadToRecoverSync(); - startResumeSync(mx, { recover }); + if (started.has(mx)) return; + started.add(mx); + startResumeSync(mx); startWatchdog({ - getSyncState: () => mx.getSyncState(), pendingAges: () => loadOutbox(mx.getUserId() ?? '') - .filter((e) => e.status === 'pending') + .filter((e) => e.status === 'pending' && e.tab === PAGE_ID) .map((e) => Date.now() - e.ts), isVisible: () => document.visibilityState === 'visible', - recover, + isOnline: () => navigator.onLine, + recover: () => reloadToRecoverSync(), }); // What a reload interrupted is sent again once sync is up. const onSync = (state: SyncState) => { @@ -93,7 +100,6 @@ export const startClient = async (mx: MatrixClient) => { }; mx.on(ClientEvent.Sync, onSync); }; - export const clearCacheAndReload = async (mx: MatrixClient) => { mx.stopClient(); clearNavToActivePathStore(mx.getSafeUserId()); diff --git a/src/client/resumeSync.test.ts b/src/client/resumeSync.test.ts index 22347a1f..e90ac6a8 100644 --- a/src/client/resumeSync.test.ts +++ b/src/client/resumeSync.test.ts @@ -1,24 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { HEALTH_CHECK_MS, MIN_HIDDEN_MS, RESUME_DEBOUNCE_MS, startResumeSync } from './resumeSync'; +import { MIN_HIDDEN_MS, RESUME_DEBOUNCE_MS, startResumeSync } from './resumeSync'; class Target extends EventTarget { visibilityState: 'visible' | 'hidden' = 'visible'; } -const setup = (state: string | null = 'SYNCING') => { +const setup = () => { const doc = new Target(); const win = new Target(); - const mx = { - state, - getSyncState: () => mx.state, - retryImmediately: vi.fn(() => true), - }; - const recover = vi.fn(); - const stop = startResumeSync(mx, { - recover, - doc: doc as never, - win: win as never, - }); + const mx = { retryImmediately: vi.fn(() => true) }; + const stop = startResumeSync(mx, { doc: doc as never, win: win as never }); const hide = () => { doc.visibilityState = 'hidden'; doc.dispatchEvent(new Event('visibilitychange')); @@ -27,7 +18,7 @@ const setup = (state: string | null = 'SYNCING') => { doc.visibilityState = 'visible'; doc.dispatchEvent(new Event('visibilitychange')); }; - return { doc, win, mx, recover, stop, hide, show }; + return { doc, win, mx, stop, hide, show }; }; const settle = () => vi.advanceTimersByTimeAsync(RESUME_DEBOUNCE_MS); @@ -55,7 +46,7 @@ describe('startResumeSync', () => { t.hide(); await vi.advanceTimersByTimeAsync(MIN_HIDDEN_MS - 1); t.show(); - await vi.advanceTimersByTimeAsync(RESUME_DEBOUNCE_MS + HEALTH_CHECK_MS); + await vi.advanceTimersByTimeAsync(RESUME_DEBOUNCE_MS); expect(t.mx.retryImmediately).not.toHaveBeenCalled(); }); @@ -67,7 +58,6 @@ describe('startResumeSync', () => { t.win.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true })); await settle(); expect(t.mx.retryImmediately).toHaveBeenCalledTimes(1); - await vi.advanceTimersByTimeAsync(HEALTH_CHECK_MS); t.win.dispatchEvent(new Event('online')); await settle(); expect(t.mx.retryImmediately).toHaveBeenCalledTimes(2); @@ -82,34 +72,14 @@ describe('startResumeSync', () => { expect(t.mx.retryImmediately).toHaveBeenCalledTimes(1); }); - it('does not restart when sync is healthy after the check window', async () => { - for (const state of ['PREPARED', 'SYNCING', 'CATCHUP']) { - const t = setup(state); - t.win.dispatchEvent(new Event('online')); - await vi.advanceTimersByTimeAsync(RESUME_DEBOUNCE_MS + HEALTH_CHECK_MS); - expect(t.recover).not.toHaveBeenCalled(); - t.stop(); - } - }); - - it('calls recover once when sync is still unhealthy, and never stops the client itself', async () => { - const t = setup('RECONNECTING'); - t.win.dispatchEvent(new Event('online')); - await vi.advanceTimersByTimeAsync(RESUME_DEBOUNCE_MS + HEALTH_CHECK_MS); - expect(t.recover).toHaveBeenCalledTimes(1); - expect(t.recover).toHaveBeenCalledWith(t.mx); - expect(Object.keys(t.mx)).not.toContain('stopClient'); - }); - it('removes listeners and cancels pending work on dispose', async () => { - const t = setup('ERROR'); + const t = setup(); t.win.dispatchEvent(new Event('online')); - await settle(); t.stop(); - await vi.advanceTimersByTimeAsync(HEALTH_CHECK_MS); - expect(t.recover).not.toHaveBeenCalled(); + await settle(); + expect(t.mx.retryImmediately).not.toHaveBeenCalled(); t.win.dispatchEvent(new Event('online')); await settle(); - expect(t.mx.retryImmediately).toHaveBeenCalledTimes(1); + expect(t.mx.retryImmediately).not.toHaveBeenCalled(); }); }); diff --git a/src/client/resumeSync.ts b/src/client/resumeSync.ts index 30fbab70..a09f39f8 100644 --- a/src/client/resumeSync.ts +++ b/src/client/resumeSync.ts @@ -1,56 +1,38 @@ /** The slice of MatrixClient this module drives; a MatrixClient satisfies it. */ export type SyncHost = { - getSyncState(): string | null; retryImmediately(): boolean; }; -// matrix-js-sdk SyncState values for a live sync loop. -const HEALTHY: ReadonlySet = new Set(['PREPARED', 'SYNCING', 'CATCHUP']); - export const RESUME_DEBOUNCE_MS = 250; export const MIN_HIDDEN_MS = 5000; -export const HEALTH_CHECK_MS = 3000; -type ResumeSyncOptions = { +type ResumeSyncOptions = { /** Event sources and visibility; default to the browser globals. */ doc?: Pick; win?: Pick; - /** - * Called once when sync is still unhealthy after the nudge. It must not stop and restart the - * client in place: stopClient() closes the rust crypto's OlmMachine for good and startClient() - * does not reopen it, so every later encrypted send fails with "null pointer passed to rust". - * A page reload is the only restart that brings crypto back. - */ - recover: (mx: Host) => void; }; /** * A backgrounded tab or PWA leaves the sync long-poll dead until its 30 s timeout. * On return (visible after a real absence, pageshow from bfcache, online) nudge the - * poll with retryImmediately; if sync is still unhealthy after HEALTH_CHECK_MS, call recover once. Returns a disposer that removes every listener and timer. + * poll with retryImmediately. It never stops and restarts the client: stopClient() closes + * the rust crypto's OlmMachine for good and startClient() does not reopen it. A connection + * that stays dead is the watchdog's business. Returns a disposer that removes every + * listener and timer. */ -export const startResumeSync = ( - mx: Host, - { recover, doc = document, win = window }: ResumeSyncOptions +export const startResumeSync = ( + mx: SyncHost, + { doc = document, win = window }: ResumeSyncOptions = {} ): (() => void) => { let hiddenAt: number | undefined; let debounce: ReturnType | undefined; - let healthCheck: ReturnType | undefined; let disposed = false; - const check = () => { - healthCheck = undefined; - if (disposed || HEALTHY.has(mx.getSyncState())) return; - recover(mx); - }; - const resume = () => { if (debounce !== undefined) clearTimeout(debounce); debounce = setTimeout(() => { debounce = undefined; - if (disposed || healthCheck !== undefined) return; - mx.retryImmediately(); - healthCheck = setTimeout(check, HEALTH_CHECK_MS); + if (!disposed) mx.retryImmediately(); }, RESUME_DEBOUNCE_MS); }; @@ -74,7 +56,6 @@ export const startResumeSync = ( return () => { disposed = true; if (debounce !== undefined) clearTimeout(debounce); - if (healthCheck !== undefined) clearTimeout(healthCheck); doc.removeEventListener('visibilitychange', onVisibility); win.removeEventListener('pageshow', onPageShow); win.removeEventListener('online', resume); diff --git a/src/client/watchdog.test.ts b/src/client/watchdog.test.ts index 4bf9cc2f..7d80f099 100644 --- a/src/client/watchdog.test.ts +++ b/src/client/watchdog.test.ts @@ -1,16 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { SEND_STALL_MS, SYNC_BAD_TICKS, WATCHDOG_INTERVAL_MS, startWatchdog } from './watchdog'; +import { SEND_STALL_MS, WATCHDOG_INTERVAL_MS, startWatchdog } from './watchdog'; const setup = (over: Partial[0]> = {}) => { const recover = vi.fn(); - const o = { - getSyncState: () => 'SYNCING' as string | null, - pendingAges: () => [] as number[], + const stop = startWatchdog({ + pendingAges: () => [], isVisible: () => true, + isOnline: () => true, recover, ...over, - }; - const stop = startWatchdog(o); + }); return { recover, stop }; }; const tick = (n: number) => vi.advanceTimersByTime(WATCHDOG_INTERVAL_MS * n); @@ -23,14 +22,14 @@ describe('watchdog', () => { vi.useRealTimers(); }); - it('stays quiet while sync is healthy and nothing is pending', () => { + it('stays quiet while nothing is pending', () => { const t = setup(); tick(100); expect(t.recover).not.toHaveBeenCalled(); t.stop(); }); - it('recovers when a send has been pending past the stall threshold', () => { + it('recovers when a send has been pending past the stall threshold, not before', () => { let age = 0; const t = setup({ pendingAges: () => [age] }); age = SEND_STALL_MS - 1; @@ -42,36 +41,14 @@ describe('watchdog', () => { t.stop(); }); - it.each(['ERROR', 'STOPPED'])('recovers when sync sits in %s for the bad-tick count, not before', (state) => { - const t = setup({ getSyncState: () => state }); - tick(SYNC_BAD_TICKS - 1); - expect(t.recover).not.toHaveBeenCalled(); - tick(1); - expect(t.recover).toHaveBeenCalledTimes(1); - t.stop(); - }); - - it('a recovered sync resets the count; RECONNECTING and a null state are js-sdk working, not bad', () => { - let state: string | null = 'ERROR'; - const t = setup({ getSyncState: () => state }); - tick(SYNC_BAD_TICKS - 1); - state = 'SYNCING'; - tick(1); - state = 'ERROR'; - tick(SYNC_BAD_TICKS - 1); - state = 'RECONNECTING'; + it('does nothing while the page is hidden or offline', () => { + const hidden = setup({ isVisible: () => false, pendingAges: () => [1e9] }); + const offline = setup({ isOnline: () => false, pendingAges: () => [1e9] }); tick(50); - state = null; - tick(50); - expect(t.recover).not.toHaveBeenCalled(); - t.stop(); - }); - - it('does nothing while the page is hidden', () => { - const t = setup({ isVisible: () => false, pendingAges: () => [1e9], getSyncState: () => 'STOPPED' }); - tick(50); - expect(t.recover).not.toHaveBeenCalled(); - t.stop(); + expect(hidden.recover).not.toHaveBeenCalled(); + expect(offline.recover).not.toHaveBeenCalled(); + hidden.stop(); + offline.stop(); }); it('stop() ends it', () => { diff --git a/src/client/watchdog.ts b/src/client/watchdog.ts index f5ea86f8..6b97e8fc 100644 --- a/src/client/watchdog.ts +++ b/src/client/watchdog.ts @@ -1,48 +1,37 @@ /** - * The page can go on looking alive while its connection is dead: sync polls get cut by their - * own timeout, and a send has no timeout at all, so it hangs unsent while its echo sits in the - * composer's room. This notices the two signs and calls `recover` (a guarded reload; the - * outbox then resends what was interrupted). - * - a send pending past `stallMs` - * - sync stuck in ERROR or STOPPED for `syncBadTicks` consecutive ticks - * Nothing fires while the page is hidden: a frozen background tab is not a dead connection. + * The page can go on looking alive while its connection is dead: sync polls are cut by their + * own timeout and js-sdk retries them, but a send has no timeout at all, so on a half-open + * connection it hangs SENDING and no request reaches the server. A send pending past + * `stallMs` is the sign, and `recover` (a guarded reload) the answer; the outbox then sends + * again what the reload interrupted. Sync state is not watched: ERROR is also what offline + * looks like, and js-sdk recovers from that itself. + * Nothing fires while the page is hidden (a frozen tab is not a dead connection) or offline + * (a reload there only blanks the page). */ export type WatchdogOptions = { - getSyncState: () => string | null; - /** Ages in ms of sends still pending. */ + /** Ages in ms of this page's sends still pending. */ pendingAges: () => number[]; isVisible: () => boolean; + isOnline: () => boolean; recover: () => void; intervalMs?: number; stallMs?: number; - syncBadTicks?: number; }; export const WATCHDOG_INTERVAL_MS = 5000; export const SEND_STALL_MS = 20_000; -export const SYNC_BAD_TICKS = 6; export const startWatchdog = ({ - getSyncState, pendingAges, isVisible, + isOnline, recover, intervalMs = WATCHDOG_INTERVAL_MS, stallMs = SEND_STALL_MS, - syncBadTicks = SYNC_BAD_TICKS, }: WatchdogOptions): (() => void) => { - let badTicks = 0; const id = setInterval(() => { - if (!isVisible()) { - badTicks = 0; - return; - } - const state = getSyncState(); - badTicks = state === 'ERROR' || state === 'STOPPED' ? badTicks + 1 : 0; - if (badTicks >= syncBadTicks || pendingAges().some((age) => age >= stallMs)) { - badTicks = 0; - recover(); - } + if (!isVisible() || !isOnline()) return; + if (pendingAges().some((age) => age >= stallMs)) recover(); }, intervalMs); return () => clearInterval(id); };