diff --git a/mobile/src/sync/README.md b/mobile/src/sync/README.md new file mode 100644 index 00000000..546f8272 --- /dev/null +++ b/mobile/src/sync/README.md @@ -0,0 +1,113 @@ +# Offline-first subscription edits (Issue #1987) + +Subscription edits made offline are written to a persisted outbox and pushed +when the engine runs. Each edit carries the server version it was made against. +The server applies it only if that version is still current. Otherwise the +edit is a conflict and is held for the user, not overwritten. + +## Usage + +```ts +import { SyncEngine, SyncOutbox, createConsoleSyncTelemetry } from '../sync'; + +const outbox = await SyncOutbox.load(storage); // storage must throw on read failure +const engine = new SyncEngine({ + outbox, + transport, // implements SyncTransport.pushUpdate + telemetry: createConsoleSyncTelemetry(), +}); + +// baseVersion = the version of the record the user was looking at +await engine.enqueueUpdate('sub-1', baseVersion, { price: 12 }); + +// call on network regain, app foreground, or after an enqueue +const summary = await engine.flush(); // { applied, conflicted, rejected, deferred } + +engine.status(); // { state, pending, held, lastError } +``` + +The caller owns scheduling. Retry delay and backoff are not built in: when +`summary.deferred` is true, call `flush()` again later. + +## Conflict policy + +Rule: versioned optimistic concurrency with a server-authoritative winner. + +- A write made against version N is applied only if the server is at version N. +- Any other server version is a conflict. The server state stays. The local + edit is held as `version_conflict` with the remote record attached. +- The user then chooses `discardHeld(heldId)` to keep the server state, or + `reapplyHeld(heldId)` to re-apply the edit on top of it. +- While a record has an unresolved conflict, `enqueueUpdate` for that record + throws `RecordConflictedError`. + +Why not last-writer-wins by device clock: mobile clocks skew and drift while +offline, so "later" is not reliably "newer". LWW also overwrites the other +device's change without a trace. The existing field-level LWW CRDT in +`src/services/cache/crdt.ts` uses this clock-based rule and is not reused here. + +Consequence: edits to different fields of one record still conflict if the +version moved. This is a deliberate false positive that never drops a change. + +## Behaviour + +- **Ordering:** FIFO. A transient failure stops the pass, so later entries wait + behind it. A version conflict or rejection removes only its own record's + entries and does not block other records. +- **Coalescing:** a new edit for a record merges into its last pending entry and + keeps the earliest `baseVersion`. It never merges into an entry that is in + flight. +- **Rebase:** after an applied push at version V, remaining pending entries for + the same record with the old base are rebased to V. +- **Retries:** errors use `isRetryableQueryError` from `../queries`. Transport + errors, 408, 429 and 5xx are transient. Other 4xx are rejected immediately. + Transient failures are held as `rejected` after `maxAttempts` (default 5). +- **Timeout:** each push gets an `AbortSignal` that fires after 10 s by default. +- **Single flight:** concurrent `flush()` calls share one pass. +- **Protocol checks:** an `applied` version must exceed `baseVersion`. A + `conflict` must name the same id and a different version. A violation is + treated as a transient failure, never as success. + +## Persistence + +- One JSON document under `subtrackr.sync.outbox.v1`. +- Each change is computed on a copy, written, and then committed. A failed + write leaves memory and storage unchanged. +- `load` throws `OutboxCorruptError` on unreadable data and never overwrites it. +- The in-flight marker is not persisted. After a restart, the entry is pushed + again. If the server had already applied it, the server reports a conflict + against the same content, and the user decides. + +## Observability + +`SyncTelemetry.emit(event)` receives `enqueued`, `push_start`, `push_success`, +`push_conflict`, `push_error`, `held` and `held_resolved`. Each event carries +ids, versions, attempt counts and durations only. Patch values are never +included, because they contain subscription names and prices. +`createConsoleSyncTelemetry()` writes one JSON line per event. `logger.warn` +receives conflicts, rejections and failed pushes. + +## Not implemented + +- The HTTP write adapter. The query layer's `createHttpSubscriptionApi` is + GET-only, so no transport exists yet. +- A server contract for versions. The backend subscription mutation handlers + have no per-record `version` and no `If-Match` or 409 response, so the server + side is missing. +- Wiring to `NetworkMonitor` or app lifecycle. The `useOfflineSync` hook is + under `src/hooks`, not `mobile/`, and is not connected. +- Conflict-resolution UI. +- A throwing `SyncStorage` adapter. `asyncStorageAdapter` in + `src/utils/storage.ts` swallows read errors and returns null, which would make + an unreadable outbox look empty. + +## Tests + +```bash +npx jest mobile/src/sync +``` + +The tests use an in-memory storage and a scripted transport. They cover the +conflict policy, outbox persistence and rebase rules, and the engine's failure +paths: conflict, rejection, transient retry, max attempts, timeout, protocol +violations, single flight, and in-flight coalescing. diff --git a/mobile/src/sync/__tests__/conflictPolicy.test.ts b/mobile/src/sync/__tests__/conflictPolicy.test.ts new file mode 100644 index 00000000..ec6d3b1c --- /dev/null +++ b/mobile/src/sync/__tests__/conflictPolicy.test.ts @@ -0,0 +1,21 @@ +import { isVersionConflict } from '../conflictPolicy'; + +describe('isVersionConflict', () => { + it('does not conflict when the server is still at the base version', () => { + expect(isVersionConflict(3, 3)).toBe(false); + }); + + it('conflicts when the server moved ahead of the base version', () => { + expect(isVersionConflict(3, 4)).toBe(true); + }); + + it('conflicts when the server reports an older version than the base', () => { + expect(isVersionConflict(3, 2)).toBe(true); + }); + + it('rejects versions that are not non-negative integers', () => { + expect(() => isVersionConflict(-1, 0)).toThrow(TypeError); + expect(() => isVersionConflict(1.5, 1)).toThrow(TypeError); + expect(() => isVersionConflict(1, Number.NaN)).toThrow(TypeError); + }); +}); diff --git a/mobile/src/sync/__tests__/engine.test.ts b/mobile/src/sync/__tests__/engine.test.ts new file mode 100644 index 00000000..a15f45a4 --- /dev/null +++ b/mobile/src/sync/__tests__/engine.test.ts @@ -0,0 +1,296 @@ +import { QueryHttpError } from '../../queries/subscriptions'; +import { createConsoleSyncTelemetry, SyncEngine } from '../engine'; +import { SyncOutbox } from '../outbox'; +import type { + PendingUpdate, + PushResult, + RemoteSubscriptionRecord, + SyncEvent, + SyncStorage, + SyncTransport, +} from '../types'; + +type Step = + | PushResult + | Error + | ((update: PendingUpdate, signal: AbortSignal) => PushResult | Promise); + +function applied(version: number): PushResult { + return { status: 'applied', version }; +} + +function conflict(version: number): PushResult { + return { status: 'conflict', remote: remote(version) }; +} + +function remote(version: number): RemoteSubscriptionRecord { + return { + id: 'sub-1', + version, + item: { id: 'sub-1', name: 'Netflix', status: 'active', price: 10, currency: 'USD' }, + }; +} + +function scriptedTransport(steps: Step[]) { + const calls: PendingUpdate[] = []; + const transport: SyncTransport = { + pushUpdate: async (update, signal) => { + calls.push({ ...update, patch: { ...update.patch } }); + const step = steps.shift(); + if (step === undefined) throw new Error('unscripted push'); + if (step instanceof Error) throw step; + if (typeof step === 'function') return step(update, signal); + return step; + }, + }; + return { transport, calls }; +} + +function createStorage(): SyncStorage { + const data = new Map(); + return { + getItem: async (key) => data.get(key) ?? null, + setItem: async (key, value) => { + data.set(key, value); + }, + }; +} + +let idCounter = 0; + +async function setup( + steps: Step[], + options: { + pushTimeoutMs?: number; + maxAttempts?: number; + telemetry?: { emit(e: SyncEvent): void }; + } = {}, +) { + idCounter = 0; + const outbox = await SyncOutbox.load(createStorage(), { + now: () => 1000, + createId: () => { + idCounter += 1; + return `m${idCounter}`; + }, + }); + const { transport, calls } = scriptedTransport(steps); + const engine = new SyncEngine({ outbox, transport, now: () => 1000, ...options }); + return { engine, outbox, calls }; +} + +describe('SyncEngine', () => { + it('pushes a queued edit with its base version, acknowledges it, and reports idle', async () => { + const { engine, outbox, calls } = await setup([applied(4)]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const summary = await engine.flush(); + + expect(summary).toEqual({ applied: 1, conflicted: 0, rejected: 0, deferred: false }); + expect(calls[0].baseVersion).toBe(3); + expect(outbox.pending()).toEqual([]); + expect(engine.status()).toMatchObject({ state: 'idle', pending: 0, held: 0 }); + }); + + it('holds a version conflict for the record and keeps other records syncing', async () => { + const { engine, outbox } = await setup([conflict(5), applied(2)]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + await engine.enqueueUpdate('sub-2', 1, { price: 1 }); + + const summary = await engine.flush(); + + expect(summary).toEqual({ applied: 1, conflicted: 1, rejected: 0, deferred: false }); + expect(outbox.held()[0]).toMatchObject({ reason: 'version_conflict', id: 'sub-1' }); + expect(outbox.held()[0].remote?.version).toBe(5); + expect(engine.status()).toMatchObject({ state: 'conflict', pending: 0, held: 1 }); + }); + + it('defers a transient failure and retries the same edit on the next flush', async () => { + const { engine, outbox, calls } = await setup([new Error('network down'), applied(4)]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const first = await engine.flush(); + + expect(first).toEqual({ applied: 0, conflicted: 0, rejected: 0, deferred: true }); + expect(engine.status()).toMatchObject({ state: 'error', pending: 1, lastError: 'network down' }); + expect(outbox.pending()[0].attempts).toBe(1); + + const second = await engine.flush(); + + expect(second.applied).toBe(1); + expect(calls.map((call) => call.baseVersion)).toEqual([3, 3]); + expect(engine.status().state).toBe('idle'); + }); + + it('holds a non-retryable rejection without blocking the rest of the queue', async () => { + const { engine, outbox } = await setup([new QueryHttpError('HTTP 422', 422), applied(2)]); + await engine.enqueueUpdate('sub-1', 3, { price: 0 }); + await engine.enqueueUpdate('sub-2', 1, { price: 1 }); + + const summary = await engine.flush(); + + expect(summary).toEqual({ applied: 1, conflicted: 0, rejected: 1, deferred: false }); + expect(outbox.held()[0]).toMatchObject({ reason: 'rejected', message: 'HTTP 422' }); + expect(engine.status().state).toBe('error'); + }); + + it('holds an edit as rejected after maxAttempts transient failures', async () => { + const { engine, outbox } = await setup( + [new Error('network down'), new Error('network down')], + { maxAttempts: 2 }, + ); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + expect((await engine.flush()).deferred).toBe(true); + const second = await engine.flush(); + + expect(second).toMatchObject({ rejected: 1, deferred: false }); + expect(outbox.held()[0].message).toBe('gave up after 2 attempts: network down'); + expect(outbox.pending()).toEqual([]); + }); + + it('treats a conflict that does not differ from the base version as a protocol error', async () => { + const { engine, outbox } = await setup([conflict(3), applied(4)]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const summary = await engine.flush(); + + expect(summary.deferred).toBe(true); + expect(summary.conflicted).toBe(0); + expect(outbox.held()).toEqual([]); + expect(outbox.pending()).toHaveLength(1); + expect(engine.status().lastError).toContain('protocol violation'); + }); + + it('treats an applied version that does not exceed the base version as a protocol error', async () => { + const { engine, outbox } = await setup([applied(3), applied(4)]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const summary = await engine.flush(); + + expect(summary.deferred).toBe(true); + expect(outbox.pending()).toHaveLength(1); + }); + + it('aborts a push that exceeds the timeout and counts it as transient', async () => { + const hang = (_update: PendingUpdate, signal: AbortSignal) => + new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('aborted'))); + }); + const { engine, outbox } = await setup([hang], { pushTimeoutMs: 1 }); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const summary = await engine.flush(); + + expect(summary.deferred).toBe(true); + expect(engine.status().lastError).toBe('aborted'); + expect(outbox.pending()).toHaveLength(1); + }); + + it('shares one pass between concurrent flush calls', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const { engine, calls } = await setup([ + async () => { + await gate; + return applied(4); + }, + ]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const first = engine.flush(); + const second = engine.flush(); + expect(second).toBe(first); + release(); + await first; + + expect(calls).toHaveLength(1); + }); + + it('sends an edit made during an in-flight push after it, with the rebased base version', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + let started!: () => void; + const pushStarted = new Promise((resolve) => { + started = resolve; + }); + const { engine, calls } = await setup([ + async () => { + started(); + await gate; + return applied(4); + }, + applied(5), + ]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + const pass = engine.flush(); + await pushStarted; + await engine.enqueueUpdate('sub-1', 3, { name: 'Renamed' }); + release(); + const summary = await pass; + + expect(summary.applied).toBe(2); + expect(calls[0].patch).toEqual({ price: 12 }); + expect(calls[1]).toMatchObject({ baseVersion: 4, patch: { name: 'Renamed' } }); + }); + + it('re-applies a held conflict and pushes it on top of the remote version', async () => { + const { engine, outbox, calls } = await setup([conflict(5), applied(6)]); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + await engine.flush(); + const heldId = outbox.held()[0].heldId; + + const entry = await engine.reapplyHeld(heldId); + const summary = await engine.flush(); + + expect(entry.baseVersion).toBe(5); + expect(summary.applied).toBe(1); + expect(calls[1].baseVersion).toBe(5); + expect(engine.status().state).toBe('idle'); + }); + + it('emits ordered, identifier-only telemetry for a successful push', async () => { + const events: SyncEvent[] = []; + const { engine } = await setup([applied(4)], { telemetry: { emit: (e) => events.push(e) } }); + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + + await engine.flush(); + + expect(events.map((event) => event.type)).toEqual(['enqueued', 'push_start', 'push_success']); + expect(events[2]).toMatchObject({ id: 'sub-1', version: 4 }); + expect(JSON.stringify(events)).not.toContain('"price"'); + }); + + it('notifies subscribers when the queue or the status changes', async () => { + const { engine } = await setup([applied(4)]); + let notifications = 0; + const unsubscribe = engine.subscribe(() => { + notifications += 1; + }); + + await engine.enqueueUpdate('sub-1', 3, { price: 12 }); + await engine.flush(); + unsubscribe(); + const before = notifications; + await engine.enqueueUpdate('sub-1', 4, { price: 13 }); + + expect(before).toBeGreaterThan(0); + expect(notifications).toBeGreaterThan(before); + }); +}); + +describe('createConsoleSyncTelemetry', () => { + it('writes one JSON line per event tagged with kind sync', () => { + const lines: string[] = []; + const sink = createConsoleSyncTelemetry({ info: (message) => lines.push(message) }); + + sink.emit({ type: 'enqueued', at: 1, id: 'sub-1' }); + + expect(JSON.parse(lines[0])).toEqual({ kind: 'sync', type: 'enqueued', at: 1, id: 'sub-1' }); + }); +}); diff --git a/mobile/src/sync/__tests__/outbox.test.ts b/mobile/src/sync/__tests__/outbox.test.ts new file mode 100644 index 00000000..d3d7c7fe --- /dev/null +++ b/mobile/src/sync/__tests__/outbox.test.ts @@ -0,0 +1,208 @@ +import { OUTBOX_STORAGE_KEY, OutboxCorruptError, SyncOutbox } from '../outbox'; +import type { RemoteSubscriptionRecord, SyncStorage } from '../types'; + +function createStorage(initial?: string) { + const data = new Map(); + if (initial !== undefined) data.set(OUTBOX_STORAGE_KEY, initial); + const control = { failWrites: false }; + const storage: SyncStorage = { + getItem: async (key) => data.get(key) ?? null, + setItem: async (key, value) => { + if (control.failWrites) throw new Error('disk full'); + data.set(key, value); + }, + }; + return { data, storage, control }; +} + +function sequentialIds() { + let counter = 0; + return () => { + counter += 1; + return `m${counter}`; + }; +} + +function remote(version: number): RemoteSubscriptionRecord { + return { + id: 'sub-1', + version, + item: { id: 'sub-1', name: 'Netflix', status: 'active', price: 10, currency: 'USD' }, + }; +} + +async function loadOutbox(storage: SyncStorage) { + return SyncOutbox.load(storage, { now: () => 1000, createId: sequentialIds() }); +} + +describe('SyncOutbox', () => { + it('persists an enqueued edit and reloads it', async () => { + const { data, storage } = createStorage(); + const outbox = await loadOutbox(storage); + + const entry = await outbox.enqueue('sub-1', 3, { price: 12 }); + + expect(entry).toMatchObject({ + mutationId: 'm1', + id: 'sub-1', + baseVersion: 3, + patch: { price: 12 }, + attempts: 0, + }); + expect(data.has(OUTBOX_STORAGE_KEY)).toBe(true); + const reloaded = await loadOutbox(storage); + expect(reloaded.pending()).toEqual([entry]); + }); + + it('coalesces pending edits for one record and keeps the earliest base version', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + + await outbox.enqueue('sub-1', 3, { price: 12 }); + await outbox.enqueue('sub-1', 5, { name: 'Hulu', price: 13 }); + + const pending = outbox.pending(); + expect(pending).toHaveLength(1); + expect(pending[0].baseVersion).toBe(3); + expect(pending[0].patch).toEqual({ price: 13, name: 'Hulu' }); + }); + + it('does not merge a new edit into the entry that is in flight', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + outbox.markInFlight(first.mutationId); + + await outbox.enqueue('sub-1', 3, { name: 'Later' }); + + const pending = outbox.pending(); + expect(pending).toHaveLength(2); + expect(pending[0].patch).toEqual({ price: 12 }); + expect(pending[1].patch).toEqual({ name: 'Later' }); + }); + + it('rebases later edits for the same base version when an entry is acknowledged', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + outbox.markInFlight(first.mutationId); + await outbox.enqueue('sub-1', 3, { name: 'Later' }); + + await outbox.ack(first.mutationId, 4); + + const pending = outbox.pending(); + expect(pending).toHaveLength(1); + expect(pending[0]).toMatchObject({ baseVersion: 4, patch: { name: 'Later' } }); + }); + + it('holds every pending edit for a conflicted record as one entry and keeps other records queued', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + outbox.markInFlight(first.mutationId); + await outbox.enqueue('sub-1', 3, { name: 'A' }); + await outbox.enqueue('sub-2', 1, { price: 1 }); + + const held = await outbox.recordVersionConflict(first.mutationId, remote(5)); + + expect(held).toMatchObject({ + reason: 'version_conflict', + id: 'sub-1', + baseVersion: 3, + patch: { price: 12, name: 'A' }, + }); + expect(outbox.held()).toEqual([held]); + expect(outbox.pending().map((entry) => entry.id)).toEqual(['sub-2']); + expect(outbox.hasVersionConflict('sub-1')).toBe(true); + }); + + it('refuses new edits to a record with an unresolved version conflict', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + await outbox.recordVersionConflict(first.mutationId, remote(5)); + + await expect(outbox.enqueue('sub-1', 5, { price: 1 })).rejects.toMatchObject({ + name: 'RecordConflictedError', + }); + }); + + it('re-applies a held conflict on top of the remote version', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + const held = await outbox.recordVersionConflict(first.mutationId, remote(5)); + + const entry = await outbox.reapplyHeld(held.heldId); + + expect(entry).toMatchObject({ id: 'sub-1', baseVersion: 5, patch: { price: 12 } }); + expect(outbox.held()).toEqual([]); + expect(outbox.hasVersionConflict('sub-1')).toBe(false); + }); + + it('discards a held conflict and keeps the server state', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + const held = await outbox.recordVersionConflict(first.mutationId, remote(5)); + + await outbox.discardHeld(held.heldId); + + expect(outbox.held()).toEqual([]); + expect(outbox.pending()).toEqual([]); + }); + + it('moves only the rejected entry to held', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + await outbox.enqueue('sub-2', 1, { price: 1 }); + + const held = await outbox.recordRejected(first.mutationId, 'HTTP 422'); + + expect(held).toMatchObject({ reason: 'rejected', message: 'HTTP 422', id: 'sub-1' }); + expect(outbox.pending().map((entry) => entry.id)).toEqual(['sub-2']); + }); + + it('counts transient attempts on the entry', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + const first = await outbox.enqueue('sub-1', 3, { price: 12 }); + + expect(await outbox.recordAttempt(first.mutationId)).toBe(1); + expect(await outbox.recordAttempt(first.mutationId)).toBe(2); + expect(outbox.pending()[0].attempts).toBe(2); + }); + + it('throws OutboxCorruptError on invalid JSON and never overwrites the stored value', async () => { + const { data, storage } = createStorage('{not json'); + + await expect(loadOutbox(storage)).rejects.toMatchObject({ name: 'OutboxCorruptError' }); + expect(data.get(OUTBOX_STORAGE_KEY)).toBe('{not json'); + }); + + it('throws OutboxCorruptError on an unknown schema version', async () => { + const { storage } = createStorage('{"schema":2,"pending":[],"held":[]}'); + + await expect(loadOutbox(storage)).rejects.toBeInstanceOf(OutboxCorruptError); + }); + + it('leaves memory and storage unchanged when a write fails', async () => { + const { data, storage, control } = createStorage(); + const outbox = await loadOutbox(storage); + control.failWrites = true; + + await expect(outbox.enqueue('sub-1', 3, { price: 12 })).rejects.toThrow('disk full'); + + expect(outbox.pending()).toEqual([]); + expect(data.has(OUTBOX_STORAGE_KEY)).toBe(false); + }); + + it('rejects non-integer base versions and empty patches', async () => { + const { storage } = createStorage(); + const outbox = await loadOutbox(storage); + + await expect(outbox.enqueue('sub-1', -1, { price: 1 })).rejects.toThrow(TypeError); + await expect(outbox.enqueue('sub-1', 1, {})).rejects.toThrow(TypeError); + }); +}); diff --git a/mobile/src/sync/conflictPolicy.ts b/mobile/src/sync/conflictPolicy.ts new file mode 100644 index 00000000..e3c95b45 --- /dev/null +++ b/mobile/src/sync/conflictPolicy.ts @@ -0,0 +1,32 @@ +/** + * Conflict policy for subscription edits (Issue #1987). + * + * Rule: versioned optimistic concurrency with a server-authoritative winner. + * A local edit made against version N is applied only if the server is still + * at version N. If the server is at any other version, the edit is a conflict: + * the server state stays, and the local edit is held for the user to keep the + * server state, or to re-apply the edit on top of it. + * + * Why not last-writer-wins by device clock: mobile clocks skew and drift while + * offline, so the "later" edit is not reliably the newer one. LWW would also + * overwrite the other device's change silently. Versions are assigned by the + * server and compare exactly. + * + * Consequence: two edits to different fields of the same record still conflict + * when the version moved. That is a deliberate false positive. It keeps the + * rule simple and never silently drops a change. + */ + +/** Shared guard for every version number the sync layer accepts. */ +export function assertVersion(name: string, value: number): void { + if (!Number.isInteger(value) || value < 0) { + throw new TypeError(`${name} must be a non-negative integer, got ${String(value)}`); + } +} + +/** True when an edit based on `baseVersion` must not be applied to `remoteVersion`. */ +export function isVersionConflict(baseVersion: number, remoteVersion: number): boolean { + assertVersion('baseVersion', baseVersion); + assertVersion('remoteVersion', remoteVersion); + return baseVersion !== remoteVersion; +} diff --git a/mobile/src/sync/engine.ts b/mobile/src/sync/engine.ts new file mode 100644 index 00000000..3929d290 --- /dev/null +++ b/mobile/src/sync/engine.ts @@ -0,0 +1,307 @@ +/** + * Offline-first push engine for subscription edits (Issue #1987). + * + * Pushes the outbox head first, one entry at a time, so a record's edits reach + * the server in order. A transient failure stops the pass and is retried by the + * next `flush()`. A version conflict holds the record and does not block other + * records. Scheduling (network regain, app foreground) belongs to the caller. + */ + +import { isRetryableQueryError, queryErrorMessage } from '../queries/queryClient'; +import { isVersionConflict } from './conflictPolicy'; +import type { SyncOutbox } from './outbox'; +import type { + PendingUpdate, + PushResult, + SyncEvent, + SyncEventType, + SyncLogger, + SyncedSubscriptionPatch, + SyncState, + SyncStatus, + SyncTelemetry, + SyncTransport, +} from './types'; + +export const DEFAULT_PUSH_TIMEOUT_MS = 10_000; +export const DEFAULT_MAX_ATTEMPTS = 5; + +export interface SyncEngineOptions { + outbox: SyncOutbox; + transport: SyncTransport; + telemetry?: SyncTelemetry; + logger?: SyncLogger; + now?: () => number; + /** Per-push deadline. Default 10 s. */ + pushTimeoutMs?: number; + /** Transient failures before an edit is held as rejected. Default 5. */ + maxAttempts?: number; +} + +export interface FlushSummary { + applied: number; + conflicted: number; + rejected: number; + /** True when the pass stopped on a transient failure and should be retried. */ + deferred: boolean; +} + +type Outcome = 'applied' | 'conflicted' | 'rejected' | 'deferred'; + +export class SyncEngine { + private readonly outbox: SyncOutbox; + private readonly transport: SyncTransport; + private readonly telemetry?: SyncTelemetry; + private readonly logger?: SyncLogger; + private readonly now: () => number; + private readonly pushTimeoutMs: number; + private readonly maxAttempts: number; + private readonly listeners = new Set<() => void>(); + private flushing: Promise | null = null; + private syncing = false; + private lastError: string | undefined; + + constructor(options: SyncEngineOptions) { + this.outbox = options.outbox; + this.transport = options.transport; + this.telemetry = options.telemetry; + this.logger = options.logger; + this.now = options.now ?? Date.now; + this.pushTimeoutMs = Math.max(1, options.pushTimeoutMs ?? DEFAULT_PUSH_TIMEOUT_MS); + this.maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS); + } + + /** Queue a local edit. Throws `RecordConflictedError` while the record is held. */ + async enqueueUpdate( + id: string, + baseVersion: number, + patch: SyncedSubscriptionPatch, + ): Promise { + const entry = await this.outbox.enqueue(id, baseVersion, patch); + this.emit('enqueued', { id, mutationId: entry.mutationId, version: baseVersion }); + this.notify(); + return entry; + } + + /** Push the queue. Concurrent callers share one pass. */ + flush(): Promise { + if (!this.flushing) { + this.flushing = this.runFlush().finally(() => { + this.flushing = null; + }); + } + return this.flushing; + } + + /** Keep the server state for a held record and drop the local edit. */ + async discardHeld(heldId: string): Promise { + await this.outbox.discardHeld(heldId); + this.emit('held_resolved', { heldId, reason: 'discarded' }); + this.notify(); + } + + /** Re-apply a held version conflict on top of the server state, then push it. */ + async reapplyHeld(heldId: string): Promise { + const entry = await this.outbox.reapplyHeld(heldId); + this.emit('held_resolved', { heldId, id: entry.id, reason: 'reapplied' }); + this.notify(); + return entry; + } + + status(): SyncStatus { + const held = this.outbox.held(); + const pending = this.outbox.pending().length; + const hasConflict = held.some((item) => item.reason === 'version_conflict'); + const hasRejected = held.some((item) => item.reason === 'rejected'); + let state: SyncState = 'idle'; + if (hasConflict) state = 'conflict'; + else if (this.syncing) state = 'syncing'; + else if (this.lastError !== undefined || hasRejected) state = 'error'; + else if (pending > 0) state = 'pending'; + return { state, pending, held: held.length, lastError: this.lastError }; + } + + subscribe(listener: () => void): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + private async runFlush(): Promise { + const summary: FlushSummary = { applied: 0, conflicted: 0, rejected: 0, deferred: false }; + this.syncing = true; + this.notify(); + try { + for (let next = this.outbox.nextPending(); next; next = this.outbox.nextPending()) { + let outcome: Outcome; + try { + outcome = await this.pushOne(next); + } catch (error) { + // Storage itself failed. Keep the entry queued and stop the pass. + this.lastError = queryErrorMessage(error); + this.logger?.warn('sync outbox write failed, pass deferred', { error: this.lastError }); + outcome = 'deferred'; + } + if (outcome === 'deferred') { + summary.deferred = true; + break; + } + if (outcome === 'applied') summary.applied += 1; + if (outcome === 'conflicted') summary.conflicted += 1; + if (outcome === 'rejected') summary.rejected += 1; + } + } finally { + this.syncing = false; + this.notify(); + } + return summary; + } + + private async pushOne(update: PendingUpdate): Promise { + const started = this.now(); + this.emit('push_start', { + id: update.id, + mutationId: update.mutationId, + attempts: update.attempts, + }); + let result: PushResult; + try { + result = await this.send(update); + } catch (error) { + return this.handleFailure(update, error, started); + } + try { + return await this.handleResult(update, result, started); + } catch (error) { + // A storage failure after the server answered: the entry stays queued and + // is re-pushed later. The server may then report a conflict with our own write. + return this.handleFailure(update, error, started); + } + } + + private async send(update: PendingUpdate): Promise { + const controller = new AbortController(); + const timer = setTimeout( + () => controller.abort(new Error('sync push timeout')), + this.pushTimeoutMs, + ); + this.outbox.markInFlight(update.mutationId); + try { + return await this.transport.pushUpdate(update, controller.signal); + } finally { + clearTimeout(timer); + this.outbox.markInFlight(null); + } + } + + private async handleResult( + update: PendingUpdate, + result: PushResult, + started: number, + ): Promise { + if (result.status === 'applied') { + if (!Number.isInteger(result.version) || result.version <= update.baseVersion) { + throw new Error('protocol violation: applied version must exceed baseVersion'); + } + await this.outbox.ack(update.mutationId, result.version); + this.lastError = undefined; + this.emit('push_success', { + id: update.id, + mutationId: update.mutationId, + version: result.version, + durationMs: this.now() - started, + }); + return 'applied'; + } + + if (result.status === 'conflict') { + const { remote } = result; + if (remote.id !== update.id || !isVersionConflict(update.baseVersion, remote.version)) { + throw new Error('protocol violation: conflict response does not differ from baseVersion'); + } + await this.outbox.recordVersionConflict(update.mutationId, remote); + this.emit('push_conflict', { + id: update.id, + mutationId: update.mutationId, + version: remote.version, + }); + this.emit('held', { id: update.id, reason: 'version_conflict', version: remote.version }); + this.logger?.warn('subscription version conflict held for user resolution', { + id: update.id, + baseVersion: update.baseVersion, + remoteVersion: remote.version, + }); + this.notify(); + return 'conflicted'; + } + + throw new Error('protocol violation: unknown push result'); + } + + private async handleFailure( + update: PendingUpdate, + error: unknown, + started: number, + ): Promise { + const message = queryErrorMessage(error); + this.lastError = message; + const retryable = isRetryableQueryError(error); + let attempts = update.attempts; + if (retryable) { + attempts = await this.outbox.recordAttempt(update.mutationId); + if (attempts < this.maxAttempts) { + this.emit('push_error', { + id: update.id, + mutationId: update.mutationId, + attempts, + retryable: true, + durationMs: this.now() - started, + reason: message, + }); + this.logger?.warn('subscription push failed, will retry', { id: update.id, attempts }); + this.notify(); + return 'deferred'; + } + } + + const reason = retryable ? `gave up after ${attempts} attempts: ${message}` : message; + await this.outbox.recordRejected(update.mutationId, reason); + this.emit('push_error', { + id: update.id, + mutationId: update.mutationId, + retryable: false, + durationMs: this.now() - started, + reason, + }); + this.emit('held', { id: update.id, reason: 'rejected' }); + this.logger?.warn('subscription edit rejected and held', { id: update.id, reason }); + this.notify(); + return 'rejected'; + } + + private emit(type: SyncEventType, extra: Omit = {}): void { + this.telemetry?.emit({ type, at: this.now(), ...extra }); + } + + private notify(): void { + for (const listener of Array.from(this.listeners)) { + try { + listener(); + } catch (error) { + this.logger?.warn('sync subscriber failed', { error: queryErrorMessage(error) }); + } + } + } +} + +/** JSON-line telemetry sink, the same shape as the query layer's console sink. */ +export function createConsoleSyncTelemetry( + logger: { info(message: string): void } = console, +): SyncTelemetry { + return { + emit(event: SyncEvent): void { + logger.info(JSON.stringify({ kind: 'sync', ...event })); + }, + }; +} diff --git a/mobile/src/sync/index.ts b/mobile/src/sync/index.ts new file mode 100644 index 00000000..a4d24df5 --- /dev/null +++ b/mobile/src/sync/index.ts @@ -0,0 +1,33 @@ +/** Public API for offline-first subscription edits (Issue #1987). */ + +export { isVersionConflict } from './conflictPolicy'; +export { + OUTBOX_STORAGE_KEY, + OutboxCorruptError, + RecordConflictedError, + SyncOutbox, +} from './outbox'; +export type { SyncOutboxOptions } from './outbox'; +export { + createConsoleSyncTelemetry, + DEFAULT_MAX_ATTEMPTS, + DEFAULT_PUSH_TIMEOUT_MS, + SyncEngine, +} from './engine'; +export type { FlushSummary, SyncEngineOptions } from './engine'; +export type { + HeldReason, + HeldUpdate, + PendingUpdate, + PushResult, + RemoteSubscriptionRecord, + SyncEvent, + SyncEventType, + SyncLogger, + SyncedSubscriptionPatch, + SyncState, + SyncStatus, + SyncStorage, + SyncTelemetry, + SyncTransport, +} from './types'; diff --git a/mobile/src/sync/outbox.ts b/mobile/src/sync/outbox.ts new file mode 100644 index 00000000..05ce9566 --- /dev/null +++ b/mobile/src/sync/outbox.ts @@ -0,0 +1,348 @@ +/** + * Persisted outbox of local subscription edits (Issue #1987). + * + * The whole outbox is one JSON document under a single storage key. Every + * change is computed on a copy, written, and only then committed in memory, so + * a failed write leaves both storage and memory unchanged. Writes are + * serialised, so the last write always holds the latest state. + */ + +import { assertVersion } from './conflictPolicy'; +import type { + HeldUpdate, + PendingUpdate, + RemoteSubscriptionRecord, + SyncedSubscriptionPatch, + SyncStorage, +} from './types'; + +export const OUTBOX_STORAGE_KEY = 'subtrackr.sync.outbox.v1'; + +const SCHEMA_VERSION = 1; + +interface OutboxState { + schema: number; + pending: PendingUpdate[]; + held: HeldUpdate[]; +} + +/** Thrown by `load` when stored data is unreadable. Storage is left untouched. */ +export class OutboxCorruptError extends Error { + constructor(reason: string) { + super(`sync outbox is corrupt: ${reason}`); + this.name = 'OutboxCorruptError'; + } +} + +/** Thrown when an edit targets a record that has an unresolved version conflict. */ +export class RecordConflictedError extends Error { + constructor(readonly id: string) { + super(`subscription ${id} has an unresolved conflict; resolve it before editing`); + this.name = 'RecordConflictedError'; + } +} + +export interface SyncOutboxOptions { + key?: string; + now?: () => number; + createId?: () => string; +} + +function defaultCreateId(): string { + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; +} + +function clone(value: T): T { + return value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isVersionNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) && value >= 0; +} + +function isPendingUpdate(value: unknown): value is PendingUpdate { + return ( + isRecord(value) && + typeof value.mutationId === 'string' && + typeof value.id === 'string' && + isVersionNumber(value.baseVersion) && + isRecord(value.patch) && + typeof value.enqueuedAt === 'number' && + isVersionNumber(value.attempts) + ); +} + +function isHeldUpdate(value: unknown): value is HeldUpdate { + return ( + isRecord(value) && + typeof value.heldId === 'string' && + (value.reason === 'version_conflict' || value.reason === 'rejected') && + typeof value.id === 'string' && + isVersionNumber(value.baseVersion) && + isRecord(value.patch) && + typeof value.heldAt === 'number' + ); +} + +function parseState(raw: string): OutboxState { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new OutboxCorruptError('not valid JSON'); + } + if (!isRecord(parsed) || parsed.schema !== SCHEMA_VERSION) { + throw new OutboxCorruptError('unknown schema'); + } + if (!Array.isArray(parsed.pending) || !parsed.pending.every(isPendingUpdate)) { + throw new OutboxCorruptError('invalid pending entries'); + } + if (!Array.isArray(parsed.held) || !parsed.held.every(isHeldUpdate)) { + throw new OutboxCorruptError('invalid held entries'); + } + return { + schema: SCHEMA_VERSION, + pending: parsed.pending as PendingUpdate[], + held: parsed.held as HeldUpdate[], + }; +} + +function assertPatch(patch: SyncedSubscriptionPatch): void { + if (Object.keys(patch).length === 0) { + throw new TypeError('patch must contain at least one field'); + } +} + +/** + * Queue an edit into a draft. A new edit merges into the last pending entry for + * the same record, unless that entry is in flight. Merged entries keep the + * earliest `baseVersion`, which is the conservative choice. + */ +function enqueueInto( + draft: OutboxState, + options: { + id: string; + baseVersion: number; + patch: SyncedSubscriptionPatch; + mutationId: string; + now: number; + inFlight: string | null; + }, +): PendingUpdate { + const { id, baseVersion, patch, mutationId, now, inFlight } = options; + if (draft.held.some((held) => held.id === id && held.reason === 'version_conflict')) { + throw new RecordConflictedError(id); + } + for (let index = draft.pending.length - 1; index >= 0; index -= 1) { + const candidate = draft.pending[index]; + if (candidate.id === id && candidate.mutationId !== inFlight) { + candidate.patch = { ...candidate.patch, ...patch }; + return clone(candidate); + } + } + const entry: PendingUpdate = { + mutationId, + id, + baseVersion, + patch: { ...patch }, + enqueuedAt: now, + attempts: 0, + }; + draft.pending.push(entry); + return clone(entry); +} + +export class SyncOutbox { + private state: OutboxState; + private inFlight: string | null = null; + private writeChain: Promise = Promise.resolve(); + private readonly storage: SyncStorage; + private readonly key: string; + private readonly now: () => number; + private readonly createId: () => string; + + private constructor(storage: SyncStorage, state: OutboxState, options: SyncOutboxOptions) { + this.storage = storage; + this.state = state; + this.key = options.key ?? OUTBOX_STORAGE_KEY; + this.now = options.now ?? Date.now; + this.createId = options.createId ?? defaultCreateId; + } + + /** Read the outbox. Throws `OutboxCorruptError` on unreadable data and never writes. */ + static async load(storage: SyncStorage, options: SyncOutboxOptions = {}): Promise { + const key = options.key ?? OUTBOX_STORAGE_KEY; + const raw = await storage.getItem(key); + const state: OutboxState = + raw === null ? { schema: SCHEMA_VERSION, pending: [], held: [] } : parseState(raw); + return new SyncOutbox(storage, state, options); + } + + /** Copies of pending entries, oldest first. */ + pending(): PendingUpdate[] { + return clone(this.state.pending); + } + + /** Copies of held entries (version conflicts and rejections). */ + held(): HeldUpdate[] { + return clone(this.state.held); + } + + /** The next entry to push, or undefined when the queue is empty. */ + nextPending(): PendingUpdate | undefined { + return clone(this.state.pending[0]); + } + + /** True while the record has an unresolved version conflict. */ + hasVersionConflict(id: string): boolean { + return this.state.held.some((held) => held.id === id && held.reason === 'version_conflict'); + } + + /** Track the entry being pushed. In-memory only: a restart re-pushes it. */ + markInFlight(mutationId: string | null): void { + this.inFlight = mutationId; + } + + async enqueue( + id: string, + baseVersion: number, + patch: SyncedSubscriptionPatch, + ): Promise { + assertVersion('baseVersion', baseVersion); + assertPatch(patch); + return this.update((draft) => + enqueueInto(draft, { + id, + baseVersion, + patch, + mutationId: this.createId(), + now: this.now(), + inFlight: this.inFlight, + }), + ); + } + + /** + * Remove an applied entry. Remaining entries for the same record that were + * based on the old version are rebased to `appliedVersion`. They were made on + * top of the same server state, and the server accepted this write against it. + */ + ack(mutationId: string, appliedVersion: number): Promise { + return this.update((draft) => { + const index = draft.pending.findIndex((entry) => entry.mutationId === mutationId); + if (index < 0) throw new Error(`unknown pending mutation ${mutationId}`); + const [acked] = draft.pending.splice(index, 1); + for (const entry of draft.pending) { + if (entry.id === acked.id && entry.baseVersion === acked.baseVersion) { + entry.baseVersion = appliedVersion; + } + } + }); + } + + /** Count one transient failure for the entry and return the new total. */ + recordAttempt(mutationId: string): Promise { + return this.update((draft) => { + const entry = draft.pending.find((candidate) => candidate.mutationId === mutationId); + if (!entry) throw new Error(`unknown pending mutation ${mutationId}`); + entry.attempts += 1; + return entry.attempts; + }); + } + + /** + * Hold every pending edit for the record as one version conflict. Holding all + * of them keeps a stale queue from being pushed over the server state. + */ + recordVersionConflict(mutationId: string, remote: RemoteSubscriptionRecord): Promise { + return this.update((draft) => { + const target = draft.pending.find((entry) => entry.mutationId === mutationId); + if (!target) throw new Error(`unknown pending mutation ${mutationId}`); + const moved = draft.pending.filter((entry) => entry.id === target.id); + draft.pending = draft.pending.filter((entry) => entry.id !== target.id); + const patch: SyncedSubscriptionPatch = {}; + for (const entry of moved) Object.assign(patch, entry.patch); + const held: HeldUpdate = { + heldId: this.createId(), + reason: 'version_conflict', + id: target.id, + baseVersion: moved[0].baseVersion, + patch, + remote, + heldAt: this.now(), + }; + draft.held.push(held); + return clone(held); + }); + } + + /** Remove an entry that the server refused for a non-retryable reason. */ + recordRejected(mutationId: string, message: string): Promise { + return this.update((draft) => { + const index = draft.pending.findIndex((entry) => entry.mutationId === mutationId); + if (index < 0) throw new Error(`unknown pending mutation ${mutationId}`); + const [entry] = draft.pending.splice(index, 1); + const held: HeldUpdate = { + heldId: this.createId(), + reason: 'rejected', + id: entry.id, + baseVersion: entry.baseVersion, + patch: entry.patch, + message, + heldAt: this.now(), + }; + draft.held.push(held); + return clone(held); + }); + } + + /** User keeps the server state and drops the held local edit. */ + discardHeld(heldId: string): Promise { + return this.update((draft) => { + const index = draft.held.findIndex((held) => held.heldId === heldId); + if (index < 0) throw new Error(`unknown held update ${heldId}`); + draft.held.splice(index, 1); + }); + } + + /** User re-applies a held version-conflict edit on top of the server state. */ + reapplyHeld(heldId: string): Promise { + return this.update((draft) => { + const index = draft.held.findIndex((held) => held.heldId === heldId); + if (index < 0) throw new Error(`unknown held update ${heldId}`); + const held = draft.held[index]; + if (held.reason !== 'version_conflict' || !held.remote) { + throw new TypeError('only version conflicts can be re-applied'); + } + draft.held.splice(index, 1); + return enqueueInto(draft, { + id: held.id, + baseVersion: held.remote.version, + patch: held.patch, + mutationId: this.createId(), + now: this.now(), + inFlight: this.inFlight, + }); + }); + } + + /** + * Serialise a change: compute it on a copy, persist the copy, then commit. + * A throw from `mutate` or from storage leaves the committed state unchanged. + */ + private update(mutate: (draft: OutboxState) => R): Promise { + const run = this.writeChain.then(async () => { + const draft = clone(this.state); + const result = mutate(draft); + await this.storage.setItem(this.key, JSON.stringify(draft)); + this.state = draft; + return clone(result); + }); + this.writeChain = run.catch(() => undefined); + return run; + } +} diff --git a/mobile/src/sync/types.ts b/mobile/src/sync/types.ts new file mode 100644 index 00000000..48cb8dd3 --- /dev/null +++ b/mobile/src/sync/types.ts @@ -0,0 +1,112 @@ +/** + * Types for offline-first subscription edits (Issue #1987). + * + * Edits are written to a persisted outbox together with the server version + * they were made against (`baseVersion`). The server is authoritative: it + * applies a write only when its current version equals `baseVersion`. Any + * other outcome is a version conflict, and the local edit is held for a user + * decision instead of being silently overwritten. See README.md for the policy. + */ + +import type { SubscriptionListItem } from '../queries/subscriptions'; + +export type SyncedSubscriptionPatch = Partial>; + +/** Authoritative server state of one subscription, with its version. */ +export interface RemoteSubscriptionRecord { + id: string; + version: number; + item: SubscriptionListItem; +} + +/** A queued local edit waiting to be pushed. */ +export interface PendingUpdate { + mutationId: string; + id: string; + /** Server version the local edits were made against. */ + baseVersion: number; + patch: SyncedSubscriptionPatch; + enqueuedAt: number; + /** Transient failed push attempts so far. */ + attempts: number; +} + +export type HeldReason = 'version_conflict' | 'rejected'; + +/** An edit that will not be pushed until the user resolves it. */ +export interface HeldUpdate { + heldId: string; + reason: HeldReason; + id: string; + baseVersion: number; + patch: SyncedSubscriptionPatch; + /** Set for `version_conflict`: the server state that won. */ + remote?: RemoteSubscriptionRecord; + /** Set for `rejected`: a short description of the failure. */ + message?: string; + heldAt: number; +} + +export type PushResult = + | { status: 'applied'; version: number } + | { status: 'conflict'; remote: RemoteSubscriptionRecord }; + +/** + * Pushes one queued edit. Implementations must send `baseVersion` to the + * server and return `conflict` (not throw) when the server version differs. + * Throw for transport and HTTP failures; `isRetryableQueryError` decides retry. + */ +export interface SyncTransport { + pushUpdate(update: PendingUpdate, signal: AbortSignal): Promise; +} + +/** + * Minimal async key/value contract. The app's `asyncStorageAdapter` is + * structurally compatible, but it swallows errors and returns null on read + * failure. Use a storage that throws so an unreadable outbox is never treated + * as empty. + */ +export interface SyncStorage { + getItem(key: string): Promise; + setItem(key: string, value: string): Promise; +} + +export type SyncEventType = + | 'enqueued' + | 'push_start' + | 'push_success' + | 'push_conflict' + | 'push_error' + | 'held' + | 'held_resolved'; + +/** Telemetry carries identifiers and counts only, never patch values. */ +export interface SyncEvent { + type: SyncEventType; + at: number; + id?: string; + mutationId?: string; + heldId?: string; + version?: number; + attempts?: number; + durationMs?: number; + retryable?: boolean; + reason?: string; +} + +export interface SyncTelemetry { + emit(event: SyncEvent): void; +} + +export interface SyncLogger { + warn(message: string, meta?: Record): void; +} + +export type SyncState = 'idle' | 'pending' | 'syncing' | 'conflict' | 'error'; + +export interface SyncStatus { + state: SyncState; + pending: number; + held: number; + lastError?: string; +}