✨ Add SignalDB collections synced with PocketBase
This commit is contained in:
@@ -0,0 +1,398 @@
|
||||
import { Collection, DefaultDataAdapter } from '@signaldb/core';
|
||||
import { SyncManager } from '@signaldb/sync';
|
||||
import svelteReactivityAdapter from '@signaldb/svelte';
|
||||
import prepareIndexedDB from '@signaldb/indexeddb';
|
||||
import { pb } from '$lib/pb';
|
||||
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> = T & SyncMeta;
|
||||
|
||||
type AnyDoc = Doc<Record<string, unknown>>;
|
||||
type AnyCollection = Collection<AnyDoc, string>;
|
||||
|
||||
interface PushResult {
|
||||
id: string;
|
||||
collection: string;
|
||||
status: 'ok' | 'stale' | 'forbidden' | 'readonly';
|
||||
record?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
const SYNC_ID = 'wotra';
|
||||
const SCHEMA_VERSION = 1;
|
||||
|
||||
const NUMBER_FIELDS: Record<CollectionName, string[]> = {
|
||||
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<Record<CollectionName, string[]>> = { entries: ['auto_stopped'] };
|
||||
|
||||
function localDbName(userId: string): string {
|
||||
return `wotra-${userId}`;
|
||||
}
|
||||
|
||||
function schema(): Record<string, string[]> {
|
||||
const s: Record<string, string[]> = {};
|
||||
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<string, unknown>): AnyDoc {
|
||||
const zeros = ZERO_MEANS_NULL[name] ?? [];
|
||||
const bools = BOOL_FIELDS[name] ?? [];
|
||||
const data: Record<string, unknown> = {};
|
||||
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<string, unknown> {
|
||||
const data: Record<string, unknown> = {};
|
||||
for (const f of DATA_FIELDS[name]) {
|
||||
const v = item[f];
|
||||
data[f] = v == null ? 0 : v;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function pick<K extends CollectionName>(name: K, data: PayloadMap[K]): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
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;
|
||||
|
||||
/** Reactive when called inside a reactive scope, a plain read otherwise. */
|
||||
function readOptions(): { reactive: false } | undefined {
|
||||
return reactivity.isInScope?.() ? undefined : { reactive: false };
|
||||
}
|
||||
|
||||
const cursorKey = (uid: string, name: string) => `wotra-cursor:${uid}:${name}`;
|
||||
let userId = '';
|
||||
let epoch = 0;
|
||||
let pullRuns = 0;
|
||||
const pendingCursor = new Map<string, string>();
|
||||
const staleBuffer = new Map<string, AnyDoc[]>();
|
||||
|
||||
function onSynced(name: string) {
|
||||
const c = pendingCursor.get(name);
|
||||
if (c && userId) {
|
||||
localStorage.setItem(cursorKey(userId, name), c);
|
||||
pendingCursor.delete(name);
|
||||
}
|
||||
status.lastSync = Date.now();
|
||||
status.error = null;
|
||||
}
|
||||
|
||||
class WotraSync extends SyncManager<Record<string, unknown>, AnyDoc, string> {
|
||||
pending(): number {
|
||||
return this.changes.find({}, readOptions()).count();
|
||||
}
|
||||
/** Lets writes in flight finish, since the sync manager rejects them after dispose(). */
|
||||
async settle(): Promise<void> {
|
||||
const busy = () => [this.changes, ...[...this.collections.values()].map((c) => c.collection)].some((c) => c.isPushing());
|
||||
const tick = () => new Promise<void>((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<void> {
|
||||
const before = pullRuns;
|
||||
await super.sync(name, options);
|
||||
if (pullRuns !== before) onSynced(name);
|
||||
}
|
||||
}
|
||||
|
||||
let sm: WotraSync | null = null;
|
||||
let cols: Record<CollectionName, AnyCollection> | null = null;
|
||||
let syncing: Promise<void> | null = null;
|
||||
let beforeSync: (() => Promise<void>) | null = null;
|
||||
const cleanups: (() => void)[] = [];
|
||||
const roundListeners = new Set<() => void>();
|
||||
let opening: Promise<void> | null = null;
|
||||
|
||||
export function openDb(uid: string): Promise<void> {
|
||||
if (opening) return opening;
|
||||
opening = doOpenDb(uid).finally(() => {
|
||||
opening = null;
|
||||
});
|
||||
return opening;
|
||||
}
|
||||
|
||||
async function doOpenDb(uid: string): Promise<void> {
|
||||
if (sm && userId === uid) return;
|
||||
await closeDb();
|
||||
const gen = epoch;
|
||||
userId = uid;
|
||||
pendingCursor.clear();
|
||||
staleBuffer.clear();
|
||||
const idb = prepareIndexedDB({ databaseName: localDbName(uid), version: SCHEMA_VERSION, schema: schema() });
|
||||
const adapter = new DefaultDataAdapter({ storage: (name) => idb(name) });
|
||||
const c = {} as Record<CollectionName, AnyCollection>;
|
||||
for (const name of COLLECTIONS) c[name] = new Collection<AnyDoc, string>(name, adapter, { reactivity });
|
||||
await Promise.all(COLLECTIONS.map((n) => c[n].ready()));
|
||||
if (gen !== epoch) {
|
||||
await Promise.all(Object.values(c).map((col) => col.dispose().catch(() => {})));
|
||||
return;
|
||||
}
|
||||
cols = c;
|
||||
const m = new WotraSync({
|
||||
id: SYNC_ID,
|
||||
dataAdapter: adapter,
|
||||
reactivity,
|
||||
autostart: false,
|
||||
debounceTime: 300,
|
||||
onError: (_opts, err) => {
|
||||
if (status.ready) status.error = err.message;
|
||||
},
|
||||
pull: async ({ name }) => {
|
||||
pullRuns += 1;
|
||||
const n = name as CollectionName;
|
||||
const cursor = localStorage.getItem(cursorKey(uid, name));
|
||||
const records = await pb.collection(name).getFullList({
|
||||
sort: 'updated',
|
||||
...(cursor ? { filter: pb.filter('updated >= {:c}', { c: cursor }) } : {})
|
||||
});
|
||||
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<string, AnyDoc>();
|
||||
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()], removed: [] } };
|
||||
},
|
||||
push: async ({ name }, { changes }) => {
|
||||
const items = [...changes.added, ...changes.modified];
|
||||
if (items.length === 0) return;
|
||||
const n = name as CollectionName;
|
||||
const res = await pb.send<{ results: PushResult[] }>('/api/sync/push', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
changes: items.map((i) => ({
|
||||
collection: name,
|
||||
id: i.id,
|
||||
data: toServerData(n, i),
|
||||
client_updated_at: i.client_updated_at,
|
||||
deleted: i.deleted
|
||||
}))
|
||||
}
|
||||
});
|
||||
for (const r of res?.results ?? []) {
|
||||
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);
|
||||
}
|
||||
},
|
||||
registerRemoteChange: async ({ name }, onChange) => {
|
||||
try {
|
||||
const unsub = await pb.collection(name).subscribe('*', () => {
|
||||
void onChange();
|
||||
});
|
||||
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>): void {
|
||||
beforeSync = fn;
|
||||
}
|
||||
|
||||
function runBeforeSync(): Promise<void> {
|
||||
return beforeSync ? beforeSync() : Promise.resolve();
|
||||
}
|
||||
|
||||
export function syncNow(): Promise<void> {
|
||||
if (syncing) return syncing;
|
||||
const m = sm;
|
||||
if (!m || !status.online) return Promise.resolve();
|
||||
const run: Promise<void> = runBeforeSync()
|
||||
.then(() => m.syncAll())
|
||||
.catch((err: Error) => {
|
||||
if (m === sm) status.error = err.message;
|
||||
})
|
||||
.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<void> {
|
||||
epoch += 1;
|
||||
status.ready = false;
|
||||
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<void> {
|
||||
await closeDb();
|
||||
for (const name of COLLECTIONS) localStorage.removeItem(cursorKey(uid, name));
|
||||
await new Promise<void>((resolve) => {
|
||||
const req = indexedDB.deleteDatabase(localDbName(uid));
|
||||
req.onsuccess = req.onerror = req.onblocked = () => resolve();
|
||||
});
|
||||
}
|
||||
|
||||
export function currentUserId(): string {
|
||||
return userId;
|
||||
}
|
||||
|
||||
export function pendingCount(): number {
|
||||
return sm?.pending() ?? 0;
|
||||
}
|
||||
|
||||
export function all<K extends CollectionName>(name: K, includeDeleted = false): Doc<PayloadMap[K]>[] {
|
||||
if (!cols) return [];
|
||||
const c = cols[name];
|
||||
return (includeDeleted ? c.find({}, readOptions()) : c.find({ deleted: false }, readOptions())).fetch() as unknown as Doc<PayloadMap[K]>[];
|
||||
}
|
||||
|
||||
export function get<K extends CollectionName>(name: K, id: string): Doc<PayloadMap[K]> | undefined {
|
||||
if (!cols) return undefined;
|
||||
return cols[name].findOne({ id }, readOptions()) as Doc<PayloadMap[K]> | undefined;
|
||||
}
|
||||
|
||||
export async function save<K extends CollectionName>(name: K, id: string | null, data: PayloadMap[K], deleted = false): Promise<string> {
|
||||
if (!cols) throw new Error('database is not open');
|
||||
const c = cols[name];
|
||||
const rid = id ?? newId();
|
||||
const now = Date.now();
|
||||
const prev = c.findOne({ id: rid }, { reactive: false });
|
||||
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;
|
||||
}
|
||||
|
||||
export async function update<K extends CollectionName>(name: K, id: string, patch: Partial<PayloadMap[K]>): Promise<void> {
|
||||
const cur = get(name, id);
|
||||
if (!cur) return;
|
||||
await save(name, id, { ...cur, ...patch } as PayloadMap[K], cur.deleted);
|
||||
}
|
||||
|
||||
export async function remove<K extends CollectionName>(name: K, id: string): Promise<void> {
|
||||
const cur = get(name, id);
|
||||
if (!cur) return;
|
||||
await save(name, id, cur, true);
|
||||
}
|
||||
Reference in New Issue
Block a user