Every PocketBase event ran its own full sync of the collection, with rejections nobody caught and around beforeSync and onSyncRound. A remote change now starts a round through syncNow(), at most one per 300 ms window; one that lands while a round runs gets its own round after it. The debounced local push is unchanged. A failed pull or push no longer sets the sync error while the browser is offline, since the layout shows "Offline" then. A failed round reports the distinct errors of its syncs on one line instead of the heading syncAll() puts above them.
614 lines
20 KiB
TypeScript
614 lines
20 KiB
TypeScript
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> = T & SyncMeta;
|
|
|
|
type AnyDoc = Doc<Record<string, unknown>>;
|
|
type AnyCollection = Collection<AnyDoc, string>;
|
|
|
|
interface PushResult {
|
|
id: string;
|
|
collection: string;
|
|
status: 'ok' | 'stale' | 'forbidden' | 'readonly' | 'invalid';
|
|
error?: unknown;
|
|
record?: Record<string, unknown> | 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<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: Partial<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;
|
|
/** 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<T extends BaseItem, R>(
|
|
c: Collection<T, string>,
|
|
selector: Selector<T> | undefined,
|
|
read: (cursor: Cursor<T, T>) => 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<string, string>();
|
|
const staleBuffer = new Map<string, AnyDoc[]>();
|
|
/** Change records the last push of a collection sent; the pull after it keeps newer local changes. */
|
|
const pushedChanges = new Map<string, Set<string>>();
|
|
/** 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<typeof setTimeout> | null = null;
|
|
|
|
/** Collections whose local state the sync is about to touch or is touching, by name and nesting depth. */
|
|
const applying = new Map<string, number>();
|
|
const pause = () => new Promise<void>((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<T extends BaseItem>(c: Collection<T, string>): Promise<void> {
|
|
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<void> {
|
|
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<RecordModel[]> {
|
|
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<Record<string, unknown>, 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<AnyDoc>; items?: never } | { items: AnyDoc[]; changes?: never }): Promise<void> {
|
|
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<string> | undefined): Promise<Set<string>> {
|
|
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<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;
|
|
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<CollectionName, AnyCollection> | null = null;
|
|
let syncing: Promise<void> | null = null;
|
|
let beforeSync: (() => Promise<void>) | 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<void> } | null = null;
|
|
|
|
export function openDb(uid: string): Promise<void> {
|
|
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<CollectionName, AnyCollection>): Promise<void> {
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const timeout = new Promise<never>((_, 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<void> {
|
|
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<CollectionName, AnyCollection>;
|
|
for (const name of COLLECTIONS) c[name] = new Collection<AnyDoc, string>(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<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()].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>): 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<void> {
|
|
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<void> {
|
|
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<void> = 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<void> {
|
|
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<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();
|
|
});
|
|
}
|
|
|
|
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<void> {
|
|
try {
|
|
localStorage.removeItem(LEGACY_TOKEN);
|
|
await new Promise<void>((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<K extends CollectionName>(name: K, includeDeleted = false): Doc<PayloadMap[K]>[] {
|
|
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<PayloadMap[K]>[];
|
|
}
|
|
|
|
export function get<K extends CollectionName>(name: K, id: string): Doc<PayloadMap[K]> | 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<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');
|
|
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<K extends CollectionName>(name: K, id: string, patch: Partial<PayloadMap[K]>, deleted?: boolean): Promise<void> {
|
|
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<K extends CollectionName>(name: K, id: string, patch: Partial<PayloadMap[K]>): Promise<void> {
|
|
await merge(name, id, patch);
|
|
}
|
|
|
|
export async function remove<K extends CollectionName>(name: K, id: string): Promise<void> {
|
|
await merge(name, id, {}, true);
|
|
}
|