diff --git a/apps/server/src/read-dispatch-debounce.test.ts b/apps/server/src/read-dispatch-debounce.test.ts index 4ae3a6c..b4f2651 100644 --- a/apps/server/src/read-dispatch-debounce.test.ts +++ b/apps/server/src/read-dispatch-debounce.test.ts @@ -110,6 +110,34 @@ describe("read-dispatch same-code debounce", () => { expect(ledger()).toHaveLength(2); }); + it("a FAILED first decision is not replayed: the repeat decides afresh, no unhandled rejection", async () => { + seed({}); + // Make the exit flow blow up once (e.g. a signer hiccup), then work. + const log = makeLog(db); + const flaky = new ExitFlow(db, log, silentLogger()); + let calls = 0; + const orig = flaky.handleAt.bind(flaky); + flaky.handleAt = async (...args: Parameters) => { + calls++; + if (calls === 1) throw new Error("signer busy"); + return orig(...args); + }; + const d2 = new ReadDispatcher(db, flaky, new SubscriptionFlow(db, log, silentLogger()), silentLogger()); + const rejections: unknown[] = []; + const onUnhandled = (r: unknown) => rejections.push(r); + process.on("unhandledRejection", onUnhandled); + try { + await expect(d2.dispatch(read("00000000000"))).rejects.toThrow("signer busy"); + const second = await d2.dispatch(read("00000000000")); // inside the window, but nothing to replay + expect(second.accepted).toBe(false); // a real decision (refused: no session), signed once + expect(ledger()).toHaveLength(1); + await new Promise((r) => setTimeout(r, 10)); + expect(rejections).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + it("a repeat arriving while the first read is still deciding gets the SAME decision", async () => { const d = seed({}); const [a, b] = await Promise.all([d.dispatch(read("00000000000")), d.dispatch(read("00000000000"))]); diff --git a/apps/server/src/read-dispatch.ts b/apps/server/src/read-dispatch.ts index baa768c..17268c1 100644 --- a/apps/server/src/read-dispatch.ts +++ b/apps/server/src/read-dispatch.ts @@ -48,6 +48,11 @@ import { relayForDevice, type ResolvedRelay } from "./device-resolve.js"; /** Default same-code debounce when a reader's config has none (ms). */ export const DEFAULT_READ_DEBOUNCE_MS = 5000; +/** Recent-reads map housekeeping: prune above the soft cap, never exceed the hard cap, and + * treat any entry older than this as expired whatever the reader's configured window. */ +const RECENT_READS_SOFT_CAP = 512; +const RECENT_READS_HARD_CAP = 4096; +const RECENT_READS_MAX_AGE_MS = 60_000; interface ReaderConfig { readonly debounceMs?: number | string | null; @@ -104,19 +109,35 @@ export class ReadDispatcher { this.#logger.info( `read debounced: '${e.value}' (${e.kind}) again on ${e.deviceId} after ${sinceMs}ms (window ${debounceMs}ms) — first verdict replayed`, ); - void prev.outcome.then((o) => this.#recordDebounced(e, sinceMs, debounceMs, o)); + prev.outcome.then( + (o) => this.#recordDebounced(e, sinceMs, debounceMs, o), + () => undefined, // the first decision failed: the caller gets that rejection, not us + ); return prev.outcome; } const outcome = this.#decide(resolved, e); if (debounceMs > 0) { this.#recent.set(key, { at: now, outcome }); - if (this.#recent.size > 512) { - for (const [k, r] of this.#recent) if (now - r.at >= debounceMs) this.#recent.delete(k); - } + // A failed decision is NOT a verdict to replay — forget it so the next read retries. + outcome.catch(() => this.#recent.delete(key)); + this.#pruneRecent(now); } return outcome; } + /** Keep the recent-reads map small: drop expired entries, and if a flood of distinct + * values inside one window still leaves it over the cap, drop the oldest. Bounded + * memory whatever a misbehaving (or hostile) reader sends. */ + #pruneRecent(now: number): void { + if (this.#recent.size <= RECENT_READS_SOFT_CAP) return; + for (const [k, r] of this.#recent) if (now - r.at >= RECENT_READS_MAX_AGE_MS) this.#recent.delete(k); + while (this.#recent.size > RECENT_READS_HARD_CAP) { + const oldest = this.#recent.keys().next().value; // insertion order = oldest first + if (oldest === undefined) break; + this.#recent.delete(oldest); + } + } + /** The actual routing of a FRESH read (not a debounced repeat). */ async #decide(resolved: ResolvedRelay, e: DeviceReadEvent): Promise { const sub = this.#subscription.match(e);