Browsers of users of the Dexie based version still hold its token in the auth_token key of localStorage and its database named wotra, next to the per user databases of this version. resolveGate() now removes both whenever it lets the user into the app, the first open included. The removal resolves on success, error and block, like wipeLocal, and never throws, so a browser that denies storage cannot keep the user out.
295 lines
11 KiB
TypeScript
295 lines
11 KiB
TypeScript
import { Collection } from '@signaldb/core';
|
|
import { tick } from 'svelte';
|
|
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { all, closeDb, get, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte';
|
|
import { watch } from './testing.svelte';
|
|
|
|
const mocks = vi.hoisted(() => {
|
|
const server = new Map<string, Map<string, Record<string, unknown>>>();
|
|
const pushes: { collection: string; id: string; data: Record<string, unknown>; client_updated_at: number; deleted: boolean }[] = [];
|
|
const batches: number[] = [];
|
|
const reject = { collection: '', error: '' };
|
|
const slow = { name: '' };
|
|
let tick = 0;
|
|
return {
|
|
server,
|
|
pushes,
|
|
batches,
|
|
reject,
|
|
slow,
|
|
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ')
|
|
};
|
|
});
|
|
|
|
vi.mock('$lib/pb', () => ({
|
|
pb: {
|
|
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 () => {
|
|
if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5));
|
|
return [...(mocks.server.get(name)?.values() ?? [])];
|
|
},
|
|
subscribe: async () => async () => undefined
|
|
}),
|
|
send: async (path: string, options: { method?: string; body?: unknown }) => {
|
|
if (path !== '/api/sync/push' || options.method !== 'POST') return {};
|
|
const body = options.body as { changes: (typeof mocks.pushes)[number][] };
|
|
mocks.batches.push(body.changes.length);
|
|
const results = body.changes.map((c) => {
|
|
mocks.pushes.push(c);
|
|
if (mocks.reject.collection === c.collection) return { id: c.id, collection: c.collection, status: 'invalid', error: mocks.reject.error };
|
|
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 };
|
|
}
|
|
}
|
|
}));
|
|
|
|
let n = 0;
|
|
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));
|
|
|
|
beforeEach(async () => {
|
|
status.online = false;
|
|
await openDb(`user-${++n}`);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await closeDb();
|
|
});
|
|
|
|
describe('local collections', () => {
|
|
it('save assigns a 15 char id and all returns the record', async () => {
|
|
const id = await save('balance_adjustments', null, { delta_ms: 1000, note: 'overtime', effective_at: 5 });
|
|
expect(id).toMatch(/^[a-z0-9]{15}$/);
|
|
const rows = all('balance_adjustments');
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0]).toMatchObject({ id, delta_ms: 1000, note: 'overtime', effective_at: 5, deleted: false, rev: 0, updated: '' });
|
|
expect(get('balance_adjustments', id)?.note).toBe('overtime');
|
|
expect(get('balance_adjustments', 'nope')).toBeUndefined();
|
|
});
|
|
|
|
it('update patches the data and bumps client_updated_at', async () => {
|
|
const id = await save('settings_history', null, settingsRow);
|
|
const before = get('settings_history', id)?.client_updated_at ?? 0;
|
|
await update('settings_history', id, { hours_per_week: 32.5 });
|
|
const row = get('settings_history', id);
|
|
expect(row).toMatchObject({ hours_per_week: 32.5, workdays_mask: 31, timezone: 'UTC', deleted: false });
|
|
expect(row?.client_updated_at).toBeGreaterThanOrEqual(before + 1);
|
|
});
|
|
|
|
it('remove hides a record from all but keeps it as deleted', async () => {
|
|
const id = await save('entries', null, { start_time: 1, end_time: 2, auto_stopped: false, note: '', day_key: '2026-01-01' });
|
|
await remove('entries', id);
|
|
expect(all('entries')).toHaveLength(0);
|
|
expect(all('entries', true)).toHaveLength(1);
|
|
expect(all('entries', true)[0]).toMatchObject({ id, deleted: true });
|
|
expect(get('entries', id)?.deleted).toBe(true);
|
|
});
|
|
|
|
it('data survives closeDb and a second openDb', async () => {
|
|
const uid = `user-${n}`;
|
|
const id = await save('settings_history', null, settingsRow);
|
|
await closeDb();
|
|
expect(status.ready).toBe(false);
|
|
expect(all('settings_history')).toEqual([]);
|
|
await openDb(uid);
|
|
expect(all('settings_history')).toHaveLength(1);
|
|
expect(get('settings_history', id)?.hours_per_week).toBe(40);
|
|
});
|
|
});
|
|
|
|
describe('read scopes', () => {
|
|
it('event style reads neither warn nor keep an observer', async () => {
|
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
let created = 0;
|
|
let disposed = 0;
|
|
const collection = Collection.getCollections().find((c) => c.name === 'balance_adjustments');
|
|
if (!collection) throw new Error('collection missing');
|
|
collection.on('observer.created', () => (created += 1));
|
|
collection.on('observer.disposed', () => (disposed += 1));
|
|
try {
|
|
const id = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 });
|
|
await update('balance_adjustments', id, { delta_ms: 2000 });
|
|
expect(all('balance_adjustments')[0]?.delta_ms).toBe(2000);
|
|
expect(get('balance_adjustments', id)?.delta_ms).toBe(2000);
|
|
expect(pendingCount()).toBe(2);
|
|
await remove('balance_adjustments', id);
|
|
expect(all('balance_adjustments')).toHaveLength(0);
|
|
expect(get('balance_adjustments', id)?.deleted).toBe(true);
|
|
expect(pendingCount()).toBe(3);
|
|
await settled();
|
|
expect(warn).not.toHaveBeenCalled();
|
|
expect(created).toBeGreaterThan(0);
|
|
expect(disposed).toBe(created);
|
|
} finally {
|
|
warn.mockRestore();
|
|
}
|
|
});
|
|
|
|
it('reads inside an effect update after every write', async () => {
|
|
const id = await save('balance_adjustments', null, { delta_ms: 1000, note: 'first', effective_at: 1 });
|
|
const total = watch(() => all('balance_adjustments').reduce((sum, a) => sum + a.delta_ms, 0));
|
|
const note = watch(() => get('balance_adjustments', id)?.note);
|
|
try {
|
|
await tick();
|
|
expect(total.current).toBe(1000);
|
|
expect(note.current).toBe('first');
|
|
await update('balance_adjustments', id, { delta_ms: 3000, note: 'second' });
|
|
await tick();
|
|
expect(total.current).toBe(3000);
|
|
expect(note.current).toBe('second');
|
|
await remove('balance_adjustments', id);
|
|
await tick();
|
|
expect(total.current).toBe(0);
|
|
expect(note.current).toBe('second');
|
|
} finally {
|
|
total.dispose();
|
|
note.dispose();
|
|
}
|
|
const runs = total.runs;
|
|
await save('balance_adjustments', null, { delta_ms: 5, note: '', effective_at: 1 });
|
|
await tick();
|
|
expect(total.runs).toBe(runs);
|
|
});
|
|
});
|
|
|
|
describe('legacy storage', () => {
|
|
const open = (name: string) =>
|
|
new Promise<void>((resolve, reject) => {
|
|
const req = indexedDB.open(name);
|
|
req.onsuccess = () => {
|
|
req.result.close();
|
|
resolve();
|
|
};
|
|
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');
|
|
await removeLegacyStorage();
|
|
expect(localStorage.getItem('auth_token')).toBeNull();
|
|
expect(await names()).not.toContain('wotra');
|
|
expect(await names()).toContain(`wotra-user-${n}`);
|
|
});
|
|
|
|
it('removeLegacyStorage never throws', async () => {
|
|
vi.stubGlobal('indexedDB', undefined);
|
|
try {
|
|
await expect(removeLegacyStorage()).resolves.toBeUndefined();
|
|
} finally {
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('sync boundary', () => {
|
|
it('toRecord turns end_time 0 into null and coerces the metadata', () => {
|
|
const doc = toRecord('entries', {
|
|
id: 'abc',
|
|
owner: 'u1',
|
|
start_time: '10',
|
|
end_time: 0,
|
|
auto_stopped: 1,
|
|
note: null,
|
|
day_key: '2026-01-01',
|
|
client_updated_at: '7',
|
|
rev: null,
|
|
deleted: false,
|
|
updated: 123,
|
|
created: 'x'
|
|
});
|
|
expect(doc).toEqual({
|
|
id: 'abc',
|
|
start_time: 10,
|
|
end_time: null,
|
|
auto_stopped: true,
|
|
note: '',
|
|
day_key: '2026-01-01',
|
|
client_updated_at: 7,
|
|
rev: 0,
|
|
deleted: false,
|
|
updated: '123'
|
|
});
|
|
});
|
|
|
|
it('toRecord keeps 0 in fields that are not zero-means-null', () => {
|
|
expect(toRecord('balance_adjustments', { id: 'a', delta_ms: 0, note: '', effective_at: 0 }).delta_ms).toBe(0);
|
|
expect(toRecord('entries', { id: 'a', start_time: 0, end_time: 5, auto_stopped: false, note: '', day_key: '' }).start_time).toBe(0);
|
|
});
|
|
|
|
it('a sync round pushes end_time null as 0 and pulls 0 back as null', async () => {
|
|
status.online = true;
|
|
await save('entries', null, { start_time: 1000, end_time: null, auto_stopped: false, note: 'run', day_key: '1970-01-01' });
|
|
expect(pendingCount()).toBe(1);
|
|
await syncNow();
|
|
expect(pendingCount()).toBe(0);
|
|
const pushed = mocks.pushes.filter((c) => c.collection === 'entries');
|
|
expect(pushed).toHaveLength(1);
|
|
expect(pushed[0].data).toEqual({ start_time: 1000, end_time: 0, auto_stopped: false, note: 'run', day_key: '1970-01-01' });
|
|
expect(pushed[0].deleted).toBe(false);
|
|
const row = all('entries')[0];
|
|
expect(row).toMatchObject({ start_time: 1000, end_time: null, note: 'run', deleted: false, rev: 1 });
|
|
expect(row.updated).not.toBe('');
|
|
expect(localStorage.getItem(`wotra-cursor:user-${n}:entries`)).not.toBeNull();
|
|
expect(status.error).toBeNull();
|
|
});
|
|
|
|
it('a sync round pushes in batches below the server limit', async () => {
|
|
status.online = true;
|
|
mocks.batches.length = 0;
|
|
for (let i = 0; i < 250; i++) {
|
|
await save('balance_adjustments', null, { delta_ms: i + 1, note: '', effective_at: i });
|
|
}
|
|
await syncNow();
|
|
expect(pendingCount()).toBe(0);
|
|
expect(mocks.batches.length).toBeGreaterThan(1);
|
|
expect(Math.max(...mocks.batches)).toBeLessThanOrEqual(200);
|
|
expect(mocks.batches.reduce((sum, size) => sum + size, 0)).toBe(250);
|
|
}, 20000);
|
|
|
|
it('a rejected change is dropped and reported, and a later success of the round keeps the message', async () => {
|
|
status.online = true;
|
|
mocks.reject.collection = 'settings_history';
|
|
mocks.reject.error = 'hours_per_week must be at most 168';
|
|
mocks.slow.name = 'balance_adjustments';
|
|
try {
|
|
const id = await save('settings_history', null, settingsRow);
|
|
await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 });
|
|
await syncNow();
|
|
expect(status.error).toBe('settings_history: hours_per_week must be at most 168');
|
|
mocks.reject.collection = '';
|
|
await syncNow();
|
|
expect(status.error).toBeNull();
|
|
expect(mocks.pushes.filter((c) => c.id === id)).toHaveLength(1);
|
|
} finally {
|
|
mocks.reject.collection = '';
|
|
mocks.slow.name = '';
|
|
}
|
|
});
|
|
|
|
it('a long rejection is cut to 200 characters', async () => {
|
|
status.online = true;
|
|
mocks.reject.collection = 'balance_adjustments';
|
|
mocks.reject.error = 'x'.repeat(300);
|
|
try {
|
|
await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 });
|
|
await syncNow();
|
|
expect(status.error).toBe(`balance_adjustments: ${'x'.repeat(200 - 'balance_adjustments: '.length)}`);
|
|
} finally {
|
|
mocks.reject.collection = '';
|
|
}
|
|
});
|
|
});
|