♻️ Coalesce realtime changes and stay quiet offline

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.
This commit is contained in:
2026-12-01 19:08:57 +01:00
parent d5b21c431e
commit cb9e250f6a
4 changed files with 92 additions and 16 deletions
+1
View File
@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => {
});
vi.mock('$lib/pb', () => ({
errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)),
pb: {
authStore: { isValid: true },
autoCancellation: () => undefined,
+28 -8
View File
@@ -11,7 +11,7 @@ import {
import { SyncManager } from '@signaldb/sync';
import svelteReactivityAdapter from '@signaldb/svelte';
import prepareIndexedDB from '@signaldb/indexeddb';
import { pb } from '$lib/pb';
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';
@@ -41,6 +41,8 @@ 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;
@@ -157,6 +159,7 @@ 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>();
@@ -212,6 +215,12 @@ 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[] = [];
@@ -330,9 +339,9 @@ async function doOpenDb(uid: string): Promise<void> {
autostart: false,
debounceTime: 300,
onError: (_opts, err) => {
if (!status.ready || syncing) return;
if (!status.ready || syncing) return;
if (!pb.authStore.isValid || unauthorized(err)) sessionExpired?.();
else status.error = err.message;
else if (status.online) status.error = err.message;
},
pull: async ({ name }) => {
pullRuns += 1;
@@ -388,11 +397,9 @@ async function doOpenDb(uid: string): Promise<void> {
enterApply(name);
}
},
registerRemoteChange: async ({ name }, onChange) => {
registerRemoteChange: async ({ name }) => {
try {
const unsub = await pb.collection(name).subscribe('*', () => {
void onChange();
});
const unsub = await pb.collection(name).subscribe('*', () => remoteChange());
if (gen !== epoch) {
void unsub().catch(() => {});
return undefined;
@@ -432,6 +439,17 @@ 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;
@@ -447,7 +465,7 @@ export function syncNow(): Promise<void> {
.catch((err: Error) => {
if (m !== sm) return;
if (!pb.authStore.isValid || m.failures.some(unauthorized)) sessionExpired?.();
else status.error = err.message;
else if (status.online) status.error = roundError(m, err);
})
.finally(() => {
if (syncing === run) syncing = null;
@@ -486,6 +504,8 @@ function installTriggers() {
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;
+62 -8
View File
@@ -1,7 +1,7 @@
import { Collection } from '@signaldb/core';
import { tick } from 'svelte';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { all, closeDb, currentUserId, get, onSessionExpired, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte';
import { all, closeDb, currentUserId, get, onBeforeSync, onSessionExpired, onSyncRound, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte';
import { holdNextOpen, watch } from './testing.svelte';
const mocks = vi.hoisted(() => {
@@ -10,9 +10,14 @@ const mocks = vi.hoisted(() => {
const batches: number[] = [];
const reject = { collection: '', error: '' };
const slow = { name: '' };
/** HTTP status the mock answers instead of a result; 0 answers normally. */
const fail = { pull: 0, push: 0 };
/** HTTP status the mock answers instead of a result, 0 like a network failure; null answers normally. */
const fail = { pull: null as number | null, push: null as number | null };
const auth = { valid: true };
/** Realtime callbacks by collection, and the subscriptions given up so far. */
const listeners = new Map<string, (data?: unknown) => void>();
const unsubscribed: string[] = [];
/** Pulls the mock answered so far. */
const pulls = { count: 0 };
let tick = 0;
/** Answers like the SDK does: a 401 also clears the auth store. */
const refuse = (status: number): never => {
@@ -27,12 +32,16 @@ const mocks = vi.hoisted(() => {
slow,
fail,
auth,
listeners,
unsubscribed,
pulls,
refuse,
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ')
};
});
vi.mock('$lib/pb', () => ({
errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)),
pb: {
authStore: {
get isValid() {
@@ -44,15 +53,21 @@ vi.mock('$lib/pb', () => ({
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
collection: (name: string) => ({
getFullList: async () => {
mocks.pulls.count += 1;
if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5));
if (mocks.fail.pull) mocks.refuse(mocks.fail.pull);
if (mocks.fail.pull !== null) mocks.refuse(mocks.fail.pull);
return [...(mocks.server.get(name)?.values() ?? [])];
},
subscribe: async () => async () => undefined
subscribe: async (topic: string, callback: (data?: unknown) => void) => {
mocks.listeners.set(topic === '*' ? name : topic, callback);
return async () => {
mocks.unsubscribed.push(name);
};
}
}),
send: async (path: string, options: { method?: string; body?: unknown }) => {
if (path !== '/api/sync/push' || options.method !== 'POST') return {};
if (mocks.fail.push) mocks.refuse(mocks.fail.push);
if (mocks.fail.push !== null) mocks.refuse(mocks.fail.push);
const body = options.body as { changes: (typeof mocks.pushes)[number][] };
mocks.batches.push(body.changes.length);
const results = body.changes.map((c) => {
@@ -83,8 +98,8 @@ beforeEach(async () => {
afterEach(() => {
mocks.pushes.length = 0;
mocks.fail.pull = 0;
mocks.fail.push = 0;
mocks.fail.pull = null;
mocks.fail.push = null;
mocks.auth.valid = true;
status.error = null;
});
@@ -410,3 +425,42 @@ describe('merge after apply', () => {
expect(await update('entries', 'missing', { note: 'ignored' })).toBeUndefined();
});
});
describe('realtime and offline', () => {
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
it('a burst of realtime events runs one round, through the sync hooks', async () => {
status.online = true;
const before = vi.fn(async () => undefined);
onBeforeSync(before);
const rounds = vi.fn();
onSyncRound(rounds);
const pulls = mocks.pulls.count;
const notify = mocks.listeners.get('entries');
if (!notify) throw new Error('no realtime subscription');
mocks.fail.pull = 0;
for (let i = 0; i < 20; i++) {
notify({});
await wait(5);
}
await wait(450);
expect(rounds).toHaveBeenCalledTimes(1);
expect(before).toHaveBeenCalledTimes(1);
expect(mocks.pulls.count - pulls).toBe(5);
expect(status.error).toBe('Failed to fetch');
});
it('a failed push of an offline write leaves the error empty', async () => {
status.online = false;
mocks.fail.pull = 0;
mocks.fail.push = 0;
await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 });
await wait(400);
expect(pendingCount()).toBe(1);
expect(status.error).toBeNull();
status.online = true;
await save('balance_adjustments', null, { delta_ms: 2000, note: '', effective_at: 1 });
await wait(400);
expect(status.error).toBe('Failed to fetch');
});
});
+1
View File
@@ -29,6 +29,7 @@ const mocks = vi.hoisted(() => {
});
vi.mock('$lib/pb', () => ({
errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)),
pb: {
authStore: { isValid: true },
autoCancellation: () => undefined,