import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { randomUUID } from "node:crypto"; import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db } from "@parking/db"; import { createTestDb } from "@parking/db/testing"; import { deviceEvents, type DeviceReadEvent, type VehicleReadEvent } from "./device-events.js"; import { silentLogger } from "./test-helpers.js"; import type { VisionClient, VisionResult, VisionVehicle } from "./vision-client.js"; import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js"; // The ANPR bridge: a camera vehicle detection → (opt-in) snapshot → plate → MATCH a // subscriber → emit a plate read. We mock the camera build (buildCamera) so no real // snapshot HTTP is made, and pass fake Vision/Subscription so the test is the bridge's // own logic only. See anpr-entry.ts. // Mock buildCamera so the bridge gets a fake camera whose captureSnapshot is a stub // (no registry, no network). The factory returns a fresh shot each call. const captureSnapshot = vi.fn(async () => ({ bytes: Buffer.from("jpg"), contentType: "image/jpeg", capturedAt: new Date().toISOString() })); // The pass sample's box normalisation (needs a real JPEG header in prod) — stubbed so a // test can hand the bridge a vehicle box, or none. const { normalizedBoxes } = vi.hoisted(() => ({ normalizedBoxes: vi.fn(async (): Promise<{ vehicleBox: unknown; plateBox: unknown }> => ({ vehicleBox: null, plateBox: null })), })); // The bridge now goes through captureSnapshotShared (the dedup wrapper, exercised in // snapshot.test.ts); here it just delegates to the fake camera's captureSnapshot so this // suite stays focused on the bridge's own match/debounce/emit logic. vi.mock("./snapshot.js", () => ({ buildCamera: () => ({ captureSnapshot }), captureSnapshotShared: (_id: string, camera: { captureSnapshot: typeof captureSnapshot }, ctx: unknown) => camera.captureSnapshot(ctx as never), // Storage re-encode is sharp's business (snapshot.test.ts); here the bytes pass through. encodeForStorage: async (shot: { bytes: Buffer; contentType: string }) => ({ bytes: shot.bytes, contentType: shot.contentType }), normalizedBoxes, })); // Import AFTER the mock is registered. const { AnprBridge } = await import("./anpr-entry.js"); let db: Db; beforeEach(() => { ({ db } = createTestDb()); captureSnapshot.mockClear(); normalizedBoxes.mockReset(); normalizedBoxes.mockResolvedValue({ vehicleBox: null, plateBox: null }); delete process.env.VISION_ENTRY_MIN_CONFIDENCE; delete process.env.ANPR_DEBOUNCE_MS; // Read-every-frame loop: keep the window tiny so a loop ends in a few ticks instead of the // 8s production window (tests stay fast); the 1ms floor keeps a mocked loop from spinning // thousands of frames. Each bridge reads these in its constructor, so set them before // `new AnprBridge`. process.env.ANPR_POLL_MS = "1"; process.env.ANPR_POLL_WINDOW_MS = "5"; }); afterEach(() => { vi.restoreAllMocks(); delete process.env.ANPR_POLL_MS; delete process.env.ANPR_POLL_WINDOW_MS; delete process.env.ANPR_POLL_MAX_MS; }); /** A camera bound to an entry relay; `anpr` toggles recognition, `anprAutoTrigger` the * per-camera auto-open gate (absent ⇒ defaults on). */ function seedCamera(opts: { anpr?: boolean; anprAutoTrigger?: boolean } = {}): string { const controllerId = randomUUID(); db.insert(devices).values({ id: controllerId, category: "access", driverId: "dingtian", config: { host: "10.0.0.5", relays: [{ relay: 1, direction: "entry" }] }, enabled: true, }).run(); const camId = randomUUID(); db.insert(devices).values({ id: camId, category: "camera", driverId: "hikvision", config: { host: "10.0.0.9", controllerId, relay: 1, ...(opts.anpr ? { anpr: true } : {}), ...(opts.anprAutoTrigger === false ? { anprAutoTrigger: false } : {}), }, enabled: true, }).run(); return camId; } /** A fake VisionClient: enabled, returning a chosen plate/confidence (or null), and * optionally a vehicle (body type + box) the way the vehicle stage reports it. */ function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number; vehicle?: VisionVehicle } = {}): VisionClient { const enabled = opts.enabled ?? true; const result: VisionResult | null = opts.plate == null && opts.vehicle == null ? null : { plate: opts.plate == null ? null : { text: opts.plate, confidence: opts.confidence ?? 0.99 }, plates: [], lowConfidence: false, vehicle: opts.vehicle ?? null, modelVersion: "test", tookMs: 1, }; return { enabled, analyze: vi.fn(async () => (enabled ? result : null)), } as unknown as VisionClient; } /** A fake SubscriptionFlow: only `match()` is called by the bridge. */ function fakeSubFlow( // A fixed answer, or a matcher by plate (several subscribers in one loop). match: SubscriptionMatch | null | ((plate: string) => SubscriptionMatch | null), // openOccurrenceCount: a constant, or a sequence consumed per call (to simulate a // credential closing an occurrence mid-poll → count changes). openCounts: number | number[] = 1, ): SubscriptionFlow { const seq = Array.isArray(openCounts) ? [...openCounts] : null; return { match: vi.fn((e: DeviceReadEvent) => (typeof match === "function" ? match(e.value) : match)), openOccurrenceCount: vi.fn(() => (seq ? (seq.length > 1 ? seq.shift()! : seq[0]) : (openCounts as number))), } as unknown as SubscriptionFlow; } const SUB_MATCH: SubscriptionMatch = { subscriptionId: "sub-1", carKey: "AA111BB", via: "plate" }; const SUB_MATCH_2: SubscriptionMatch = { subscriptionId: "sub-2", carKey: "CC333DD", via: "plate" }; /** A VisionClient whose analyze() walks a sequence of (plate, confidence) frames, holding the * last one — the way a car's read evolves as it approaches and settles, or as one car gives * way to the next. `vehicle` (optional) rides every frame. */ function sequenceVision(frames: { plate: string; confidence: number }[], vehicle: VisionVehicle | null = null): VisionClient { let i = 0; return { enabled: true, analyze: vi.fn(async () => { const f = frames[Math.min(i++, frames.length - 1)]!; return { plate: { text: f.plate, confidence: f.confidence }, plates: [], lowConfidence: false, vehicle, modelVersion: "test", tookMs: 1 }; }), } as unknown as VisionClient; } /** Capture read events emitted during `fn` (async). */ async function captureReads(fn: () => Promise): Promise { const got: DeviceReadEvent[] = []; const off = deviceEvents.onRead((e) => got.push(e)); try { await fn(); } finally { off(); } return got; } /** Capture vehicle-read (pass sample) events during `fn`, waiting for the bridge's * fire-and-forget recording to land. */ async function captureVehicleReads(fn: () => Promise, expectCount: number): Promise { const got: VehicleReadEvent[] = []; const off = deviceEvents.onVehicleRead((e) => got.push(e)); try { await fn(); if (expectCount > 0) await vi.waitFor(() => expect(got).toHaveLength(expectCount)); else await new Promise((r) => setTimeout(r, 20)); } finally { off(); } return got; } describe("AnprBridge pass sample — every detected car, ticket or not", () => { const VEHICLE: VisionVehicle = { bodyType: "car", confidence: 0.91, bbox: { x1: 10, y1: 10, x2: 200, y2: 120 } }; const BOX = { x1: 0.1, y1: 0.1, x2: 0.5, y2: 0.6 }; it("stores the frame + emits a vehicle read with NO plate at all (barriers up: no ticket, no session)", async () => { normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null }); const cam = seedCamera({ anpr: true }); const bridge = new AnprBridge(db, fakeVision({ vehicle: VEHICLE }), fakeSubFlow(null), silentLogger()); const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 1); const read = got[0]!; expect(read).toMatchObject({ direction: "entry", deviceId: cam, read: { bodyType: "car", confidence: 0.91, box: BOX, plateBox: null } }); expect(read.identity).toBe(`pass:${read.read.snapshotId}`); const row = db.select().from(snapshots).where(eq(snapshots.id, read.read.snapshotId!)).get(); expect(row).toMatchObject({ direction: "entry", deviceId: cam, identity: read.identity, contentType: "image/jpeg" }); }); it("is ONE sample per car even when the loop polls several frames, and rides along a subscriber emit", async () => { normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: { x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 } }); const cam = seedCamera({ anpr: true }); const bridge = new AnprBridge(db, fakeVision({ plate: "AA111BB", confidence: 0.97, vehicle: VEHICLE }), fakeSubFlow(SUB_MATCH), silentLogger()); let reads: DeviceReadEvent[] = []; const got = await captureVehicleReads(async () => { reads = await captureReads(() => bridge.onVehicleDetected(cam)); }, 1); expect(reads).toHaveLength(1); // the subscriber's plate read still goes out expect(got[0]!.read.plateBox).toEqual({ x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 }); // for the crop's blur expect(db.select().from(snapshots).all()).toHaveLength(1); }); it("samples EACH plated car of a loop once — two cars back to back → two samples", async () => { normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null }); const cam = seedCamera({ anpr: true }); // Car A (3 frames) then car B, both framed; a non-subscriber lot (match null) — the // sample is about the reviewer's stream, not about admission. const vision = sequenceVision( [{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 }, { plate: "CC333DD", confidence: 0.96 }], VEHICLE, ); process.env.ANPR_POLL_WINDOW_MS = "200"; const bridge = new AnprBridge(db, vision, fakeSubFlow(null), silentLogger()); const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 2); expect(got).toHaveLength(2); expect(db.select().from(snapshots).all()).toHaveLength(2); }); it("records nothing without a vehicle box (nothing to crop) — a bare class is not a sample", async () => { const cam = seedCamera({ anpr: true }); const bridge = new AnprBridge(db, fakeVision({ vehicle: { bodyType: "car", confidence: 0.9 } }), fakeSubFlow(null), silentLogger()); const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 0); expect(got).toEqual([]); expect(db.select().from(snapshots).all()).toHaveLength(0); }); }); describe("AnprBridge", () => { it("does nothing for an opt-OUT camera (no anpr flag) — no analyze, no read", async () => { const cam = seedCamera({ anpr: false }); const vision = fakeVision({ plate: "AA111BB" }); const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toEqual([]); expect(vision.analyze).not.toHaveBeenCalled(); expect(captureSnapshot).not.toHaveBeenCalled(); }); it("does NOT auto-trigger when anprAutoTrigger=false (recognition on, auto-open off)", async () => { // Shared entry/exit lane: the exit cam keeps anpr (recognition) but auto-trigger off, so a // car driving IN isn't phantom-EXITed by its back plate. The bridge bails before snapshot. const cam = seedCamera({ anpr: true, anprAutoTrigger: false }); const vision = fakeVision({ plate: "AA111BB", confidence: 0.99 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toEqual([]); expect(captureSnapshot).not.toHaveBeenCalled(); // gated before the poll loop }); it("emits a plate read (upper-cased) for a high-confidence SUBSCRIBER plate", async () => { const cam = seedCamera({ anpr: true }); const vision = fakeVision({ plate: " aa111bb ", confidence: 0.97 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toHaveLength(1); expect(reads[0]).toMatchObject({ deviceId: cam, value: "AA111BB", kind: "plate", driverId: "hikvision" }); }); it("ignores a plate below the entry confidence floor", async () => { const cam = seedCamera({ anpr: true }); const vision = fakeVision({ plate: "AA111BB", confidence: 0.6 }); // < default 0.85 const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toEqual([]); }); it("POLLS until confident: low-confidence approach frames, then a clean stop-at-barrier frame", async () => { // The car APPROACHES (garbage reads) then STOPS at the barrier (clean read) — the bridge // must re-pull until one frame clears the floor, not give up on the first bad frame. const cam = seedCamera({ anpr: true }); // analyze escalates: 0.20, 0.20, then 0.97 on the 3rd pull → that one emits. const confs = [0.2, 0.2, 0.97]; let i = 0; const vision = { enabled: true, analyze: vi.fn(async () => ({ plate: { text: "AA111BB", confidence: confs[Math.min(i++, confs.length - 1)] }, plates: [], lowConfidence: false, vehicle: null, modelVersion: "test", tookMs: 1, })), } as unknown as VisionClient; // Generous window so all 3 escalation attempts run deterministically under suite load // (the global beforeEach sets a tiny 5ms window for the give-up cases). The loop keeps // reading until the window ends — the same plate must still be emitted exactly once. process.env.ANPR_POLL_MS = "1"; process.env.ANPR_POLL_WINDOW_MS = "150"; const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toHaveLength(1); expect(reads[0]).toMatchObject({ value: "AA111BB", kind: "plate" }); expect(captureSnapshot.mock.calls.length).toBeGreaterThanOrEqual(3); // re-pulled fresh frames }); it("SLIDES the window: a push mid-poll keeps the loop alive past the initial deadline", async () => { // A loop started by an early/far car would expire — but a NEW push (another car arriving) // extends the deadline, so the loop keeps polling and reads the car that settles at the // barrier. Here: a SHORT base window, vision stays low until attempt 5; a second push at // the start bumps the deadline so attempt 5's confident read still lands. const cam = seedCamera({ anpr: true }); const confs = [0.2, 0.2, 0.2, 0.2, 0.97]; let i = 0; const vision = { enabled: true, analyze: vi.fn(async () => ({ plate: { text: "AA111BB", confidence: confs[Math.min(i++, confs.length - 1)] }, plates: [], lowConfidence: false, vehicle: null, modelVersion: "test", tookMs: 1, })), } as unknown as VisionClient; process.env.ANPR_POLL_MS = "5"; process.env.ANPR_POLL_WINDOW_MS = "12"; // tiny — would expire ~attempt 2 WITHOUT a slide process.env.ANPR_POLL_MAX_MS = "5000"; // ceiling far above, so the slide is what matters const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(async () => { const loop = bridge.onVehicleDetected(cam); // starts the loop // Joining pushes keep sliding the deadline forward so the slow-to-confident read lands. for (let k = 0; k < 5; k++) { await new Promise((r) => setTimeout(r, 5)); void bridge.onVehicleDetected(cam); // each bumps the deadline (loop already running) } await loop; }); expect(reads).toHaveLength(1); expect(reads[0]).toMatchObject({ value: "AA111BB" }); }); it("does NOT emit if the subscriber transacts by another credential mid-poll (no double-act)", async () => { // The car's plate is read (identity known) while still below the floor; meanwhile the // subscriber scans their card → openOccurrenceCount drops. When the plate finally reads // confidently the bridge must NOT emit (it would exit the NEXT open occurrence — a // phantom double-exit, esp. fleet). const cam = seedCamera({ anpr: true }); const vision = sequenceVision([{ plate: "AA111BB", confidence: 0.5 }, { plate: "AA111BB", confidence: 0.97 }]); // openOccurrenceCount: 1 at first sighting, then 0 (the card exit closed it) at settle time. const sub = fakeSubFlow(SUB_MATCH, [1, 0]); process.env.ANPR_POLL_WINDOW_MS = "200"; const bridge = new AnprBridge(db, vision, sub, silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toEqual([]); // declined — the credential already handled it expect(vision.analyze).toHaveBeenCalledTimes; // (the loop itself kept going) }); it("KEEPS READING after a confident plate: a second car in the same loop is emitted too", async () => { // Car A reads confidently on frames 1-3, then car B pulls into the zone (frames 4+). // Before 2026-10-11 the loop broke on A's first read and the camera-level debounce then // dropped every push for 12s — B was invisible. Now A is settled once and the loop goes // on; B is read by the same loop. Each plate exactly once, however many frames repeat. const cam = seedCamera({ anpr: true }); const vision = sequenceVision([ { plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 }, { plate: "CC333DD", confidence: 0.96 }, ]); const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null)); process.env.ANPR_POLL_WINDOW_MS = "200"; const bridge = new AnprBridge(db, vision, sub, silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]); expect(captureSnapshot.mock.calls.length).toBeGreaterThan(4); // it did not stop at A }); it("does NOT emit for a plate matching no subscription — records an advisory anpr-skip", async () => { const cam = seedCamera({ anpr: true }); const vision = fakeVision({ plate: "ZZ999ZZ", confidence: 0.97 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(null), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toEqual([]); const skips = db.select().from(deviceEventsTable).where(eq(deviceEventsTable.kind, "anpr-skip")).all(); expect(skips).toHaveLength(1); expect((skips[0].detail as { plate?: string }).plate).toBe("ZZ999ZZ"); }); it("analyzes AT LEAST ONE frame even if the poll window already elapsed (loaded host)", async () => { // Regression for a CI flake (2026-07-04): with a plain `while`, a window that lapsed // between deadline-set and loop-entry (slow runner; here forced with a 0ms window) // meant ZERO analyze attempts — the detection was silently dropped ("gave up") and no // skip was recorded. The do-while guarantees one frame per detection regardless of load. process.env.ANPR_POLL_WINDOW_MS = "0"; const cam = seedCamera({ anpr: true }); const vision = fakeVision({ plate: "ZZ999ZZ", confidence: 0.97 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(null), silentLogger()); await captureReads(() => bridge.onVehicleDetected(cam)); expect(captureSnapshot).toHaveBeenCalledTimes(1); // the guaranteed first attempt const skips = db.select().from(deviceEventsTable).where(eq(deviceEventsTable.kind, "anpr-skip")).all(); expect(skips).toHaveLength(1); }); it("debounces PER PLATE: the same car re-detected within the window is emitted once", async () => { const cam = seedCamera({ anpr: true }); const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(async () => { await bridge.onVehicleDetected(cam); await bridge.onVehicleDetected(cam); // a second loop — the same plate within 12s → suppressed }); expect(reads).toHaveLength(1); expect(captureSnapshot.mock.calls.length).toBeGreaterThanOrEqual(2); // the 2nd loop DID look }); it("is NOT blind after a read: a different car detected right after is emitted", async () => { // The old camera-level debounce dropped every push for 12s after a success. A car behind // the first, arriving after the first loop ended, must get its own loop and its own read. const cam = seedCamera({ anpr: true }); const frames = [{ plate: "AA111BB", confidence: 0.97 }]; const vision = sequenceVision(frames); const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null)); const bridge = new AnprBridge(db, vision, sub, silentLogger()); const reads = await captureReads(async () => { await bridge.onVehicleDetected(cam); // car A frames[0] = { plate: "CC333DD", confidence: 0.96 }; // car B now in the zone await bridge.onVehicleDetected(cam); // its push starts a new loop }); expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]); }); it("is a no-op (no throw) when vision is disabled or reads nothing", async () => { const cam = seedCamera({ anpr: true }); const disabled = new AnprBridge(db, fakeVision({ enabled: false, plate: "AA111BB" }), fakeSubFlow(SUB_MATCH), silentLogger()); const noPlate = new AnprBridge(db, fakeVision({ plate: undefined }), fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(async () => { await disabled.onVehicleDetected(cam); await noPlate.onVehicleDetected(cam); }); expect(reads).toEqual([]); }); it("never throws on an unknown device id", async () => { const bridge = new AnprBridge(db, fakeVision({ plate: "AA111BB" }), fakeSubFlow(SUB_MATCH), silentLogger()); await expect(bridge.onVehicleDetected("nope")).resolves.toBeUndefined(); }); it("does NOTHING when the admin has disabled the bridge (site_config.anprEntryEnabled = false)", async () => { const cam = seedCamera({ anpr: true }); db.insert(siteConfig).values({ id: 1, anprEntryEnabled: false }).run(); const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toEqual([]); // The flag is checked FIRST — no snapshot, no analyze, no match attempt. expect(captureSnapshot).not.toHaveBeenCalled(); expect(vision.analyze).not.toHaveBeenCalled(); }); it("still emits when the bridge is explicitly enabled (anprEntryEnabled = true)", async () => { const cam = seedCamera({ anpr: true }); db.insert(siteConfig).values({ id: 1, anprEntryEnabled: true }).run(); const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 }); const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger()); const reads = await captureReads(() => bridge.onVehicleDetected(cam)); expect(reads).toHaveLength(1); }); });