feat(review): sample every detected car, not only ticketed entries
Build & push images / images (push) Successful in 5m20s

The entry stream for the reviewer was fed from the session-tied read only (ticket
printed / exit signed). park-2 ran an afternoon with its barriers up: hundreds of
camera vehicle pushes, zero tickets, zero samples.

- anpr-entry: keep the best-framed vehicle of each poll loop (highest body-type
  confidence with a box), store that frame as a snapshot (identity pass:<id>, no
  session) and emit a vehicle read with the camera id — plate or no plate. One
  sample per detection, fire-and-forget, never on the ANPR path.
- snapshot.ts: normalizedBoxes() shared by the session-tied read and the bridge;
  vehicle reads now carry deviceId.
- review-outbox: sampleEntry(deviceId) dedups per camera for 30 s so the pass
  sample and a ticket entry's read (same car, seconds apart) go once.
- wiki: outbox page (entry stream, troubleshooting checklist for 'nothing arrives':
  the month-long silence was a missing Netbird policy, not code), park-2 camera
  port-forward procedure (site-device-installation §7), log.
This commit is contained in:
2026-10-08 19:30:03 +02:00
parent 354de04a3d
commit 30a1180108
10 changed files with 288 additions and 28 deletions
+76 -9
View File
@@ -1,10 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db } from "@parking/db";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
import { deviceEvents, type DeviceReadEvent, type VehicleReadEvent } from "./device-events.js";
import { silentLogger } from "./test-helpers.js";
import type { VisionClient, VisionResult } from "./vision-client.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
@@ -14,7 +14,12 @@ import type { SubscriptionFlow, SubscriptionMatch } from "./subscription-flow.js
// 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" }));
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.
@@ -22,6 +27,9 @@ 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.
@@ -31,6 +39,8 @@ 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;
// Poll-until-confident loop: keep the window + interval tiny so a below-floor / no-plate
@@ -74,17 +84,18 @@ function seedCamera(opts: { anpr?: boolean; anprAutoTrigger?: boolean } = {}): s
return camId;
}
/** A fake VisionClient: enabled, returning a chosen plate/confidence (or null). */
function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: number } = {}): VisionClient {
/** 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.plate == null && opts.vehicle == null
? null
: {
plate: { text: opts.plate, confidence: opts.confidence ?? 0.99 },
plate: opts.plate == null ? null : { text: opts.plate, confidence: opts.confidence ?? 0.99 },
plates: [],
lowConfidence: false,
vehicle: null,
vehicle: opts.vehicle ?? null,
modelVersion: "test",
tookMs: 1,
};
@@ -122,6 +133,62 @@ async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]>
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<void>, expectCount: number): Promise<VehicleReadEvent[]> {
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 detection 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("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 });
+43 -3
View File
@@ -1,11 +1,12 @@
import { randomUUID } from "node:crypto";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, type Db, type DeviceRow } from "@parking/db";
import { devices, deviceEvents as deviceEventsTable, eq, siteConfig, snapshots, type Db, type DeviceRow } from "@parking/db";
import type { Snapshot } from "@parking/devices";
import type { FastifyBaseLogger } from "fastify";
import { deviceEvents, type DeviceReadEvent } from "./device-events.js";
import { directionOf, type FlowDirection } from "./device-resolve.js";
import { buildCamera } from "./snapshot.js";
import { buildCamera, encodeForStorage, normalizedBoxes } from "./snapshot.js";
import type { SubscriptionFlow } from "./subscription-flow.js";
import type { VisionClient } from "./vision-client.js";
import type { VisionClient, VisionResult } from "./vision-client.js";
// The ANPR "bridge": a subscriber's plate, read from the lane camera, admits them through
// the SAME gated SubscriptionFlow a QR/card scan uses. It is the one missing wire between
@@ -191,6 +192,9 @@ export class AnprBridge {
// pushes) is read from #pollDeadline each tick but never allowed past this cap.
const hardCap = Date.now() + this.#pollMaxMs;
let attempts = 0;
// The best-framed vehicle of this loop (highest body-type confidence with a box):
// recorded once per detection as a PASS sample, whatever happens to the plate.
let best: { shot: Snapshot; r: VisionResult } | null = null;
try {
// DO-while: a detection always analyzes AT LEAST ONE frame, however loaded the
// host — a plain while could zero-iterate if the window elapsed between setting
@@ -201,6 +205,7 @@ export class AnprBridge {
attempts++;
const shot = await camera.captureSnapshot({ direction });
const r = await this.#vision.analyze(shot.bytes, shot.contentType);
if (r?.vehicle?.bbox && (!best || r.vehicle.confidence > best.r.vehicle!.confidence)) best = { shot, r };
// Identify the subscriber from ANY readable plate (even below the barrier floor),
// and baseline their open count once — so we can detect a credential beating us.
@@ -238,6 +243,7 @@ export class AnprBridge {
} finally {
this.#polling.delete(deviceId);
this.#pollDeadline.delete(deviceId);
if (best) void this.#recordPass(deviceId, direction, best);
}
if (!result || !result.plate) {
@@ -302,6 +308,40 @@ export class AnprBridge {
this.#lastFire.set(key, Date.now());
}
/** EVERY car the camera flagged becomes one stored frame + one vehicle read on the bus —
* plate or no plate, ticket or no ticket. The read is what the Car Wash module samples
* for the reviewer (wiki/concepts/vision-review-outbox.md §entry stream); until this,
* only session-tied reads were sampled, so a lot with its barriers up (nobody takes a
* ticket) sent nothing however many cars the camera saw. One sample per poll loop, i.e.
* per detection, from its best-framed vehicle. Fire-and-forget: never on the ANPR path,
* a failure is a log line. Identity `pass:<snapshotId>` — no session to tie it to. */
async #recordPass(deviceId: string, direction: FlowDirection, best: { shot: Snapshot; r: VisionResult }): Promise<void> {
try {
const vehicle = best.r.vehicle;
if (!vehicle) return;
const { vehicleBox, plateBox } = await normalizedBoxes(best.shot.bytes, best.r);
if (!vehicleBox) return;
const stored = await encodeForStorage(best.shot, this.#logger);
const id = randomUUID();
const identity = `pass:${id}`;
this.#db
.insert(snapshots)
.values({ id, direction, deviceId, identity, contentType: stored.contentType, bytes: stored.bytes, capturedAt: best.shot.capturedAt })
.run();
// plateBox whenever the detector saw a plate, confident or not: it is what the
// review crop blurs — privacy, not identity.
deviceEvents.emitVehicleRead({
identity,
direction,
deviceId,
read: { bodyType: vehicle.bodyType, confidence: vehicle.confidence, snapshotId: id, box: vehicleBox, plateBox },
});
this.#logger.debug(`anpr-bridge: pass sample ${id} '${vehicle.bodyType}' (${vehicle.confidence.toFixed(3)}) from ${deviceId}`);
} catch (err) {
this.#logger.warn(`anpr-bridge: pass sample failed for ${deviceId}: ${(err as Error).message}`);
}
}
/** Advisory telemetry: a plate was read at the lane but matched no subscription. Not a
* read on the bus — just a breadcrumb so the operator can see ANPR is working. */
#recordSkip(deviceId: string, plate: string, confidence: number): void {
+3
View File
@@ -114,6 +114,9 @@ export interface PlateRecognizedEvent {
export interface VehicleReadEvent {
readonly identity: string;
readonly direction: "entry" | "exit";
/** The camera that took the frame, so a listener can tell "same car, two reads seconds
* apart" (the bridge's pass sample + the ticket entry's read) from two cars. */
readonly deviceId?: string;
readonly read: VehicleRead;
}
+1 -1
View File
@@ -23,7 +23,7 @@ export const carwashModule: ServerModule = {
// training material (the gate view, no order attached). The core announces the read;
// the module decides. Off unless CARWASH_REVIEW_ENTRY_SAMPLE is set.
const offVehicleRead = deviceEvents.onVehicleRead((e) => {
if (e.direction === "entry" && outbox.sampleEntry()) void outbox.enqueueEntry(e.read);
if (e.direction === "entry" && outbox.sampleEntry(e.deviceId)) void outbox.enqueueEntry(e.read);
});
app.addHook("onClose", async () => offVehicleRead());
app.addHook("onClose", async () => outbox.stop());
@@ -6,7 +6,7 @@ import type { FastifyInstance } from "fastify";
import { deviceEvents as deviceEventBus } from "../../device-events.js";
import { buildServer } from "../../server.js";
import { login, makeLog, minutesAgo, seedTariff, seedUser, silentLogger } from "../../test-helpers.js";
import { EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
import { ENTRY_DEDUP_MS, EXPIRE_DAYS, ReviewOutbox, makeReviewCrop, operatorRef, reviewUploadConfigFromEnv } from "./review-outbox.js";
// The review outbox, booth side (wiki/concepts/vision-review-outbox.md): a plate-blurred
// vehicle crop + the operator's choice, queued off the intake path, drained one-way with
@@ -165,6 +165,20 @@ describe("queue + drain", () => {
const sampler = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 3 }, fetchFn);
expect([sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry(), sampler.sampleEntry()]).toEqual([false, false, true, false]);
expect(ob.sampleEntry()).toBe(false); // entrySample 0 = off
// Per-camera dedup: the bridge's pass sample and the ticket entry's read, seconds
// apart from the same camera, are ONE car — the second is skipped and not counted.
vi.useFakeTimers();
try {
const every = new ReviewOutbox(db, silentLogger(), { ...cfg, entrySample: 1 }, fetchFn);
expect(every.sampleEntry("cam-a")).toBe(true);
expect(every.sampleEntry("cam-a")).toBe(false);
expect(every.sampleEntry("cam-b")).toBe(true); // another camera = another car
vi.advanceTimersByTime(ENTRY_DEDUP_MS + 1);
expect(every.sampleEntry("cam-a")).toBe(true);
expect(every.sampleEntry()).toBe(true); // camera unknown → no dedup
} finally {
vi.useRealTimers();
}
expect(await sampler.enqueueEntry(read)).toBe(true);
const entryRow = db.select().from(carwashReviewOutbox).where(eq(carwashReviewOutbox.orderId, "entry:snap-1")).get()!;
expect(entryRow.payload).toMatchObject({ v: 1, kind: "entry", booth: "booth-7", vision: { class: "car", confidence: 0.86 }, image: { plateBlurred: true } });
@@ -63,6 +63,9 @@ const CROP_MARGIN = 0.08;
/** Items older than this are abandoned (failed "expired") — a booth cut off for two weeks
* should not resurface a fortnight of crops in one burst. */
export const EXPIRE_DAYS = 14;
/** Two entry reads from the same camera closer than this are one car (the ANPR bridge's
* per-detection pass sample, then the ticket entry's session-tied read ~seconds later). */
export const ENTRY_DEDUP_MS = 30_000;
/** Backoff: 1 min · 2^attempts, capped. */
const BACKOFF_BASE_MS = 60_000;
const BACKOFF_CAP_MS = 6 * 60 * 60 * 1000;
@@ -166,6 +169,9 @@ export class ReviewOutbox {
#timer: NodeJS.Timeout | null = null;
#draining = false;
#entrySeen = 0;
/** Last entry sample per camera: the bridge's pass sample and the ticket entry's read are
* the SAME car seconds apart — one goes, the other is skipped (and not counted). */
readonly #lastEntryByDevice = new Map<string, number>();
constructor(db: Db, logger: FastifyBaseLogger, cfg: ReviewUploadConfig | null, fetchFn?: FetchLike) {
this.#db = db;
@@ -202,9 +208,15 @@ export class ReviewOutbox {
/** Every Nth entry read is a sample (N = entrySample); the caller queues it. Counted
* in-process, so "1 in 5" is exactly that across a booth's day. */
sampleEntry(): boolean {
sampleEntry(deviceId?: string): boolean {
const n = this.#cfg?.entrySample ?? 0;
if (n <= 0) return false;
if (deviceId) {
const now = Date.now();
const last = this.#lastEntryByDevice.get(deviceId);
if (last != null && now - last < ENTRY_DEDUP_MS) return false;
this.#lastEntryByDevice.set(deviceId, now);
}
this.#entrySeen += 1;
return this.#entrySeen % n === 0;
}
+25 -12
View File
@@ -2,12 +2,12 @@ import { randomUUID } from "node:crypto";
import sharp from "sharp";
import { and, eq, gte, sessions, deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db";
import { registry, type CameraDevice, type Snapshot } from "@parking/devices";
import { reasonPayload } from "@parking/shared";
import { reasonPayload, type NormBox } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify";
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
import { deviceEvents } from "./device-events.js";
import type { EventLog } from "./event-log.js";
import type { VisionClient } from "./vision-client.js";
import type { VisionClient, VisionResult } from "./vision-client.js";
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
@@ -171,23 +171,16 @@ async function recognizePlate(
// Boxes are kept as FRACTIONS of the analysed frame (the stored snapshot is a
// downscaled copy — see reencodeForStorage), so the wash's review crop can cut the
// vehicle out of whatever copy survives and blur the plate inside it.
const frame = await frameSize(shot.bytes);
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined) =>
b && frame
? {
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
}
: null;
const boxes = await normalizedBoxes(shot.bytes, result);
// The vehicle's body type (advisory; the wash desk's category suggestion — see
// venue-modules.md §Vehicle category). Rides the plate's read row when there is one,
// else a row of its own: a car with an unreadable plate is still a car of some class.
const vehicleBox = norm(result.vehicle?.bbox);
const vehicleBox = boxes.vehicleBox;
const vehicle = result.vehicle
? { bodyType: result.vehicle.bodyType, bodyConfidence: result.vehicle.confidence, ...(vehicleBox ? { vehicleBox } : {}) }
: {};
const plate = !result.plate || result.lowConfidence ? "" : result.plate.text.trim().toUpperCase();
const plateBox = plate ? norm(result.plate?.bbox) : null;
const plateBox = plate ? boxes.plateBox : null;
if (!plate && !result.vehicle) return; // nothing trustworthy to record
db.insert(deviceEventsTable)
.values({
@@ -216,6 +209,7 @@ async function recognizePlate(
deviceEvents.emitVehicleRead({
identity,
direction,
deviceId,
read: { bodyType: result.vehicle.bodyType, confidence: result.vehicle.confidence, snapshotId, box: vehicleBox, plateBox },
});
}
@@ -241,6 +235,25 @@ function clamp01(v: number): number {
return Math.max(0, Math.min(1, v));
}
/** The vehicle's and the plate's boxes as FRACTIONS of the analysed frame (null when the
* stage found none or the frame size is unreadable). Fractions, so the box fits the
* downscaled stored copy the wash's review crop is cut from. Shared by the session-tied
* recognition above and the ANPR bridge's per-car pass sample (anpr-entry.ts). */
export async function normalizedBoxes(
bytes: Buffer,
result: VisionResult,
): Promise<{ vehicleBox: NormBox | null; plateBox: NormBox | null }> {
const frame = await frameSize(bytes);
const norm = (b: { x1: number; y1: number; x2: number; y2: number } | null | undefined): NormBox | null =>
b && frame
? {
x1: clamp01(b.x1 / frame.w), y1: clamp01(b.y1 / frame.h),
x2: clamp01(b.x2 / frame.w), y2: clamp01(b.y2 / frame.h),
}
: null;
return { vehicleBox: norm(result.vehicle?.bbox), plateBox: norm(result.plate?.bbox) };
}
/** Pixel size of the analysed frame (JPEG header only — cheap). Null when unreadable. */
async function frameSize(bytes: Buffer): Promise<{ w: number; h: number } | null> {
try {