73ada89a13
Build & push images / images (push) Successful in 3m45s
park-2 (2026-10-24): GET /api/sessions/active ran ~2 s synchronously — PayStation.activeSessions called quote() per open unpaid transient (664 rows), each 3-4 unindexed ledger_events scans by identity — 2234x/day. The frozen event loop made the Dingtian driver's 2 s timer fire before the already-received UDP reply (timers run before poll I/O), so healthy pulses logged "timeout"; the subscription flow then unwound before firing the camera or writing the sessions row, leaving signed entries with no snapshot. Cost grew ~120 ms/day with the operator's open-ticket count. - pay-station: price every list row from the one ledger scan (rows grouped per identity -> #quoteFromRows); tariff resolver built once per request; quote(identity) wraps the same core. validations: sessionValidationsFromRows / liveValidationsFromRows. Test pins list == quote(). - db 0032_hot_path_indexes: ledger_events(identity,index), device_events(category,kind, occurred_at), device_events(kind,occurred_at), snapshots(identity), sessions(state), sessions(subscription_id,state). Additive. - access-dingtian binaryUdp: defer the timeout rejection with setImmediate so a datagram that already arrived wins over an expired timer. - subscription-flow: snapshot fired and session cache written/closed BEFORE the pulse. wiki/concepts/park-2-event-loop-stall.md has the full analysis.
177 lines
7.5 KiB
TypeScript
177 lines
7.5 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
import { createTestDb } from "@parking/db/testing";
|
|
import { ledgerEvents, eq, type Db } from "@parking/db";
|
|
import { PayStation, NoOpenSessionError, NoTariffError } from "./pay-station.js";
|
|
import type { EventLog } from "./event-log.js";
|
|
import { makeLog, silentLogger, seedTariff, minutesAgo } from "./test-helpers.js";
|
|
|
|
// The pay station prices an open session against the tariff frozen at entry and writes
|
|
// a SIGNED payment event (never a mutable "paid" flag). These tests pin the quote math,
|
|
// the signed-payment side effect, the no-session / no-tariff errors, and the lookup
|
|
// view the booth modal reads.
|
|
|
|
let db: Db;
|
|
let close: () => void;
|
|
let log: EventLog;
|
|
let pay: PayStation;
|
|
|
|
beforeEach(() => {
|
|
const t = createTestDb();
|
|
db = t.db;
|
|
close = t.close;
|
|
log = makeLog(db);
|
|
pay = new PayStation(db, log, silentLogger());
|
|
});
|
|
afterEach(() => close());
|
|
|
|
async function enter(identity: string, enteredAt: string, payload?: Record<string, unknown>) {
|
|
await log.append({ type: "vehicle_entry", direction: "entry", identity, occurredAt: enteredAt, payload: payload ?? null });
|
|
}
|
|
|
|
describe("PayStation.forgive (forgiven exit)", () => {
|
|
it("signs a $0 payment with the quoted fee as forgoneMinor and marks the session paid", async () => {
|
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
|
|
await enter("T1", minutesAgo(90));
|
|
const r = await pay.forgive("T1", { operator: "owner", note: "lost ticket, known customer" });
|
|
expect(r).toEqual({ ok: true, forgoneMinor: 20000, currency: expect.any(String) });
|
|
const ev = db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, "T1")).all().find((e) => e.type === "payment")!;
|
|
expect(ev.payload).toMatchObject({ amountMinor: 0, forgoneMinor: 20000, operator: "owner", reasonCode: "exit.forgiven" });
|
|
expect((ev.payload as { tender?: string }).tender).toBeUndefined(); // nothing was tendered
|
|
expect(pay.lookup("T1").paidAt).not.toBeNull();
|
|
});
|
|
|
|
it("throws like quote() for an unknown ticket", async () => {
|
|
seedTariff(db);
|
|
await expect(pay.forgive("nope", { operator: "owner", note: "x" })).rejects.toThrow(NoOpenSessionError);
|
|
});
|
|
});
|
|
|
|
describe("PayStation.quote", () => {
|
|
it("throws NoOpenSessionError for an unknown ticket", () => {
|
|
seedTariff(db);
|
|
expect(() => pay.quote("nope")).toThrow(NoOpenSessionError);
|
|
});
|
|
|
|
it("throws NoTariffError when no site tariff is configured", async () => {
|
|
await enter("T1", minutesAgo(120));
|
|
expect(() => pay.quote("T1")).toThrow(NoTariffError);
|
|
});
|
|
|
|
it("prices a stay against the frozen tariff (90min → 2 increments at 100/h = 200)", async () => {
|
|
// 90 min rounds UP to a 2nd 60-min increment; well clear of the boundary so a few
|
|
// ms of test runtime can't tip it into a 3rd increment.
|
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60 });
|
|
await enter("T1", minutesAgo(90));
|
|
const q = pay.quote("T1");
|
|
expect(q.amountMinor).toBe(20000);
|
|
expect(q.currency).toBe("ALL");
|
|
expect(q.overstay).toBe(false);
|
|
});
|
|
|
|
it("prices 0 within the entry grace (quick in-and-out)", async () => {
|
|
seedTariff(db, { gracePeriodEntryMin: 10 });
|
|
await enter("T1", minutesAgo(5));
|
|
expect(pay.quote("T1").amountMinor).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("PayStation.pay — signed payment side effect", () => {
|
|
it("appends a signed payment event carrying amount, currency, tender, grace", async () => {
|
|
const { currency } = seedTariff(db, { pricePerIncrementMinor: 10000, gracePeriodExitMin: 15 });
|
|
await enter("T1", minutesAgo(90));
|
|
|
|
const res = await pay.pay("T1", "cash");
|
|
expect(res.amountMinor).toBe(20000);
|
|
expect(res.currency).toBe(currency);
|
|
|
|
const payments = db.select().from(ledgerEvents).where(eq(ledgerEvents.type, "payment")).all();
|
|
expect(payments).toHaveLength(1);
|
|
const pl = payments[0].payload as Record<string, unknown>;
|
|
expect(pl.amountMinor).toBe(20000);
|
|
expect(pl.tender).toBe("cash");
|
|
expect(pl.graceExitMin).toBe(15);
|
|
// It must be a real signed chain event.
|
|
expect(log.verifyChain()).toEqual({ ok: true });
|
|
});
|
|
|
|
it("honours an operator override amount (lost ticket / dispute)", async () => {
|
|
seedTariff(db);
|
|
await enter("T1", minutesAgo(120));
|
|
const res = await pay.pay("T1", "card", 99900);
|
|
expect(res.amountMinor).toBe(99900);
|
|
const pl = db.select().from(ledgerEvents).where(eq(ledgerEvents.type, "payment")).all()[0].payload as Record<string, unknown>;
|
|
expect(pl.amountMinor).toBe(99900);
|
|
expect(pl.reason).toBe("operator-set amount");
|
|
});
|
|
});
|
|
|
|
describe("PayStation.lookup — booth modal view", () => {
|
|
it("reports not-found for an unknown ticket", () => {
|
|
const v = pay.lookup("ghost");
|
|
expect(v.found).toBe(false);
|
|
expect(v.open).toBe(false);
|
|
});
|
|
|
|
it("shows an open unpaid transient with the amount owed", async () => {
|
|
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
|
await enter("T1", minutesAgo(90));
|
|
const v = pay.lookup("T1");
|
|
expect(v.found).toBe(true);
|
|
expect(v.open).toBe(true);
|
|
expect(v.paidAt).toBeNull();
|
|
expect(v.amountMinor).toBe(20000);
|
|
expect(v.subscription).toBe(false);
|
|
});
|
|
|
|
it("after payment shows paid + within grace, amount cleared", async () => {
|
|
seedTariff(db, { pricePerIncrementMinor: 10000, gracePeriodExitMin: 15 });
|
|
await enter("T1", minutesAgo(120));
|
|
await pay.pay("T1", "cash");
|
|
const v = pay.lookup("T1");
|
|
expect(v.paidAt).not.toBeNull();
|
|
expect(v.withinGrace).toBe(true);
|
|
expect(v.overstay).toBe(false);
|
|
});
|
|
|
|
it("flags a subscription occurrence (prepaid — never a transient charge)", async () => {
|
|
seedTariff(db);
|
|
await enter("SUBSESS-1", minutesAgo(120), { permit: true, permitId: "sub-1" });
|
|
const v = pay.lookup("SUBSESS-1");
|
|
expect(v.subscription).toBe(true);
|
|
expect(v.subscriptionId).toBe("sub-1");
|
|
expect(v.amountMinor).toBeNull(); // no timeframes → nothing owed
|
|
});
|
|
});
|
|
|
|
describe("PayStation.activeSessions", () => {
|
|
it("lists open sessions newest-first and omits exited-past-grace", async () => {
|
|
seedTariff(db, { pricePerIncrementMinor: 10000 });
|
|
await enter("OLD", minutesAgo(200));
|
|
await enter("NEW", minutesAgo(30));
|
|
const list = pay.activeSessions();
|
|
expect(list.map((s) => s.identity)).toEqual(["NEW", "OLD"]);
|
|
expect(list.every((s) => s.open)).toBe(true);
|
|
});
|
|
|
|
// The list prices each open transient from ONE whole-ledger scan (no per-row ledger
|
|
// reads — those froze park-2's server, 2026-10-24). The amounts must match the
|
|
// single-session quote() exactly, including after a payment (overstay repricing) and
|
|
// for a subscription (never quoted).
|
|
it("prices every row identically to quote() without per-session ledger reads", async () => {
|
|
seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 });
|
|
await enter("UNPAID", minutesAgo(150));
|
|
await enter("PAID", minutesAgo(300));
|
|
await pay.pay("PAID", "cash"); // grace 0 → paid-but-open ⇒ overstay, re-priced from now
|
|
await enter("SUB", minutesAgo(10), { permit: true, permitId: "sub-1" });
|
|
|
|
const list = pay.activeSessions();
|
|
const by = new Map(list.map((s) => [s.identity, s]));
|
|
expect(by.get("UNPAID")!.amountMinor).toBe(pay.quote("UNPAID").amountMinor);
|
|
expect(by.get("UNPAID")!.currency).toBe(pay.quote("UNPAID").currency);
|
|
expect(by.get("PAID")!.overstay).toBe(true);
|
|
expect(by.get("PAID")!.amountMinor).toBe(pay.quote("PAID").amountMinor);
|
|
expect(by.get("SUB")!.subscription).toBe(true);
|
|
expect(by.get("SUB")!.amountMinor).toBeNull();
|
|
});
|
|
});
|