diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index e6aa6a8..873ba85 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -156,7 +156,7 @@ const pendingCursor = new Map(); const staleBuffer = new Map(); /** Change records the last push of a collection sent; the pull after it keeps newer local changes. */ const pushedChanges = new Map>(); -/** Set when the server rejected a change of the current round; its message stays until a round succeeds. */ +/** Set when the server rejected or overrode a change; its message stays until a manual sync or a new rejection. */ let rejected = false; let sessionExpired: (() => void) | null = null; let remoteTimer: ReturnType | null = null; @@ -215,6 +215,18 @@ function unauthorized(e: unknown): boolean { return (e as { status?: unknown } | null)?.status === 401; } +/** What the server gives for a change it did not apply, where it sends no text of its own. */ +const REJECTION_TEXT: Record<'forbidden' | 'readonly', string> = { + forbidden: 'the record belongs to another account', + readonly: 'the collection is read only' +}; + +/** Shows that the server did not take a change; the message replaces an earlier one and stays until a manual sync. */ +function report(name: string, id: string, text: string): void { + status.error = `${name} ${id}: ${text}`.slice(0, 200); + rejected = true; +} + /** What a failed round reports: the distinct errors of its syncs on one line, since syncAll() only lists them below a heading. */ function roundError(m: WotraSync, err: Error): string { const messages = [...new Set(m.failures.map(errorMessage))]; @@ -381,17 +393,19 @@ async function doOpenDb(uid: string): Promise { })) } }); - for (const r of res?.results ?? []) { - if (r.status === 'invalid') { - if (!rejected) status.error = `${name}: ${String(r.error ?? 'rejected')}`.slice(0, 200); - rejected = true; - continue; + const byId = new Map(items.map((it) => [it.id, it])); + for (const r of res?.results ?? []) { + if (r.status === 'ok') continue; + const deletion = byId.get(r.id)?.deleted === true; + if (r.status === 'invalid') report(name, r.id, String(r.error ?? 'rejected')); + else if (r.status === 'forbidden' || r.status === 'readonly') report(name, r.id, REJECTION_TEXT[r.status]); + else if (r.record && isCollection(r.collection)) { + if (deletion) report(name, r.id, 'the server kept a newer version of that record'); + const list = staleBuffer.get(r.collection) ?? []; + list.push(toRecord(r.collection, r.record)); + staleBuffer.set(r.collection, list); + } } - if (r.status === 'ok' || !r.record || !isCollection(r.collection)) continue; - const list = staleBuffer.get(r.collection) ?? []; - list.push(toRecord(r.collection, r.record)); - staleBuffer.set(r.collection, list); - } } } finally { enterApply(name); @@ -418,7 +432,7 @@ async function doOpenDb(uid: string): Promise { status.ready = true; installTriggers(); await runBeforeSync(); - void syncNow(); + void autoSync(); } export function onSyncRound(fn: () => void): () => void { @@ -445,13 +459,22 @@ function remoteChange(): void { remoteTimer = setTimeout(() => { remoteTimer = null; void (syncing ?? Promise.resolve()) - .then(() => syncNow()) + .then(() => autoSync()) .catch(() => {}); }, REMOTE_DEBOUNCE); } -/** Runs the preparation and a round; offline only the preparation runs, which keeps the stale entries stopped. */ export function syncNow(): Promise { + return round(true); +} + +/** A round the app starts on its own; it leaves the message of an earlier rejection in place. */ +function autoSync(): Promise { + return round(false); +} + +/** Runs the preparation and a round; offline only the preparation runs, which keeps the stale entries stopped. */ +function round(manual: boolean): Promise { if (syncing) return syncing; const m = sm; if (!m) return Promise.resolve(); @@ -459,7 +482,7 @@ export function syncNow(): Promise { sessionExpired?.(); return Promise.resolve(); } - rejected = false; + if (manual) rejected = false; m.failures.length = 0; const run: Promise = runBeforeSync() .then(() => (status.online && m === sm ? m.syncAll() : undefined)) @@ -480,19 +503,19 @@ function installTriggers() { const online = () => { status.online = true; void sm?.startAll().catch(() => {}); - void syncNow(); + void autoSync(); }; const offline = () => { status.online = false; }; const focus = () => { - if (document.visibilityState === 'visible') void syncNow(); + if (document.visibilityState === 'visible') void autoSync(); }; window.addEventListener('online', online); window.addEventListener('offline', offline); window.addEventListener('focus', focus); document.addEventListener('visibilitychange', focus); - const iv = setInterval(() => void syncNow(), 60000); + const iv = setInterval(() => void autoSync(), 60000); cleanups.push(() => { window.removeEventListener('online', online); window.removeEventListener('offline', offline); diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index 798380f..a866ad7 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -8,7 +8,8 @@ const mocks = vi.hoisted(() => { const server = new Map>>(); const pushes: { collection: string; id: string; data: Record; client_updated_at: number; deleted: boolean }[] = []; const batches: number[] = []; - const reject = { collection: '', error: '' }; + /** Status the mock answers for every change of a collection instead of applying it, with the text it sends. */ + const reject = { collection: '', answer: 'invalid', error: '' }; const slow = { name: '' }; /** HTTP status the mock answers instead of a result, 0 like a network failure; null answers normally. */ const fail = { pull: null as number | null, push: null as number | null }; @@ -72,13 +73,19 @@ vi.mock('$lib/pb', () => ({ mocks.batches.push(body.changes.length); const results = body.changes.map((c) => { mocks.pushes.push(c); - if (mocks.reject.collection === c.collection) return { id: c.id, collection: c.collection, status: 'invalid', error: mocks.reject.error }; - const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() }; + if (mocks.reject.collection === c.collection) { + return { id: c.id, collection: c.collection, status: mocks.reject.answer, error: mocks.reject.error }; + } let store = mocks.server.get(c.collection); if (!store) { store = new Map(); mocks.server.set(c.collection, store); } + const existing = store.get(c.id); + if (existing && c.client_updated_at < Number(existing.client_updated_at)) { + return { id: c.id, collection: c.collection, status: 'stale', record: existing }; + } + const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() }; store.set(c.id, record); return { id: c.id, collection: c.collection, status: 'ok', record }; }); @@ -319,7 +326,7 @@ describe('sync boundary', () => { expect(mocks.batches.reduce((sum, size) => sum + size, 0)).toBe(250); }, 20000); - it('a rejected change is dropped and reported, and a later success of the round keeps the message', async () => { + it('a rejected change is dropped, and a later success of the round keeps its message', async () => { status.online = true; mocks.reject.collection = 'settings_history'; mocks.reject.error = 'hours_per_week must be at most 168'; @@ -328,7 +335,8 @@ describe('sync boundary', () => { const id = await save('settings_history', null, settingsRow); await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); await syncNow(); - expect(status.error).toBe('settings_history: hours_per_week must be at most 168'); + expect(status.error).toBe(`settings_history ${id}: hours_per_week must be at most 168`); + expect(get('settings_history', id)).toBeUndefined(); mocks.reject.collection = ''; await syncNow(); expect(status.error).toBeNull(); @@ -344,15 +352,85 @@ describe('sync boundary', () => { mocks.reject.collection = 'balance_adjustments'; mocks.reject.error = 'x'.repeat(300); try { - await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + const id = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); await syncNow(); - expect(status.error).toBe(`balance_adjustments: ${'x'.repeat(200 - 'balance_adjustments: '.length)}`); + const prefix = `balance_adjustments ${id}: `; + expect(status.error).toBe(prefix + 'x'.repeat(200 - prefix.length)); } finally { mocks.reject.collection = ''; } }); }); +describe('rejections', () => { + const answers: [string, string, string][] = [ + ['invalid', 'day_key "x" is not a calendar date', 'day_key "x" is not a calendar date'], + ['forbidden', '', 'the record belongs to another account'], + ['readonly', '', 'the collection is read only'] + ]; + + /** Resolves after the next round the app starts on its own. */ + const nextAutoRound = () => + new Promise((resolve) => { + const off = onSyncRound(() => { + off(); + resolve(); + }); + }); + + it.each(answers)('a %s answer is reported with collection, id and text, and stays until a manual sync', async (answer, error, text) => { + status.online = true; + const id = await save('settings_history', null, settingsRow); + mocks.reject.collection = 'settings_history'; + mocks.reject.answer = answer; + mocks.reject.error = error; + try { + await syncNow(); + expect(get('settings_history', id)).toBeUndefined(); + expect(status.error).toBe(`settings_history ${id}: ${text}`); + status.online = false; + const round = nextAutoRound(); + window.dispatchEvent(new Event('online')); + await round; + expect(status.error).toBe(`settings_history ${id}: ${text}`); + await syncNow(); + expect(status.error).toBeNull(); + } finally { + mocks.reject.collection = ''; + mocks.reject.answer = 'invalid'; + } + }); + + it('a stale answer to a deletion is reported, and the newer server record comes back', async () => { + status.online = true; + const id = await save('settings_history', null, settingsRow); + await syncNow(); + const store = mocks.server.get('settings_history'); + const record = store?.get(id); + if (!store || !record) throw new Error('server record missing'); + store.set(id, { ...record, hours_per_week: 20, client_updated_at: Number(record.client_updated_at) + 1_000_000, updated: mocks.stamp() }); + await remove('settings_history', id); + await syncNow(); + expect(status.error).toBe(`settings_history ${id}: the server kept a newer version of that record`); + expect(get('settings_history', id)).toMatchObject({ deleted: false, hours_per_week: 20 }); + expect(pendingCount()).toBe(0); + }); + + it('a stale answer to an edit applies the server record without a message', async () => { + status.online = true; + const id = await save('settings_history', null, settingsRow); + await syncNow(); + const store = mocks.server.get('settings_history'); + const record = store?.get(id); + if (!store || !record) throw new Error('server record missing'); + store.set(id, { ...record, hours_per_week: 20, client_updated_at: Number(record.client_updated_at) + 1_000_000, updated: mocks.stamp() }); + await update('settings_history', id, { hours_per_week: 30 }); + await syncNow(); + expect(status.error).toBeNull(); + expect(get('settings_history', id)).toMatchObject({ deleted: false, hours_per_week: 20 }); + }); +}); + describe('session expiry', () => { it('a 401 from the push ends the session and the round is not reported as synced', async () => { status.online = true;