🧪 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.
This commit is contained in:
@@ -528,6 +528,7 @@ function installTriggers() {
|
|||||||
export async function closeDb(): Promise<void> {
|
export async function closeDb(): Promise<void> {
|
||||||
epoch += 1;
|
epoch += 1;
|
||||||
status.ready = false;
|
status.ready = false;
|
||||||
|
status.lastSync = 0;
|
||||||
if (remoteTimer) clearTimeout(remoteTimer);
|
if (remoteTimer) clearTimeout(remoteTimer);
|
||||||
remoteTimer = null;
|
remoteTimer = null;
|
||||||
for (const c of cleanups.splice(0)) c();
|
for (const c of cleanups.splice(0)) c();
|
||||||
|
|||||||
+148
-9
@@ -1,8 +1,27 @@
|
|||||||
import { Collection } from '@signaldb/core';
|
import { Collection } from '@signaldb/core';
|
||||||
import { tick } from 'svelte';
|
import { tick } from 'svelte';
|
||||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
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 { holdNextOpen, watch } from './testing.svelte';
|
||||||
|
import { COLLECTIONS } from './types';
|
||||||
|
|
||||||
const mocks = vi.hoisted(() => {
|
const mocks = vi.hoisted(() => {
|
||||||
const server = new Map<string, Map<string, Record<string, unknown>>>();
|
const server = new Map<string, Map<string, Record<string, unknown>>>();
|
||||||
@@ -17,8 +36,9 @@ const mocks = vi.hoisted(() => {
|
|||||||
/** Realtime callbacks by collection, and the subscriptions given up so far. */
|
/** Realtime callbacks by collection, and the subscriptions given up so far. */
|
||||||
const listeners = new Map<string, (data?: unknown) => void>();
|
const listeners = new Map<string, (data?: unknown) => void>();
|
||||||
const unsubscribed: string[] = [];
|
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 pulls = { count: 0 };
|
||||||
|
const filters: (string | null)[] = [];
|
||||||
let tick = 0;
|
let tick = 0;
|
||||||
/** Answers like the SDK does: a 401 also clears the auth store. */
|
/** Answers like the SDK does: a 401 also clears the auth store. */
|
||||||
const refuse = (status: number): never => {
|
const refuse = (status: number): never => {
|
||||||
@@ -36,6 +56,7 @@ const mocks = vi.hoisted(() => {
|
|||||||
listeners,
|
listeners,
|
||||||
unsubscribed,
|
unsubscribed,
|
||||||
pulls,
|
pulls,
|
||||||
|
filters,
|
||||||
refuse,
|
refuse,
|
||||||
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ')
|
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ')
|
||||||
};
|
};
|
||||||
@@ -53,11 +74,13 @@ vi.mock('$lib/pb', () => ({
|
|||||||
autoCancellation: () => undefined,
|
autoCancellation: () => undefined,
|
||||||
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
|
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
|
||||||
collection: (name: string) => ({
|
collection: (name: string) => ({
|
||||||
getFullList: async () => {
|
getFullList: async (options?: { filter?: string }) => {
|
||||||
mocks.pulls.count += 1;
|
mocks.pulls.count += 1;
|
||||||
|
mocks.filters.push(options?.filter ?? null);
|
||||||
if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5));
|
if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||||
if (mocks.fail.pull !== null) mocks.refuse(mocks.fail.pull);
|
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) => {
|
subscribe: async (topic: string, callback: (data?: unknown) => void) => {
|
||||||
mocks.listeners.set(topic === '*' ? name : topic, callback);
|
mocks.listeners.set(topic === '*' ? name : topic, callback);
|
||||||
@@ -97,6 +120,8 @@ vi.mock('$lib/pb', () => ({
|
|||||||
let n = 0;
|
let n = 0;
|
||||||
const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' };
|
const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' };
|
||||||
const settled = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
|
const settled = () => new Promise<void>((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 () => {
|
beforeEach(async () => {
|
||||||
status.online = false;
|
status.online = false;
|
||||||
@@ -239,16 +264,14 @@ describe('legacy storage', () => {
|
|||||||
};
|
};
|
||||||
req.onerror = () => reject(req.error);
|
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 () => {
|
it('removeLegacyStorage drops the token and the Dexie database', async () => {
|
||||||
localStorage.setItem('auth_token', 'secret');
|
localStorage.setItem('auth_token', 'secret');
|
||||||
await open('wotra');
|
await open('wotra');
|
||||||
expect(await names()).toContain('wotra');
|
expect(await databaseNames()).toContain('wotra');
|
||||||
await removeLegacyStorage();
|
await removeLegacyStorage();
|
||||||
expect(localStorage.getItem('auth_token')).toBeNull();
|
expect(localStorage.getItem('auth_token')).toBeNull();
|
||||||
expect(await names()).not.toContain('wotra');
|
expect(await databaseNames()).not.toContain('wotra');
|
||||||
expect(await names()).toContain(`wotra-user-${n}`);
|
expect(await databaseNames()).toContain(`wotra-user-${n}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('removeLegacyStorage never throws', async () => {
|
it('removeLegacyStorage never throws', async () => {
|
||||||
@@ -564,3 +587,119 @@ describe('realtime and offline', () => {
|
|||||||
expect(status.error).toBe('Failed to fetch');
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { tick } from 'svelte';
|
import { tick } from 'svelte';
|
||||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
import { addAdjustment, balance, deleteAdjustment } from './app.svelte';
|
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';
|
import { watch, type Watcher } from './testing.svelte';
|
||||||
|
|
||||||
const mocks = vi.hoisted(() => {
|
const mocks = vi.hoisted(() => {
|
||||||
@@ -107,6 +107,15 @@ const tables: Table[] = [
|
|||||||
|
|
||||||
const sum = (values: Map<string, number>) => [...values.values()].reduce((total, v) => total + v, 0);
|
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 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', () => {
|
describe('reactive reads after writes', () => {
|
||||||
let anchor = '';
|
let anchor = '';
|
||||||
@@ -180,6 +189,7 @@ describe('reactive reads after writes', () => {
|
|||||||
if (round % FLIGHT_EVERY !== 0) continue;
|
if (round % FLIGHT_EVERY !== 0) continue;
|
||||||
await syncNow();
|
await syncNow();
|
||||||
expect(pendingCount()).toBe(0);
|
expect(pendingCount()).toBe(0);
|
||||||
|
expectMirrorsServer();
|
||||||
const push = mocks.holdNextPush();
|
const push = mocks.holdNextPush();
|
||||||
const adjustment = await addAdjustment({ delta_ms: 7, effective_at: round });
|
const adjustment = await addAdjustment({ delta_ms: 7, effective_at: round });
|
||||||
tables[2].live.set(adjustment, 7);
|
tables[2].live.set(adjustment, 7);
|
||||||
@@ -196,6 +206,7 @@ describe('reactive reads after writes', () => {
|
|||||||
await syncNow();
|
await syncNow();
|
||||||
await expectModel(round, true);
|
await expectModel(round, true);
|
||||||
expect(pendingCount()).toBe(0);
|
expect(pendingCount()).toBe(0);
|
||||||
|
expectMirrorsServer();
|
||||||
expect(pending.current).toBe(0);
|
expect(pending.current).toBe(0);
|
||||||
const counts = watchers[2]?.count.seen.slice(seen) ?? [];
|
const counts = watchers[2]?.count.seen.slice(seen) ?? [];
|
||||||
expect(counts.every((count) => count === tables[2].live.size)).toBe(true);
|
expect(counts.every((count) => count === tables[2].live.size)).toBe(true);
|
||||||
|
|||||||
Reference in New Issue
Block a user