diff --git a/backend/src/routes/__tests__/subscriptions.test.ts b/backend/src/routes/__tests__/subscriptions.test.ts new file mode 100644 index 00000000..70357d9c --- /dev/null +++ b/backend/src/routes/__tests__/subscriptions.test.ts @@ -0,0 +1,213 @@ +import { + SubscriptionEditsErrorCode, + SubscriptionEditsError, + DEFAULT_SUBSCRIPTION_EDITS_CONFIG, + createSubscriptionEditsApplier, + applySubscriptionEditsBatch, + noopSubscriptionEditsMetrics, + noopSubscriptionEditsLogger, + type SubscriptionEdit, + type SubscriptionEditsStore, + type SubscriptionEditsMetrics, + type SubscriptionEditsLogger, + type SubscriptionEditsBatchResult, +} from '../subscriptions'; + +interface Write { id: string; patch: Readonly>; expectedVersion: number } + +function memoryStore(initial: Record = {}, failIds: string[] = []): SubscriptionEditsStore & { writes: Write[] } { + const versions = new Map(Object.entries(initial)); + const writes: Write[] = []; + return { + writes, + async load(id) { + const version = versions.get(id); + return version === undefined ? undefined : { version }; + }, + async commit(id, patch, expectedVersion) { + if (failIds.includes(id)) throw new Error('disk unavailable'); + const current = versions.get(id) ?? 0; + if (current !== expectedVersion) throw new Error('version mismatch'); + const version = expectedVersion + 1; + versions.set(id, version); + writes.push({ id, patch, expectedVersion }); + return { version }; + }, + }; +} + +function spyMetrics(): { metrics: SubscriptionEditsMetrics; log: { applied: string[]; skipped: string[]; failed: string[]; batches: number[] } } { + const log = { applied: [] as string[], skipped: [] as string[], failed: [] as string[], batches: [] as number[] }; + const metrics: SubscriptionEditsMetrics = { + batchCompleted: (_applied, _skipped, _failed, durationMs) => log.batches.push(durationMs), + itemApplied: (id) => log.applied.push(id), + itemSkipped: (id) => log.skipped.push(id), + itemFailed: (id) => log.failed.push(id), + }; + return { metrics, log }; +} + +function spyLogger(): { logger: SubscriptionEditsLogger; messages: string[] } { + const messages: string[] = []; + const logger: SubscriptionEditsLogger = { + debug: (message) => messages.push(`debug:${message}`), + warn: (message) => messages.push(`warn:${message}`), + error: (message) => messages.push(`error:${message}`), + }; + return { logger, messages }; +} + +function codeOf(fn: () => unknown): string { + try { fn(); } catch (error) { return (error as SubscriptionEditsError).code; } + throw new Error('expected fn to throw'); +} + +async function rejectionCode(fn: () => Promise): Promise { + try { await fn(); } catch (error) { return (error as SubscriptionEditsError).code; } + throw new Error('expected fn to reject'); +} + +describe('subscription edits vocabulary (#2266)', () => { + it('exposes frozen, stable error codes', () => { + expect(Object.isFrozen(SubscriptionEditsErrorCode)).toBe(true); + expect(SubscriptionEditsErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(SubscriptionEditsErrorCode.INVALID_INPUT).toBe('INVALID_INPUT'); + expect(SubscriptionEditsErrorCode.VERSION_CONFLICT).toBe('VERSION_CONFLICT'); + expect(SubscriptionEditsErrorCode.STORE_ERROR).toBe('STORE_ERROR'); + }); + + it('exposes a frozen config and frozen no-op hooks', () => { + expect(Object.isFrozen(DEFAULT_SUBSCRIPTION_EDITS_CONFIG)).toBe(true); + expect(DEFAULT_SUBSCRIPTION_EDITS_CONFIG.maxBatchSize).toBe(50); + expect(DEFAULT_SUBSCRIPTION_EDITS_CONFIG.initialVersion).toBe(0); + expect(Object.isFrozen(noopSubscriptionEditsMetrics)).toBe(true); + expect(Object.isFrozen(noopSubscriptionEditsLogger)).toBe(true); + }); + + it('builds typed errors with frozen details', () => { + const error = new SubscriptionEditsError(SubscriptionEditsErrorCode.INVALID_INPUT, 'bad batch', { count: 2 }); + expect(error).toBeInstanceOf(Error); + expect(error).toBeInstanceOf(SubscriptionEditsError); + expect(error.name).toBe('SubscriptionEditsError'); + expect(error.code).toBe('INVALID_INPUT'); + expect(Object.isFrozen(error.details)).toBe(true); + expect(error.details.count).toBe(2); + }); +}); + +describe('coalesced batch application', () => { + it('applies a new subscription with observability', async () => { + const store = memoryStore(); + const { metrics, log } = spyMetrics(); + const { logger, messages } = spyLogger(); + const result: SubscriptionEditsBatchResult = await applySubscriptionEditsBatch( + [{ id: 'sub_1', patch: { name: 'Netflix' }, version: 0 }], + store, + { metrics, logger, now: () => 1000 }, + ); + expect(result.applied).toBe(1); + expect(result.skipped).toBe(0); + expect(result.failed).toBe(0); + expect(result.results[0].outcome).toBe('applied'); + expect(result.results[0].version).toBe(1); + expect(result.durationMs).toBe(0); + expect(Object.isFrozen(result)).toBe(true); + expect(Object.isFrozen(result.results)).toBe(true); + expect(store.writes).toHaveLength(1); + expect(store.writes[0].expectedVersion).toBe(0); + expect(log.applied).toEqual(['sub_1']); + expect(log.batches).toEqual([0]); + expect(messages[0]).toBe('debug:subscription edit applied'); + }); + + it('is idempotent by id and version across repeated calls', async () => { + const store = memoryStore(); + const batch: SubscriptionEdit[] = [{ id: 'sub_1', patch: { amount: 10 }, version: 0 }]; + const first = await applySubscriptionEditsBatch(batch, store); + const second = await applySubscriptionEditsBatch(batch, store); + expect(first.applied).toBe(1); + expect(second.applied).toBe(0); + expect(second.skipped).toBe(1); + expect(second.results[0].outcome).toBe('duplicate'); + expect(second.results[0].code).toBe(SubscriptionEditsErrorCode.VERSION_CONFLICT); + expect(store.writes).toHaveLength(1); + }); + + it('shares idempotency state on an explicit applier', async () => { + const store = memoryStore(); + const applier = createSubscriptionEditsApplier(store); + const batch: SubscriptionEdit[] = [{ id: 'sub_1', patch: { amount: 10 } }]; + expect((await applier.apply(batch)).applied).toBe(1); + expect((await applier.apply(batch)).skipped).toBe(1); + expect(applier.seenKeys).toEqual(['sub_1@0']); + expect(Object.isFrozen(applier)).toBe(true); + expect(Object.isFrozen(applier.config)).toBe(true); + }); + + it('reports a version conflict without writing', async () => { + const store = memoryStore({ sub_1: 3 }); + const result = await applySubscriptionEditsBatch( + [{ id: 'sub_1', patch: { amount: 10 }, version: 1 }], + store, + ); + expect(result.results[0].outcome).toBe('conflict'); + expect(result.results[0].code).toBe(SubscriptionEditsErrorCode.VERSION_CONFLICT); + expect(result.results[0].version).toBe(3); + expect(result.skipped).toBe(1); + expect(store.writes).toHaveLength(0); + }); + + it('captures store failures and keeps processing', async () => { + const store = memoryStore({}, ['bad']); + const { metrics, log } = spyMetrics(); + const { logger, messages } = spyLogger(); + const result = await applySubscriptionEditsBatch( + [ + { id: 'bad', patch: { amount: 1 } }, + { id: 'good', patch: { amount: 2 } }, + ], + store, + { metrics, logger }, + ); + expect(result.failed).toBe(1); + expect(result.applied).toBe(1); + expect(result.results[0].outcome).toBe('error'); + expect(result.results[0].code).toBe(SubscriptionEditsErrorCode.STORE_ERROR); + expect(result.results[1].outcome).toBe('applied'); + expect(log.failed).toEqual(['bad']); + expect(messages[0]).toBe('error:subscription edit store failure'); + }); + + it('rejects malformed items with typed codes', async () => { + const store = memoryStore(); + const result = await applySubscriptionEditsBatch( + [ + { id: '', patch: {} }, + { id: 'a', patch: [] as never }, + { id: 'b', patch: {}, version: -1 }, + ], + store, + ); + expect(result.failed).toBe(3); + expect(result.results.map((item) => item.code)).toEqual(['INVALID_INPUT', 'INVALID_INPUT', 'INVALID_VERSION']); + expect(store.writes).toHaveLength(0); + }); + + it('rejects oversized batches and invalid configuration', async () => { + const store = memoryStore(); + const oversized: SubscriptionEdit[] = Array.from({ length: 6 }, (_, index) => ({ id: `s${index}`, patch: {} })); + expect(await rejectionCode(() => applySubscriptionEditsBatch(oversized, store, { config: { maxBatchSize: 5 } }))).toBe( + SubscriptionEditsErrorCode.BATCH_TOO_LARGE, + ); + expect(codeOf(() => createSubscriptionEditsApplier(store, { config: { maxBatchSize: 0 } }))).toBe( + SubscriptionEditsErrorCode.INVALID_CONFIG, + ); + }); + + it('rejects a non-array batch with a typed error', async () => { + const store = memoryStore(); + expect(await rejectionCode(() => applySubscriptionEditsBatch(null as never, store))).toBe( + SubscriptionEditsErrorCode.INVALID_INPUT, + ); + }); +}); diff --git a/backend/src/routes/subscriptions.ts b/backend/src/routes/subscriptions.ts new file mode 100644 index 00000000..8dbfe681 --- /dev/null +++ b/backend/src/routes/subscriptions.ts @@ -0,0 +1,373 @@ +/** + * backend/src/routes/subscriptions.ts + * + * Issue #2266: idempotent, coalesced server writes for subscription edits. + * + * The mobile autosave controller emits bounded batches of last-write-wins + * edits; this route-level module applies them in one pass. Each edit is keyed + * by `(id, version)` so a retried batch is a no-op rather than a duplicate + * write, and optimistic version checks prevent a stale coalesced edit from + * clobbering a newer record. The module is framework-agnostic and depends on + * nothing: the store, clock and observability hooks are all injected. + */ + +/** Stable, machine-readable error codes. Frozen. */ +export const SubscriptionEditsErrorCode = Object.freeze({ + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_INPUT: 'INVALID_INPUT', + INVALID_VERSION: 'INVALID_VERSION', + BATCH_TOO_LARGE: 'BATCH_TOO_LARGE', + VERSION_CONFLICT: 'VERSION_CONFLICT', + STORE_ERROR: 'STORE_ERROR', +} as const); + +/** Union of {@link SubscriptionEditsErrorCode} values. */ +export type SubscriptionEditsErrorCode = + (typeof SubscriptionEditsErrorCode)[keyof typeof SubscriptionEditsErrorCode]; + +/** + * Error thrown for a rejected batch or invalid configuration. + * + * The `code` is stable and safe to expose to callers; `details` carries + * non-sensitive context for logging and tests. + */ +export class SubscriptionEditsError extends Error { + /** Stable machine-readable code. */ + readonly code: SubscriptionEditsErrorCode; + /** Additional non-sensitive context about the rejection. */ + readonly details: Readonly>; + + constructor( + code: SubscriptionEditsErrorCode, + message: string, + details: Readonly> = {}, + ) { + super(message); + this.name = 'SubscriptionEditsError'; + this.code = code; + this.details = Object.freeze({ ...details }); + } +} + +/** A single coalesced subscription edit sent by the client. */ +export interface SubscriptionEdit { + /** Stable subscription identifier. */ + readonly id: string; + /** Fields to update. */ + readonly patch: Readonly>; + /** Expected current version; defaults to {@link SubscriptionEditsConfig.initialVersion}. */ + readonly version?: number; +} + +/** Minimum record shape the store must return. */ +export interface SubscriptionEditRecord { + /** Current persisted version. */ + readonly version: number; +} + +/** Persistence surface. `commit` must enforce the expected version atomically. */ +export interface SubscriptionEditsStore { + /** Load the current record for `id`, or `undefined` when it does not exist. */ + load(id: string): Promise; + /** Apply `patch` only when the stored version equals `expectedVersion`. */ + commit( + id: string, + patch: Readonly>, + expectedVersion: number, + ): Promise; +} + +/** Tunable policy for a batch applier. */ +export interface SubscriptionEditsConfig { + /** Maximum number of edits accepted in one batch. */ + readonly maxBatchSize: number; + /** Version assigned to a subscription that has never been written. */ + readonly initialVersion: number; +} + +/** Default policy: at most 50 edits per batch, starting at version 0. Frozen. */ +export const DEFAULT_SUBSCRIPTION_EDITS_CONFIG: Readonly = Object.freeze({ + maxBatchSize: 50, + initialVersion: 0, +}); + +/** Per-item application outcome. */ +export type SubscriptionEditOutcome = 'applied' | 'duplicate' | 'conflict' | 'error'; + +/** Result of applying one edit. */ +export interface SubscriptionEditResult { + /** Subscription id from the request. */ + readonly id: string; + /** What happened to this edit. */ + readonly outcome: SubscriptionEditOutcome; + /** Version of the record after the operation. */ + readonly version: number; + /** Typed code when the edit was skipped or failed. */ + readonly code?: SubscriptionEditsErrorCode; + /** Human-readable reason when the edit was skipped or failed. */ + readonly message?: string; +} + +/** Result of applying a whole batch. */ +export interface SubscriptionEditsBatchResult { + /** One frozen result per input edit, in request order. */ + readonly results: readonly SubscriptionEditResult[]; + /** Number of edits that produced a new commit. */ + readonly applied: number; + /** Number of edits skipped as duplicates. */ + readonly skipped: number; + /** Number of edits that conflicted or failed. */ + readonly failed: number; + /** Wall-clock duration in milliseconds. */ + readonly durationMs: number; +} + +/** Observability hooks for batch application. */ +export interface SubscriptionEditsMetrics { + /** Called once per completed batch, including partially failed ones. */ + batchCompleted(applied: number, skipped: number, failed: number, durationMs: number): void; + /** Called after a successful commit. */ + itemApplied(id: string, version: number): void; + /** Called after an idempotent skip or version conflict. */ + itemSkipped(id: string, code: SubscriptionEditsErrorCode): void; + /** Called after a store failure. */ + itemFailed(id: string, code: SubscriptionEditsErrorCode): void; +} + +/** No-op metrics, safe to use in pure contexts. Frozen. */ +export const noopSubscriptionEditsMetrics: SubscriptionEditsMetrics = Object.freeze({ + batchCompleted() {}, + itemApplied() {}, + itemSkipped() {}, + itemFailed() {}, +}); + +/** Minimal structured logger interface. Receives no secrets. */ +export interface SubscriptionEditsLogger { + /** Emit a debug-level event with optional non-sensitive context. */ + debug(message: string, details?: Readonly>): void; + /** Emit a warn-level event with optional non-sensitive context. */ + warn(message: string, details?: Readonly>): void; + /** Emit an error-level event with optional non-sensitive context. */ + error(message: string, details?: Readonly>): void; +} + +/** No-op logger. Frozen. */ +export const noopSubscriptionEditsLogger: SubscriptionEditsLogger = Object.freeze({ + debug() {}, + warn() {}, + error() {}, +}); + +/** Dependencies of a batch applier. All optional. */ +export interface SubscriptionEditsDeps { + /** Partial overrides merged onto {@link DEFAULT_SUBSCRIPTION_EDITS_CONFIG}. */ + readonly config?: Partial; + /** Called for batch and per-item telemetry. */ + readonly metrics?: SubscriptionEditsMetrics; + /** Receives non-sensitive events. */ + readonly logger?: SubscriptionEditsLogger; + /** Current time source; defaults to `Date.now`. */ + readonly now?: () => number; + /** Optional externally owned idempotency key set. */ + readonly seen?: Set; +} + +/** A bound, stateful applier that remembers applied `(id, version)` keys. */ +export interface SubscriptionEditsApplier { + /** Apply a batch of edits, returning a frozen per-item result. */ + apply(batch: readonly SubscriptionEdit[]): Promise; + /** The validated, frozen configuration in use. */ + readonly config: Readonly; + /** Snapshot of the idempotency keys recorded so far. */ + readonly seenKeys: readonly string[]; +} + +function fail( + code: SubscriptionEditsErrorCode, + message: string, + details: Readonly>, + metrics: SubscriptionEditsMetrics, + logger: SubscriptionEditsLogger, +): never { + const error = new SubscriptionEditsError(code, message, details); + metrics.itemFailed('(batch)', code); + logger.warn('subscription edits batch rejected', { code, ...details }); + throw error; +} + +function validateConfig(config: Readonly): void { + if ( + !Number.isInteger(config.maxBatchSize) || + config.maxBatchSize < 1 || + !Number.isInteger(config.initialVersion) || + config.initialVersion < 0 + ) { + throw new SubscriptionEditsError('INVALID_CONFIG', 'Invalid subscription edits configuration', { + maxBatchSize: config.maxBatchSize, + initialVersion: config.initialVersion, + }); + } +} + +function makeResult( + id: string, + outcome: SubscriptionEditOutcome, + version: number, + code?: SubscriptionEditsErrorCode, + message?: string, +): SubscriptionEditResult { + return Object.freeze({ id, outcome, version, code, message }); +} + +/** + * Create a batch applier bound to a store. + * + * The applier owns an idempotency set so replaying a batch with the same + * `(id, version)` keys produces `duplicate` results instead of extra writes. + */ +export function createSubscriptionEditsApplier( + store: SubscriptionEditsStore, + deps: SubscriptionEditsDeps = {}, +): SubscriptionEditsApplier { + const config: Readonly = Object.freeze({ + ...DEFAULT_SUBSCRIPTION_EDITS_CONFIG, + ...deps.config, + }); + validateConfig(config); + + const metrics = deps.metrics ?? noopSubscriptionEditsMetrics; + const logger = deps.logger ?? noopSubscriptionEditsLogger; + const clock = deps.now ?? Date.now; + const seen = deps.seen ?? new Set(); + + const apply = async (batch: readonly SubscriptionEdit[]): Promise => { + const began = clock(); + if (!Number.isFinite(began)) { + fail('INVALID_INPUT', 'now must return a finite number', { began }, metrics, logger); + } + if (!Array.isArray(batch)) { + fail('INVALID_INPUT', 'batch must be an array', {}, metrics, logger); + } + if (batch.length > config.maxBatchSize) { + fail( + 'BATCH_TOO_LARGE', + `Batch has ${batch.length} edits (limit ${config.maxBatchSize})`, + { count: batch.length, limit: config.maxBatchSize }, + metrics, + logger, + ); + } + + const results: SubscriptionEditResult[] = []; + let applied = 0; + let skipped = 0; + let failed = 0; + + for (const edit of batch) { + const id = edit?.id; + if (typeof id !== 'string' || id.trim().length === 0) { + results.push(makeResult(String(id), 'error', config.initialVersion, 'INVALID_INPUT', 'id must be non-empty')); + metrics.itemFailed(String(id), 'INVALID_INPUT'); + failed += 1; + continue; + } + if (edit.patch === null || typeof edit.patch !== 'object' || Array.isArray(edit.patch)) { + results.push(makeResult(id, 'error', config.initialVersion, 'INVALID_INPUT', 'patch must be an object')); + metrics.itemFailed(id, 'INVALID_INPUT'); + failed += 1; + continue; + } + const version = edit.version ?? config.initialVersion; + if (!Number.isInteger(version) || version < 0) { + results.push(makeResult(id, 'error', version, 'INVALID_VERSION', 'version must be a non-negative integer')); + metrics.itemFailed(id, 'INVALID_VERSION'); + failed += 1; + continue; + } + + const key = `${id}@${version}`; + if (seen.has(key)) { + results.push(makeResult(id, 'duplicate', version + 1, 'VERSION_CONFLICT', 'edit already applied')); + metrics.itemSkipped(id, 'VERSION_CONFLICT'); + skipped += 1; + logger.debug('subscription edit skipped as duplicate', { id, version }); + continue; + } + + try { + const record = await store.load(id); + const current = record?.version ?? config.initialVersion; + if (current !== version) { + const code = current > version ? 'VERSION_CONFLICT' : 'INVALID_VERSION'; + results.push(makeResult(id, 'conflict', current, code, `stored version ${current}, expected ${version}`)); + metrics.itemSkipped(id, code); + skipped += 1; + logger.warn('subscription edit skipped on version mismatch', { id, version, current }); + continue; + } + + const committed = await store.commit(id, edit.patch, version); + const nextVersion = Number.isFinite(committed?.version) ? committed.version : version + 1; + seen.add(key); + results.push(makeResult(id, 'applied', nextVersion)); + metrics.itemApplied(id, nextVersion); + applied += 1; + logger.debug('subscription edit applied', { id, version, nextVersion }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + results.push(makeResult(id, 'error', version, 'STORE_ERROR', message)); + metrics.itemFailed(id, 'STORE_ERROR'); + failed += 1; + logger.error('subscription edit store failure', { id, version, error: message }); + } + } + + const durationMs = Math.max(0, clock() - began); + const result: SubscriptionEditsBatchResult = Object.freeze({ + results: Object.freeze(results), + applied, + skipped, + failed, + durationMs, + }); + metrics.batchCompleted(applied, skipped, failed, durationMs); + logger.debug('subscription edits batch completed', { applied, skipped, failed, durationMs }); + return result; + }; + + const applier: SubscriptionEditsApplier = Object.freeze({ + apply, + config, + get seenKeys(): readonly string[] { + return Object.freeze([...seen]); + }, + }); + return applier; +} + +/** Idempotency keys shared between convenience calls, keyed by store identity. */ +const DEFAULT_SEEN = new WeakMap>(); + +/** + * Apply a batch using the default applier for `store`. + * + * Repeated calls with the same store share idempotency state, so a retried + * coalesced write is a no-op. Use {@link createSubscriptionEditsApplier} when + * the caller wants to own that state or pass observability hooks. + */ +export function applySubscriptionEditsBatch( + batch: readonly SubscriptionEdit[], + store: SubscriptionEditsStore, + deps: SubscriptionEditsDeps = {}, +): Promise { + let seen = deps.seen; + if (seen === undefined) { + seen = DEFAULT_SEEN.get(store); + if (seen === undefined) { + seen = new Set(); + DEFAULT_SEEN.set(store, seen); + } + } + return createSubscriptionEditsApplier(store, { ...deps, seen }).apply(batch); +} diff --git a/mobile/src/features/subscriptions/__tests__/autosave.test.ts b/mobile/src/features/subscriptions/__tests__/autosave.test.ts new file mode 100644 index 00000000..1780c113 --- /dev/null +++ b/mobile/src/features/subscriptions/__tests__/autosave.test.ts @@ -0,0 +1,357 @@ +import { + AutosaveErrorCode, + AutosaveError, + DEFAULT_AUTOSAVE_CONFIG, + createAutosaveController, + noopAutosaveMetrics, + noopAutosaveLogger, + systemAutosaveTimers, + type AutosaveBatch, + type AutosaveMetrics, + type AutosaveLogger, + type AutosaveTimers, +} from '../autosave'; + +interface Timer { handle: number; at: number; fn: () => void; cancelled: boolean } +interface Log { + queued: Array<{ id: string; coalesced: boolean }>; + scheduled: Array<{ reason: string; delayMs: number }>; + flushed: Array<{ reason: string; batches: number; edits: number }>; + cancelled: Array<{ id: string | undefined; edits: number }>; + rejected: Array<{ code: string; id?: string }>; + listenerFailed: unknown[]; +} + +function harness(clock: { now: number }) { + let next = 0; + const scheduled: Timer[] = []; + const timers: AutosaveTimers = { + setTimeout: (fn, ms) => { + const timer: Timer = { handle: ++next, at: clock.now + ms, fn, cancelled: false }; + scheduled.push(timer); + return timer.handle; + }, + clearTimeout: (handle) => { + const timer = scheduled.find((item) => item.handle === handle); + if (timer) timer.cancelled = true; + }, + }; + const advanceTo = (target: number): void => { + clock.now = target; + for (;;) { + const due = scheduled.filter((item) => !item.cancelled && item.at <= clock.now).sort((a, b) => a.at - b.at)[0]; + if (!due) return; + due.cancelled = true; + due.fn(); + } + }; + return { timers, scheduled, advanceTo }; +} + +function spy(): { metrics: AutosaveMetrics; log: Log } { + const log: Log = { queued: [], scheduled: [], flushed: [], cancelled: [], rejected: [], listenerFailed: [] }; + const metrics: AutosaveMetrics = { + queued: (id, coalesced) => log.queued.push({ id, coalesced }), + scheduled: (reason, delayMs) => log.scheduled.push({ reason, delayMs }), + flushed: (reason, batches, edits) => log.flushed.push({ reason, batches, edits }), + cancelled: (id, edits) => log.cancelled.push({ id, edits }), + rejected: (code, id) => log.rejected.push({ code, id }), + listenerFailed: (error) => log.listenerFailed.push(error), + }; + return { metrics, log }; +} + +function codeOf(fn: () => unknown): string { + try { fn(); } catch (error) { return (error as AutosaveError).code; } + throw new Error('expected fn to throw'); +} + +describe('autosave vocabulary (#2266)', () => { + it('exposes frozen, stable error codes', () => { + expect(Object.isFrozen(AutosaveErrorCode)).toBe(true); + expect(AutosaveErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(AutosaveErrorCode.INVALID_INPUT).toBe('INVALID_INPUT'); + expect(AutosaveErrorCode.INVALID_VERSION).toBe('INVALID_VERSION'); + expect(AutosaveErrorCode.DISPOSED).toBe('DISPOSED'); + }); + + it('exposes a frozen default config', () => { + expect(Object.isFrozen(DEFAULT_AUTOSAVE_CONFIG)).toBe(true); + expect(DEFAULT_AUTOSAVE_CONFIG.delayMs).toBe(400); + expect(DEFAULT_AUTOSAVE_CONFIG.maxWaitMs).toBe(2500); + expect(DEFAULT_AUTOSAVE_CONFIG.maxBatchSize).toBe(20); + }); + + it('ships frozen no-op observability hooks', () => { + expect(Object.isFrozen(noopAutosaveMetrics)).toBe(true); + expect(Object.isFrozen(noopAutosaveLogger)).toBe(true); + expect(Object.isFrozen(systemAutosaveTimers)).toBe(true); + }); + + it('builds typed errors with frozen details', () => { + const error = new AutosaveError(AutosaveErrorCode.INVALID_INPUT, 'bad id', { id: 'sub_1' }); + expect(error).toBeInstanceOf(Error); + expect(error).toBeInstanceOf(AutosaveError); + expect(error.name).toBe('AutosaveError'); + expect(error.code).toBe(AutosaveErrorCode.INVALID_INPUT); + expect(error.message).toBe('bad id'); + expect(Object.isFrozen(error.details)).toBe(true); + expect(error.details.id).toBe('sub_1'); + }); +}); + +describe('queue and last-write-wins coalescing', () => { + it('returns a frozen pending snapshot', () => { + const clock = { now: 1000 }; + const { timers } = harness(clock); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, undefined, undefined, () => clock.now, timers); + const pending = controller.queue('sub_1', { name: 'Netflix' }, 3); + expect(Object.isFrozen(pending)).toBe(true); + expect(pending).toHaveLength(1); + expect(pending[0].id).toBe('sub_1'); + expect(pending[0].patch).toEqual({ name: 'Netflix' }); + expect(pending[0].version).toBe(3); + expect(pending[0].queuedAt).toBe(1000); + expect(Object.isFrozen(pending[0])).toBe(true); + expect(controller.size()).toBe(1); + }); + + it('merges patches for the same id', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + controller.queue('sub_1', { name: 'Netflix', amount: 10 }, 1); + clock.now = 50; + const pending = controller.queue('sub_1', { amount: 12 }, 2); + expect(controller.size()).toBe(1); + expect(pending[0].patch).toEqual({ name: 'Netflix', amount: 12 }); + expect(pending[0].version).toBe(2); + expect(pending[0].queuedAt).toBe(50); + expect(log.queued).toEqual([ + { id: 'sub_1', coalesced: false }, + { id: 'sub_1', coalesced: true }, + ]); + }); + + it('keeps separate ids separate and does not mutate patches', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, undefined, undefined, () => clock.now, timers); + controller.queue('a', { amount: 1 }); + controller.queue('b', { amount: 2 }); + expect(controller.size()).toBe(2); + expect(controller.pending().map((edit) => edit.id)).toEqual(['a', 'b']); + const patch = { name: 'Spotify' }; + const pending = controller.queue('c', patch); + expect(pending[0].patch).not.toBe(patch); + expect(Object.isFrozen(pending[0].patch)).toBe(true); + expect(patch).toEqual({ name: 'Spotify' }); + }); +}); + +describe('debounce and max-wait flushing', () => { + it('flushes one quiescence batch after the quiet period', () => { + const clock = { now: 0 }; + const { timers, advanceTo } = harness(clock); + const { metrics, log } = spy(); + const batches: AutosaveBatch[] = []; + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + controller.subscribe((batch) => batches.push(batch)); + controller.queue('sub_1', { name: 'Netflix' }); + advanceTo(99); + expect(controller.size()).toBe(1); + advanceTo(100); + expect(controller.size()).toBe(0); + expect(batches).toHaveLength(1); + expect(batches[0].edits[0].id).toBe('sub_1'); + expect(batches[0].reason).toBe('quiescence'); + expect(batches[0].sequence).toBe(1); + expect(Object.isFrozen(batches[0])).toBe(true); + expect(Object.isFrozen(batches[0].edits)).toBe(true); + expect(log.flushed).toEqual([{ reason: 'quiescence', batches: 1, edits: 1 }]); + }); + + it('resets the debounce timer on every same-id edit', () => { + const clock = { now: 0 }; + const { timers, advanceTo } = harness(clock); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 1000 }, undefined, undefined, () => clock.now, timers); + controller.queue('sub_1', { amount: 1 }); + advanceTo(80); + controller.queue('sub_1', { amount: 2 }); + advanceTo(150); + expect(controller.size()).toBe(1); + advanceTo(180); + expect(controller.size()).toBe(0); + }); + + it('forces a maxWait flush under continuous typing', () => { + const clock = { now: 0 }; + const { timers, advanceTo } = harness(clock); + const { metrics, log } = spy(); + const reasons: string[] = []; + const controller = createAutosaveController({ delayMs: 150, maxWaitMs: 400 }, metrics, undefined, () => clock.now, timers); + controller.subscribe((batch) => reasons.push(batch.reason)); + controller.queue('sub_1', { amount: 1 }); + for (let step = 1; step <= 3; step += 1) { + clock.now = step * 100; + controller.queue('sub_1', { amount: step + 1 }); + } + advanceTo(400); + expect(controller.size()).toBe(0); + expect(reasons).toEqual(['maxWait']); + expect(log.flushed).toEqual([{ reason: 'maxWait', batches: 1, edits: 1 }]); + }); + + it('splits pending edits into bounded sequenced batches', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const batches: AutosaveBatch[] = []; + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500, maxBatchSize: 2 }, undefined, undefined, () => clock.now, timers); + controller.subscribe((batch) => batches.push(batch)); + ['a', 'b', 'c', 'd', 'e'].forEach((id) => controller.queue(id, { amount: 1 })); + const flushed = controller.flush(); + expect(flushed).toHaveLength(3); + expect(flushed.map((batch) => batch.edits.map((edit) => edit.id))).toEqual([['a', 'b'], ['c', 'd'], ['e']]); + expect(flushed.map((batch) => batch.sequence)).toEqual([1, 2, 3]); + expect(Object.isFrozen(flushed)).toBe(true); + expect(batches).toHaveLength(3); + }); + + it('supports manual and empty flushes', () => { + const clock = { now: 10 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + expect(controller.flush()).toEqual([]); + expect(Object.isFrozen(controller.flush())).toBe(true); + controller.queue('sub_1', { amount: 1 }); + const flushed = controller.flush(); + expect(flushed[0].reason).toBe('manual'); + expect(flushed[0].flushedAt).toBe(10); + expect(log.flushed).toEqual([ + { reason: 'manual', batches: 0, edits: 0 }, + { reason: 'manual', batches: 0, edits: 0 }, + { reason: 'manual', batches: 1, edits: 1 }, + ]); + }); + + it('records scheduling of both timers', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + controller.queue('sub_1', { amount: 1 }); + expect(log.scheduled[0]).toEqual({ reason: 'maxWait', delayMs: 500 }); + expect(log.scheduled[1]).toEqual({ reason: 'debounce', delayMs: 100 }); + }); +}); + +describe('cancel, dispose and rejection paths', () => { + it('cancels a single id and keeps the others', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + controller.queue('a', { amount: 1 }); + controller.queue('b', { amount: 2 }); + expect(controller.cancel('a')).toBe(1); + expect(controller.size()).toBe(1); + expect(controller.pending()[0].id).toBe('b'); + expect(log.cancelled).toEqual([{ id: 'a', edits: 1 }]); + expect(controller.cancel('missing')).toBe(0); + }); + + it('cancels all edits and clears timers', () => { + const clock = { now: 0 }; + const { timers, advanceTo } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + controller.queue('a', { amount: 1 }); + controller.queue('b', { amount: 2 }); + expect(controller.cancel()).toBe(2); + expect(controller.size()).toBe(0); + advanceTo(10000); + expect(log.flushed).toEqual([]); + expect(log.cancelled).toEqual([{ id: undefined, edits: 2 }]); + }); + + it('unsubscribes listeners and isolates failures', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const messages: string[] = []; + const logger: AutosaveLogger = { + debug: () => undefined, + warn: () => undefined, + error: (message) => messages.push(message), + }; + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, logger, () => clock.now, timers); + const received: string[] = []; + const stopThrower = controller.subscribe(() => { throw new Error('listener boom'); }); + const stopReceiver = controller.subscribe((batch) => received.push(batch.edits[0].id)); + controller.queue('a', { amount: 1 }); + controller.flush(); + expect(received).toEqual(['a']); + expect(log.listenerFailed).toHaveLength(1); + expect(messages[0]).toBe('autosave listener failed'); + stopThrower(); + stopReceiver(); + controller.queue('b', { amount: 2 }); + controller.flush(); + expect(received).toEqual(['a']); + expect(log.listenerFailed).toHaveLength(1); + }); + + it('rejects invalid ids, patches and versions', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + expect(codeOf(() => controller.queue('', {}))).toBe(AutosaveErrorCode.INVALID_INPUT); + expect(codeOf(() => controller.queue('a', null as never))).toBe(AutosaveErrorCode.INVALID_INPUT); + expect(codeOf(() => controller.queue('a', [], 0))).toBe(AutosaveErrorCode.INVALID_INPUT); + expect(codeOf(() => controller.queue('a', {}, -1))).toBe(AutosaveErrorCode.INVALID_VERSION); + expect(codeOf(() => controller.queue('a', {}, 1.5))).toBe(AutosaveErrorCode.INVALID_VERSION); + expect(log.rejected).toHaveLength(5); + expect(log.rejected[0].code).toBe(AutosaveErrorCode.INVALID_INPUT); + expect(log.rejected[3].code).toBe(AutosaveErrorCode.INVALID_VERSION); + expect(controller.size()).toBe(0); + }); + + it('validates configuration and a non-finite clock', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + expect(codeOf(() => createAutosaveController({ delayMs: -1 }))).toBe(AutosaveErrorCode.INVALID_CONFIG); + expect(codeOf(() => createAutosaveController({ maxWaitMs: 0 }))).toBe(AutosaveErrorCode.INVALID_CONFIG); + expect(codeOf(() => createAutosaveController({ maxBatchSize: 1.5 }))).toBe(AutosaveErrorCode.INVALID_CONFIG); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, undefined, undefined, () => Number.NaN, timers); + expect(codeOf(() => controller.queue('a', {}))).toBe(AutosaveErrorCode.INVALID_CONFIG); + }); + + it('disposes cleanly and refuses further queues', () => { + const clock = { now: 0 }; + const { timers, advanceTo } = harness(clock); + const { metrics, log } = spy(); + const received: string[] = []; + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + controller.subscribe((batch) => received.push(batch.edits[0].id)); + controller.queue('a', { amount: 1 }); + controller.dispose(); + controller.dispose(); + expect(controller.size()).toBe(0); + expect(codeOf(() => controller.queue('b', {}))).toBe(AutosaveErrorCode.DISPOSED); + advanceTo(10000); + expect(received).toEqual([]); + expect(log.cancelled).toEqual([{ id: undefined, edits: 1 }]); + }); + + it('rejects a non-function listener', () => { + const clock = { now: 0 }; + const { timers } = harness(clock); + const { metrics, log } = spy(); + const controller = createAutosaveController({ delayMs: 100, maxWaitMs: 500 }, metrics, undefined, () => clock.now, timers); + expect(codeOf(() => controller.subscribe(null as never))).toBe(AutosaveErrorCode.INVALID_INPUT); + expect(log.rejected).toHaveLength(1); + }); +}); diff --git a/mobile/src/features/subscriptions/autosave.ts b/mobile/src/features/subscriptions/autosave.ts new file mode 100644 index 00000000..0aaef200 --- /dev/null +++ b/mobile/src/features/subscriptions/autosave.ts @@ -0,0 +1,476 @@ +/** + * mobile/src/features/subscriptions/autosave.ts + * + * Issue #2266: debounced, coalesced autosaves for mobile subscription edits. + * + * Rapid edits to the same subscription used to issue one server write per + * keystroke. This controller keeps a single pending edit per subscription id + * (last write wins), resets a quiet-period timer on every new edit, and caps + * how long any edit may wait via `maxWaitMs`. When a flush happens the pending + * edits are sliced into `maxBatchSize` batches so the network layer can send + * a bounded number of coalesced writes. + * + * The controller performs no I/O: time and timers are injected, observability + * goes through injected hooks, and flushed batches are handed to listeners. + * That makes it deterministic under tests and safe to use from React Native. + */ + +/** Stable, machine-readable error codes. Frozen. */ +export const AutosaveErrorCode = Object.freeze({ + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_INPUT: 'INVALID_INPUT', + INVALID_VERSION: 'INVALID_VERSION', + DISPOSED: 'DISPOSED', +} as const); + +/** Union of {@link AutosaveErrorCode} values. */ +export type AutosaveErrorCode = (typeof AutosaveErrorCode)[keyof typeof AutosaveErrorCode]; + +/** + * Error thrown for every rejected autosave operation. + * + * The `code` is stable and safe to expose to callers; `details` carries + * non-sensitive context (ids, timestamps, limits) for logging and tests. + */ +export class AutosaveError extends Error { + /** Stable machine-readable code. */ + readonly code: AutosaveErrorCode; + /** Additional non-sensitive context about the rejection. */ + readonly details: Readonly>; + + constructor(code: AutosaveErrorCode, message: string, details: Readonly> = {}) { + super(message); + this.name = 'AutosaveError'; + this.code = code; + this.details = Object.freeze({ ...details }); + } +} + +/** Tunable policy for an autosave controller. */ +export interface AutosaveConfig { + /** Quiet period after the latest edit before a flush, in milliseconds. */ + readonly delayMs: number; + /** Hard cap from the first pending edit to a forced flush, in milliseconds. */ + readonly maxWaitMs: number; + /** Maximum number of edits included in one coalesced batch. */ + readonly maxBatchSize: number; +} + +/** Default policy: 400ms debounce, 2.5s hard cap, 20 edits per batch. Frozen. */ +export const DEFAULT_AUTOSAVE_CONFIG: Readonly = Object.freeze({ + delayMs: 400, + maxWaitMs: 2500, + maxBatchSize: 20, +}); + +/** A single pending, coalesced subscription edit. All fields are read-only. */ +export interface PendingEdit { + /** Stable subscription identifier. */ + readonly id: string; + /** Shallow-merged patch; latest value per field wins. */ + readonly patch: Readonly>; + /** Expected record version supplied by the caller, when known. */ + readonly version?: number; + /** Timestamp (ms) of the most recent edit for this id. */ + readonly queuedAt: number; +} + +/** Why a flush was triggered. */ +export type AutosaveFlushReason = 'quiescence' | 'maxWait' | 'manual' | 'shutdown'; + +/** A frozen, bounded group of edits ready for one server write. */ +export interface AutosaveBatch { + /** Coalesced edits in first-queued order. */ + readonly edits: readonly PendingEdit[]; + /** Trigger that caused this batch to be flushed. */ + readonly reason: AutosaveFlushReason; + /** Monotonically increasing batch number, starting at 1. */ + readonly sequence: number; + /** Timestamp (ms) at which the batch was produced. */ + readonly flushedAt: number; +} + +/** Observability hooks called for queue/flush/cancel/reject events. */ +export interface AutosaveMetrics { + /** Called for every accepted edit; `coalesced` is true for a same-id update. */ + queued(id: string, coalesced: boolean): void; + /** Called when a debounce or max-wait timer is (re)scheduled. */ + scheduled(reason: 'debounce' | 'maxWait', delayMs: number): void; + /** Called after a flush, including empty and forced flushes. */ + flushed(reason: AutosaveFlushReason, batches: number, edits: number): void; + /** Called after a cancel, with the id when one was targeted. */ + cancelled(id: string | undefined, edits: number): void; + /** Called for every rejected operation, before the error is thrown. */ + rejected(code: AutosaveErrorCode, id?: string): void; + /** Called when a flush listener throws. */ + listenerFailed(error: unknown): void; +} + +/** No-op metrics, safe to use in pure/browser contexts. Frozen. */ +export const noopAutosaveMetrics: AutosaveMetrics = Object.freeze({ + queued() {}, + scheduled() {}, + flushed() {}, + cancelled() {}, + rejected() {}, + listenerFailed() {}, +}); + +/** Minimal structured logger interface. Receives no secrets. */ +export interface AutosaveLogger { + /** Emit a debug-level event with optional non-sensitive context. */ + debug(message: string, details?: Readonly>): void; + /** Emit a warn-level event with optional non-sensitive context. */ + warn(message: string, details?: Readonly>): void; + /** Emit an error-level event with optional non-sensitive context. */ + error(message: string, details?: Readonly>): void; +} + +/** No-op logger. Frozen. */ +export const noopAutosaveLogger: AutosaveLogger = Object.freeze({ + debug() {}, + warn() {}, + error() {}, +}); + +/** Injectable timer surface. Defaults to the host `setTimeout`/`clearTimeout`. */ +export interface AutosaveTimers { + /** Schedule a callback after `delayMs` and return an opaque handle. */ + readonly setTimeout: (fn: () => void, delayMs: number) => unknown; + /** Cancel a handle previously returned by {@link AutosaveTimers.setTimeout}. */ + readonly clearTimeout: (handle: unknown) => void; +} + +/** Host timers. Frozen. */ +export const systemAutosaveTimers: AutosaveTimers = Object.freeze({ + setTimeout: (fn, delayMs) => setTimeout(fn, delayMs), + clearTimeout: (handle) => { + clearTimeout(handle as ReturnType); + }, +}); + +/** Injectable clock returning the current time in milliseconds. */ +export type AutosaveClock = () => number; + +/** Receives each flushed batch so the caller can perform the server write. */ +export type AutosaveFlushListener = (batch: AutosaveBatch) => void; + +/** A bound autosave controller. */ +export interface AutosaveController { + /** Queue (or coalesce) an edit and reschedule the debounce timer. */ + queue(id: string, patch: Readonly>, version?: number): readonly PendingEdit[]; + /** Drain all pending edits into frozen batches. Defaults to `manual`. */ + flush(reason?: AutosaveFlushReason): readonly AutosaveBatch[]; + /** Drop one edit by id, or all edits when no id is given. Returns the count removed. */ + cancel(id?: string): number; + /** Frozen snapshot of the currently pending edits. */ + pending(): readonly PendingEdit[]; + /** Number of distinct subscription ids currently pending. */ + size(): number; + /** Register a flush listener; returns an unsubscribe function. */ + subscribe(listener: AutosaveFlushListener): () => void; + /** Cancel all timers and listeners; the controller becomes unusable. */ + dispose(): void; + /** The validated, frozen configuration in use. */ + readonly config: Readonly; +} + +/** Internal entry carrying ordering and max-wait bookkeeping. */ +interface PendingEntry extends PendingEdit { + /** Time of the first edit in this coalescing window. */ + readonly firstQueuedAt: number; + /** Monotonic insertion order. */ + readonly sequence: number; +} + +function reject( + code: AutosaveErrorCode, + message: string, + details: Readonly>, + metrics: AutosaveMetrics, + logger: AutosaveLogger, + id?: string, +): never { + const error = new AutosaveError(code, message, details); + metrics.rejected(code, id); + logger.warn('autosave rejected', { code, ...details }); + throw error; +} + +function validateConfig(config: Readonly): void { + if ( + !Number.isFinite(config.delayMs) || + config.delayMs < 0 || + !Number.isFinite(config.maxWaitMs) || + config.maxWaitMs <= 0 || + !Number.isInteger(config.maxBatchSize) || + config.maxBatchSize < 1 + ) { + throw new AutosaveError(AutosaveErrorCode.INVALID_CONFIG, 'Invalid autosave configuration', { + delayMs: config.delayMs, + maxWaitMs: config.maxWaitMs, + maxBatchSize: config.maxBatchSize, + }); + } +} + +/** + * Create a bound autosave controller. + * + * @param config Partial overrides merged onto {@link DEFAULT_AUTOSAVE_CONFIG}. + * @param metrics Called on queue/flush/cancel/reject events. + * @param logger Receives non-sensitive debug events. + * @param clock Current time source; defaults to `Date.now`. + * @param timers Timer surface; defaults to host timers. + */ +export function createAutosaveController( + config: Partial = {}, + metrics: AutosaveMetrics = noopAutosaveMetrics, + logger: AutosaveLogger = noopAutosaveLogger, + clock: AutosaveClock = Date.now, + timers: AutosaveTimers = systemAutosaveTimers, +): AutosaveController { + const merged: Readonly = Object.freeze({ ...DEFAULT_AUTOSAVE_CONFIG, ...config }); + validateConfig(merged); + + const entries = new Map(); + const listeners = new Set(); + let debounceHandle: unknown; + let maxWaitHandle: unknown; + let hasDebounce = false; + let hasMaxWait = false; + let editSequence = 0; + let batchSequence = 0; + let disposed = false; + + const now = (): number => { + const value = clock(); + if (!Number.isFinite(value)) { + reject(AutosaveErrorCode.INVALID_CONFIG, 'autosave clock must return a finite number', { value }, metrics, logger); + } + return value; + }; + + const clearDebounce = (): void => { + if (hasDebounce) { + timers.clearTimeout(debounceHandle); + debounceHandle = undefined; + hasDebounce = false; + } + }; + + const clearMaxWait = (): void => { + if (hasMaxWait) { + timers.clearTimeout(maxWaitHandle); + maxWaitHandle = undefined; + hasMaxWait = false; + } + }; + + const schedule = (reason: 'debounce' | 'maxWait', fn: () => void, delayMs: number): void => { + const delay = Math.max(0, delayMs); + const handle = timers.setTimeout(fn, delay); + if (reason === 'debounce') { + debounceHandle = handle; + hasDebounce = true; + } else { + maxWaitHandle = handle; + hasMaxWait = true; + } + metrics.scheduled(reason, delay); + logger.debug('autosave timer scheduled', { reason, delayMs: delay }); + }; + + const snapshot = (): readonly PendingEdit[] => + Object.freeze( + [...entries.values()] + .sort((a, b) => a.sequence - b.sequence) + .map((entry) => snapshotEntry(entry)), + ); + + const flushInternal = (reason: AutosaveFlushReason): readonly AutosaveBatch[] => { + clearDebounce(); + clearMaxWait(); + + if (entries.size === 0) { + metrics.flushed(reason, 0, 0); + return Object.freeze([]); + } + + const items = [...entries.values()].sort((a, b) => a.sequence - b.sequence); + entries.clear(); + const flushedAt = now(); + const batches: AutosaveBatch[] = []; + + for (let index = 0; index < items.length; index += merged.maxBatchSize) { + batches.push( + Object.freeze({ + edits: Object.freeze(items.slice(index, index + merged.maxBatchSize).map((entry) => snapshotEntry(entry))), + reason, + sequence: ++batchSequence, + flushedAt, + }), + ); + } + + const frozen = Object.freeze(batches); + metrics.flushed(reason, frozen.length, items.length); + logger.debug('autosave flushed', { reason, batches: frozen.length, edits: items.length }); + + for (const batch of frozen) { + for (const listener of listeners) { + try { + listener(batch); + } catch (error) { + metrics.listenerFailed(error); + logger.error('autosave listener failed', { + sequence: batch.sequence, + error: error instanceof Error ? error.message : String(error), + }); + } + } + } + return frozen; + }; + + const onDebounce = (): void => { + debounceHandle = undefined; + hasDebounce = false; + flushInternal('quiescence'); + }; + + const onMaxWait = (): void => { + maxWaitHandle = undefined; + hasMaxWait = false; + flushInternal('maxWait'); + }; + + const queue = ( + id: string, + patch: Readonly>, + version?: number, + ): readonly PendingEdit[] => { + if (disposed) { + reject(AutosaveErrorCode.DISPOSED, 'autosave controller has been disposed', { id }, metrics, logger, id); + } + if (typeof id !== 'string' || id.trim().length === 0) { + reject(AutosaveErrorCode.INVALID_INPUT, 'id must be a non-empty string', { id }, metrics, logger); + } + if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { + reject(AutosaveErrorCode.INVALID_INPUT, 'patch must be a non-null object', { id, patch }, metrics, logger, id); + } + if (version !== undefined && (!Number.isFinite(version) || !Number.isInteger(version) || version < 0)) { + reject( + AutosaveErrorCode.INVALID_VERSION, + 'version must be a non-negative integer', + { id, version }, + metrics, + logger, + id, + ); + } + + const queuedAt = now(); + const existing = entries.get(id); + + if (existing !== undefined) { + const coalesced: PendingEntry = { + id, + patch: Object.freeze({ ...existing.patch, ...patch }), + version: version ?? existing.version, + queuedAt, + firstQueuedAt: existing.firstQueuedAt, + sequence: existing.sequence, + }; + entries.delete(id); + entries.set(id, coalesced); + metrics.queued(id, true); + logger.debug('autosave edit coalesced', { id, queuedAt }); + } else { + const wasEmpty = entries.size === 0; + const entry: PendingEntry = { + id, + patch: Object.freeze({ ...patch }), + version, + queuedAt, + firstQueuedAt: queuedAt, + sequence: ++editSequence, + }; + entries.set(id, entry); + metrics.queued(id, false); + logger.debug('autosave edit queued', { id, queuedAt, version }); + if (wasEmpty) { + schedule('maxWait', onMaxWait, entry.firstQueuedAt + merged.maxWaitMs - queuedAt); + } + } + + clearDebounce(); + schedule('debounce', onDebounce, merged.delayMs); + return snapshot(); + }; + + const cancel = (id?: string): number => { + let removed = 0; + if (id === undefined) { + removed = entries.size; + entries.clear(); + clearDebounce(); + clearMaxWait(); + } else if (entries.delete(id)) { + removed = 1; + clearDebounce(); + if (entries.size === 0) { + clearMaxWait(); + } else { + const earliest = [...entries.values()].sort((a, b) => a.queuedAt - b.queuedAt)[0]; + schedule('debounce', onDebounce, earliest.queuedAt + merged.delayMs - now()); + } + } + metrics.cancelled(id, removed); + logger.debug('autosave cancelled', { id: id ?? null, removed }); + return removed; + }; + + const subscribe = (listener: AutosaveFlushListener): (() => void) => { + if (typeof listener !== 'function') { + reject(AutosaveErrorCode.INVALID_INPUT, 'listener must be a function', {}, metrics, logger); + } + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }; + + const controller: AutosaveController = Object.freeze({ + queue, + flush: (reason: AutosaveFlushReason = 'manual') => flushInternal(reason), + cancel, + pending: snapshot, + size: () => entries.size, + subscribe, + dispose: () => { + if (disposed) return; + disposed = true; + clearDebounce(); + clearMaxWait(); + const removed = entries.size; + entries.clear(); + listeners.clear(); + metrics.cancelled(undefined, removed); + logger.debug('autosave disposed', { removed }); + }, + config: merged, + }); + + return controller; +} + +/** Convert an internal entry into a frozen public edit snapshot. */ +function snapshotEntry(entry: PendingEntry): PendingEdit { + return Object.freeze({ + id: entry.id, + patch: entry.patch, + version: entry.version, + queuedAt: entry.queuedAt, + }); +}