fix(readers): never replay a failed read decision; bound the recent-reads map
Build & push images / images (push) Successful in 3m3s

Follow-up to ec01591. A first decision that threw was cached and replayed
to repeats inside the window, and the telemetry hook on it had no rejection
handler, so one throwing flow became an unhandled rejection per repeat. A
failed decision is now forgotten (the next read decides afresh) and the
hook handles rejection. The recent-reads map prunes above 512 entries and
never exceeds 4096, whatever a misbehaving reader sends.
This commit is contained in:
2026-10-11 18:58:10 +02:00
parent ec015911e9
commit 965937352d
2 changed files with 53 additions and 4 deletions
+25 -4
View File
@@ -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<ReadOutcome> {
const sub = this.#subscription.match(e);