import { Collection, DefaultDataAdapter, createReactivityAdapter, type BaseItem, type Changeset, type Cursor, type ReactivityAdapter, type Selector } from '@signaldb/core'; import { SyncManager } from '@signaldb/sync'; import svelteReactivityAdapter from '@signaldb/svelte'; import prepareIndexedDB from '@signaldb/indexeddb'; import { errorMessage, 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'; export interface SyncMeta { id: string; client_updated_at: number; rev: number; deleted: boolean; updated: string; } export type Doc = T & SyncMeta; type AnyDoc = Doc>; type AnyCollection = Collection; interface PushResult { id: string; collection: string; status: 'ok' | 'stale' | 'forbidden' | 'readonly' | 'invalid'; error?: unknown; record?: Record | null; } const SYNC_ID = 'wotra'; const SCHEMA_VERSION = 1; /** Changes per push request; the server rejects more than 500. */ const PUSH_BATCH = 200; /** Window in which realtime events share one round. */ const REMOTE_DEBOUNCE = 300; /** Upper bound for opening the local database in milliseconds. */ const OPEN_TIMEOUT = 8000; const NUMBER_FIELDS: Record = { entries: ['start_time', 'end_time'], closed_days: ['worked_ms', 'closed_at'], closed_weeks: ['expected_ms', 'worked_ms', 'delta_ms', 'closed_at'], settings_history: ['hours_per_week', 'workdays_mask'], balance_adjustments: ['delta_ms', 'effective_at'] }; const BOOL_FIELDS: Partial> = { entries: ['auto_stopped'] }; function localDbName(userId: string): string { return `wotra-${userId}`; } function schema(): Record { const s: Record = {}; for (const c of COLLECTIONS) s[c] = []; s[`${SYNC_ID}-changes`] = ['collectionName']; s[`${SYNC_ID}-snapshots`] = ['collectionName']; s[`${SYNC_ID}-sync-operations`] = ['collectionName', 'status']; return s; } function isCollection(name: string): name is CollectionName { return (COLLECTIONS as string[]).includes(name); } /** Local shape of a server record: only the data fields plus the sync metadata. */ export function toRecord(name: CollectionName, r: Record): AnyDoc { const zeros = ZERO_MEANS_NULL[name] ?? []; const bools = BOOL_FIELDS[name] ?? []; const data: Record = {}; for (const f of DATA_FIELDS[name]) { const raw = r[f]; if (NUMBER_FIELDS[name].includes(f)) { const n = Number(raw ?? 0); data[f] = zeros.includes(f) && n === 0 ? null : n; } else if (bools.includes(f)) { data[f] = Boolean(raw); } else { data[f] = raw == null ? '' : String(raw); } } return { ...data, id: String(r.id), client_updated_at: Number(r.client_updated_at ?? 0), rev: Number(r.rev ?? 0), deleted: Boolean(r.deleted), updated: String(r.updated ?? '') }; } /** Server shape of a local record: only the data fields, null numbers become 0. */ function toServerData(name: CollectionName, item: AnyDoc): Record { const data: Record = {}; for (const f of DATA_FIELDS[name]) { const v = item[f]; data[f] = v == null ? 0 : v; } return data; } function pick(name: K, data: Partial): Record { const out: Record = {}; for (const [f, v] of Object.entries(data)) { if (DATA_FIELDS[name].includes(f)) out[f] = v; } return out; } export const status = $state({ online: typeof navigator === 'undefined' ? true : navigator.onLine, lastSync: 0 as number, error: null as string | null, ready: false }); const reactivity = svelteReactivityAdapter; /** Reports a reactive scope where there is none, so a cursor reads silently and wakes nobody. */ const silent: ReactivityAdapter = createReactivityAdapter({ create: () => ({ depend() {}, notify() {} }), isInScope: () => true }); function inScope(): boolean { return reactivity.isInScope ? reactivity.isInScope() : true; } /** Reads outside a reactive scope: registers no dependency and releases the cursor's observer. */ function readOnce( c: Collection, selector: Selector | undefined, read: (cursor: Cursor) => R ): R { const cursor = c.find(selector, { reactive: silent }); try { return read(cursor); } finally { cursor.cleanup(); } } const cursorKey = (uid: string, name: string) => `wotra-cursor:${uid}:${name}`; let userId = ''; 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>(); /** Set when the server rejected a change of the current round; its message stays until a round succeeds. */ let rejected = false; let sessionExpired: (() => void) | null = null; let remoteTimer: ReturnType | null = null; /** 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) { if (!pb.authStore.isValid) return; const c = pendingCursor.get(name); if (c && userId) { localStorage.setItem(cursorKey(userId, name), c); pendingCursor.delete(name); } status.lastSync = Date.now(); if (!rejected) status.error = null; } /** A 401 ends the session; the SDK has usually cleared the auth store already. */ function unauthorized(e: unknown): boolean { return (e as { status?: unknown } | null)?.status === 401; } /** What a failed round reports: the distinct errors of its syncs on one line, since syncAll() only lists them below a heading. */ function roundError(m: WotraSync, err: Error): string { const messages = [...new Set(m.failures.map(errorMessage))]; return messages.length ? messages.join(', ') : err.message; } class WotraSync extends SyncManager, AnyDoc, string> { /** Errors of the sync calls of the current round as they were thrown, before syncAll() summarized them. */ readonly failures: unknown[] = []; pending(): number { 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()); const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); let idle = false; while (!idle) { if (busy()) { await tick(); continue; } await tick(); idle = !busy(); } } override async sync(name: string, options?: { force?: boolean; onlyWithChanges?: boolean }): Promise { const before = pullRuns; try { await super.sync(name, options); } catch (e) { this.failures.push(e); throw e; } if (pullRuns !== before) onSynced(name); } } let sm: WotraSync | null = null; let cols: Record | null = null; let syncing: Promise | null = null; let beforeSync: (() => Promise) | null = null; const cleanups: (() => void)[] = []; const roundListeners = new Set<() => void>(); /** An open in flight and the user it is for; an open for another user waits for it. */ let opening: { uid: string; done: Promise } | null = null; export function openDb(uid: string): Promise { if (opening?.uid === uid) return opening.done; const settled = opening?.done.catch(() => {}) ?? Promise.resolve(); const done = settled .then(() => doOpenDb(uid)) .finally(() => { if (opening?.done === done) opening = null; }); opening = { uid, done }; return done; } /** Resolves once every collection is ready; rejects when the database cannot be opened or a blocked open does not answer in time. */ function ready(c: Record): Promise { let timer: ReturnType | undefined; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('the browser blocked it or did not answer')), OPEN_TIMEOUT); }); const all = Promise.all(COLLECTIONS.map((n) => c[n].ready())).then(() => undefined); return Promise.race([all, timeout]).finally(() => clearTimeout(timer)); } async function doOpenDb(uid: string): Promise { if (sm && userId === uid) return; await closeDb(); const gen = epoch; userId = uid; pendingCursor.clear(); staleBuffer.clear(); pushedChanges.clear(); applying.clear(); const idb = prepareIndexedDB({ databaseName: localDbName(uid), version: SCHEMA_VERSION, schema: schema() }); let opened = false; const adapter = new DefaultDataAdapter({ storage: (name) => idb(name), onError: (e) => { if (opened) console.error(e); } }); const c = {} as Record; for (const name of COLLECTIONS) c[name] = new Collection(name, adapter, { reactivity }); try { await ready(c); } catch (e) { await Promise.all(Object.values(c).map((col) => col.dispose().catch(() => {}))); userId = ''; throw e; } opened = true; if (gen !== epoch) { await Promise.all(Object.values(c).map((col) => col.dispose().catch(() => {}))); return; } cols = c; const m: WotraSync = new WotraSync({ id: SYNC_ID, dataAdapter: adapter, reactivity, autostart: false, debounceTime: 300, onError: (_opts, err) => { if (!status.ready || syncing) return; if (!pb.authStore.isValid || unauthorized(err)) sessionExpired?.(); else if (status.online) status.error = err.message; }, 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 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); const stale = staleBuffer.get(name) ?? []; staleBuffer.delete(name); 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()].filter((doc) => !waiting?.has(doc.id)), removed: [] } }; }, 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; 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 === 'invalid') { if (!rejected) status.error = `${name}: ${String(r.error ?? 'rejected')}`.slice(0, 200); rejected = true; continue; } 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 }) => { try { const unsub = await pb.collection(name).subscribe('*', () => remoteChange()); if (gen !== epoch) { void unsub().catch(() => {}); return undefined; } return () => { void unsub().catch(() => {}); }; } catch { return undefined; } } }); sm = m; for (const name of COLLECTIONS) m.addCollection(c[name], { name }); void m.startAll().catch(() => {}); status.ready = true; installTriggers(); await runBeforeSync(); void syncNow(); } export function onSyncRound(fn: () => void): () => void { roundListeners.add(fn); return () => roundListeners.delete(fn); } export function onBeforeSync(fn: () => Promise): void { beforeSync = fn; } /** Registers what runs when a round found the session gone; the session module ends itself there. */ export function onSessionExpired(fn: () => void): void { sessionExpired = fn; } function runBeforeSync(): Promise { return beforeSync ? beforeSync() : Promise.resolve(); } /** A remote change runs a full round, at most one per window; one that lands during a round gets its own round after it. */ function remoteChange(): void { if (remoteTimer) return; remoteTimer = setTimeout(() => { remoteTimer = null; void (syncing ?? Promise.resolve()) .then(() => syncNow()) .catch(() => {}); }, REMOTE_DEBOUNCE); } export function syncNow(): Promise { if (syncing) return syncing; const m = sm; if (!m || !status.online) return Promise.resolve(); if (!pb.authStore.isValid) { sessionExpired?.(); return Promise.resolve(); } rejected = false; m.failures.length = 0; const run: Promise = runBeforeSync() .then(() => m.syncAll()) .catch((err: Error) => { if (m !== sm) return; if (!pb.authStore.isValid || m.failures.some(unauthorized)) sessionExpired?.(); else if (status.online) status.error = roundError(m, err); }) .finally(() => { if (syncing === run) syncing = null; for (const fn of roundListeners) fn(); }); syncing = run; return run; } function installTriggers() { const online = () => { status.online = true; void sm?.startAll().catch(() => {}); void syncNow(); }; const offline = () => { status.online = false; }; const focus = () => { if (document.visibilityState === 'visible') void syncNow(); }; window.addEventListener('online', online); window.addEventListener('offline', offline); window.addEventListener('focus', focus); document.addEventListener('visibilitychange', focus); const iv = setInterval(() => void syncNow(), 60000); cleanups.push(() => { window.removeEventListener('online', online); window.removeEventListener('offline', offline); window.removeEventListener('focus', focus); document.removeEventListener('visibilitychange', focus); clearInterval(iv); }); } export async function closeDb(): Promise { epoch += 1; status.ready = false; if (remoteTimer) clearTimeout(remoteTimer); remoteTimer = null; for (const c of cleanups.splice(0)) c(); const m = sm; sm = null; syncing = null; if (m) { await m.pauseAll().catch(() => {}); await m.settle(); await m.dispose().catch(() => {}); } const c = cols; cols = null; if (c) await Promise.all(Object.values(c).map((col) => col.dispose().catch(() => {}))); } export async function wipeLocal(uid: string): Promise { await closeDb(); for (const name of COLLECTIONS) localStorage.removeItem(cursorKey(uid, name)); await new Promise((resolve) => { const req = indexedDB.deleteDatabase(localDbName(uid)); req.onsuccess = req.onerror = req.onblocked = () => resolve(); }); } const LEGACY_TOKEN = 'auth_token'; const LEGACY_DB = 'wotra'; /** Token and database of the Dexie based app; removed on sign-in, whatever the browser allows. */ export async function removeLegacyStorage(): Promise { try { localStorage.removeItem(LEGACY_TOKEN); await new Promise((resolve) => { const req = indexedDB.deleteDatabase(LEGACY_DB); req.onsuccess = req.onerror = req.onblocked = () => resolve(); }); } catch {} } export function currentUserId(): string { return userId; } export function pendingCount(): number { return sm?.pending() ?? 0; } export function all(name: K, includeDeleted = false): Doc[] { const c = cols?.[name]; if (!c) return []; const selector = includeDeleted ? {} : { deleted: false }; const rows = inScope() ? c.find(selector).fetch() : readOnce(c, selector, (cursor) => cursor.fetch()); return rows as unknown as Doc[]; } export function get(name: K, id: string): Doc | undefined { const c = cols?.[name]; if (!c) return undefined; const row = inScope() ? c.findOne({ id }) : readOnce(c, { id }, (cursor) => cursor.fetch()[0]); return row as Doc | undefined; } export async function save(name: K, id: string | null, data: PayloadMap[K], deleted = false): Promise { if (!cols) throw new Error('database is not open'); 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]); const cua = Math.max(now, (prev?.client_updated_at ?? 0) + 1); const rec: AnyDoc = { ...pick(name, data), id: rid, client_updated_at: cua, rev: prev?.rev ?? 0, deleted, updated: prev?.updated ?? '' }; if (prev) await c.replaceOne({ id: rid }, rec); else await c.insert(rec); return rid; } /** Applies a patch once the sync applied the server state it was waiting for, so the fields the patch leaves out keep a newer remote value. */ async function merge(name: K, id: string, patch: Partial, deleted?: boolean): Promise { if (!cols) throw new Error('database is not open'); await waitForApply(name); const c = cols?.[name]; if (!c) throw new Error('database is not open'); const prev = readOnce(c, { id }, (cursor) => cursor.fetch()[0]); if (!prev) return; await c.replaceOne({ id }, { ...prev, ...pick(name, patch), client_updated_at: Math.max(Date.now(), prev.client_updated_at + 1), deleted: deleted ?? prev.deleted }); } export async function update(name: K, id: string, patch: Partial): Promise { await merge(name, id, patch); } export async function remove(name: K, id: string): Promise { await merge(name, id, {}, true); }