feat(server): log every relay pulse and echo it to device_events (kind relay)
One pulse path, pulseBarrier (relay-pulse.ts), for all six callers: entry button/operator mint, reader and booth exits, subscription opens, manual (forgiven) exits and the setup relay test. Each pulse writes an info line naming relay, controller, direction, identity and operator, and inserts a device_events row of kind "relay" for success and failure alike; failures are still re-thrown so each flow keeps its own anomaly handling. Prompted by the 2026-10-09 park-2 "barrier opened by itself" claim: the ledger showed the why, but nothing recorded the moment a relay was actually driven. The signed ledger stays the authority; this is unsigned telemetry. Also git-ignores tmp/ (site snapshots pulled for incident review).
This commit is contained in:
@@ -33,3 +33,6 @@ questions.txt
|
||||
task_plan.md
|
||||
findings.md
|
||||
progress.md
|
||||
|
||||
# local scratch (site snapshots pulled for incident review, never committed)
|
||||
tmp/
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "@parking/devices";
|
||||
import { DEFAULT_VEHICLE_CATEGORY, reasonPayload } from "@parking/shared";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { pulseBarrier } from "./relay-pulse.js";
|
||||
import type { DeviceInputEvent, LaneStatusEvent } from "./device-events.js";
|
||||
import { getOccupancy } from "./occupancy.js";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
@@ -386,7 +387,12 @@ export class EntryFlow {
|
||||
const access = this.#buildAccess(resolved.controller);
|
||||
let opened = false;
|
||||
if (access) {
|
||||
await access.pulseOpen(resolved.relay);
|
||||
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||
direction: "entry",
|
||||
identity: ticketId,
|
||||
source: opts.source,
|
||||
...(opts.operator ? { operator: opts.operator } : {}),
|
||||
});
|
||||
opened = true;
|
||||
} else this.#logger.warn(`entry signed for ${ticketId} but the entry relay won't build`);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db, type DeviceRow } from "@parking/db";
|
||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||
import { pulseBarrier } from "./relay-pulse.js";
|
||||
import { firstRelayByDirection, type ResolvedRelay } from "./device-resolve.js";
|
||||
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
||||
import { snapshotAsync } from "./snapshot.js";
|
||||
@@ -210,7 +211,12 @@ export class ExitFlow {
|
||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
||||
}
|
||||
try {
|
||||
await access.pulseOpen(resolved.relay);
|
||||
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||
direction: "exit",
|
||||
identity: id,
|
||||
source: "booth",
|
||||
...(opts?.operator ? { operator: opts.operator } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
await this.#openFailedAnomaly(id, `pulseOpen failed: ${(err as Error).message}`);
|
||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
||||
@@ -300,7 +306,7 @@ export class ExitFlow {
|
||||
this.#logger.info(`barrier re-open also closed open session ${id} (human-intervention exit)`);
|
||||
}
|
||||
|
||||
const r = await this.#pulseExit(resolved, `barrier re-open for ${id}`);
|
||||
const r = await this.#pulseExit(resolved, id, operator, `barrier re-open for ${id}`);
|
||||
if (r.opened) {
|
||||
if (forgiven) this.#logger.warn(`FORGIVEN exit barrier open for ${id} by ${operator ?? "?"}: ${forgiven.note}`);
|
||||
else this.#logger.info(`manual barrier open for ${id}${operator ? ` by ${operator}` : ""}`);
|
||||
@@ -337,7 +343,7 @@ export class ExitFlow {
|
||||
},
|
||||
});
|
||||
this.#fireExitSnapshot(ref);
|
||||
const r = await this.#pulseExit(resolved, `forgiven open (no session) ${ref}`);
|
||||
const r = await this.#pulseExit(resolved, ref, operator, `forgiven open (no session) ${ref}`);
|
||||
if (r.opened) this.#logger.warn(`FORGIVEN exit barrier open with no session by ${operator}: ${note}`);
|
||||
return r;
|
||||
} finally {
|
||||
@@ -347,7 +353,12 @@ export class ExitFlow {
|
||||
|
||||
/** Drive the exit relay for a human-intervention open; the exit/anomaly is already
|
||||
* signed, so every failure is `ok: true, opened: false` + the reason to open by hand. */
|
||||
async #pulseExit(resolved: ResolvedRelay | null, label: string): Promise<Extract<BoothReopenResult, { ok: true }>> {
|
||||
async #pulseExit(
|
||||
resolved: ResolvedRelay | null,
|
||||
identity: string,
|
||||
operator: string | undefined,
|
||||
label: string,
|
||||
): Promise<Extract<BoothReopenResult, { ok: true }>> {
|
||||
if (!resolved) {
|
||||
this.#logger.warn(`${label}: no exit relay configured`);
|
||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.noBarrier") };
|
||||
@@ -358,7 +369,12 @@ export class ExitFlow {
|
||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.unavailable") };
|
||||
}
|
||||
try {
|
||||
await access.pulseOpen(resolved.relay);
|
||||
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||
direction: "exit",
|
||||
identity,
|
||||
source: "booth",
|
||||
...(operator ? { operator } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
this.#logger.error(`${label}: pulseOpen failed: ${(err as Error).message}`);
|
||||
return { ok: true, opened: false, reason: renderReasonEn("exit.open.failed") };
|
||||
@@ -473,8 +489,13 @@ export class ExitFlow {
|
||||
await this.#signExit(e.value, e.kind === "plate" ? "lpr" : "ticket");
|
||||
|
||||
const access = this.#buildAccess(resolved.controller);
|
||||
if (access) await access.pulseOpen(resolved.relay);
|
||||
else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
||||
if (access) {
|
||||
await pulseBarrier(this.#db, this.#logger, access, resolved, {
|
||||
direction: "exit",
|
||||
identity: e.value,
|
||||
source: e.kind === "plate" ? "lpr" : "ticket",
|
||||
});
|
||||
} else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
||||
|
||||
this.#fireExitSnapshot(e.value);
|
||||
this.#closeSessionCache(e.value);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
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<string, unknown> }));
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { deviceEvents as deviceEventsTable, type Db, type DeviceRow } from "@parking/db";
|
||||
import type { AccessControlDevice } from "@parking/devices";
|
||||
import type { Direction } from "./device-resolve.js";
|
||||
|
||||
// The ONE place a barrier relay is pulsed from business logic. Every pulse is logged at
|
||||
// info (relay, controller, who asked and for which identity) and echoed into the UNSIGNED
|
||||
// device_events stream (kind "relay") whether it succeeded or failed — so "did the server
|
||||
// open the barrier at 15:50?" is answerable from `docker logs` or the telemetry table
|
||||
// without reading the ledger. The signed ledger stays the authority on WHY (the
|
||||
// vehicle_entry/exit/anomaly is appended BEFORE the pulse); this is the device-side echo
|
||||
// (wiki/concepts/device-events.md). Failures are recorded, then re-thrown so each flow keeps
|
||||
// its own anomaly/result handling. park-2 2026-10-09: a "barrier opened by itself" claim
|
||||
// took ledger + snapshots to settle because pulses were only logged when they failed.
|
||||
|
||||
export interface PulseContext {
|
||||
/** The barrier's direction (the relay's configured event). */
|
||||
readonly direction: Direction;
|
||||
/** The session/ticket/card/ref the open is for (matches the signed event's identity). */
|
||||
readonly identity: string;
|
||||
/** Who asked: ticket | manual | booth | lpr | subscription | relay-test … (free-form). */
|
||||
readonly source: string;
|
||||
readonly operator?: string;
|
||||
}
|
||||
|
||||
export async function pulseBarrier(
|
||||
db: Db,
|
||||
logger: FastifyBaseLogger,
|
||||
access: Pick<AccessControlDevice, "pulseOpen">,
|
||||
target: { readonly controller: DeviceRow; readonly relay: number },
|
||||
ctx: PulseContext,
|
||||
): Promise<void> {
|
||||
const { controller, relay } = target;
|
||||
const who = ctx.operator ? ` by ${ctx.operator}` : "";
|
||||
logger.info(
|
||||
`relay pulse: ${ctx.direction} relay ${relay} on ${controller.driverId} ${controller.id} ← ${ctx.source} ${ctx.identity}${who}`,
|
||||
);
|
||||
const startedAt = Date.now();
|
||||
const firedAt = new Date(startedAt).toISOString();
|
||||
try {
|
||||
await access.pulseOpen(relay);
|
||||
record(db, logger, controller, relay, ctx, firedAt, { ok: true, tookMs: Date.now() - startedAt });
|
||||
} catch (err) {
|
||||
const error = (err as Error).message;
|
||||
logger.error(`relay pulse FAILED: ${ctx.direction} relay ${relay} on ${controller.id} for ${ctx.identity}: ${error}`);
|
||||
record(db, logger, controller, relay, ctx, firedAt, { ok: false, error, tookMs: Date.now() - startedAt });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function record(
|
||||
db: Db,
|
||||
logger: FastifyBaseLogger,
|
||||
controller: DeviceRow,
|
||||
relay: number,
|
||||
ctx: PulseContext,
|
||||
firedAt: string,
|
||||
outcome: { ok: boolean; error?: string; tookMs: number },
|
||||
): void {
|
||||
// Telemetry must never block or fail the open — swallow insert errors (logged).
|
||||
try {
|
||||
db.insert(deviceEventsTable)
|
||||
.values({
|
||||
id: randomUUID(),
|
||||
deviceId: controller.id,
|
||||
category: "access",
|
||||
kind: "relay",
|
||||
detail: {
|
||||
driverId: controller.driverId,
|
||||
relay,
|
||||
direction: ctx.direction,
|
||||
identity: ctx.identity,
|
||||
source: ctx.source,
|
||||
...(ctx.operator ? { operator: ctx.operator } : {}),
|
||||
...outcome,
|
||||
},
|
||||
occurredAt: firedAt,
|
||||
})
|
||||
.run();
|
||||
} catch (err) {
|
||||
logger.error(`relay pulse telemetry insert failed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, devices, setupState, type Db } from "@parking/db";
|
||||
import { pulseBarrier } from "../relay-pulse.js";
|
||||
import {
|
||||
hasPreconditions,
|
||||
hasPushConfig,
|
||||
@@ -507,7 +508,7 @@ export async function setupRoutes(
|
||||
return reply.code(400).send({ error: `device ${id} is not a controller` });
|
||||
}
|
||||
const cfg = (row.config ?? {}) as Record<string, unknown>;
|
||||
const relays = Array.isArray(cfg.relays) ? (cfg.relays as { relay?: number }[]) : [];
|
||||
const relays = Array.isArray(cfg.relays) ? (cfg.relays as { relay?: number; direction?: string }[]) : [];
|
||||
if (!relays.some((r) => r.relay === relay)) {
|
||||
return reply.code(400).send({ error: `controller ${id} has no relay ${relay}` });
|
||||
}
|
||||
@@ -545,8 +546,14 @@ export async function setupRoutes(
|
||||
});
|
||||
|
||||
const startedAt = Date.now();
|
||||
const relayDir = relays.find((r) => r.relay === relay)?.direction;
|
||||
try {
|
||||
await device.pulseOpen(relay);
|
||||
await pulseBarrier(db, req.log, device, { controller: row, relay }, {
|
||||
direction: relayDir === "entry" || relayDir === "exit" ? relayDir : "both",
|
||||
identity: `relay-test:${id}:${relay}`,
|
||||
source: "relay-test",
|
||||
operator,
|
||||
});
|
||||
} catch (err) {
|
||||
// The failure we're testing for (relay unreachable, wrong password). The open is
|
||||
// already signed; report the pulse failure, don't 500.
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||
import { reasonPayload, type PlanTimeframes, type ReasonCode } from "@parking/shared";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { pulseBarrier } from "./relay-pulse.js";
|
||||
import { printWindowChargeNotice } from "./booth-print.js";
|
||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
@@ -410,8 +411,9 @@ export class SubscriptionFlow {
|
||||
|
||||
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
|
||||
const access = this.#buildAccess(resolved.controller);
|
||||
if (access) await access.pulseOpen(resolved.relay);
|
||||
else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
||||
if (access) {
|
||||
await pulseBarrier(this.#db, this.#logger, access, resolved, { direction: dir, identity: carKey, source: "subscription" });
|
||||
} else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
||||
|
||||
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
|
||||
this.#fireSnapshot(dir, carKey);
|
||||
|
||||
@@ -14,8 +14,14 @@ diagnostics, and live booth status — **not** anti-fraud.
|
||||
|
||||
## What lands here
|
||||
|
||||
- **Relays/barriers:** relay fired/released, pulseOpen issued (the *device-side* echo; the
|
||||
authoritative `barrier_open_command` is a signed ledger event).
|
||||
- **Relays/barriers:** every `pulseOpen` issued from business logic — kind `relay`, detail
|
||||
`{driverId, relay, direction, identity, source, operator?, ok, error?, tookMs}` — success **and**
|
||||
failure, written by `apps/server/src/relay-pulse.ts` (`pulseBarrier`, the ONE pulse path: entry
|
||||
button/operator mint, reader + booth exits, subscription opens, manual exits, the setup relay
|
||||
test). Also an info log line `relay pulse: exit relay 2 on dingtian <id> ← booth <identity> by
|
||||
<operator>`. The *device-side* echo; the authoritative record of WHY is the signed ledger event
|
||||
appended before the pulse. Built 2026-10-09 after a park-2 "barrier opened by itself" claim took
|
||||
ledger + snapshots to settle because pulses were only logged when they *failed*.
|
||||
- **Printers:** paper-out / near-end / cover-open / cutter / offline (already polled —
|
||||
[[printer-status-monitoring]]).
|
||||
- **Cameras:** reachable/offline, snapshot success/failure ([[lpr-camera]]).
|
||||
|
||||
Reference in New Issue
Block a user