diff --git a/src/lib/sync.test.ts b/src/lib/sync.test.ts index 3806afa..e0b042d 100644 --- a/src/lib/sync.test.ts +++ b/src/lib/sync.test.ts @@ -107,4 +107,26 @@ describe("trySyncWithBackend", () => { expect(await db.eventLog.count()).toBe(countBefore); expect(computeBalances(await readAll()).balances["remoteAcct"]).toBe(42); }); + + it("coalesces concurrent syncs so one pulled entry is ingested exactly once (dedup race)", async () => { + const wire = await signedWireEntry( + { type: "wallet.issue", account: "raceAcct", amount: 10 }, + 3, + ); + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(okResponse({ stored: 0, entries: [wire], cursor: 1 })), + ); + + const results = await Promise.all([ + trySyncWithBackend({ endpoint: "http://relay/api/sync" }), + trySyncWithBackend({ endpoint: "http://relay/api/sync" }), + trySyncWithBackend({ endpoint: "http://relay/api/sync" }), + trySyncWithBackend({ endpoint: "http://relay/api/sync" }), + ]); + + expect(results.every((r) => r.ok)).toBe(true); + expect(await db.eventLog.count()).toBe(1); + expect(computeBalances(await readAll()).balances["raceAcct"]).toBe(10); + }); }); diff --git a/src/lib/sync.ts b/src/lib/sync.ts index babc25f..0d65acc 100644 --- a/src/lib/sync.ts +++ b/src/lib/sync.ts @@ -81,6 +81,20 @@ export function resetSyncCursors(): void { cursors.clear(); } +const SYNC_NOOP: SyncResult = { ok: false, pushed: 0, pulled: 0 }; + +/** + * One promise chain shared by every caller so concurrent sync requests run + * one-at-a-time. Several mini-app mounts plus the shell's periodic poll can + * fire `trySyncWithBackend()` at once; the pulled-entry dedup in `runSync` is a + * non-atomic read-modify-write (read the `existing` (authorPubkey, signature) + * set, then `appendEntry` in a loop), so two overlapping runs would both see a + * remote entry as absent and ingest it twice - duplicating it in the local log + * and corrupting the replayed ledger. Chaining each run after the previous one + * settles makes that dedup effectively atomic. + */ +let syncChain: Promise = Promise.resolve(SYNC_NOOP); + function bytesToHex(bytes: Uint8Array): string { return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } @@ -126,6 +140,19 @@ function fromWire(wire: unknown): UnsignedEventLogEntry | null { }; } +/** + * Serialized entry point (see `syncChain`): safe to call fire-and-forget from + * any number of mini-app mounts and the shell's poll at once. + */ +export function trySyncWithBackend(options: SyncOptions = {}): Promise { + const result = syncChain.then( + () => runSync(options), + () => runSync(options), + ); + syncChain = result.catch(() => SYNC_NOOP); + return result; +} + /** * Push new local events and pull new remote entries through the relay, * persisting each pulled entry via `appendEntry()` after a (authorPubkey, @@ -133,7 +160,7 @@ function fromWire(wire: unknown): UnsignedEventLogEntry | null { * resolves to `{ ok: false }` without throwing and without touching the local * log - safe to call on any mini-app mount. */ -export async function trySyncWithBackend( +async function runSync( options: SyncOptions = {}, ): Promise { const endpoint = options.endpoint ?? "/api/sync";