diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index ea825e6..f642bb2 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -3,6 +3,7 @@ import { DefaultDataAdapter, createReactivityAdapter, type BaseItem, + type Changeset, type Cursor, type ReactivityAdapter, type Selector @@ -11,6 +12,7 @@ import { SyncManager } from '@signaldb/sync'; import svelteReactivityAdapter from '@signaldb/svelte'; import prepareIndexedDB from '@signaldb/indexeddb'; import { 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'; @@ -147,6 +149,46 @@ let epoch = 0; let pullRuns = 0; 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>(); + +/** Collections whose local state the sync is about to touch or is touching, by name and nesting depth. */ +const applying = new Map(); +const pause = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function enterApply(name: string): void { + applying.set(name, (applying.get(name) ?? 0) + 1); +} + +function leaveApply(name: string): void { + const depth = (applying.get(name) ?? 0) - 1; + if (depth > 0) applying.set(name, depth); + else applying.delete(name); +} + +/** A write in flight has no change record yet, so the server state must wait for it. */ +async function quiesce(c: Collection): Promise { + while (c.isPushing()) await pause(); +} + +/** The sync knows nothing of a write made while it applies server state, so writes wait for it. */ +async function waitForApply(name: string): Promise { + while (applying.has(name)) await pause(); +} + +/** Server records changed since the cursor; a pull inside an apply lets local writes run while the request is out. */ +async function pullRecords(name: string, cursor: string | null): Promise { + const inside = applying.has(name); + if (inside) leaveApply(name); + try { + return await pb.collection(name).getFullList({ + sort: 'updated', + ...(cursor ? { filter: pb.filter('updated >= {:c}', { c: cursor }) } : {}) + }); + } finally { + if (inside) enterApply(name); + } +} function onSynced(name: string) { const c = pendingCursor.get(name); @@ -163,6 +205,21 @@ class WotraSync extends SyncManager, AnyDoc, string> { const changes = this.changes; return inScope() ? changes.find({}).count() : readOnce(changes, {}, (cursor) => cursor.count()); } + override async syncWithData(name: string, data: { changes: Changeset; items?: never } | { items: AnyDoc[]; changes?: never }): Promise { + enterApply(name); + try { + await super.syncWithData(name, data); + } finally { + leaveApply(name); + } + } + /** Items with a change record that the push of this round did not send; a scan, since an index lags behind a write in flight. */ + async unpushed(name: string, pushed: Set | undefined): Promise> { + await quiesce(this.changes); + const records = await this.changes.find({}, { reactive: false, async: true }).fetch(); + const ids = records.filter((c) => c.collectionName === name && !pushed?.has(c.id)).map((c) => (typeof c.data === 'object' ? c.data.id : c.data)); + return new Set(ids.map(String)); + } /** Lets writes in flight finish, since the sync manager rejects them after dispose(). */ async settle(): Promise { const busy = () => [this.changes, ...[...this.collections.values()].map((c) => c.collection)].some((c) => c.isPushing()); @@ -207,6 +264,8 @@ async function doOpenDb(uid: string): Promise { userId = uid; pendingCursor.clear(); staleBuffer.clear(); + pushedChanges.clear(); + applying.clear(); const idb = prepareIndexedDB({ databaseName: localDbName(uid), version: SCHEMA_VERSION, schema: schema() }); const adapter = new DefaultDataAdapter({ storage: (name) => idb(name) }); const c = {} as Record; @@ -217,7 +276,7 @@ async function doOpenDb(uid: string): Promise { return; } cols = c; - const m = new WotraSync({ + const m: WotraSync = new WotraSync({ id: SYNC_ID, dataAdapter: adapter, reactivity, @@ -229,11 +288,12 @@ async function doOpenDb(uid: string): Promise { pull: async ({ name }) => { pullRuns += 1; const n = name as CollectionName; + const pushed = pushedChanges.get(name); + pushedChanges.delete(name); const cursor = localStorage.getItem(cursorKey(uid, name)); - const records = await pb.collection(name).getFullList({ - sort: 'updated', - ...(cursor ? { filter: pb.filter('updated >= {:c}', { c: cursor }) } : {}) - }); + const records = await pullRecords(name, cursor); + await quiesce(c[n]); + const waiting = await m.unpushed(name, pushed); let max = cursor ?? ''; for (const r of records) if (r.updated > max) max = r.updated; if (max) pendingCursor.set(name, max); @@ -242,30 +302,36 @@ async function doOpenDb(uid: string): Promise { const merged = new Map(); for (const r of stale) merged.set(r.id, r); for (const r of records) merged.set(r.id, toRecord(n, r)); - return { changes: { added: [], modified: [...merged.values()], removed: [] } }; + return { changes: { added: [], modified: [...merged.values()].filter((doc) => !waiting?.has(doc.id)), removed: [] } }; }, - push: async ({ name }, { changes }) => { + push: async ({ name }, { changes, rawChanges }) => { + pushedChanges.set(name, new Set((rawChanges as unknown as { id: string }[]).map((c) => c.id))); const items = [...changes.added, ...changes.modified]; const n = name as CollectionName; - for (let i = 0; i < items.length; i += PUSH_BATCH) { - const res = await pb.send<{ results: PushResult[] }>('/api/sync/push', { - method: 'POST', - body: { - changes: items.slice(i, i + PUSH_BATCH).map((it) => ({ - collection: name, - id: it.id, - data: toServerData(n, it), - client_updated_at: it.client_updated_at, - deleted: it.deleted - })) + leaveApply(name); + try { + for (let i = 0; i < items.length; i += PUSH_BATCH) { + const res = await pb.send<{ results: PushResult[] }>('/api/sync/push', { + method: 'POST', + body: { + changes: items.slice(i, i + PUSH_BATCH).map((it) => ({ + collection: name, + id: it.id, + data: toServerData(n, it), + client_updated_at: it.client_updated_at, + deleted: it.deleted + })) + } + }); + for (const r of res?.results ?? []) { + 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); } - }); - for (const r of res?.results ?? []) { - 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); } }, registerRemoteChange: async ({ name }, onChange) => { @@ -401,7 +467,9 @@ export function get(name: K, id: string): Doc(name: K, id: string | null, data: PayloadMap[K], deleted = false): Promise { if (!cols) throw new Error('database is not open'); - const c = cols[name]; + await waitForApply(name); + const c = cols?.[name]; + if (!c) throw new Error('database is not open'); const rid = id ?? newId(); const now = Date.now(); const prev = readOnce(c, { id: rid }, (cursor) => cursor.fetch()[0]); diff --git a/web/src/lib/sync.test.ts b/web/src/lib/sync.test.ts new file mode 100644 index 0000000..11265e8 --- /dev/null +++ b/web/src/lib/sync.test.ts @@ -0,0 +1,202 @@ +import { tick } from 'svelte'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { addAdjustment, balance, deleteAdjustment } from './app.svelte'; +import { all, closeDb, get, openDb, pendingCount, remove, save, status, syncNow, update } from './db.svelte'; +import { watch, type Watcher } from './testing.svelte'; + +const mocks = vi.hoisted(() => { + const server = new Map>>(); + let tick = 0; + let hold: { promise: Promise; entered: () => void } | null = null; + return { + server, + stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' '), + holdNextPush(): { entered: Promise; release: () => void } { + let release!: () => void; + let enter!: () => void; + const entered = new Promise((resolve) => (enter = resolve)); + hold = { promise: new Promise((resolve) => (release = resolve)), entered: enter }; + return { entered, release }; + }, + async gate() { + const current = hold; + if (!current) return; + hold = null; + current.entered(); + await current.promise; + } + }; +}); + +vi.mock('$lib/pb', () => ({ + pb: { + autoCancellation: () => undefined, + filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), + collection: (name: string) => ({ + getFullList: async (options: { filter?: string }) => { + const since = /updated >= "([^"]+)"/.exec(options?.filter ?? '')?.[1]; + return [...(mocks.server.get(name)?.values() ?? [])].filter((r) => !since || String(r.updated) >= since); + }, + subscribe: async () => async () => undefined + }), + send: async (path: string, options: { method?: string; body?: unknown }) => { + if (path !== '/api/sync/push' || options.method !== 'POST') return {}; + await mocks.gate(); + const body = options.body as { + changes: { collection: string; id: string; data: Record; client_updated_at: number; deleted: boolean }[]; + }; + const results = body.changes.map((c) => { + const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() }; + let store = mocks.server.get(c.collection); + if (!store) { + store = new Map(); + mocks.server.set(c.collection, store); + } + store.set(c.id, record); + return { id: c.id, collection: c.collection, status: 'ok', record }; + }); + return { results }; + } + } +})); + +type Field = 'start_time' | 'worked_ms' | 'delta_ms' | 'hours_per_week'; +interface Table { + name: 'entries' | 'closed_days' | 'balance_adjustments' | 'settings_history'; + field: Field; + live: Map; + add: (value: number) => Promise; + set: (id: string, value: number) => Promise; +} + +const ROUNDS = 300; +const FLIGHT_EVERY = 10; + +const tables: Table[] = [ + { + name: 'entries', + field: 'start_time', + live: new Map(), + add: (value) => save('entries', null, { start_time: value, end_time: value + 1000, auto_stopped: false, note: '', day_key: '2026-01-01' }), + set: (id, value) => update('entries', id, { start_time: value, end_time: value + 1000 }) + }, + { + name: 'closed_days', + field: 'worked_ms', + live: new Map(), + add: (value) => save('closed_days', null, { day_key: `2026-01-${String((value % 28) + 1).padStart(2, '0')}`, worked_ms: value, kind: 'work', closed_at: 1 }), + set: (id, value) => update('closed_days', id, { worked_ms: value }) + }, + { + name: 'balance_adjustments', + field: 'delta_ms', + live: new Map(), + add: (value) => addAdjustment({ delta_ms: value, effective_at: value }), + set: (id, value) => update('balance_adjustments', id, { delta_ms: value }) + }, + { + name: 'settings_history', + field: 'hours_per_week', + live: new Map(), + add: (value) => save('settings_history', null, { effective_from: '2000-01-01', hours_per_week: value, workdays_mask: 31, timezone: 'UTC' }), + set: (id, value) => update('settings_history', id, { hours_per_week: value }) + } +]; + +const sum = (values: Map) => [...values.values()].reduce((total, v) => total + v, 0); +const rowsOf = (table: Table) => all(table.name) as unknown as ({ id: string } & Record)[]; + +describe('reactive reads after writes', () => { + let anchor = ''; + let watchers: { count: Watcher; sum: Watcher }[] = []; + let total!: Watcher; + let note!: Watcher; + let pending!: Watcher; + + const expectModel = async (round: number, deep: boolean) => { + await tick(); + for (const [k, table] of tables.entries()) { + const rows = rowsOf(table); + expect(rows).toHaveLength(table.live.size); + expect(rows.reduce((total, row) => total + row[table.field], 0)).toBe(sum(table.live)); + expect(watchers[k]?.count.current).toBe(table.live.size); + expect(watchers[k]?.sum.current).toBe(sum(table.live)); + if (!deep) continue; + for (const [id, value] of table.live) expect(get(table.name, id)).toMatchObject({ id, [table.field]: value, deleted: false }); + } + expect(total.current).toBe(sum(tables[2].live)); + expect(note.current).toBe(`note ${round}`); + expect(get('entries', anchor)?.note).toBe(`note ${round}`); + }; + + beforeAll(async () => { + await openDb('stress-user'); + status.online = true; + anchor = await save('entries', null, { start_time: 1, end_time: 2, auto_stopped: false, note: 'note 0', day_key: '2026-01-01' }); + tables[0].live.set(anchor, 1); + watchers = tables.map((table) => ({ + count: watch(() => all(table.name).length), + sum: watch(() => rowsOf(table).reduce((total, row) => total + row[table.field], 0)) + })); + total = watch(() => balance().total_delta_ms); + note = watch(() => get('entries', anchor)?.note); + pending = watch(() => pendingCount()); + }); + + afterAll(async () => { + for (const w of watchers) { + w.count.dispose(); + w.sum.dispose(); + } + total.dispose(); + note.dispose(); + pending.dispose(); + await closeDb(); + }); + + it(`reflect the last write in ${ROUNDS} rounds, with the sync idle and with a push in flight`, async () => { + for (let round = 1; round <= ROUNDS; round += 1) { + const value = round * 10; + const target = tables[round % tables.length]; + if (!target) throw new Error('table missing'); + const added = await target.add(value); + target.live.set(added, value); + for (const table of tables) { + const newest = [...table.live.keys()].at(-1); + if (!newest) continue; + await table.set(newest, value + 1); + table.live.set(newest, value + 1); + } + const oldest = [...target.live.keys()][0]; + if (target.live.size > 2 && oldest) { + await remove(target.name, oldest); + target.live.delete(oldest); + } + await update('entries', anchor, { note: `note ${round}` }); + await expectModel(round, round % FLIGHT_EVERY === 0); + + if (round % FLIGHT_EVERY !== 0) continue; + await syncNow(); + expect(pendingCount()).toBe(0); + const push = mocks.holdNextPush(); + const adjustment = await addAdjustment({ delta_ms: 7, effective_at: round }); + tables[2].live.set(adjustment, 7); + const flight = syncNow(); + await push.entered; + await deleteAdjustment(adjustment); + tables[2].live.delete(adjustment); + const day = await tables[1].add(value); + tables[1].live.set(day, value); + await expectModel(round, true); + const seen = watchers[2]?.count.seen.length ?? 0; + push.release(); + await flight; + await syncNow(); + await expectModel(round, true); + expect(pendingCount()).toBe(0); + expect(pending.current).toBe(0); + const counts = watchers[2]?.count.seen.slice(seen) ?? []; + expect(counts.every((count) => count === tables[2].live.size)).toBe(true); + } + }, 120000); +});