import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createTestDb } from "@parking/db/testing"; import { devices, deviceEvents as deviceEventsTable, type Db, type DeviceRow } from "@parking/db"; import { pulseBarrier } from "./relay-pulse.js"; import type { FastifyBaseLogger } from "fastify"; const silentLogger = { info() {}, warn() {}, error() {}, debug() {} } as unknown as FastifyBaseLogger; // Every barrier pulse — success or failure — must leave an UNSIGNED device_events row // (kind "relay") naming the relay, the direction, the identity and who asked, so a // "did the server open the barrier?" question is answerable from telemetry alone // (park-2, 2026-10-09). A failure is recorded AND re-thrown (each flow keeps its own // anomaly handling). let db: Db; let close: () => void; let controller: DeviceRow; beforeEach(() => { const t = createTestDb(); db = t.db; close = t.close; db.insert(devices) .values({ id: "ctl-1", category: "access", driverId: "stub-access", config: { relays: [{ relay: 2, direction: "exit" }] }, enabled: true, }) .run(); controller = db.select().from(devices).get()!; }); afterEach(() => close()); function relayRows() { return db .select() .from(deviceEventsTable) .all() .filter((r) => r.kind === "relay") .map((r) => ({ deviceId: r.deviceId, category: r.category, detail: r.detail as Record })); } describe("pulseBarrier", () => { it("pulses the relay and records a successful relay event with the context", async () => { const fired: number[] = []; const access = { pulseOpen: async (door: number) => void fired.push(door) }; await pulseBarrier(db, silentLogger, access, { controller, relay: 2 }, { direction: "exit", identity: "forgiven:abc", source: "booth", operator: "admin", }); expect(fired).toEqual([2]); const rows = relayRows(); expect(rows).toHaveLength(1); expect(rows[0].deviceId).toBe("ctl-1"); expect(rows[0].category).toBe("access"); expect(rows[0].detail).toMatchObject({ driverId: "stub-access", relay: 2, direction: "exit", identity: "forgiven:abc", source: "booth", operator: "admin", ok: true, }); expect(typeof rows[0].detail.tookMs).toBe("number"); }); it("records a failed pulse with the error, then re-throws it", async () => { const access = { pulseOpen: async () => { throw new Error("timeout"); }, }; await expect( pulseBarrier(db, silentLogger, access, { controller, relay: 2 }, { direction: "exit", identity: "T1", source: "ticket" }), ).rejects.toThrow("timeout"); const rows = relayRows(); expect(rows).toHaveLength(1); expect(rows[0].detail).toMatchObject({ relay: 2, identity: "T1", source: "ticket", ok: false, error: "timeout" }); expect(rows[0].detail.operator).toBeUndefined(); }); });