watchdog: send stall only, own-page entries, online only; resume sync nudges and never restarts

Soul pass on 77edebff: the watchdog no longer counts interrupted entries from
a previous page (reload loop at startup), no longer reloads on sync ERROR/STOPPED
(js-sdk recovers offline by itself) or while offline, refuses instead of
throwing when sessionStorage is unusable, startClient is idempotent, and the
slow-send label says Resend may duplicate. resumeSync drops its health check
and recover hook: nudge only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Void 2026-11-12 21:34:21 +00:00
commit 69d752ff0b
12 changed files with 112 additions and 156 deletions

View file

@ -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/);
});
});

View file

@ -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 };
};

View file

@ -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);

View file

@ -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<Storage, 'getItem' | 'setItem' | 'removeItem'>;
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

View file

@ -13,7 +13,12 @@ export const PAGE_START = Date.now();
const attempt = async (mx: MatrixClient, userId: string, entry: OutboxEntry): Promise<void> => {
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<voi
return attempt(mx, userId, { ...entry, txnId, status: 'pending', ts: Date.now() });
};
/**
* After a reload, send again every entry the reload interrupted. They have no SDK echo, so each
* keeps its txn id and the server deduplicates one that did land. Failed entries are left for
* the user: they failed with an answer, these are only unknown.
*/
export const resendInterrupted = (mx: MatrixClient, since: number = PAGE_START): Promise<void[]> => {
export const resendInterrupted = (
mx: MatrixClient,
since: number = PAGE_START
): Promise<void[]> => {
const userId = mx.getUserId() ?? '';
return Promise.all(
loadOutbox(userId)

View file

@ -20,9 +20,7 @@ export type TUploadItem = {
export type TUploadListAtom = ReturnType<typeof createListAtom<TUploadItem>>;
export const roomIdToUploadItemsAtomFamily = atomFamily<string, TUploadListAtom>(
createListAtom
);
export const roomIdToUploadItemsAtomFamily = atomFamily<string, TUploadListAtom>(createListAtom);
export const roomUploadAtomFamily = createUploadAtomFamily();

View file

@ -3,9 +3,12 @@ import { RECOVER_RELOAD_MIN_GAP_MS, reloadToRecoverSync } from './initMatrix';
const memory = () => {
const m = new Map<string, string>();
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();
});
});

View file

@ -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<Storage, 'getItem' | 'setItem'> = 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<MatrixClient>();
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());

View file

@ -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();
});
});

View file

@ -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<string | null> = 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<Host> = {
type ResumeSyncOptions = {
/** Event sources and visibility; default to the browser globals. */
doc?: Pick<Document, 'addEventListener' | 'removeEventListener' | 'visibilityState'>;
win?: Pick<Window, 'addEventListener' | 'removeEventListener'>;
/**
* 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 = <Host extends SyncHost>(
mx: Host,
{ recover, doc = document, win = window }: ResumeSyncOptions<Host>
export const startResumeSync = (
mx: SyncHost,
{ doc = document, win = window }: ResumeSyncOptions = {}
): (() => void) => {
let hiddenAt: number | undefined;
let debounce: ReturnType<typeof setTimeout> | undefined;
let healthCheck: ReturnType<typeof setTimeout> | 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 = <Host extends SyncHost>(
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);

View file

@ -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<Parameters<typeof startWatchdog>[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', () => {

View file

@ -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);
};