diff --git a/web/src/lib/app.test.ts b/web/src/lib/app.test.ts index 1146f45..431cea0 100644 --- a/web/src/lib/app.test.ts +++ b/web/src/lib/app.test.ts @@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => { }); vi.mock('$lib/pb', () => ({ + errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)), pb: { authStore: { isValid: true }, autoCancellation: () => undefined, diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index 13c98ba..68a3990 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -11,7 +11,7 @@ import { import { SyncManager } from '@signaldb/sync'; import svelteReactivityAdapter from '@signaldb/svelte'; import prepareIndexedDB from '@signaldb/indexeddb'; -import { pb } from '$lib/pb'; +import { errorMessage, pb } from '$lib/pb'; import type { RecordModel } from 'pocketbase'; import { COLLECTIONS, DATA_FIELDS, ZERO_MEANS_NULL, type CollectionName, type PayloadMap } from '$lib/types'; import { newId } from '$lib/utils'; @@ -41,6 +41,8 @@ const SYNC_ID = 'wotra'; const SCHEMA_VERSION = 1; /** Changes per push request; the server rejects more than 500. */ const PUSH_BATCH = 200; +/** Window in which realtime events share one round. */ +const REMOTE_DEBOUNCE = 300; /** Upper bound for opening the local database in milliseconds. */ const OPEN_TIMEOUT = 8000; @@ -157,6 +159,7 @@ const pushedChanges = new Map>(); /** Set when the server rejected a change of the current round; its message stays until a round succeeds. */ let rejected = false; let sessionExpired: (() => void) | null = null; +let remoteTimer: ReturnType | null = null; /** Collections whose local state the sync is about to touch or is touching, by name and nesting depth. */ const applying = new Map(); @@ -212,6 +215,12 @@ function unauthorized(e: unknown): boolean { return (e as { status?: unknown } | null)?.status === 401; } +/** 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))]; + return messages.length ? messages.join(', ') : err.message; +} + class WotraSync extends SyncManager, AnyDoc, string> { /** Errors of the sync calls of the current round as they were thrown, before syncAll() summarized them. */ readonly failures: unknown[] = []; @@ -330,9 +339,9 @@ async function doOpenDb(uid: string): Promise { autostart: false, debounceTime: 300, onError: (_opts, err) => { - if (!status.ready || syncing) return; + if (!status.ready || syncing) return; if (!pb.authStore.isValid || unauthorized(err)) sessionExpired?.(); - else status.error = err.message; + else if (status.online) status.error = err.message; }, pull: async ({ name }) => { pullRuns += 1; @@ -388,11 +397,9 @@ async function doOpenDb(uid: string): Promise { enterApply(name); } }, - registerRemoteChange: async ({ name }, onChange) => { + registerRemoteChange: async ({ name }) => { try { - const unsub = await pb.collection(name).subscribe('*', () => { - void onChange(); - }); + const unsub = await pb.collection(name).subscribe('*', () => remoteChange()); if (gen !== epoch) { void unsub().catch(() => {}); return undefined; @@ -432,6 +439,17 @@ function runBeforeSync(): Promise { return beforeSync ? beforeSync() : Promise.resolve(); } +/** A remote change runs a full round, at most one per window; one that lands during a round gets its own round after it. */ +function remoteChange(): void { + if (remoteTimer) return; + remoteTimer = setTimeout(() => { + remoteTimer = null; + void (syncing ?? Promise.resolve()) + .then(() => syncNow()) + .catch(() => {}); + }, REMOTE_DEBOUNCE); +} + export function syncNow(): Promise { if (syncing) return syncing; const m = sm; @@ -447,7 +465,7 @@ export function syncNow(): Promise { .catch((err: Error) => { if (m !== sm) return; if (!pb.authStore.isValid || m.failures.some(unauthorized)) sessionExpired?.(); - else status.error = err.message; + else if (status.online) status.error = roundError(m, err); }) .finally(() => { if (syncing === run) syncing = null; @@ -486,6 +504,8 @@ function installTriggers() { export async function closeDb(): Promise { epoch += 1; status.ready = false; + if (remoteTimer) clearTimeout(remoteTimer); + remoteTimer = null; for (const c of cleanups.splice(0)) c(); const m = sm; sm = null; diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index 5103079..d79d776 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -1,7 +1,7 @@ import { Collection } from '@signaldb/core'; import { tick } from 'svelte'; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { all, closeDb, currentUserId, get, onSessionExpired, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte'; +import { all, closeDb, currentUserId, get, onBeforeSync, onSessionExpired, onSyncRound, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte'; import { holdNextOpen, watch } from './testing.svelte'; const mocks = vi.hoisted(() => { @@ -10,9 +10,14 @@ const mocks = vi.hoisted(() => { const batches: number[] = []; const reject = { collection: '', error: '' }; const slow = { name: '' }; - /** HTTP status the mock answers instead of a result; 0 answers normally. */ - const fail = { pull: 0, push: 0 }; + /** 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 }; const auth = { valid: true }; + /** Realtime callbacks by collection, and the subscriptions given up so far. */ + const listeners = new Map void>(); + const unsubscribed: string[] = []; + /** Pulls the mock answered so far. */ + const pulls = { count: 0 }; let tick = 0; /** Answers like the SDK does: a 401 also clears the auth store. */ const refuse = (status: number): never => { @@ -27,12 +32,16 @@ const mocks = vi.hoisted(() => { slow, fail, auth, + listeners, + unsubscribed, + pulls, refuse, stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ') }; }); vi.mock('$lib/pb', () => ({ + errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)), pb: { authStore: { get isValid() { @@ -44,15 +53,21 @@ vi.mock('$lib/pb', () => ({ filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), collection: (name: string) => ({ getFullList: async () => { + mocks.pulls.count += 1; if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5)); - if (mocks.fail.pull) mocks.refuse(mocks.fail.pull); + if (mocks.fail.pull !== null) mocks.refuse(mocks.fail.pull); return [...(mocks.server.get(name)?.values() ?? [])]; }, - subscribe: async () => async () => undefined + subscribe: async (topic: string, callback: (data?: unknown) => void) => { + mocks.listeners.set(topic === '*' ? name : topic, callback); + return async () => { + mocks.unsubscribed.push(name); + }; + } }), send: async (path: string, options: { method?: string; body?: unknown }) => { if (path !== '/api/sync/push' || options.method !== 'POST') return {}; - if (mocks.fail.push) mocks.refuse(mocks.fail.push); + if (mocks.fail.push !== null) mocks.refuse(mocks.fail.push); const body = options.body as { changes: (typeof mocks.pushes)[number][] }; mocks.batches.push(body.changes.length); const results = body.changes.map((c) => { @@ -83,8 +98,8 @@ beforeEach(async () => { afterEach(() => { mocks.pushes.length = 0; - mocks.fail.pull = 0; - mocks.fail.push = 0; + mocks.fail.pull = null; + mocks.fail.push = null; mocks.auth.valid = true; status.error = null; }); @@ -410,3 +425,42 @@ describe('merge after apply', () => { expect(await update('entries', 'missing', { note: 'ignored' })).toBeUndefined(); }); }); + +describe('realtime and offline', () => { + const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + + it('a burst of realtime events runs one round, through the sync hooks', async () => { + status.online = true; + const before = vi.fn(async () => undefined); + onBeforeSync(before); + const rounds = vi.fn(); + onSyncRound(rounds); + const pulls = mocks.pulls.count; + const notify = mocks.listeners.get('entries'); + if (!notify) throw new Error('no realtime subscription'); + mocks.fail.pull = 0; + for (let i = 0; i < 20; i++) { + notify({}); + await wait(5); + } + await wait(450); + expect(rounds).toHaveBeenCalledTimes(1); + expect(before).toHaveBeenCalledTimes(1); + expect(mocks.pulls.count - pulls).toBe(5); + expect(status.error).toBe('Failed to fetch'); + }); + + it('a failed push of an offline write leaves the error empty', async () => { + status.online = false; + mocks.fail.pull = 0; + mocks.fail.push = 0; + await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + await wait(400); + expect(pendingCount()).toBe(1); + expect(status.error).toBeNull(); + status.online = true; + await save('balance_adjustments', null, { delta_ms: 2000, note: '', effective_at: 1 }); + await wait(400); + expect(status.error).toBe('Failed to fetch'); + }); +}); diff --git a/web/src/lib/sync.test.ts b/web/src/lib/sync.test.ts index fff1e15..ae1f7f9 100644 --- a/web/src/lib/sync.test.ts +++ b/web/src/lib/sync.test.ts @@ -29,6 +29,7 @@ const mocks = vi.hoisted(() => { }); vi.mock('$lib/pb', () => ({ + errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)), pb: { authStore: { isValid: true }, autoCancellation: () => undefined,