🐛 Report every change the server rejects or overrides

Only an invalid answer set the sync error: forbidden and readonly were
silent, a stale answer to a deletion silently brought the row back,
the message named no record, and the next automatic round cleared it
before the user saw it.

Every answer the server did not apply now sets the message
"<collection> <record>: <text>", cut to 200 characters, with a text
of its own where the server sends none, and a stale answer to a
deletion says that the server kept a newer version of that record
while that version is applied. The message stays across the automatic
rounds until the user syncs by hand or another rejection replaces it;
the rounds the app starts on its own now run separately from the
manual sync for that.
This commit is contained in:
2026-12-01 19:12:27 +01:00
parent 4359bedde4
commit a29cedbef1
2 changed files with 126 additions and 25 deletions
+41 -18
View File
@@ -156,7 +156,7 @@ const pendingCursor = new Map<string, string>();
const staleBuffer = new Map<string, AnyDoc[]>(); const staleBuffer = new Map<string, AnyDoc[]>();
/** Change records the last push of a collection sent; the pull after it keeps newer local changes. */ /** Change records the last push of a collection sent; the pull after it keeps newer local changes. */
const pushedChanges = new Map<string, Set<string>>(); 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. */ /** Set when the server rejected or overrode a change; its message stays until a manual sync or a new rejection. */
let rejected = false; let rejected = false;
let sessionExpired: (() => void) | null = null; let sessionExpired: (() => void) | null = null;
let remoteTimer: ReturnType<typeof setTimeout> | null = null; let remoteTimer: ReturnType<typeof setTimeout> | null = null;
@@ -215,6 +215,18 @@ function unauthorized(e: unknown): boolean {
return (e as { status?: unknown } | null)?.status === 401; return (e as { status?: unknown } | null)?.status === 401;
} }
/** What the server gives for a change it did not apply, where it sends no text of its own. */
const REJECTION_TEXT: Record<'forbidden' | 'readonly', string> = {
forbidden: 'the record belongs to another account',
readonly: 'the collection is read only'
};
/** Shows that the server did not take a change; the message replaces an earlier one and stays until a manual sync. */
function report(name: string, id: string, text: string): void {
status.error = `${name} ${id}: ${text}`.slice(0, 200);
rejected = true;
}
/** What a failed round reports: the distinct errors of its syncs on one line, since syncAll() only lists them below a heading. */ /** 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 { function roundError(m: WotraSync, err: Error): string {
const messages = [...new Set(m.failures.map(errorMessage))]; const messages = [...new Set(m.failures.map(errorMessage))];
@@ -381,17 +393,19 @@ async function doOpenDb(uid: string): Promise<void> {
})) }))
} }
}); });
for (const r of res?.results ?? []) { const byId = new Map(items.map((it) => [it.id, it]));
if (r.status === 'invalid') { for (const r of res?.results ?? []) {
if (!rejected) status.error = `${name}: ${String(r.error ?? 'rejected')}`.slice(0, 200); if (r.status === 'ok') continue;
rejected = true; const deletion = byId.get(r.id)?.deleted === true;
continue; if (r.status === 'invalid') report(name, r.id, String(r.error ?? 'rejected'));
else if (r.status === 'forbidden' || r.status === 'readonly') report(name, r.id, REJECTION_TEXT[r.status]);
else if (r.record && isCollection(r.collection)) {
if (deletion) report(name, r.id, 'the server kept a newer version of that record');
const list = staleBuffer.get(r.collection) ?? [];
list.push(toRecord(r.collection, r.record));
staleBuffer.set(r.collection, list);
}
} }
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 { } finally {
enterApply(name); enterApply(name);
@@ -418,7 +432,7 @@ async function doOpenDb(uid: string): Promise<void> {
status.ready = true; status.ready = true;
installTriggers(); installTriggers();
await runBeforeSync(); await runBeforeSync();
void syncNow(); void autoSync();
} }
export function onSyncRound(fn: () => void): () => void { export function onSyncRound(fn: () => void): () => void {
@@ -445,13 +459,22 @@ function remoteChange(): void {
remoteTimer = setTimeout(() => { remoteTimer = setTimeout(() => {
remoteTimer = null; remoteTimer = null;
void (syncing ?? Promise.resolve()) void (syncing ?? Promise.resolve())
.then(() => syncNow()) .then(() => autoSync())
.catch(() => {}); .catch(() => {});
}, REMOTE_DEBOUNCE); }, REMOTE_DEBOUNCE);
} }
/** Runs the preparation and a round; offline only the preparation runs, which keeps the stale entries stopped. */
export function syncNow(): Promise<void> { export function syncNow(): Promise<void> {
return round(true);
}
/** A round the app starts on its own; it leaves the message of an earlier rejection in place. */
function autoSync(): Promise<void> {
return round(false);
}
/** Runs the preparation and a round; offline only the preparation runs, which keeps the stale entries stopped. */
function round(manual: boolean): Promise<void> {
if (syncing) return syncing; if (syncing) return syncing;
const m = sm; const m = sm;
if (!m) return Promise.resolve(); if (!m) return Promise.resolve();
@@ -459,7 +482,7 @@ export function syncNow(): Promise<void> {
sessionExpired?.(); sessionExpired?.();
return Promise.resolve(); return Promise.resolve();
} }
rejected = false; if (manual) rejected = false;
m.failures.length = 0; m.failures.length = 0;
const run: Promise<void> = runBeforeSync() const run: Promise<void> = runBeforeSync()
.then(() => (status.online && m === sm ? m.syncAll() : undefined)) .then(() => (status.online && m === sm ? m.syncAll() : undefined))
@@ -480,19 +503,19 @@ function installTriggers() {
const online = () => { const online = () => {
status.online = true; status.online = true;
void sm?.startAll().catch(() => {}); void sm?.startAll().catch(() => {});
void syncNow(); void autoSync();
}; };
const offline = () => { const offline = () => {
status.online = false; status.online = false;
}; };
const focus = () => { const focus = () => {
if (document.visibilityState === 'visible') void syncNow(); if (document.visibilityState === 'visible') void autoSync();
}; };
window.addEventListener('online', online); window.addEventListener('online', online);
window.addEventListener('offline', offline); window.addEventListener('offline', offline);
window.addEventListener('focus', focus); window.addEventListener('focus', focus);
document.addEventListener('visibilitychange', focus); document.addEventListener('visibilitychange', focus);
const iv = setInterval(() => void syncNow(), 60000); const iv = setInterval(() => void autoSync(), 60000);
cleanups.push(() => { cleanups.push(() => {
window.removeEventListener('online', online); window.removeEventListener('online', online);
window.removeEventListener('offline', offline); window.removeEventListener('offline', offline);
+85 -7
View File
@@ -8,7 +8,8 @@ const mocks = vi.hoisted(() => {
const server = new Map<string, Map<string, Record<string, unknown>>>(); const server = new Map<string, Map<string, Record<string, unknown>>>();
const pushes: { collection: string; id: string; data: Record<string, unknown>; client_updated_at: number; deleted: boolean }[] = []; const pushes: { collection: string; id: string; data: Record<string, unknown>; client_updated_at: number; deleted: boolean }[] = [];
const batches: number[] = []; const batches: number[] = [];
const reject = { collection: '', error: '' }; /** Status the mock answers for every change of a collection instead of applying it, with the text it sends. */
const reject = { collection: '', answer: 'invalid', error: '' };
const slow = { name: '' }; const slow = { name: '' };
/** HTTP status the mock answers instead of a result, 0 like a network failure; null answers normally. */ /** 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 fail = { pull: null as number | null, push: null as number | null };
@@ -72,13 +73,19 @@ vi.mock('$lib/pb', () => ({
mocks.batches.push(body.changes.length); mocks.batches.push(body.changes.length);
const results = body.changes.map((c) => { const results = body.changes.map((c) => {
mocks.pushes.push(c); mocks.pushes.push(c);
if (mocks.reject.collection === c.collection) return { id: c.id, collection: c.collection, status: 'invalid', error: mocks.reject.error }; if (mocks.reject.collection === c.collection) {
const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() }; return { id: c.id, collection: c.collection, status: mocks.reject.answer, error: mocks.reject.error };
}
let store = mocks.server.get(c.collection); let store = mocks.server.get(c.collection);
if (!store) { if (!store) {
store = new Map(); store = new Map();
mocks.server.set(c.collection, store); mocks.server.set(c.collection, store);
} }
const existing = store.get(c.id);
if (existing && c.client_updated_at < Number(existing.client_updated_at)) {
return { id: c.id, collection: c.collection, status: 'stale', record: existing };
}
const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() };
store.set(c.id, record); store.set(c.id, record);
return { id: c.id, collection: c.collection, status: 'ok', record }; return { id: c.id, collection: c.collection, status: 'ok', record };
}); });
@@ -319,7 +326,7 @@ describe('sync boundary', () => {
expect(mocks.batches.reduce((sum, size) => sum + size, 0)).toBe(250); expect(mocks.batches.reduce((sum, size) => sum + size, 0)).toBe(250);
}, 20000); }, 20000);
it('a rejected change is dropped and reported, and a later success of the round keeps the message', async () => { it('a rejected change is dropped, and a later success of the round keeps its message', async () => {
status.online = true; status.online = true;
mocks.reject.collection = 'settings_history'; mocks.reject.collection = 'settings_history';
mocks.reject.error = 'hours_per_week must be at most 168'; mocks.reject.error = 'hours_per_week must be at most 168';
@@ -328,7 +335,8 @@ describe('sync boundary', () => {
const id = await save('settings_history', null, settingsRow); const id = await save('settings_history', null, settingsRow);
await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 });
await syncNow(); await syncNow();
expect(status.error).toBe('settings_history: hours_per_week must be at most 168'); expect(status.error).toBe(`settings_history ${id}: hours_per_week must be at most 168`);
expect(get('settings_history', id)).toBeUndefined();
mocks.reject.collection = ''; mocks.reject.collection = '';
await syncNow(); await syncNow();
expect(status.error).toBeNull(); expect(status.error).toBeNull();
@@ -344,15 +352,85 @@ describe('sync boundary', () => {
mocks.reject.collection = 'balance_adjustments'; mocks.reject.collection = 'balance_adjustments';
mocks.reject.error = 'x'.repeat(300); mocks.reject.error = 'x'.repeat(300);
try { try {
await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); const id = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 });
await syncNow(); await syncNow();
expect(status.error).toBe(`balance_adjustments: ${'x'.repeat(200 - 'balance_adjustments: '.length)}`); const prefix = `balance_adjustments ${id}: `;
expect(status.error).toBe(prefix + 'x'.repeat(200 - prefix.length));
} finally { } finally {
mocks.reject.collection = ''; mocks.reject.collection = '';
} }
}); });
}); });
describe('rejections', () => {
const answers: [string, string, string][] = [
['invalid', 'day_key "x" is not a calendar date', 'day_key "x" is not a calendar date'],
['forbidden', '', 'the record belongs to another account'],
['readonly', '', 'the collection is read only']
];
/** Resolves after the next round the app starts on its own. */
const nextAutoRound = () =>
new Promise<void>((resolve) => {
const off = onSyncRound(() => {
off();
resolve();
});
});
it.each(answers)('a %s answer is reported with collection, id and text, and stays until a manual sync', async (answer, error, text) => {
status.online = true;
const id = await save('settings_history', null, settingsRow);
mocks.reject.collection = 'settings_history';
mocks.reject.answer = answer;
mocks.reject.error = error;
try {
await syncNow();
expect(get('settings_history', id)).toBeUndefined();
expect(status.error).toBe(`settings_history ${id}: ${text}`);
status.online = false;
const round = nextAutoRound();
window.dispatchEvent(new Event('online'));
await round;
expect(status.error).toBe(`settings_history ${id}: ${text}`);
await syncNow();
expect(status.error).toBeNull();
} finally {
mocks.reject.collection = '';
mocks.reject.answer = 'invalid';
}
});
it('a stale answer to a deletion is reported, and the newer server record comes back', async () => {
status.online = true;
const id = await save('settings_history', null, settingsRow);
await syncNow();
const store = mocks.server.get('settings_history');
const record = store?.get(id);
if (!store || !record) throw new Error('server record missing');
store.set(id, { ...record, hours_per_week: 20, client_updated_at: Number(record.client_updated_at) + 1_000_000, updated: mocks.stamp() });
await remove('settings_history', id);
await syncNow();
expect(status.error).toBe(`settings_history ${id}: the server kept a newer version of that record`);
expect(get('settings_history', id)).toMatchObject({ deleted: false, hours_per_week: 20 });
expect(pendingCount()).toBe(0);
});
it('a stale answer to an edit applies the server record without a message', async () => {
status.online = true;
const id = await save('settings_history', null, settingsRow);
await syncNow();
const store = mocks.server.get('settings_history');
const record = store?.get(id);
if (!store || !record) throw new Error('server record missing');
store.set(id, { ...record, hours_per_week: 20, client_updated_at: Number(record.client_updated_at) + 1_000_000, updated: mocks.stamp() });
await update('settings_history', id, { hours_per_week: 30 });
await syncNow();
expect(status.error).toBeNull();
expect(get('settings_history', id)).toMatchObject({ deleted: false, hours_per_week: 20 });
});
});
describe('session expiry', () => { describe('session expiry', () => {
it('a 401 from the push ends the session and the round is not reported as synced', async () => { it('a 401 from the push ends the session and the round is not reported as synced', async () => {
status.online = true; status.online = true;