feat(readers): same-code debounce at the dispatcher, per-reader window (default 5000 ms)
Build & push images / images (push) Successful in 3m7s

park-2, 2026-10-11: the DT-008 entry reader reported one card twice 560 ms
apart; the permit flow opened two sessions on the same permit and pulsed the
barrier twice (caught by the new relay-pulse log). The 24h before showed
2 entry + 2 exit opens within 2 s of the previous one.

ReadDispatcher now treats the same value from the same reader inside the
reader's debounceMs window as ONE presentation: the first verdict is replayed
(same beep, no second decision, nothing signed twice) and the repeat lands in
device_events as unsigned telemetry. Every lane and every credential kind,
so a ticket re-scanned at exit inside its grace period no longer signs a
noSession refusal for a car that just left. The window slides with repeats;
a repeat arriving while the first read is still deciding gets that decision.

The window is a Setup field on all three reader drivers ("Same-code
debounce (ms)", default 5000, 0 = off); readers configured before the field
existed get the default.
This commit is contained in:
2026-10-11 18:55:29 +02:00
parent c94269379e
commit ec015911e9
5 changed files with 256 additions and 4 deletions
+89 -1
View File
@@ -5,7 +5,7 @@ import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
import type { ExitFlow } from "./exit-flow.js";
import { validateTicketCode } from "./entry-flow.js";
import type { SubscriptionFlow } from "./subscription-flow.js";
import { relayForDevice } from "./device-resolve.js";
import { relayForDevice, type ResolvedRelay } from "./device-resolve.js";
// Routes a credential read (ticket scan / plate / card) to the right flow. A read
// can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the
@@ -35,12 +35,44 @@ import { relayForDevice } from "./device-resolve.js";
// - ANY read on a CONFIRMED RF channel (a physically present card, enrolled or
// not, is a real event — RF is never sun noise),
// - plates (different population; never shape-filtered here).
//
// SAME-CODE DEBOUNCE (2026-10-11, park-2). The DT-008 reported one card TWICE 560 ms
// apart; the permit flow opened two sessions on the same permit and pulsed the barrier
// twice. Any reader can double-read (a card held a beat too long, a QR re-decoded while
// the hand moves), and at exit a second scan of a ticket inside its grace period would
// sign a noSession refusal for a car that just left. So the SAME value from the SAME
// reader within the reader's `debounceMs` (Setup → reader; default 5000; 0 = off) is one
// presentation: the first verdict is REPLAYED (same beep, no second decision, nothing
// signed twice) and the repeat is kept as unsigned telemetry. Every lane, every kind
// (card / QR / ticket / plate) — the ANPR bridge debounces plates itself, longer.
/** Default same-code debounce when a reader's config has none (ms). */
export const DEFAULT_READ_DEBOUNCE_MS = 5000;
interface ReaderConfig {
readonly debounceMs?: number | string | null;
readonly [k: string]: unknown;
}
/** The reader's debounce window: its config value (the Setup form may store a string),
* else the default; 0 (or a negative/garbage value coerced to 0) disables. */
export function readDebounceMs(config: unknown): number {
const v = (config as ReaderConfig | null)?.debounceMs;
if (v == null || v === "") return DEFAULT_READ_DEBOUNCE_MS;
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
}
export class ReadDispatcher {
readonly #db: Db;
readonly #exit: ExitFlow;
readonly #subscription: SubscriptionFlow;
readonly #logger: FastifyBaseLogger;
/** Recent reads keyed `deviceId:kind:value` → when last seen + the FIRST verdict (a
* promise, so a repeat arriving while the first is still deciding gets that same
* decision). `at` slides on each repeat: a card held against the reader stays one
* presentation for as long as it keeps re-reading. */
readonly #recent = new Map<string, { at: number; outcome: Promise<ReadOutcome> }>();
constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) {
this.#db = db;
@@ -59,6 +91,34 @@ export class ReadDispatcher {
return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" };
}
// Same code, same reader, inside the window → replay the first verdict. Checked
// BEFORE matching so a repeat never reaches a flow (no second entry, no second exit,
// no refusal anomaly for a car that was just admitted).
const debounceMs = readDebounceMs(reader.config);
const key = `${e.deviceId}:${e.kind}:${e.value}`;
const now = Date.now();
const prev = this.#recent.get(key);
if (debounceMs > 0 && prev && now - prev.at < debounceMs) {
const sinceMs = now - prev.at;
prev.at = now;
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));
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);
}
}
return outcome;
}
/** 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);
if (sub) {
return this.#subscription.run(resolved, e, sub);
@@ -86,6 +146,34 @@ export class ReadDispatcher {
return this.#exit.handleAt(resolved, e);
}
/** Unsigned telemetry for a debounced repeat — auditable in device_events (the double
* read is still a fact about the hardware), out of the signed feed. */
#recordDebounced(e: DeviceReadEvent, sinceMs: number, debounceMs: number, replayed: ReadOutcome): void {
try {
this.#db
.insert(deviceEventsTable)
.values({
id: randomUUID(),
deviceId: e.deviceId,
category: "reader",
kind: "read",
detail: {
debounced: true,
value: e.value,
readKind: e.kind,
...(e.channel ? { channel: e.channel } : {}),
sinceMs,
debounceMs,
replayedAccepted: replayed.accepted,
},
occurredAt: e.at,
})
.run();
} catch (err) {
this.#logger.error(`debounced-read telemetry insert failed: ${(err as Error).message}`);
}
}
/** Unsigned telemetry for a filtered read — auditable in device_events, out of the
* signed feed. Mirrors the entry flow's suppressed-press pattern. */
#recordUnrecognized(e: DeviceReadEvent): void {