diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index 873ba85..8dd4850 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -528,6 +528,7 @@ function installTriggers() { export async function closeDb(): Promise { epoch += 1; status.ready = false; + status.lastSync = 0; if (remoteTimer) clearTimeout(remoteTimer); remoteTimer = null; for (const c of cleanups.splice(0)) c(); diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index a866ad7..2ea4145 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -1,8 +1,27 @@ import { Collection } from '@signaldb/core'; import { tick } from 'svelte'; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { all, closeDb, currentUserId, get, onBeforeSync, onSessionExpired, onSyncRound, 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, + wipeLocal +} from './db.svelte'; import { holdNextOpen, watch } from './testing.svelte'; +import { COLLECTIONS } from './types'; const mocks = vi.hoisted(() => { const server = new Map>>(); @@ -17,8 +36,9 @@ const mocks = vi.hoisted(() => { /** 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. */ + /** Pulls the mock answered so far, with the filter each one asked for. */ const pulls = { count: 0 }; + const filters: (string | null)[] = []; let tick = 0; /** Answers like the SDK does: a 401 also clears the auth store. */ const refuse = (status: number): never => { @@ -36,6 +56,7 @@ const mocks = vi.hoisted(() => { listeners, unsubscribed, pulls, + filters, refuse, stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ') }; @@ -53,11 +74,13 @@ vi.mock('$lib/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 () => { + getFullList: async (options?: { filter?: string }) => { mocks.pulls.count += 1; + mocks.filters.push(options?.filter ?? null); if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5)); if (mocks.fail.pull !== null) mocks.refuse(mocks.fail.pull); - return [...(mocks.server.get(name)?.values() ?? [])]; + const since = /updated >= "([^"]+)"/.exec(options?.filter ?? '')?.[1]; + return [...(mocks.server.get(name)?.values() ?? [])].filter((r) => !since || String(r.updated) >= since); }, subscribe: async (topic: string, callback: (data?: unknown) => void) => { mocks.listeners.set(topic === '*' ? name : topic, callback); @@ -97,6 +120,8 @@ vi.mock('$lib/pb', () => ({ let n = 0; const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' }; const settled = () => new Promise((resolve) => setTimeout(resolve, 0)); +const databaseNames = async () => (await indexedDB.databases()).map((d) => d.name); +const cursor = (uid: string, name: string) => localStorage.getItem(`wotra-cursor:${uid}:${name}`); beforeEach(async () => { status.online = false; @@ -239,16 +264,14 @@ describe('legacy storage', () => { }; req.onerror = () => reject(req.error); }); - const names = async () => (await indexedDB.databases()).map((d) => d.name); - it('removeLegacyStorage drops the token and the Dexie database', async () => { localStorage.setItem('auth_token', 'secret'); await open('wotra'); - expect(await names()).toContain('wotra'); + expect(await databaseNames()).toContain('wotra'); await removeLegacyStorage(); expect(localStorage.getItem('auth_token')).toBeNull(); - expect(await names()).not.toContain('wotra'); - expect(await names()).toContain(`wotra-user-${n}`); + expect(await databaseNames()).not.toContain('wotra'); + expect(await databaseNames()).toContain(`wotra-user-${n}`); }); it('removeLegacyStorage never throws', async () => { @@ -564,3 +587,119 @@ describe('realtime and offline', () => { expect(status.error).toBe('Failed to fetch'); }); }); + +describe('user switch', () => { + it('a second user starts without the collections, cursors, subscriptions and status of the first', async () => { + status.online = true; + const a = `switch-a-${n}`; + const b = `switch-b-${n}`; + await closeDb(); + await openDb(a); + const id = await save('settings_history', null, settingsRow); + await syncNow(); + expect(cursor(a, 'settings_history')).not.toBeNull(); + expect(status.lastSync).toBeGreaterThan(0); + expect(await databaseNames()).toContain(`wotra-${a}`); + mocks.server.clear(); + const givenUp = mocks.unsubscribed.length; + await wipeLocal(a); + expect(mocks.unsubscribed.length - givenUp).toBe(COLLECTIONS.length); + await openDb(b); + expect(status.ready).toBe(true); + expect(status.lastSync).toBe(0); + expect(all('settings_history', true)).toEqual([]); + expect(get('settings_history', id)).toBeUndefined(); + expect(cursor(a, 'settings_history')).toBeNull(); + expect(cursor(b, 'settings_history')).toBeNull(); + expect(await databaseNames()).not.toContain(`wotra-${a}`); + mocks.filters.length = 0; + await syncNow(); + expect(mocks.filters).toEqual(COLLECTIONS.map(() => null)); + expect(all('settings_history', true)).toEqual([]); + }); + + it('wipeLocal removes the cursors and the database, and the next open pulls everything again', async () => { + status.online = true; + const uid = `user-${n}`; + const id = await save('settings_history', null, settingsRow); + await syncNow(); + const stored = cursor(uid, 'settings_history'); + expect(stored).not.toBeNull(); + mocks.filters.length = 0; + await syncNow(); + expect(mocks.filters[COLLECTIONS.indexOf('settings_history')]).toBe(`updated >= "${stored}"`); + await wipeLocal(uid); + expect(status.ready).toBe(false); + expect(cursor(uid, 'settings_history')).toBeNull(); + expect(await databaseNames()).not.toContain(`wotra-${uid}`); + mocks.filters.length = 0; + await openDb(uid); + expect(all('settings_history', true)).toEqual([]); + await syncNow(); + expect(mocks.filters).toEqual(COLLECTIONS.map(() => null)); + expect(get('settings_history', id)?.hours_per_week).toBe(40); + }); +}); + +describe('network failures', () => { + it('a push failing after a good pull keeps the change records and the cursor, and the next round pushes everything', async () => { + status.online = true; + const first = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + const second = await save('balance_adjustments', null, { delta_ms: 2000, note: '', effective_at: 2 }); + mocks.fail.push = 0; + await syncNow(); + expect(pendingCount()).toBe(2); + expect(status.error).toBe('Failed to fetch'); + expect(cursor(`user-${n}`, 'balance_adjustments')).toBeNull(); + expect(mocks.pushes).toHaveLength(0); + mocks.fail.push = null; + await syncNow(); + expect(pendingCount()).toBe(0); + expect(status.error).toBeNull(); + expect(mocks.pushes.map((c) => c.id).sort()).toEqual([first, second].sort()); + expect(cursor(`user-${n}`, 'balance_adjustments')).not.toBeNull(); + }); + + it('a pull failing before the push keeps the change records, and the next round pushes everything', async () => { + status.online = true; + const id = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + mocks.fail.pull = 0; + await syncNow(); + expect(pendingCount()).toBe(1); + expect(mocks.pushes).toHaveLength(0); + expect(status.error).toBe('Failed to fetch'); + expect(cursor(`user-${n}`, 'balance_adjustments')).toBeNull(); + mocks.fail.pull = null; + await syncNow(); + expect(pendingCount()).toBe(0); + expect(mocks.pushes.map((c) => c.id)).toEqual([id]); + expect(cursor(`user-${n}`, 'balance_adjustments')).not.toBeNull(); + }); +}); + +describe('stale answers', () => { + /** Puts a newer version of a settings row on the server, as another device would. */ + const newer = (id: string, hours: number) => { + 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: hours, client_updated_at: Number(record.client_updated_at) + 1_000_000, updated: mocks.stamp() }); + }; + + it('a stale answer applies the server record, and a newer local change wins afterwards', async () => { + status.online = true; + const id = await save('settings_history', null, settingsRow); + await syncNow(); + newer(id, 20); + await update('settings_history', id, { timezone: 'Europe/Berlin' }); + await syncNow(); + expect(status.error).toBeNull(); + expect(get('settings_history', id)).toMatchObject({ hours_per_week: 20, timezone: 'UTC' }); + await update('settings_history', id, { hours_per_week: 30 }); + await syncNow(); + const local = get('settings_history', id); + expect(local).toMatchObject({ hours_per_week: 30, timezone: 'UTC' }); + expect(mocks.server.get('settings_history')?.get(id)).toMatchObject({ hours_per_week: 30, client_updated_at: local?.client_updated_at }); + expect(pendingCount()).toBe(0); + }); +}); diff --git a/web/src/lib/sync.test.ts b/web/src/lib/sync.test.ts index ae1f7f9..309e468 100644 --- a/web/src/lib/sync.test.ts +++ b/web/src/lib/sync.test.ts @@ -1,7 +1,7 @@ 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 { 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(() => { @@ -107,6 +107,15 @@ const tables: Table[] = [ 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)[]; +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 = ''; @@ -180,6 +189,7 @@ describe('reactive reads after writes', () => { 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); @@ -196,6 +206,7 @@ describe('reactive reads after writes', () => { 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);