Files
wotra/web/src/lib/sync.test.ts
T
aksdb 03c7b17ccb 🧪 Cover session expiry, network failures and user switches
The db tests get an echo server that honours the pull cursor, records
the filter of every pull, answers with a status of the test's choice
and keeps stale answers like the real one. New cases: a second user
opens without the collections, cursors, realtime subscriptions and
sync status of the first; wipeLocal really removes the cursors and the
database so that the next open pulls everything again; a push that
fails after a good pull and a pull that fails before the push both
keep the change records and the cursor, and the next round pushes it
all; a stale answer applies the server record and a newer local change
wins afterwards.

The stress test now compares every local record, tombstones included,
with the mock server after each round, so a divergence between the two
fails the test. closeDb() resets the last sync time for the same
reason: it belonged to the session that just ended.
2026-12-01 19:16:35 +01:00

216 lines
8.1 KiB
TypeScript

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, toRecord, update } from './db.svelte';
import { watch, type Watcher } from './testing.svelte';
const mocks = vi.hoisted(() => {
const server = new Map<string, Map<string, Record<string, unknown>>>();
let tick = 0;
let hold: { promise: Promise<void>; entered: () => void } | null = null;
return {
server,
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' '),
holdNextPush(): { entered: Promise<void>; release: () => void } {
let release!: () => void;
let enter!: () => void;
const entered = new Promise<void>((resolve) => (enter = resolve));
hold = { promise: new Promise<void>((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', () => ({
errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)),
pb: {
authStore: { isValid: true },
autoCancellation: () => undefined,
filter: (tpl: string, params: Record<string, unknown>) => 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<string, unknown>; 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<string, number>;
add: (value: number) => Promise<string>;
set: (id: string, value: number) => Promise<void>;
}
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<string, number>) => [...values.values()].reduce((total, v) => total + v, 0);
const rowsOf = (table: Table) => all(table.name) as unknown as ({ id: string } & Record<Field, number>)[];
const byId = (a: { id: string }, b: { id: string }) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
/** After a round every local record, tombstones included, equals its server record; a round may not leave the two apart. */
const expectMirrorsServer = () => {
for (const table of tables) {
const server = [...(mocks.server.get(table.name)?.values() ?? [])].map((r) => toRecord(table.name, r)).sort(byId);
expect(all(table.name, true).sort(byId)).toEqual(server);
}
};
describe('reactive reads after writes', () => {
let anchor = '';
let watchers: { count: Watcher<number>; sum: Watcher<number> }[] = [];
let total!: Watcher<number>;
let note!: Watcher<string | undefined>;
let pending!: Watcher<number>;
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);
expectMirrorsServer();
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);
expectMirrorsServer();
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);
});