♻️ 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
+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;