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
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it } from "vitest";
import { devices, deviceEvents as deviceEventsTable, ledgerEvents, subscriptionCredentials, subscriptions, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import { ReadDispatcher, readDebounceMs, DEFAULT_READ_DEBOUNCE_MS } from "./read-dispatch.js";
import { ExitFlow } from "./exit-flow.js";
import { SubscriptionFlow } from "./subscription-flow.js";
import type { DeviceReadEvent } from "./device-events.js";
import { makeLog, silentLogger } from "./test-helpers.js";
// SAME-CODE DEBOUNCE at the dispatcher (2026-10-11): the same value from the same reader
// inside the reader's `debounceMs` window is ONE presentation — the first verdict is
// replayed, nothing is signed twice, the repeat lands in device_events as telemetry.
// Born at park-2: the DT-008 reported one card twice 560 ms apart; the permit flow opened
// two sessions and pulsed the barrier twice. Every lane, every credential kind.
let db: Db;
function seed(readerCfg: Record<string, unknown>, direction: "entry" | "exit" = "exit"): ReadDispatcher {
({ db } = createTestDb());
db.insert(devices).values({
id: "ctl",
category: "access",
driverId: "stub-access",
config: { relays: [{ relay: 1, direction }] },
enabled: true,
}).run();
db.insert(devices).values({
id: "reader",
category: "reader",
driverId: "dingtian-qr-reader",
config: { serial: "H05MA5B0", controllerId: "ctl", relay: 1, ...readerCfg },
enabled: true,
}).run();
const log = makeLog(db);
return new ReadDispatcher(db, new ExitFlow(db, log, silentLogger()), new SubscriptionFlow(db, log, silentLogger()), silentLogger());
}
function read(value: string, opts: { kind?: DeviceReadEvent["kind"]; channel?: DeviceReadEvent["channel"] } = {}): DeviceReadEvent {
return {
driverId: "dingtian-qr-reader",
deviceId: "reader",
value,
kind: opts.kind ?? "qr",
...(opts.channel ? { channel: opts.channel } : {}),
at: new Date().toISOString(),
};
}
const ledger = () => db.select().from(ledgerEvents).all();
const debounced = () =>
db.select().from(deviceEventsTable).all()
.map((r) => r.detail as { debounced?: boolean; value?: string; sinceMs?: number; replayedAccepted?: boolean })
.filter((d) => d.debounced === true);
describe("readDebounceMs", () => {
it("defaults to 5000 when the reader has no value; honours numbers and form strings; 0 = off", () => {
expect(readDebounceMs({})).toBe(DEFAULT_READ_DEBOUNCE_MS);
expect(readDebounceMs({ debounceMs: "" })).toBe(5000);
expect(readDebounceMs({ debounceMs: 2500 })).toBe(2500);
expect(readDebounceMs({ debounceMs: "800" })).toBe(800);
expect(readDebounceMs({ debounceMs: 0 })).toBe(0);
expect(readDebounceMs({ debounceMs: "nope" })).toBe(0);
});
});
describe("read-dispatch same-code debounce", () => {
it("a repeat of the same unknown ticket at exit signs ONE refusal, replays the verdict, logs telemetry", async () => {
const d = seed({}); // default window
const first = await d.dispatch(read("00000000000")); // Luhn-valid, no session → refused + signed
const second = await d.dispatch(read("00000000000"));
expect(ledger()).toHaveLength(1); // not a second red row for the same scan
expect(second).toEqual(first); // same verdict → same beep
expect(debounced()).toHaveLength(1);
expect(debounced()[0]).toMatchObject({ value: "00000000000", replayedAccepted: false });
});
it("a double-read SUBSCRIBER card at ENTRY opens ONE occurrence and the repeat is accepted (replayed)", async () => {
const d = seed({}, "entry");
db.insert(subscriptions).values({ id: "s1", status: "active", quantity: 1, period: "month" }).run();
db.insert(subscriptionCredentials).values({ id: "c1", subscriptionId: "s1", kind: "rf", value: "3F3AFC" }).run();
const first = await d.dispatch(read("3F3AFC", { kind: "card", channel: "rf" }));
const second = await d.dispatch(read("3F3AFC", { kind: "card", channel: "rf" }));
expect(first.accepted).toBe(true);
expect(second.accepted).toBe(true); // the card WAS read; beep ok, but no second entry
expect(ledger().filter((e) => e.type === "vehicle_entry")).toHaveLength(1);
expect(debounced()).toHaveLength(1);
});
it("a DIFFERENT code inside the window is not debounced", async () => {
const d = seed({});
await d.dispatch(read("00000000000"));
await d.dispatch(read("00000000026")); // another Luhn-valid shape
expect(ledger()).toHaveLength(2);
expect(debounced()).toHaveLength(0);
});
it("the window comes from the reader's config and expires", async () => {
const d = seed({ debounceMs: 30 });
await d.dispatch(read("00000000000"));
await new Promise((r) => setTimeout(r, 45));
await d.dispatch(read("00000000000")); // outside the 30ms window → a fresh decision
expect(ledger()).toHaveLength(2);
expect(debounced()).toHaveLength(0);
});
it("debounceMs = 0 turns it off", async () => {
const d = seed({ debounceMs: 0 });
await d.dispatch(read("00000000000"));
await d.dispatch(read("00000000000"));
expect(ledger()).toHaveLength(2);
});
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"))]);
expect(b).toEqual(a);
expect(ledger()).toHaveLength(1);
});
});
+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 {