✨ Add SignalDB collections synced with PocketBase

This commit is contained in:
2026-11-29 17:21:41 +00:00
parent c00b393bec
commit 6a6c2bb71d
3 changed files with 538 additions and 3 deletions
+398
View File
@@ -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);
}
+70
View File
@@ -0,0 +1,70 @@
export type DayKind = 'work' | 'holiday' | 'vacation' | 'sick';
export interface Entry {
start_time: number;
end_time: number | null;
auto_stopped: boolean;
note: string;
day_key: string;
}
export interface ClosedDay {
day_key: string;
worked_ms: number;
kind: DayKind;
closed_at: number;
}
export interface ClosedWeek {
week_key: string;
expected_ms: number;
worked_ms: number;
delta_ms: number;
closed_at: number;
}
export interface Settings {
effective_from: string;
hours_per_week: number;
workdays_mask: number;
timezone: string;
}
export interface BalanceAdjustment {
delta_ms: number;
note: string;
effective_at: number;
}
export interface BalanceSummary {
total_delta_ms: number;
weeks_delta_ms: number;
adjustments_delta_ms: number;
closed_week_count: number;
adjustment_count: number;
}
export interface PayloadMap {
entries: Entry;
closed_days: ClosedDay;
closed_weeks: ClosedWeek;
settings_history: Settings;
balance_adjustments: BalanceAdjustment;
}
export type CollectionName = keyof PayloadMap;
export const COLLECTIONS: CollectionName[] = ['entries', 'closed_days', 'closed_weeks', 'settings_history', 'balance_adjustments'];
export const DATA_FIELDS: Record<CollectionName, string[]> = {
entries: ['start_time', 'end_time', 'auto_stopped', 'note', 'day_key'],
closed_days: ['day_key', 'worked_ms', 'kind', 'closed_at'],
closed_weeks: ['week_key', 'expected_ms', 'worked_ms', 'delta_ms', 'closed_at'],
settings_history: ['effective_from', 'hours_per_week', 'workdays_mask', 'timezone'],
balance_adjustments: ['delta_ms', 'note', 'effective_at']
};
/** Fields the server stores as 0 because PocketBase numbers cannot be null. */
export const ZERO_MEANS_NULL: Partial<Record<CollectionName, string[]>> = { entries: ['end_time'] };
export const DEFAULT_SETTINGS: Settings = { effective_from: '2000-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' };
+70 -3
View File
@@ -182,8 +182,75 @@ export function dayCapabilities(
} }
/** Default day to select for a given week: today if in the week, else Monday. */ /** Default day to select for a given week: today if in the week, else Monday. */
export function defaultDayForWeek(weekKey: string): string { export function defaultDayForWeek(weekKey: string, today: string = todayKey()): string {
const keys = weekDayKeys(weekKey); const keys = weekDayKeys(weekKey);
const t = todayKey(); return keys.includes(today) ? today : keys[0];
return keys.includes(t) ? t : keys[0]; }
const ID_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789';
/** Random record id: 15 chars [a-z0-9], like PocketBase generates them. */
export function newId(): string {
const bytes = crypto.getRandomValues(new Uint8Array(15));
let s = '';
for (const b of bytes) s += ID_CHARS[b % 36];
return s;
}
const tzFormatters = new Map<string, Intl.DateTimeFormat>();
/** Cached date formatter for an IANA timezone; throws for an unknown zone. */
function tzFormatter(tz: string): Intl.DateTimeFormat {
let f = tzFormatters.get(tz);
if (!f) {
f = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hourCycle: 'h23'
});
tzFormatters.set(tz, f);
}
return f;
}
/** Numeric date and time fields of an instant as shown in the timezone. */
function tzParts(tz: string, ms: number): Record<string, number> {
const parts: Record<string, number> = {};
for (const p of tzFormatter(tz).formatToParts(new Date(ms))) {
if (p.type !== 'literal') parts[p.type] = Number(p.value);
}
return parts;
}
/** Day key (YYYY-MM-DD) of a unix ms instant in an IANA timezone. */
export function dayKeyForMs(ms: number, tz: string): string {
const p = tzParts(tz, ms);
return `${String(p.year).padStart(4, '0')}-${pad(p.month)}-${pad(p.day)}`;
}
/** Offset of a timezone from UTC (in ms) at the given instant. */
function tzOffsetMs(tz: string, ms: number): number {
const t = Math.floor(ms / 1000) * 1000;
const p = tzParts(tz, t);
const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour % 24, p.minute, p.second);
return asUtc - t;
}
/** UTC ms of 23:59:59.999 local time of a day (YYYY-MM-DD) in an IANA timezone. */
export function endOfDayMs(dayKey: string, tz: string): number {
const [y, m, d] = dayKey.split('-').map(Number);
const nextMidnight = Date.UTC(y, m - 1, d + 1);
let offset = tzOffsetMs(tz, nextMidnight);
let midnight = nextMidnight - offset;
const verified = tzOffsetMs(tz, midnight);
if (verified !== offset) {
offset = verified;
midnight = nextMidnight - offset;
}
return midnight - 1;
} }