fix(server): bound active-sessions cost, index hot paths, no phantom relay timeouts
Build & push images / images (push) Successful in 3m45s
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.
This commit is contained in:
@@ -4,7 +4,13 @@ import type { FastifyBaseLogger } from "fastify";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
import { plateForIdentity, platesForIdentities } from "./plate-lookup.js";
|
||||
import { windowOwedBetween } from "./subscription-window.js";
|
||||
import { liveValidations } from "./validations.js";
|
||||
import { liveValidationsFromRows } from "./validations.js";
|
||||
|
||||
/** A `ledger_events` row as the pricing fold reads it. */
|
||||
type LedgerRow = typeof ledgerEvents.$inferSelect;
|
||||
/** Resolves the tariff version in force at an instant. Built once per request so a list
|
||||
* view does not re-read the tariff tables for every row. */
|
||||
type TariffResolver = (at: string) => typeof tariffVersions.$inferSelect | null;
|
||||
|
||||
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
|
||||
// car (pay-on-foot — payment is decoupled from exit). Two steps:
|
||||
@@ -200,12 +206,23 @@ export class PayStation {
|
||||
* 0 and a multi-day overstay would exit free (ticket 1245791632490). A new period
|
||||
* reflects the reality and re-accrues the fee. No side effect. */
|
||||
quote(identity: string): Quote {
|
||||
const entry = this.#openEntry(identity);
|
||||
return this.#quoteFromRows(identity, this.#identityRows(identity), this.#tariffResolver());
|
||||
}
|
||||
|
||||
/** `quote` over the identity's ledger rows the caller already holds (oldest first) and
|
||||
* a prebuilt tariff resolver. The single-session `quote()` wraps this with one
|
||||
* identity-scoped read; `activeSessions()` feeds it per-identity groups of ONE whole-
|
||||
* ledger scan. Both paths MUST price identically — pinned by pay-station.test.ts.
|
||||
* Why: the list view used to call `quote()` per open unpaid row, each doing 3–4
|
||||
* ledger scans; with ~660 such rows at park-2 the synchronous handler ran ~2 s and
|
||||
* froze the event loop — relay replies then "timed out" (2026-10-24). */
|
||||
#quoteFromRows(identity: string, rows: readonly LedgerRow[], tariffFor: TariffResolver): Quote {
|
||||
const entry = PayStation.#openEntryFromRows(rows);
|
||||
if (!entry) throw new NoOpenSessionError(identity);
|
||||
|
||||
// The tariff in force is keyed to ENTRY (the version frozen for this session), even
|
||||
// for an overstay period — the customer keeps the rate card they entered under.
|
||||
const tv = this.#tariffVersionFor(entry.occurredAt);
|
||||
const tv = tariffFor(entry.occurredAt);
|
||||
if (!tv) throw new NoTariffError();
|
||||
const structure = tv.structure as unknown as TariffStructure;
|
||||
|
||||
@@ -220,8 +237,8 @@ export class PayStation {
|
||||
// Merchant validations: fold the LIVE ones (applied, unvoided, not consumed by a
|
||||
// prior payment) so the quote is NET — the payment then stamps their ids as
|
||||
// consumed. See wiki/concepts/validation-discounts.md.
|
||||
const last = this.#lastPayment(identity);
|
||||
const validations = liveValidations(this.#db, identity);
|
||||
const last = PayStation.#lastPaymentFromRows(rows);
|
||||
const validations = liveValidationsFromRows(rows);
|
||||
const p = priceSession(
|
||||
entry.occurredAt,
|
||||
new Date().toISOString(),
|
||||
@@ -254,12 +271,17 @@ export class PayStation {
|
||||
/** The latest signed `payment` for this session (time + the grace window it granted),
|
||||
* or null if never paid. Folds the append-only ledger. */
|
||||
#lastPayment(identity: string): { paidAt: string; graceExitMin: number | null } | null {
|
||||
const rows = this.#db
|
||||
.select({ type: ledgerEvents.type, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload })
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, identity))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all();
|
||||
return PayStation.#lastPaymentFromRows(this.#identityRows(identity));
|
||||
}
|
||||
|
||||
/** All ledger rows of one identity, oldest first (the fold order every helper expects). */
|
||||
#identityRows(identity: string): LedgerRow[] {
|
||||
return this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).orderBy(ledgerEvents.index).all();
|
||||
}
|
||||
|
||||
static #lastPaymentFromRows(
|
||||
rows: readonly Pick<LedgerRow, "type" | "occurredAt" | "payload">[],
|
||||
): { paidAt: string; graceExitMin: number | null } | null {
|
||||
let last: { paidAt: string; graceExitMin: number | null } | null = null;
|
||||
for (const r of rows) {
|
||||
if (r.type !== "payment") continue;
|
||||
@@ -541,9 +563,15 @@ export class PayStation {
|
||||
subscriptionId?: string | null;
|
||||
};
|
||||
const byId = new Map<string, Acc>();
|
||||
// Every row per identity (oldest first — `rows` is index-ordered), so the quotes
|
||||
// below price from THIS scan instead of re-reading the ledger per session.
|
||||
const rowsById = new Map<string, LedgerRow[]>();
|
||||
for (const r of rows) {
|
||||
const id = r.identity;
|
||||
if (!id) continue;
|
||||
const group = rowsById.get(id);
|
||||
if (group) group.push(r);
|
||||
else rowsById.set(id, [r]);
|
||||
if (r.type === "vehicle_entry") {
|
||||
const a = byId.get(id) ?? { source: r.source ?? null };
|
||||
a.enteredAt = r.occurredAt;
|
||||
@@ -570,6 +598,8 @@ export class PayStation {
|
||||
// Resolve advisory plates for all candidate identities in ONE device_events scan
|
||||
// (cheaper than one lookup per row).
|
||||
const plates = platesForIdentities(this.#db, byId.keys());
|
||||
// One tariff read for the whole list (quotes below reuse it).
|
||||
const tariffFor = this.#tariffResolver();
|
||||
|
||||
const now = Date.now();
|
||||
const out: ActiveSession[] = [];
|
||||
@@ -607,7 +637,9 @@ export class PayStation {
|
||||
let currency: string | null = null;
|
||||
if (open && !isSubscription && (a.paidAt == null || overstay)) {
|
||||
try {
|
||||
const q = this.quote(identity);
|
||||
// Priced from the rows already in hand — no per-session ledger reads. The
|
||||
// charge providers (car wash) still run one indexed lookup per row.
|
||||
const q = this.#quoteFromRows(identity, rowsById.get(identity) ?? [], tariffFor);
|
||||
amountMinor = q.amountMinor;
|
||||
currency = q.currency;
|
||||
} catch {
|
||||
@@ -710,12 +742,10 @@ export class PayStation {
|
||||
|
||||
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
|
||||
#openEntry(identity: string) {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, identity))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all();
|
||||
return PayStation.#openEntryFromRows(this.#identityRows(identity));
|
||||
}
|
||||
|
||||
static #openEntryFromRows(rows: readonly LedgerRow[]): LedgerRow | null {
|
||||
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||
if (!entry) return null;
|
||||
if (rows.some((r) => r.type === "vehicle_exit")) return null; // already closed
|
||||
@@ -725,14 +755,20 @@ export class PayStation {
|
||||
/** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the
|
||||
* (single, for now) active site tariff. */
|
||||
#tariffVersionFor(at: string) {
|
||||
return this.#tariffResolver()(at);
|
||||
}
|
||||
|
||||
/** Read the site tariff + its versions ONCE and return a resolver over them. A list
|
||||
* view builds one resolver per request instead of two tariff reads per row. */
|
||||
#tariffResolver(): TariffResolver {
|
||||
const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
||||
if (!tariff) return null;
|
||||
if (!tariff) return () => null;
|
||||
const versions = this.#db
|
||||
.select()
|
||||
.from(tariffVersions)
|
||||
.where(eq(tariffVersions.tariffId, tariff.id))
|
||||
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||
.all();
|
||||
return versions.find((v) => v.effectiveFrom <= at) ?? null;
|
||||
return (at) => versions.find((v) => v.effectiveFrom <= at) ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user