diff --git a/apps/server/src/broker/broker.ts b/apps/server/src/broker/broker.ts index f1af204..6d264ef 100644 --- a/apps/server/src/broker/broker.ts +++ b/apps/server/src/broker/broker.ts @@ -6,11 +6,11 @@ import { randomUUID } from 'node:crypto'; import type { Logger } from '../logger.js'; import type { KafkaEvent, KafkaTail } from '../kafka/tail.js'; import type { GatewayClient } from '../rest/gateway-client.js'; -import { resolveQuery } from './queries.js'; -import type { Delta, Snapshot, Subscription } from './types.js'; -import type { QueryName, QueryParams } from '@eveys-console/protocol'; +import { mergeConnectorFromStatusEvent, resolveQuery } from './queries.js'; +import type { Delta, Snapshot, Subscription, SubscriptionError } from './types.js'; +import { applySubscriptionDelta, type QueryName, type QueryParams } from '@eveys-console/protocol'; -export type DeliveryHandler = (subscriptionId: string, delta: Delta) => void; +export type DeliveryHandler = (subscriptionId: string, delta: Delta | SubscriptionError) => void; interface ConnectionState { connectionId: string; @@ -64,11 +64,20 @@ export class Broker { if (!conn) throw new Error(`unknown connection ${connectionId}`); const subscriptionId = randomUUID(); - const sub: Subscription = { id: subscriptionId, query, params }; - const resolver = resolveQuery(query); const snapshot = await resolver.snapshot(params, this.gateway); - + if (this.connections.get(connectionId) !== conn) + throw new Error('Connection closed during subscribe'); + const sub: Subscription = { + id: subscriptionId, + query, + params, + snapshot: snapshot.snapshot, + sequence: 0, + applied: new Map(), + pendingStatus: new Map(), + stoppedTransactions: new Set(), + }; conn.subscriptions.set(subscriptionId, sub); return { subscriptionId, snapshot }; } @@ -89,27 +98,103 @@ export class Broker { for (const conn of this.connections.values()) { for (const sub of conn.subscriptions.values()) { const resolver = resolveQuery(sub.query); + const sequence = ++sub.sequence; + const key = + sub.query === 'charge-points' || sub.query === 'charge-point' ? event.cpId : null; + // Keep in-flight status events even before a new charger has a fleet + // row. The next completed refetch folds in every observed connector. + if ( + event.topic === 'cp.status' && + key && + (sub.query === 'charge-points' || sub.params.cp_id === key) + ) { + const pending = sub.pendingStatus.get(key) ?? []; + pending.push(event); + sub.pendingStatus.set(key, pending); + } + const current = () => + this.connections.get(conn.connectionId) === conn && + conn.subscriptions.get(sub.id) === sub; void resolver .deltasFromEvent(sub.params, event, this.gateway) .then((deltas) => { - for (const delta of deltas) { + if ( + !current() || + deltas.length === 0 || + (key && sequence < (sub.applied.get(key) ?? 0)) + ) + return; + if (key) sub.applied.set(key, sequence); + for (const raw of deltas) { + let delta = raw; + // Start and stop arrive on different topics. A transaction ID + // is terminal after stop, even if its old start is delivered later. + // This state lasts only for this active subscription. + if (delta.delta.kind === 'transactions-active') { + if (delta.delta.op === 'remove' && delta.delta.transaction_id !== undefined) + sub.stoppedTransactions.add(delta.delta.transaction_id); + if ( + delta.delta.op === 'upsert' && + delta.delta.row && + sub.stoppedTransactions.has(delta.delta.row.transaction_id) + ) + continue; + } + if ( + (delta.delta.kind === 'charge-point' || delta.delta.kind === 'charge-points') && + delta.delta.row + ) { + let row = delta.delta.row; + for (const statusEvent of sub.pendingStatus.get(row.cp_id) ?? []) + row = mergeConnectorFromStatusEvent(row, statusEvent); + delta = { ...delta, delta: { ...delta.delta, row } }; + } + sub.snapshot = applySubscriptionDelta(sub.snapshot, delta.delta) ?? sub.snapshot; + if (delta.delta.kind === 'charge-point' && sub.snapshot.kind === 'charge-point') { + delta = { ...delta, delta: { ...delta.delta, row: sub.snapshot.row } }; + } else if ( + delta.delta.kind === 'charge-points' && + delta.delta.row && + sub.snapshot.kind === 'charge-points' + ) { + const incoming = delta.delta.row; + delta = { + ...delta, + delta: { + ...delta.delta, + row: sub.snapshot.rows.find((row) => row.cp_id === incoming.cp_id) ?? incoming, + }, + }; + } try { conn.deliver(sub.id, delta); } catch (err) { this.log.warn({ err, connectionId: conn.connectionId }, 'broker.deliver_failed'); } } + if (key) sub.pendingStatus.delete(key); }) .catch((err: unknown) => { + if (!current() || (key && sequence < (sub.applied.get(key) ?? 0))) return; + if (key) sub.applied.set(key, sequence); + if (key) sub.pendingStatus.delete(key); this.log.warn( { - err, + errorClass: err instanceof Error ? err.name : 'unknown', connectionId: conn.connectionId, subscriptionId: sub.id, topic: event.topic, }, 'broker.resolver_failed', ); + try { + conn.deliver(sub.id, { + cursor: event.cursor, + error: 'Gateway refresh failed. Showing last known data.', + }); + } catch { + this.log.warn({ connectionId: conn.connectionId }, 'broker.deliver_failed'); + } }); } } diff --git a/apps/server/src/broker/queries.ts b/apps/server/src/broker/queries.ts index 5ce28ec..9a7cf8f 100644 --- a/apps/server/src/broker/queries.ts +++ b/apps/server/src/broker/queries.ts @@ -13,6 +13,7 @@ // protocol's wire shape is snake_case, so each resolver maps between // the two. +import { mergeChargePoint, withConnectorFreshness } from '@eveys-console/protocol'; import type { ChargePointSummary, DeltaForQuery, @@ -92,7 +93,7 @@ const chargePoints: QueryResolver = { const cursor = `gw:cp-list:${Date.now()}`; const snapshot: SnapshotForQuery = { kind: 'charge-points', - rows: data.charge_points, + rows: data.charge_points.map(withConnectorFreshness), next_cursor: data.next_cursor ?? null, }; if (data.pagination) { @@ -129,12 +130,8 @@ const chargePoints: QueryResolver = { // call per event. Acceptable while load is low; a future commit // will replace this with an in-memory snapshot store fed by the // same Kafka tail. - let row: ChargePointSummary; - try { - row = (await gateway.getChargePoint(event.cpId)) as ChargePointSummary; - } catch { - return []; - } + let row = (await gateway.getChargePoint(event.cpId)) as ChargePointSummary; + if (row.cp_id !== event.cpId) throw new Error('Gateway charger identity mismatch'); // The gateway sources `connectors[]` from ClickHouse (`cp_status`), // which the ingestor fills in batches. Right after a charger emits @@ -216,35 +213,32 @@ const chargePoints: QueryResolver = { // UI doesn't have to wait for the gateway's ClickHouse-backed // connectors[] to catch up. Idempotent: if the row already carries a // newer entry for the same connector, the event is dropped. -function mergeConnectorFromStatusEvent( +export function mergeConnectorFromStatusEvent( row: ChargePointSummary, event: KafkaEvent, ): ChargePointSummary { const p = event.payload as Record | null; if (!p || typeof p !== 'object') return row; const connectorId = Number(p.connectorId ?? NaN); - if (!Number.isFinite(connectorId)) return row; + if (!Number.isInteger(connectorId) || connectorId < 0) return row; const status = typeof p.status === 'string' ? p.status : null; if (!status) return row; - const reportedAt = - typeof p.chargerReportedAt === 'string' && p.chargerReportedAt - ? p.chargerReportedAt - : event.timestamp.toISOString(); + // EventEnvelope.occurred_at is the gateway receive time, also used by + // ClickHouse. A charger clock cannot outrank later server observations. + const reportedAt = event.timestamp.toISOString(); const errorCode = typeof p.errorCode === 'string' && p.errorCode !== '' ? p.errorCode : null; - const existing = row.connectors.find((c) => c.connector_id === connectorId); - if (existing && existing.last_changed_at && existing.last_changed_at >= reportedAt) { - return row; - } - const next = row.connectors.filter((c) => c.connector_id !== connectorId); - next.push({ - connector_id: connectorId, - status, - error_code: errorCode, - last_changed_at: reportedAt, + return mergeChargePoint(row, { + ...row, + connectors: [ + { + connector_id: connectorId, + status, + error_code: errorCode, + last_changed_at: reportedAt, + }, + ], }); - next.sort((a, b) => a.connector_id - b.connector_id); - return { ...row, connectors: next }; } const chargePoint: QueryResolver = { @@ -252,7 +246,7 @@ const chargePoint: QueryResolver = { const cpId = stringParam(params, 'cp_id'); const data = (await gateway.getChargePoint(cpId)) as ChargePointSummary; const cursor = `gw:cp:${cpId}:${Date.now()}`; - return { cursor, snapshot: { kind: 'charge-point', row: data } }; + return { cursor, snapshot: { kind: 'charge-point', row: withConnectorFreshness(data) } }; }, async deltasFromEvent(params, event, gateway) { const cpId = stringParam(params, 'cp_id'); @@ -277,12 +271,9 @@ const chargePoint: QueryResolver = { // Same approach as the list resolver: re-fetch the full row from // the gateway so the UI gets a complete update. This page is one // charger so the cost is bounded. - let row: ChargePointSummary; - try { - row = (await gateway.getChargePoint(cpId)) as ChargePointSummary; - } catch { - return []; - } + let row = (await gateway.getChargePoint(cpId)) as ChargePointSummary; + if (row.cp_id !== cpId) throw new Error('Gateway charger identity mismatch'); + if (event.topic === 'cp.status') row = mergeConnectorFromStatusEvent(row, event); const delta: DeltaForQuery = { kind: 'charge-point', row }; return [{ cursor: event.cursor, delta }]; }, @@ -299,15 +290,25 @@ const transactionsActive: QueryResolver = { }; }, async deltasFromEvent(_params, event) { - if (event.topic !== 'tx.started') return []; + if (event.topic !== 'tx.started' && event.topic !== 'tx.stopped') return []; const p = event.payload as Record | null; if (!p || typeof p !== 'object') return []; + const transactionId = Number(p.transactionId ?? NaN); + if (!Number.isInteger(transactionId)) return []; + if (event.topic === 'tx.stopped') { + return [ + { + cursor: event.cursor, + delta: { kind: 'transactions-active', op: 'remove', transaction_id: transactionId }, + }, + ]; + } // The wire shape mirrors the gateway's GET /api/v1/transactions row. // For a delta from a tx.started event we only have a subset; the // missing fields (stopped_*, consumed_wh) are null because the // session is still open. const row = { - transaction_id: Number(p.transactionId ?? 0), + transaction_id: transactionId, cp_id: event.cpId ?? '', connector_id: Number(p.connectorId ?? 0), id_tag: String(p.idTag ?? ''), @@ -435,17 +436,21 @@ const deviceEvents: QueryResolver = { // that don't need history) or the CP has no recorded events // yet. let rows: DeviceEvent[] = []; + let history_state: 'available' | 'unavailable' | 'unconfigured' = 'unconfigured'; + let history_error: 'read_failed' | null = null; const cpIdRaw = params.cp_id; if (eventLogRoot && typeof cpIdRaw === 'string' && cpIdRaw.length > 0) { try { rows = await tailLastN(eventLogRoot, cpIdRaw, { limit: bootstrapLimit }); + history_state = 'available'; } catch { - rows = []; + history_state = 'unavailable'; + history_error = 'read_failed'; } } return { cursor: `gw:device-events:bootstrap:${Date.now()}`, - snapshot: { kind: 'device-events', rows }, + snapshot: { kind: 'device-events', rows, history_state, history_error }, }; }, async deltasFromEvent(params, event) { diff --git a/apps/server/src/broker/types.ts b/apps/server/src/broker/types.ts index 5b79112..5e336d1 100644 --- a/apps/server/src/broker/types.ts +++ b/apps/server/src/broker/types.ts @@ -4,11 +4,17 @@ import type { QueryParams, SnapshotForQuery, } from '@eveys-console/protocol'; +import type { KafkaEvent } from '../kafka/tail.js'; export interface Subscription { id: string; query: QueryName; params: QueryParams; + snapshot: SnapshotForQuery; + sequence: number; + applied: Map; + pendingStatus: Map; + stoppedTransactions: Set; } export interface Snapshot { @@ -20,3 +26,8 @@ export interface Delta { cursor: string; delta: DeltaForQuery; } + +export interface SubscriptionError { + cursor: string; + error: string; +} diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index d7c411f..88b81f2 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -172,7 +172,7 @@ async function main() { // healthchecks already need to know the deployment's URL shape. await app.register( async (api) => { - await registerHealthRoutes(api); + await registerHealthRoutes(api, { kafka, gateway }); await registerMetricsRoute(api); await registerAuthRoutes(api, { pow, users }); await registerSysStatusRoute(api, { broker, gateway, kafka, startedAt }); diff --git a/apps/server/src/rest/gateway-client.ts b/apps/server/src/rest/gateway-client.ts index 0d25a0b..833e1db 100644 --- a/apps/server/src/rest/gateway-client.ts +++ b/apps/server/src/rest/gateway-client.ts @@ -17,7 +17,11 @@ export class GatewayClient { private async json( op: GatewayOp, path: string, - init?: { method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; body?: unknown }, + init?: { + method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; + body?: unknown; + signal?: AbortSignal; + }, ): Promise { const url = `${this.cfg.GATEWAY_BASE_URL}${path}`; const headers: Record = { @@ -29,6 +33,7 @@ export class GatewayClient { const start = Date.now(); const method = init?.method ?? 'GET'; const reqOpts: Parameters[1] = { method, headers }; + if (init?.signal) reqOpts.signal = init.signal; if (init?.body !== undefined) reqOpts.body = JSON.stringify(init.body); // `op` is a closed enum (see GatewayOp) so the {op,status} label // cartesian stays bounded; URL paths never become labels. @@ -49,8 +54,8 @@ export class GatewayClient { } } - health() { - return this.json('health', '/api/v1/health'); + health(signal?: AbortSignal) { + return this.json('health', '/api/v1/health', signal ? { signal } : undefined); } sysConfig() { diff --git a/apps/server/src/routes/health.ts b/apps/server/src/routes/health.ts index 4361c48..34fdec5 100644 --- a/apps/server/src/routes/health.ts +++ b/apps/server/src/routes/health.ts @@ -1,8 +1,53 @@ +import type { KafkaTail } from '../kafka/tail.js'; +import type { GatewayClient } from '../rest/gateway-client.js'; + +interface HealthDeps { + kafka: Pick; + gateway: Pick; +} + // Use a loose `app` type so this helper composes with any FastifyInstance // regardless of how the parent app's logger / type provider were narrowed. // Strict typing happens at the route handler, not the registrar. // eslint-disable-next-line @typescript-eslint/no-explicit-any -export async function registerHealthRoutes(app: any) { +export async function registerHealthRoutes(app: any, deps: HealthDeps) { app.get('/healthz', async () => ({ ok: true })); - app.get('/readyz', async () => ({ ok: true })); + app.get('/readyz', async (_req: unknown, reply: { code: (status: number) => unknown }) => { + const running = deps.kafka.isRunning(); + const topics = deps.kafka.subscribedTopics(); + const kafka = { ok: running && topics.length > 0, consumer_running: running, topics }; + const gateway = await coreGatewayProbe(deps.gateway); + const ok = kafka.ok && gateway.ok; + reply.code(ok ? 200 : 503); + // Scope is request availability, not archive completeness or ingestion progress. + return { ok, scope: 'console_gateway_core', components: { kafka, gateway } }; + }); +} + +async function coreGatewayProbe(gateway: HealthDeps['gateway']) { + const controller = new AbortController(); + let timer: ReturnType | undefined; + try { + const body = (await Promise.race([ + gateway.health(controller.signal), + new Promise((_resolve, reject) => { + timer = setTimeout(() => { + controller.abort(); + reject(new Error('probe timeout')); + }, 1000); + }), + ])) as { status?: string; components?: Record; archive?: unknown }; + const components = body?.components; + const coreOk = components?.postgres === 'ok' && components?.redis === 'ok'; + return { + ok: coreOk && (body?.status === 'ok' || body?.status === 'degraded'), + status: body?.status ?? 'unknown', + ...(components ? { components } : {}), + ...(body?.archive ? { archive: body.archive } : {}), + }; + } catch { + return { ok: false, status: 'unavailable' }; + } finally { + if (timer !== undefined) clearTimeout(timer); + } } diff --git a/apps/server/src/routes/sys-status.ts b/apps/server/src/routes/sys-status.ts index 78cf190..a1786fb 100644 --- a/apps/server/src/routes/sys-status.ts +++ b/apps/server/src/routes/sys-status.ts @@ -28,7 +28,7 @@ interface SysStatusResponse { }; gateway: ComponentStatus & { version?: string; - components?: Record; + components?: Record; }; kafka: ComponentStatus & { topics?: string[]; @@ -80,7 +80,7 @@ async function probeGatewayHealth(gateway: GatewayClient): Promise; + components?: Record; }; const latency = Date.now() - t0; if (body.status !== 'ok') { @@ -109,11 +109,13 @@ async function probeGatewayHealth(gateway: GatewayClient): Promise 0, consumer_running: running, - topics: kafka.subscribedTopics(), + topics, }; if (!running) base.detail = 'consumer not running'; + else if (topics.length === 0) base.detail = 'consumer has no subscribed topics'; return base; } diff --git a/apps/server/src/routes/ws.ts b/apps/server/src/routes/ws.ts index ae211e2..ed46c7e 100644 --- a/apps/server/src/routes/ws.ts +++ b/apps/server/src/routes/ws.ts @@ -66,6 +66,15 @@ export async function registerWsRoute( recordWsConnection(1); deps.broker.registerConnection(connectionId, (subscriptionId, delta) => { + if ('error' in delta) { + send(socket, { + v: PROTOCOL_VERSION, + type: 'error', + subscriptionId, + error: { code: 'upstream_unavailable', message: delta.error }, + }); + return; + } send(socket, { v: PROTOCOL_VERSION, type: 'delta', diff --git a/apps/server/test/broker.test.ts b/apps/server/test/broker.test.ts index 19b3223..9460388 100644 --- a/apps/server/test/broker.test.ts +++ b/apps/server/test/broker.test.ts @@ -47,7 +47,7 @@ function makeFakeGateway(opts: FakeGatewayOptions = {}) { model: 'X1', firmware_version: '1.0', serial_number: 'SN1', - last_boot_at: null, + last_boot_at: '2026-05-01T00:00:00Z', last_heartbeat_at: null, last_status: opts.last_status ?? 'Available', last_seen_seq: 0, @@ -110,6 +110,174 @@ describe('Broker — subscribe and snapshot', () => { }); describe('Broker — charge-point (single) deltas', () => { + it('retains both connectors when a new fleet row has concurrent first status refetches', async () => { + const kafka = new FakeKafka(); + const { client, getSpy } = makeFakeGateway(); + const initial = await getSpy('NEW'); + const broker = new Broker(kafka as unknown as KafkaTail, client, silentLog); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'charge-points', {}); + let finishOld!: (row: typeof initial) => void; + getSpy.mockImplementationOnce( + () => + new Promise((resolve) => { + finishOld = resolve; + }), + ); + getSpy.mockResolvedValueOnce(initial); + kafka.emit({ + topic: 'cp.status', + cpId: 'NEW', + cursor: 'one', + timestamp: new Date('2026-10-13T10:00:00Z'), + payload: { connectorId: 1, status: 'Charging' }, + }); + kafka.emit({ + topic: 'cp.status', + cpId: 'NEW', + cursor: 'two', + timestamp: new Date('2026-10-13T10:01:00Z'), + payload: { connectorId: 2, status: 'Charging' }, + }); + await flushAsync(); + finishOld(initial); + await flushAsync(); + expect( + deliver.mock.calls + .at(-1)?.[1] + .delta.row.connectors.map((c: { connector_id: number }) => c.connector_id), + ).toEqual([1, 2]); + expect(deliver).toHaveBeenCalledTimes(1); + }); + it('shows a connector status event in detail even when the gateway archive is empty', async () => { + const kafka = new FakeKafka(); + const broker = new Broker( + kafka as unknown as KafkaTail, + fakeGateway({ connectors: [] }), + silentLog, + ); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'charge-point', { cp_id: 'A' }); + kafka.emit({ + topic: 'cp.status', + cpId: 'A', + cursor: '1', + timestamp: new Date('2026-10-13T10:00:00Z'), + payload: { connectorId: 2, status: 'Charging', errorCode: 'NoError' }, + }); + await flushAsync(); + expect(deliver.mock.calls[0]?.[1].delta.row.connectors).toEqual([ + { + connector_id: 2, + status: 'Charging', + error_code: 'NoError', + last_changed_at: '2026-10-13T10:00:00.000Z', + status_freshness: 'current', + stale_reason: null, + }, + ]); + }); + + it('retains both live connectors across status and boot refetches', async () => { + const kafka = new FakeKafka(); + const broker = new Broker( + kafka as unknown as KafkaTail, + fakeGateway({ connectors: [] }), + silentLog, + ); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'charge-point', { cp_id: 'A' }); + for (const id of [1, 2]) { + kafka.emit({ + topic: 'cp.status', + cpId: 'A', + cursor: String(id), + timestamp: new Date(`2026-10-13T10:0${id}:00Z`), + payload: { connectorId: id, status: 'Charging' }, + }); + await flushAsync(); + } + kafka.emit({ + topic: 'cp.boot', + cpId: 'A', + cursor: '3', + timestamp: new Date('2026-10-13T10:03:00Z'), + payload: {}, + }); + await flushAsync(); + expect( + deliver.mock.calls + .at(-1)?.[1] + .delta.row.connectors.map((c: { connector_id: number }) => c.connector_id), + ).toEqual([1, 2]); + }); + + it('drops an older refetch completing after a newer event', async () => { + const kafka = new FakeKafka(); + const { client, getSpy } = makeFakeGateway(); + const initial = await getSpy('A'); + const broker = new Broker(kafka as unknown as KafkaTail, client, silentLog); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'charge-point', { cp_id: 'A' }); + let finishOld!: (row: typeof initial) => void; + getSpy.mockImplementationOnce( + () => + new Promise((resolve) => { + finishOld = resolve; + }), + ); + getSpy.mockResolvedValueOnce({ ...initial, last_status: 'Charging' }); + kafka.emit({ + topic: 'cp.status', + cpId: 'A', + cursor: 'old', + timestamp: new Date('2026-10-13T10:00:00Z'), + payload: { connectorId: 1, status: 'Available' }, + }); + kafka.emit({ + topic: 'cp.status', + cpId: 'A', + cursor: 'new', + timestamp: new Date('2026-10-13T10:01:00Z'), + payload: { connectorId: 1, status: 'Charging' }, + }); + await flushAsync(); + finishOld(initial); + await flushAsync(); + expect(deliver.mock.calls.at(-1)?.[1].delta.row.connectors[0].status).toBe('Charging'); + expect(deliver).toHaveBeenCalledTimes(1); + }); + + it('reports a refetch failure to the subscription without exposing the upstream message', async () => { + const kafka = new FakeKafka(); + const { client, getSpy } = makeFakeGateway(); + const broker = new Broker(kafka as unknown as KafkaTail, client, silentLog); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'charge-point', { cp_id: 'A' }); + getSpy.mockRejectedValueOnce(new Error('sensitive upstream payload')); + kafka.emit({ + topic: 'cp.status', + cpId: 'A', + cursor: 'error', + timestamp: new Date(), + payload: { connectorId: 1, status: 'Charging' }, + }); + await flushAsync(); + expect(deliver.mock.calls.at(-1)?.[1]).toMatchObject({ + error: 'Gateway refresh failed. Showing last known data.', + }); + expect(JSON.stringify(deliver.mock.calls)).not.toContain('sensitive upstream'); + }); it('delivers a delta when a status event arrives for the subscribed cp', async () => { const kafka = new FakeKafka(); const broker = new Broker(kafka as unknown as KafkaTail, fakeGateway(), silentLog); @@ -229,6 +397,73 @@ describe('Broker — charge-point (single) deltas', () => { }); }); +describe('Broker — active transaction stop', () => { + it.each([true, false])( + 'does not reopen a stopped transaction after a late start (settled stop: %s)', + async (settleStop) => { + const kafka = new FakeKafka(); + const broker = new Broker(kafka as unknown as KafkaTail, fakeGateway(), silentLog); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'transactions-active', {}); + kafka.emit({ + topic: 'tx.stopped', + cpId: 'CP_A', + cursor: 'stop', + timestamp: new Date('2026-10-13T10:02:00Z'), + payload: { transactionId: 7 }, + }); + if (settleStop) await flushAsync(); + kafka.emit({ + topic: 'tx.started', + cpId: 'CP_A', + cursor: 'late-start', + timestamp: new Date('2026-10-13T10:01:00Z'), + payload: { transactionId: 7 }, + }); + kafka.emit({ + topic: 'tx.started', + cpId: 'CP_A', + cursor: 'new-start', + timestamp: new Date('2026-10-13T10:03:00Z'), + payload: { transactionId: 8 }, + }); + await flushAsync(); + expect(deliver.mock.calls.map(([, delivery]) => delivery.delta)).toEqual([ + { kind: 'transactions-active', op: 'remove', transaction_id: 7 }, + expect.objectContaining({ + kind: 'transactions-active', + op: 'upsert', + row: expect.objectContaining({ transaction_id: 8 }), + }), + ]); + }, + ); + + it('emits a remove when the active transaction stops', async () => { + const kafka = new FakeKafka(); + const broker = new Broker(kafka as unknown as KafkaTail, fakeGateway(), silentLog); + broker.start(); + const deliver = vi.fn(); + broker.registerConnection('c1', deliver); + await broker.subscribe('c1', 'transactions-active', {}); + kafka.emit({ + topic: 'tx.stopped', + cpId: 'A', + cursor: 'stop', + timestamp: new Date(), + payload: { transactionId: 7 }, + }); + await flushAsync(); + expect(deliver.mock.calls.at(-1)?.[1].delta).toEqual({ + kind: 'transactions-active', + op: 'remove', + transaction_id: 7, + }); + }); +}); + describe('Broker — charge-points (list) deltas', () => { it('emits an upsert when a status event arrives', async () => { const kafka = new FakeKafka(); @@ -446,7 +681,9 @@ describe('Broker — charge-points (list) deltas', () => { connector_id: 2, status: 'Charging', error_code: 'NoError', - last_changed_at: '2026-05-11T09:59:55Z', + last_changed_at: '2026-05-11T10:00:00.000Z', + status_freshness: 'current', + stale_reason: null, }, ]); }); @@ -478,7 +715,7 @@ describe('Broker — charge-points (list) deltas', () => { topic: 'cp.status', cpId: 'CP_M', cursor: 'k:cp.status:0:15', - timestamp: new Date('2026-05-11T10:01:30Z'), + timestamp: new Date('2026-05-11T10:00:00Z'), payload: { connectorId: 1, status: 'Preparing', diff --git a/apps/server/test/connector-freshness.test.ts b/apps/server/test/connector-freshness.test.ts new file mode 100644 index 0000000..cfe583d --- /dev/null +++ b/apps/server/test/connector-freshness.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import type { ChargePointSummary } from '@eveys-console/protocol'; +import { mergeConnectorFromStatusEvent, resolveQuery } from '../src/broker/queries.js'; +import type { KafkaEvent } from '../src/kafka/tail.js'; +import type { GatewayClient } from '../src/rest/gateway-client.js'; + +const row = (): ChargePointSummary => ({ + cp_id: 'CP_TEST', + online: true, + pod_id: 'test', + vendor: null, + model: null, + firmware_version: null, + serial_number: null, + last_status: 'Available', + last_boot_at: '2026-10-13T09:12:44Z', + last_heartbeat_at: null, + connectors: [ + { + connector_id: 1, + status: 'Charging', + error_code: 'NoError', + last_changed_at: '2026-10-13T08:47:04Z', + }, + ], +}); +describe('connector source freshness', () => { + it('does not use an incorrect charger clock to outrank server-received status', () => { + const event = { + cpId: 'CP_TEST', + topic: 'cp.status', + cursor: 'k:1', + timestamp: new Date('2026-10-13T14:10:00Z'), + payload: { + connectorId: 1, + status: 'Available', + errorCode: 'NoError', + chargerReportedAt: '2099-01-01T00:00:00Z', + }, + } as KafkaEvent; + expect(mergeConnectorFromStatusEvent(row(), event).connectors[0]).toMatchObject({ + status: 'Available', + last_changed_at: '2026-10-13T14:10:00.000Z', + }); + }); + it('marks stale connector data on initial detail snapshot, including older gateways', async () => { + const gw = { getChargePoint: async () => row() } as unknown as GatewayClient; + const result = await resolveQuery('charge-point').snapshot({ cp_id: 'CP_TEST' }, gw); + if (result.snapshot.kind !== 'charge-point') throw new Error('incorrect snapshot'); + expect(result.snapshot.row.connectors[0]).toMatchObject({ + status_freshness: 'stale', + stale_reason: 'before_boot', + }); + }); +}); diff --git a/apps/server/test/event-log/bootstrap-from-log.test.ts b/apps/server/test/event-log/bootstrap-from-log.test.ts index 1f02811..33d9b5e 100644 --- a/apps/server/test/event-log/bootstrap-from-log.test.ts +++ b/apps/server/test/event-log/bootstrap-from-log.test.ts @@ -54,6 +54,36 @@ function statusEvent(iso: string, cpId = 'CP_A'): KafkaEvent { } describe('device-events bootstrap from log', () => { + it('marks a failed archive read unavailable without preventing live subscription', async () => { + // A file where the CP directory belongs yields a real ENOTDIR read failure. + await fs.writeFile(path.join(root, 'CP_BROKEN'), 'not a directory'); + configureEventLogReader({ root, bootstrapLimit: 10 }); + const resolver = resolveQuery('device-events'); + const snap = await resolver.snapshot({ cp_id: 'CP_BROKEN' }, gateway); + expect(snap.snapshot).toMatchObject({ + kind: 'device-events', + rows: [], + history_state: 'unavailable', + history_error: 'read_failed', + }); + expect( + await resolver.deltasFromEvent( + { cp_id: 'CP_BROKEN' }, + statusEvent('2026-10-13T07:00:00Z', 'CP_BROKEN'), + gateway, + ), + ).toHaveLength(1); + }); + + it('marks disabled history unconfigured rather than claiming an empty archive', async () => { + resetEventLogReader(); + expect( + (await resolveQuery('device-events').snapshot({ cp_id: 'CP_A' }, gateway)).snapshot, + ).toMatchObject({ + history_state: 'unconfigured', + history_error: null, + }); + }); it('returns up to bootstrapLimit recent events for the requested cp_id', async () => { for (let i = 0; i < 5; i++) { const sec = String(i).padStart(2, '0'); @@ -78,6 +108,7 @@ describe('device-events bootstrap from log', () => { const snap = await resolver.snapshot({ cp_id: 'CP_NEW' }, gateway); if (snap.snapshot.kind === 'device-events') { expect(snap.snapshot.rows).toEqual([]); + expect(snap.snapshot).toMatchObject({ history_state: 'available', history_error: null }); } }); diff --git a/apps/server/test/health.test.ts b/apps/server/test/health.test.ts new file mode 100644 index 0000000..ae20760 --- /dev/null +++ b/apps/server/test/health.test.ts @@ -0,0 +1,143 @@ +import Fastify from 'fastify'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { registerHealthRoutes } from '../src/routes/health.js'; + +const apps: ReturnType[] = []; +afterEach(async () => { + await Promise.all(apps.splice(0).map((app) => app.close())); + vi.useRealTimers(); +}); +async function fixture({ + running = true, + topics = ['cp.status'], + health = async (_signal?: AbortSignal) => ({ + status: 'ok', + components: { postgres: 'ok', redis: 'ok', clickhouse: 'ok', ingestor: 'unknown' }, + }), +}: { + running?: boolean; + topics?: string[]; + health?: (signal?: AbortSignal) => Promise; +} = {}) { + const app = Fastify(); + apps.push(app); + await registerHealthRoutes(app, { + kafka: { isRunning: () => running, subscribedTopics: () => topics }, + gateway: { health }, + }); + return app; +} + +describe('process liveness and observation readiness', () => { + it('keeps process liveness healthy without checking any upstream', async () => { + const health = vi.fn().mockRejectedValue(new Error('upstream failed')); + const app = await fixture({ running: false, topics: [], health }); + const response = await app.inject('/healthz'); + expect(response.statusCode).toBe(200); + expect(response.json()).toEqual({ ok: true }); + expect(health).not.toHaveBeenCalled(); + }); + it.each([ + { running: false, topics: ['cp.status'] }, + { running: true, topics: [] }, + ])('reports idle/stopped Kafka unready without changing liveness', async (kafka) => { + const app = await fixture(kafka); + const response = await app.inject('/readyz'); + expect(response.statusCode).toBe(503); + expect(response.json()).toMatchObject({ ok: false, components: { kafka: { ok: false } } }); + }); + it('reports a gateway 500 as unavailable without exposing the raw error', async () => { + const app = await fixture({ + health: async () => { + throw new Error('upstream 500 private detail'); + }, + }); + const response = await app.inject('/readyz'); + expect(response.statusCode).toBe(503); + expect(response.json()).toMatchObject({ + ok: false, + components: { gateway: { ok: false, status: 'unavailable' } }, + }); + expect(response.body).not.toContain('private detail'); + }); + it('keeps Console available to inspect a degraded archive when gateway core is healthy', async () => { + const app = await fixture({ + health: async () => ({ + status: 'degraded', + components: { postgres: 'ok', redis: 'ok', clickhouse: 'error', ingestor: 'unknown' }, + }), + }); + const response = await app.inject('/readyz'); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ + ok: true, + components: { + gateway: { + ok: true, + status: 'degraded', + components: { clickhouse: 'error', ingestor: 'unknown' }, + }, + }, + }); + }); + it('does not call a failed gateway core ready', async () => { + const app = await fixture({ + health: async () => ({ + status: 'degraded', + components: { postgres: 'error', redis: 'ok', clickhouse: 'ok' }, + }), + }); + const response = await app.inject('/readyz'); + expect(response.statusCode).toBe(503); + expect(response.json()).toMatchObject({ + ok: false, + components: { gateway: { ok: false, status: 'degraded' } }, + }); + }); + it.each([ + { status: 'ok', components: { postgres: 'error', redis: 'ok' } }, + { status: 'ok', components: { postgres: 'ok', redis: 'error' } }, + { status: 'ok' }, + { status: 'ok', components: null }, + { status: 'ok', components: [] }, + { status: 'ok', components: { postgres: true, redis: 'ok' } }, + { status: 'ok', components: { postgres: 'ok' } }, + { status: 'degraded', components: { postgres: 'ok' } }, + { status: 'unknown', components: { postgres: 'ok', redis: 'ok' } }, + { components: { postgres: 'ok', redis: 'ok' } }, + null, + ])('fails closed for an unhealthy or malformed gateway core response: %j', async (body) => { + const app = await fixture({ health: async () => body }); + const response = await app.inject('/readyz'); + expect(response.statusCode).toBe(503); + expect(response.json()).toMatchObject({ + ok: false, + components: { gateway: { ok: false } }, + }); + }); + it('returns ready only for running subscribed Kafka and healthy gateway', async () => { + const response = await (await fixture()).inject('/readyz'); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ + ok: true, + components: { kafka: { ok: true }, gateway: { ok: true, status: 'ok' } }, + }); + }); + it('bounds an unresponsive gateway probe and aborts its transport', async () => { + let signal: AbortSignal | undefined; + const app = await fixture({ + health: async (candidate) => { + signal = candidate; + return new Promise(() => {}); + }, + }); + await app.ready(); + vi.useFakeTimers(); + const pending = app.inject('/readyz'); + await vi.advanceTimersByTimeAsync(1100); + const response = await pending; + expect(response.statusCode).toBe(503); + expect(signal?.aborted).toBe(true); + expect(response.json()).toMatchObject({ components: { gateway: { status: 'unavailable' } } }); + }); +}); diff --git a/apps/server/test/sys-status.test.ts b/apps/server/test/sys-status.test.ts new file mode 100644 index 0000000..dbed30e --- /dev/null +++ b/apps/server/test/sys-status.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest'; +import { registerSysStatusRoute } from '../src/routes/sys-status.js'; +import type { GatewayClient } from '../src/rest/gateway-client.js'; +import type { KafkaTail } from '../src/kafka/tail.js'; +import type { Broker } from '../src/broker/broker.js'; + +async function status(body: unknown, topics = ['cp.status']) { + let handler!: () => Promise; + const app = { + get: (_path: string, _opts: unknown, callback: typeof handler) => { + handler = callback; + }, + }; + await registerSysStatusRoute(app, { + gateway: { health: vi.fn().mockResolvedValue(body) } as unknown as GatewayClient, + kafka: { isRunning: () => true, subscribedTopics: () => topics } as unknown as KafkaTail, + broker: { connectionCount: () => 1 } as unknown as Broker, + startedAt: new Date('2026-10-13T10:00:00Z'), + }); + return await handler(); +} + +describe('system observation health', () => { + it('passes through the configured ClickHouse failure without treating degraded as healthy', async () => { + expect( + await status({ + status: 'degraded', + components: { + postgres: 'ok', + redis: 'ok', + clickhouse: 'error', + clickhouse_error_class: 'ConnectionError', + }, + }), + ).toMatchObject({ + gateway: { + ok: false, + detail: 'status=degraded', + components: { clickhouse: 'error', clickhouse_error_class: 'ConnectionError' }, + }, + }); + }); + + it('does not call an idle Kafka consumer healthy when no topics were subscribed', async () => { + expect(await status({ status: 'ok' }, [])).toMatchObject({ + kafka: { + ok: false, + consumer_running: true, + topics: [], + detail: 'consumer has no subscribed topics', + }, + }); + }); +}); diff --git a/apps/web/src/api/sys-client.ts b/apps/web/src/api/sys-client.ts index aafd65a..9d37254 100644 --- a/apps/web/src/api/sys-client.ts +++ b/apps/web/src/api/sys-client.ts @@ -13,7 +13,7 @@ export interface SysStatus { console: { uptime_seconds: number; started_at: string }; gateway: ComponentStatus & { version?: string; - components?: Record; + components?: Record; }; kafka: ComponentStatus & { topics?: string[]; consumer_running?: boolean }; connections: { websockets: number }; diff --git a/apps/web/src/api/transactions-client.ts b/apps/web/src/api/transactions-client.ts index 654abbd..664bb9d 100644 --- a/apps/web/src/api/transactions-client.ts +++ b/apps/web/src/api/transactions-client.ts @@ -53,6 +53,9 @@ export interface TransactionDetail { stop_reason: string | null; open: boolean; telemetry: TransactionTelemetry | null; + /** Archive readability only; older gateways omit these additive fields. */ + telemetry_state?: 'available' | 'unavailable' | 'unconfigured'; + telemetry_error?: 'ARCHIVE_UNAVAILABLE' | 'ARCHIVE_UNCONFIGURED' | null; } export interface MeterValueSample { diff --git a/apps/web/src/api/ws-client.ts b/apps/web/src/api/ws-client.ts index 5504e6a..f988fe3 100644 --- a/apps/web/src/api/ws-client.ts +++ b/apps/web/src/api/ws-client.ts @@ -70,6 +70,7 @@ interface PendingSubscribe { resolveHandle: (h: SubscriptionHandle) => void; rejectHandle: (err: Error) => void; inFlightId: string; + replaces?: ActiveSubscription; } interface ActiveSubscription { @@ -165,6 +166,7 @@ export class ConsoleClient { this.socket = socket; socket.onopen = () => { + if (this.socket !== socket) return; this.reconnectAttempt = 0; this.setStatus('open'); this.emitDiagnostics(); @@ -183,14 +185,17 @@ export class ConsoleClient { ); } for (const sub of this.active.values()) { + if ([...this.pendingSubscribes.values()].some((pending) => pending.replaces === sub)) + continue; const id = this.requestId(); this.pendingSubscribes.set(id, { query: sub.query, params: sub.params, handlers: sub.handlers, resolveHandle: () => undefined, - rejectHandle: () => undefined, + rejectHandle: (err) => sub.handlers.onError?.(err.message), inFlightId: id, + replaces: sub, }); socket.send( JSON.stringify({ @@ -205,6 +210,7 @@ export class ConsoleClient { }; socket.onmessage = (ev) => { + if (this.socket !== socket) return; let msg: ServerMessage; try { msg = serverMessage.parse(JSON.parse(ev.data)); @@ -216,6 +222,7 @@ export class ConsoleClient { }; socket.onclose = (ev) => { + if (this.socket !== socket) return; this.setStatus('closed'); this.lastCloseCode = ev.code; this.lastCloseReason = ev.reason || null; @@ -251,10 +258,25 @@ export class ConsoleClient { case 'subscription.accepted': { const pending = this.pendingSubscribes.get(msg.inReplyTo); if (!pending) return; - const handle: SubscriptionHandle = { + if ( + pending.replaces && + this.active.get(pending.replaces.handle.subscriptionId) !== pending.replaces + ) { + this.send({ + v: PROTOCOL_VERSION, + id: this.requestId(), + type: 'unsubscribe', + subscriptionId: msg.subscriptionId, + }); + this.pendingSubscribes.delete(msg.inReplyTo); + return; + } + const handle: SubscriptionHandle = pending.replaces?.handle ?? { subscriptionId: msg.subscriptionId, - unsubscribe: () => this.unsubscribe(msg.subscriptionId), + unsubscribe: () => this.unsubscribe(handle.subscriptionId), }; + if (pending.replaces) this.active.delete(handle.subscriptionId); + handle.subscriptionId = msg.subscriptionId; this.active.set(msg.subscriptionId, { handle, query: pending.query, @@ -282,6 +304,8 @@ export class ConsoleClient { return; } case 'error': { + if (msg.subscriptionId) + this.active.get(msg.subscriptionId)?.handlers.onError?.(msg.error.message); const inReplyTo = msg.inReplyTo; if (inReplyTo) { const pending = this.pendingSubscribes.get(inReplyTo); diff --git a/apps/web/src/components/CommandTranscript.tsx b/apps/web/src/components/CommandTranscript.tsx index edd4e67..220f642 100644 --- a/apps/web/src/components/CommandTranscript.tsx +++ b/apps/web/src/components/CommandTranscript.tsx @@ -37,6 +37,7 @@ const OUTCOME_LABEL: Record = { 'soft-reject': 'soft-reject', pending: 'sending…', error: 'transport error', + unknown: 'result unknown', }; const OUTCOME_VARIANT: Record< @@ -48,6 +49,7 @@ const OUTCOME_VARIANT: Record< 'soft-reject': 'warning', pending: 'muted', error: 'destructive', + unknown: 'warning', }; type Filter = 'all' | 'failed' | 'accepted'; diff --git a/apps/web/src/components/CommandsDrawer.tsx b/apps/web/src/components/CommandsDrawer.tsx index dce2723..dfa1ab9 100644 --- a/apps/web/src/components/CommandsDrawer.tsx +++ b/apps/web/src/components/CommandsDrawer.tsx @@ -26,6 +26,7 @@ import { } from '@/components/ui/sheet'; import { useToast } from '@/components/ui/toaster'; import { useConsoleClient } from '@/lib/ws-context'; +import { describeCommandResponse } from '@/lib/command-outcome'; interface CommandsDrawerProps { cpId: string; @@ -50,8 +51,23 @@ export function CommandsDrawer({ cpId, trigger }: CommandsDrawerProps) { setBusy(method); try { const result = await client.rpc(method, { cp_id: cpId, ...params }); - onResult?.(result); - toast({ title: method, description: 'Command accepted by charger' }); + const reply = describeCommandResponse(method, result); + if (reply.outcome === 'accepted') { + onResult?.(result); + toast({ + title: method, + description: `${reply.status}. Request acknowledged; check device state for completion.`, + }); + } else { + toast({ + variant: 'destructive', + title: method, + description: + reply.outcome === 'unknown' + ? 'Command result unknown. Check device state before retrying.' + : reply.status, + }); + } } catch (err) { toast({ variant: 'destructive', diff --git a/apps/web/src/components/ConnectorDataNotice.tsx b/apps/web/src/components/ConnectorDataNotice.tsx new file mode 100644 index 0000000..b51d054 --- /dev/null +++ b/apps/web/src/components/ConnectorDataNotice.tsx @@ -0,0 +1,50 @@ +import { withConnectorFreshness } from '@eveys-console/protocol'; +import type { ChargePointSummary } from '@eveys-console/protocol'; + +import { TimeAgo } from '@/components/TimeAgo'; + +function displayedConnectors(cp: ChargePointSummary) { + return withConnectorFreshness(cp).connectors.map((connector) => + connector.status_freshness === 'current' + ? connector + : { ...connector, reported_status: connector.status, status: 'Unknown' }, + ); +} + +export function physicalConnectors(cp: ChargePointSummary) { + return displayedConnectors(cp).filter((connector) => connector.connector_id > 0); +} + +export function controllerConnector(cp: ChargePointSummary) { + return displayedConnectors(cp).find((connector) => connector.connector_id === 0); +} + +export function ConnectorDataNotice({ cp }: { cp: ChargePointSummary }) { + const stale = withConnectorFreshness(cp).connectors.filter( + (connector) => connector.status_freshness !== 'current', + ); + if (cp.connectors_state !== 'unavailable' && stale.length === 0) return null; + return ( +

+ {stale.length > 0 ? ( + <> + Current connector status is unknown. Awaiting a newer status notification. Last reported:{' '} + {stale.map((connector) => `${connector.connector_id}: ${connector.status}`).join(', ')}. + + ) : ( + <> + Connector data unavailable. + {physicalConnectors(cp).length > 0 + ? ' Showing last known or live connector states.' + : ' Connector count is unknown.'} + + )} + {cp.connectors_last_successful_at ? ( + + {' '} + Last successful read: . + + ) : null} +

+ ); +} diff --git a/apps/web/src/components/DeviceEventsPanel.tsx b/apps/web/src/components/DeviceEventsPanel.tsx index b8a9774..aaeda1f 100644 --- a/apps/web/src/components/DeviceEventsPanel.tsx +++ b/apps/web/src/components/DeviceEventsPanel.tsx @@ -228,19 +228,8 @@ export function DeviceEventsPanel({ cpId }: DeviceEventsPanelProps) { return next; }); - if (sub.error) { - return ( - - - Live events - - -

Couldn't subscribe: {sub.error}

-
-
- ); - } - + const historyState = + sub.snapshot?.kind === 'device-events' ? sub.snapshot.history_state : undefined; const bufferedCount = pauseBufferRef.current.length; return ( @@ -351,13 +340,37 @@ export function DeviceEventsPanel({ cpId }: DeviceEventsPanelProps) { + {sub.error && ( +

+ Couldn't subscribe: {sub.error} + {events.length > 0 ? ' Showing last known events.' : ''} +

+ )} + {historyState === 'unavailable' && ( +

+ Event history unavailable. Live events may still arrive; the local archive could not be + read. +

+ )} + {historyState === 'unconfigured' && ( +

+ Event history is not configured. Showing live events only. +

+ )} {events.length === 0 ? (
- - Waiting for events… + {sub.loading ? ( + <> + Loading events… + + ) : historyState === 'available' ? ( + 'No recorded events in the loaded history. Waiting for live events…' + ) : ( + 'Waiting for events…' + )}
) : visible.length === 0 ? (

diff --git a/apps/web/src/components/OcppLogPanel.tsx b/apps/web/src/components/OcppLogPanel.tsx index 5adcd6d..966c34f 100644 --- a/apps/web/src/components/OcppLogPanel.tsx +++ b/apps/web/src/components/OcppLogPanel.tsx @@ -46,6 +46,7 @@ export function OcppLogPanel({ cpId }: OcppLogPanelProps) { const [rangeMinutes, setRangeMinutes] = useState(60); const [direction, setDirection] = useState('all'); const [actionFilter, setActionFilter] = useState(''); + const [committedAction, setCommittedAction] = useState(''); const [nonce, setNonce] = useState(0); // bump to force a refetch const [state, setState] = useState< | { phase: 'loading' } @@ -53,24 +54,19 @@ export function OcppLogPanel({ cpId }: OcppLogPanelProps) { | { phase: 'error'; detail: string } >({ phase: 'loading' }); - const window = useMemo(() => { - const to = new Date(); - const from = new Date(to.getTime() - rangeMinutes * 60 * 1000); - return { from: from.toISOString(), to: to.toISOString() }; - }, [rangeMinutes]); - useEffect(() => { if (!token) return; let cancelled = false; setState({ phase: 'loading' }); + const to = new Date(); + const from = new Date(to.getTime() - rangeMinutes * 60 * 1000); const params: Parameters[2] = { - from: window.from, - to: window.to, + from: from.toISOString(), + to: to.toISOString(), limit: 500, }; if (direction !== 'all') params.direction = direction; - const trimmedAction = actionFilter.trim(); - if (trimmedAction) params.action = trimmedAction; + if (committedAction) params.action = committedAction; fetchCpFrames(token, cpId, params) .then((data) => { if (!cancelled) setState({ phase: 'ok', data }); @@ -85,11 +81,7 @@ export function OcppLogPanel({ cpId }: OcppLogPanelProps) { return () => { cancelled = true; }; - // actionFilter is intentionally committed here on each render to - // keep the wiring simple — the input is debounced below by only - // refetching on blur/Enter, not every keystroke. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cpId, token, window, direction, nonce]); + }, [cpId, token, rangeMinutes, direction, committedAction, nonce]); return ( @@ -127,7 +119,7 @@ export function OcppLogPanel({ cpId }: OcppLogPanelProps) { onDirectionChange={setDirection} actionFilter={actionFilter} onActionFilterChange={setActionFilter} - onCommitActionFilter={() => setNonce((n) => n + 1)} + onCommitActionFilter={() => setCommittedAction(actionFilter.trim())} /> diff --git a/apps/web/src/components/ServiceStatusPills.tsx b/apps/web/src/components/ServiceStatusPills.tsx index a02d7d8..e96cf0a 100644 --- a/apps/web/src/components/ServiceStatusPills.tsx +++ b/apps/web/src/components/ServiceStatusPills.tsx @@ -28,7 +28,7 @@ function gatewayPill(s: SysStatus): Pill { return { key: 'gateway', label: 'Gateway', - tone: 'destructive', + tone: g.detail === 'status=degraded' ? 'warning' : 'destructive', hint: g.detail ?? 'gateway probe failed', }; } @@ -40,12 +40,22 @@ function componentPills(s: SysStatus): Pill[] { const out: Pill[] = []; const comps = s.gateway.components ?? {}; for (const [name, status] of Object.entries(comps)) { + if (name.endsWith('_error_class') || typeof status !== 'string') continue; const ok = status === 'ok'; out.push({ key: `gw-${name}`, label: prettyComponentName(name), - tone: ok ? 'success' : 'destructive', - hint: ok ? 'ok' : status, + tone: ok + ? 'success' + : status === 'unconfigured' || status === 'unknown' + ? 'warning' + : 'destructive', + hint: + name === 'ingestor' && status === 'unknown' + ? 'unknown — ingestion progress is not observed' + : ok + ? 'ok' + : status, }); } return out; @@ -73,6 +83,7 @@ function kafkaPill(s: SysStatus): Pill { } function prettyComponentName(name: string): string { + if (name === 'clickhouse') return 'ClickHouse'; // The gateway emits component keys in lowercase ("postgres", "redis"). // Capitalising matches how the rest of the row reads ("Console", // "Gateway", "Kafka"). No other transformation needed. diff --git a/apps/web/src/hooks/use-command-transcript.ts b/apps/web/src/hooks/use-command-transcript.ts index 28de50c..529024d 100644 --- a/apps/web/src/hooks/use-command-transcript.ts +++ b/apps/web/src/hooks/use-command-transcript.ts @@ -21,6 +21,7 @@ import { useCallback, useSyncExternalStore } from 'react'; import type { ConsoleClient } from '@/api/ws-client'; +import { describeCommandResponse } from '@/lib/command-outcome'; const RING_CAP = 200; @@ -35,6 +36,7 @@ export type TranscriptOutcome = | 'rejected' | 'soft-reject' // Occupied / Unavailable / Faulted / NotImplemented / NotSupported / Failed | 'pending' + | 'unknown' | 'error'; export interface TranscriptEntry { @@ -229,9 +231,9 @@ export function useCommandTranscript( try { const response = await client.rpc(method, request); const elapsedMs = Math.round(performance.now() - startMs); - const { status, outcome } = describeResponse(response); + const { status, outcome } = describeCommandResponse(method, response); store.complete(id, method, { phase: 'ok', response, status, outcome, elapsedMs }); - onResult?.(response); + if (outcome === 'accepted') onResult?.(response); } catch (err) { const elapsedMs = Math.round(performance.now() - startMs); const message = err instanceof Error ? err.message : 'rpc failed'; @@ -262,29 +264,3 @@ export function useCommandTranscript( resume, }; } - -/** Map a charger response (shape varies per command) to a short - * human-readable status + coarse outcome bucket. Falls back to - * "OK" / accepted for shapes we don't recognise (e.g. Unlock's - * Unlocked, GetConfiguration's keys list). The full response is - * always available on the entry; this is just the colour cue. */ -function describeResponse(response: unknown): { status: string; outcome: TranscriptOutcome } { - if (response == null || typeof response !== 'object') { - return { status: 'OK', outcome: 'accepted' }; - } - const r = response as Record; - const raw = r.status; - if (typeof raw !== 'string') { - return { status: 'OK', outcome: 'accepted' }; - } - const lower = raw.toLowerCase(); - if (lower === 'accepted' || lower === 'unlocked') { - return { status: raw, outcome: 'accepted' }; - } - if (lower === 'rejected' || lower === 'unknowntransaction') { - return { status: raw, outcome: 'rejected' }; - } - // Occupied / Unavailable / Faulted / NotImplemented / NotSupported / Failed - // — soft-rejects that mean "the charger said no, but not a hard error". - return { status: raw, outcome: 'soft-reject' }; -} diff --git a/apps/web/src/hooks/use-subscription.ts b/apps/web/src/hooks/use-subscription.ts index ee55ba1..d381666 100644 --- a/apps/web/src/hooks/use-subscription.ts +++ b/apps/web/src/hooks/use-subscription.ts @@ -1,10 +1,12 @@ import { useEffect, useState } from 'react'; -import type { - DeltaForQuery, - QueryName, - QueryParams, - SnapshotForQuery, +import { + applySubscriptionDelta, + retainUnavailableConnectors, + type DeltaForQuery, + type QueryName, + type QueryParams, + type SnapshotForQuery, } from '@eveys-console/protocol'; import { useConsoleClient } from '../lib/ws-context'; @@ -22,33 +24,82 @@ export function useSubscription { const { client, status } = useConsoleClient(); - const [state, setState] = useState>({ + const paramsKey = JSON.stringify(params); + const scopeKey = `${query}:${paramsKey}`; + const emptyState: SubscriptionState = { loading: true, error: null, snapshot: null, lastDelta: null, cursor: null, - }); + }; + const [scoped, setScoped] = useState({ client, scopeKey, state: emptyState }); useEffect(() => { - if (status !== 'open') return; + setScoped((prev) => { + if (prev.client === client && prev.scopeKey === scopeKey) return prev; + // No render is needed when the old scope is already empty. This also + // avoids a reset-driven loop in consumers whose client is not stable. + if ( + prev.scopeKey === scopeKey && + !prev.state.snapshot && + !prev.state.error && + !prev.state.lastDelta && + !prev.state.cursor + ) + return prev; + return { client, scopeKey, state: emptyState }; + }); let unsub: (() => void) | null = null; let cancelled = false; + const setState = (update: (prev: SubscriptionState) => SubscriptionState) => { + setScoped((prev) => ({ + client, + scopeKey, + state: update( + prev.client === client && prev.scopeKey === scopeKey ? prev.state : emptyState, + ), + })); + }; void client .subscribe(query, params, { onSnapshot: (snapshot, cursor) => { if (cancelled) return; + if ( + snapshot.kind !== query || + (snapshot.kind === 'charge-point' && snapshot.row.cp_id !== params.cp_id) + ) + return; setState((prev) => ({ - ...prev, loading: false, - snapshot: snapshot as S, + error: null, + lastDelta: null, + snapshot: retainUnavailableConnectors(prev.snapshot, snapshot) as S, cursor, })); }, onDelta: (delta, cursor) => { if (cancelled) return; - setState((prev) => ({ ...prev, lastDelta: delta as D, cursor })); + if ( + delta.kind !== query || + (delta.kind === 'charge-point' && delta.row.cp_id !== params.cp_id) + ) + return; + setState((prev) => { + const snapshot = applySubscriptionDelta(prev.snapshot, delta) as S | null; + // Pages still exposing lastDelta receive the merged row as well. + let mergedDelta: DeltaForQuery = delta; + if (delta.kind === 'charge-point' && snapshot?.kind === 'charge-point') + mergedDelta = { ...delta, row: snapshot.row }; + if (delta.kind === 'charge-points' && delta.row && snapshot?.kind === 'charge-points') { + mergedDelta = { + ...delta, + row: snapshot.rows.find((row) => row.cp_id === delta.row?.cp_id) ?? delta.row, + }; + } + return { ...prev, error: null, snapshot, lastDelta: mergedDelta as D, cursor }; + }); }, onError: (msg) => { if (cancelled) return; @@ -56,6 +107,10 @@ export function useSubscription { + if (cancelled) { + handle.unsubscribe(); + return; + } unsub = handle.unsubscribe; }) .catch((err: unknown) => { @@ -72,7 +127,14 @@ export function useSubscription c.status === 'Faulted'); + const faulted = cp.connectors.some( + (c) => + c.status_freshness !== 'stale' && + c.status_freshness !== 'unknown' && + c.status === 'Faulted', + ); if (faulted) { alerts.push({ id: `charger-faulted:${cp.cp_id}`, @@ -180,6 +185,7 @@ export function computeAlerts(input: ComputeAlertsInput): Alert[] { for (const cp of cps) { for (const conn of cp.connectors) { + if (conn.status_freshness === 'stale' || conn.status_freshness === 'unknown') continue; if (!conn.error_code || conn.error_code === NO_ERROR) continue; // If the connector is also Faulted, the charger-faulted critical // already covers it — we don't want one connector producing both diff --git a/apps/web/src/lib/charger-state.ts b/apps/web/src/lib/charger-state.ts index 47ca54c..f5960e3 100644 --- a/apps/web/src/lib/charger-state.ts +++ b/apps/web/src/lib/charger-state.ts @@ -15,6 +15,7 @@ // and another Available, in which case RemoteStart is still useful // (different connector) and RemoteStop is meaningful too. +import { withConnectorFreshness } from '@eveys-console/protocol'; import type { ChargePointSummary } from '@eveys-console/protocol'; export const ACTIVE_SESSION_STATUSES = new Set([ @@ -30,21 +31,23 @@ export const STARTABLE_STATUSES = new Set(['Available', 'Preparing']); type Connector = ChargePointSummary['connectors'][number]; function isActiveSession(c: Connector): boolean { - return ACTIVE_SESSION_STATUSES.has(c.status); + return ( + c.connector_id > 0 && c.status_freshness === 'current' && ACTIVE_SESSION_STATUSES.has(c.status) + ); } function isStartable(c: Connector): boolean { - return STARTABLE_STATUSES.has(c.status); + return c.connector_id > 0 && c.status_freshness === 'current' && STARTABLE_STATUSES.has(c.status); } /** Any connector currently inside a session. */ export function hasActiveSession(cp: ChargePointSummary): boolean { - return cp.connectors.some(isActiveSession); + return withConnectorFreshness(cp).connectors.some(isActiveSession); } /** Any connector currently free to start a session on. */ export function hasStartableConnector(cp: ChargePointSummary): boolean { - return cp.connectors.some(isStartable); + return withConnectorFreshness(cp).connectors.some(isStartable); } export interface CommandAvailability { diff --git a/apps/web/src/lib/command-outcome.ts b/apps/web/src/lib/command-outcome.ts new file mode 100644 index 0000000..7b1a3e2 --- /dev/null +++ b/apps/web/src/lib/command-outcome.ts @@ -0,0 +1,74 @@ +import type { TranscriptOutcome } from '@/hooks/use-command-transcript'; + +const ACCEPTED_STATUSES: Record = { + 'remote-start': ['Accepted'], + 'remote-stop': ['Accepted'], + reset: ['Accepted'], + 'trigger-message': ['Accepted'], + 'unlock-connector': ['Unlocked'], + 'change-configuration': ['Accepted', 'RebootRequired'], + 'clear-cache': ['Accepted'], + 'reserve-now': ['Accepted'], + 'cancel-reservation': ['Accepted'], + 'data-transfer': ['Accepted'], + 'get-log': ['Accepted'], +}; + +// A reply proves only the command's response, never physical session completion. +export function describeCommandResponse( + method: string, + response: unknown, +): { status: string; outcome: TranscriptOutcome } { + const unknown = { status: 'Result unknown', outcome: 'unknown' as const }; + if (!response || typeof response !== 'object' || Array.isArray(response)) return unknown; + const r = response as Record; + if (method === 'get-configuration') { + const keys = r.configuration_key; + const missing = r.unknown_key; + if ( + !Array.isArray(keys) || + !Array.isArray(missing) || + !missing.every((key) => typeof key === 'string') + ) + return unknown; + if ( + !keys.every( + (key) => + key && + typeof key === 'object' && + typeof key.key === 'string' && + typeof key.readonly === 'boolean' && + (key.value === undefined || typeof key.value === 'string'), + ) + ) + return unknown; + return { status: 'Configuration received', outcome: 'accepted' }; + } + if (method === 'get-diagnostics') { + if (typeof r.file_name !== 'string') return unknown; + return r.file_name + ? { status: 'Diagnostics file announced', outcome: 'accepted' } + : { status: 'No diagnostics file available', outcome: 'soft-reject' }; + } + const raw = r.status; + if (typeof raw !== 'string') return unknown; + if (Object.hasOwn(ACCEPTED_STATUSES, method) && ACCEPTED_STATUSES[method]?.includes(raw)) + return { status: raw, outcome: 'accepted' }; + if (raw === 'Rejected' || raw === 'UnknownTransaction') + return { status: raw, outcome: 'rejected' }; + if ( + [ + 'Occupied', + 'Unavailable', + 'Faulted', + 'NotImplemented', + 'NotSupported', + 'Failed', + 'UnlockFailed', + 'UnknownMessageId', + 'UnknownVendorId', + ].includes(raw) + ) + return { status: raw, outcome: 'soft-reject' }; + return unknown; +} diff --git a/apps/web/src/lib/fault.ts b/apps/web/src/lib/fault.ts index 40da2ce..cbd1d41 100644 --- a/apps/web/src/lib/fault.ts +++ b/apps/web/src/lib/fault.ts @@ -23,6 +23,8 @@ export type FaultLevel = 'fault' | 'advisory' | 'ok'; type Connector = ChargePointSummary['connectors'][number]; export function connectorFaultLevel(c: Connector): FaultLevel { + // Retained reports remain visible in the data notice, not as current faults. + if (c.status_freshness === 'stale' || c.status_freshness === 'unknown') return 'ok'; if (c.status === 'Faulted') return 'fault'; if (c.error_code && c.error_code !== NO_ERROR) return 'advisory'; return 'ok'; diff --git a/apps/web/src/pages/ChargerDetailPage.tsx b/apps/web/src/pages/ChargerDetailPage.tsx index b576ece..0b951fc 100644 --- a/apps/web/src/pages/ChargerDetailPage.tsx +++ b/apps/web/src/pages/ChargerDetailPage.tsx @@ -2,9 +2,14 @@ import { useParams } from '@tanstack/react-router'; import { AlertTriangle, Loader2 } from 'lucide-react'; import { useMemo } from 'react'; -import type { ChargePointSummary } from '@eveys-console/protocol'; +import { mergeChargePoint, type ChargePointSummary } from '@eveys-console/protocol'; import { ChargerSpecChips } from '@/components/ChargerSpecChips'; +import { + ConnectorDataNotice, + controllerConnector, + physicalConnectors, +} from '@/components/ConnectorDataNotice'; import { TimeAgo } from '@/components/TimeAgo'; import { Uptime } from '@/components/Uptime'; import { UptimeChip } from '@/components/UptimeChip'; @@ -40,26 +45,32 @@ export function ChargerDetailPage() { const isPhone = useIsBelow('sm'); const sub = useSubscription('charge-point', { cp_id: cpId }); - if (sub.error) { - return ( - - Couldn't load {cpId} - {sub.error} - - ); - } // Merge the most recent delta into the rendered row so a // BootNotification or StatusNotification visibly updates the page // without waiting for the next snapshot refresh. The resolver // re-fetches the full row from the gateway on each `cp.boot` / // `cp.status` event (see apps/server/src/broker/queries.ts). const cp = useMemo(() => { - if (!sub.snapshot || sub.snapshot.kind !== 'charge-point') return null; - if (sub.lastDelta && sub.lastDelta.kind === 'charge-point') { - return sub.lastDelta.row; + if (!sub.snapshot || sub.snapshot.kind !== 'charge-point' || sub.snapshot.row.cp_id !== cpId) + return null; + if ( + sub.lastDelta && + sub.lastDelta.kind === 'charge-point' && + sub.lastDelta.row.cp_id === cpId + ) { + return mergeChargePoint(sub.snapshot.row, sub.lastDelta.row); } return sub.snapshot.row; - }, [sub.snapshot, sub.lastDelta]); + }, [sub.snapshot, sub.lastDelta, cpId]); + + if (sub.error && !cp) { + return ( + + Couldn't load {cpId} + {sub.error} + + ); + } if (sub.loading || !cp) { return ( @@ -72,7 +83,14 @@ export function ChargerDetailPage() { return (

+ {sub.error ? ( + + Live data unavailable + {sub.error} + + ) : null}
+ @@ -84,7 +102,9 @@ export function ChargerDetailPage() { Connectors - {cp.connectors.length} + {cp.connectors_state === 'unavailable' && physicalConnectors(cp).length === 0 + ? '—' + : physicalConnectors(cp).length} @@ -117,10 +137,12 @@ export function ChargerDetailPage() { Connectors - {isPhone ? ( - + {cp.connectors_state === 'unavailable' && physicalConnectors(cp).length === 0 ? ( + + ) : isPhone ? ( + ) : ( - + )} @@ -169,13 +191,19 @@ function FaultBanner({ cp }: { cp: ChargePointSummary }) { if (connectors.length === 0) return null; const overall = chargePointFaultLevel(cp); const variant = overall === 'fault' ? 'destructive' : 'default'; + const physicalCount = connectors.filter((connector) => connector.connector_id > 0).length; + const hasController = connectors.some((connector) => connector.connector_id === 0); + const affected = + physicalCount > 0 + ? `${physicalCount} connector${physicalCount === 1 ? '' : 's'}${hasController ? ' and controller' : ''}` + : 'controller'; return ( {overall === 'fault' - ? `Faulted — ${connectors.length} connector${connectors.length === 1 ? '' : 's'}` - : `Advisory — ${connectors.length} connector${connectors.length === 1 ? '' : 's'} reporting an error`} + ? `Faulted — ${affected}` + : `Advisory — ${affected} reporting an error`} {connectors.map((c) => { @@ -225,6 +253,7 @@ function FaultBanner({ cp }: { cp: ChargePointSummary }) { } function Header({ cp }: { cp: ChargePointSummary }) { + const controller = controllerConnector(cp); // Title row with metadata under it, status badges below the title // — wraps cleanly at any width without the right edge competing // with the title. @@ -254,6 +283,19 @@ function Header({ cp }: { cp: ChargePointSummary }) { last_status: {cp.last_status ?? '—'} + {controller ? ( + + controller: {controller.status} + + ) : null} {cp.online && cp.last_boot_at ? ( (sub.snapshot.rows.map((r) => [r.cp_id, r])); if (sub.lastDelta && sub.lastDelta.kind === 'charge-points') { const d = sub.lastDelta; - if (d.op === 'upsert' && d.row) byId.set(d.row.cp_id, d.row); + if (d.op === 'upsert' && d.row) + byId.set(d.row.cp_id, mergeChargePoint(byId.get(d.row.cp_id), d.row)); if (d.op === 'remove' && d.cp_id) byId.delete(d.cp_id); } return { @@ -190,7 +192,7 @@ export function FleetPage() { return allRows.filter((r) => chargePointFaultLevel(r) !== 'ok'); }, [allRows, faultsOnly]); - if (sub.error) { + if (sub.error && !sub.snapshot) { return ( Couldn't load charge points @@ -209,6 +211,12 @@ export function FleetPage() { return (
+ {sub.error ? ( + + Live data unavailable + {sub.error} + + ) : null}

@@ -578,7 +586,8 @@ function FleetTableRow({ - + +
@@ -603,7 +612,11 @@ function FleetTableRow({ {isOpen ? ( - + {row.connectors_state === 'unavailable' && physicalConnectors(row).length === 0 ? ( + + ) : ( + + )} ) : null} @@ -649,11 +662,14 @@ function FleetCard({ row }: { row: ChargePointSummary }) {
- {row.connectors.length === 0 ? ( - no connectors reported + {physicalConnectors(row).length === 0 ? ( + row.connectors_state === 'unavailable' ? null : ( + no connectors reported + ) ) : ( - row.connectors.map((c) => ) + physicalConnectors(row).map((c) => ) )} +
diff --git a/apps/web/src/pages/SystemPage.tsx b/apps/web/src/pages/SystemPage.tsx index be60315..9954863 100644 --- a/apps/web/src/pages/SystemPage.tsx +++ b/apps/web/src/pages/SystemPage.tsx @@ -175,14 +175,14 @@ export function SystemPage() { /> 0 ? 'success' : 'default'} to="/inspect/transactions" diff --git a/apps/web/src/pages/TransactionDetailPage.tsx b/apps/web/src/pages/TransactionDetailPage.tsx index d4fc5f1..cb1aee8 100644 --- a/apps/web/src/pages/TransactionDetailPage.tsx +++ b/apps/web/src/pages/TransactionDetailPage.tsx @@ -50,6 +50,32 @@ export function TransactionDetailPage() { }); const tx = txQuery.data; + const telemetryUnavailable = + tx?.telemetry_state === 'unavailable' || tx?.telemetry_state === 'unconfigured'; + const lastTelemetry = useRef<{ + txId: number; + cpId: string; + connectorId: number; + data: TransactionDetail['telemetry']; + } | null>(null); + if ( + lastTelemetry.current && + (lastTelemetry.current.txId !== txId || + (tx && + (lastTelemetry.current.cpId !== tx.cp_id || + lastTelemetry.current.connectorId !== tx.connector_id))) + ) { + lastTelemetry.current = null; + } + if (tx && !telemetryUnavailable) { + lastTelemetry.current = { + txId, + cpId: tx.cp_id, + connectorId: tx.connector_id, + data: tx.telemetry, + }; + } + const telemetry = tx?.telemetry ?? (telemetryUnavailable ? lastTelemetry.current?.data : null); // Window for the curve queries. For a CLOSED tx the window is fixed // (`from`…`stopped_at`); for an OPEN tx we want the upper bound to // slide forward on each refetch. @@ -123,8 +149,8 @@ export function TransactionDetailPage() { // on the Kafka tail. const livePhases = useMemo(() => derivePhaseSnapshots(liveSamples), [liveSamples]); const mergedPhases = useMemo( - () => mergePhases(tx?.telemetry?.phases ?? null, livePhases), - [tx?.telemetry?.phases, livePhases], + () => mergePhases(telemetry?.phases ?? null, livePhases), + [telemetry?.phases, livePhases], ); // Live-refresh the two curves the moment a MeterValues arrives. @@ -169,7 +195,7 @@ export function TransactionDetailPage() { ); } - if (txQuery.error || !tx) { + if (!tx) { return ( @@ -184,16 +210,43 @@ export function TransactionDetailPage() { return (
+ {txQuery.error ? ( + + Couldn't refresh transaction {txId} + + Showing the previously loaded transaction.{' '} + {txQuery.error instanceof Error ? txQuery.error.message : 'request failed'} + + + ) : null} + {telemetryUnavailable ? ( + + + {tx.telemetry_state === 'unconfigured' + ? 'Telemetry archive is not configured' + : 'Archived telemetry unavailable'} + + + The transaction record remains available.{' '} + {telemetry + ? 'Showing previously loaded readings.' + : 'Archived readings could not be loaded.'}{' '} + Live readings may still arrive; this does not confirm archive completeness. + + + ) : null} - - {tx.telemetry?.soc.last != null ? : null} + + {telemetry?.soc.last != null ? : null}
); @@ -247,22 +300,31 @@ interface ChartCardProps { children: React.ReactNode; empty: boolean; loading: boolean; + error: unknown; } -function ChartCard({ title, children, empty, loading }: ChartCardProps) { +function ChartCard({ title, children, empty, loading, error }: ChartCardProps) { return ( {title} + {error ? ( +

+ Couldn't load samples: {error instanceof Error ? error.message : 'request failed'}. + {!empty ? ' Showing previously loaded or live samples.' : ''} +

+ ) : null} {loading ? (
Loading…
) : empty ? ( -

No samples in this window.

+ error ? null : ( +

No samples in this window.

+ ) ) : ( children )} @@ -277,11 +339,19 @@ function ChartCard({ title, children, empty, loading }: ChartCardProps) { // become the 'sum' line. We don't synthesize a sum from the per-phase // samples — chargers' clocks aren't aligned tightly enough for that to // be meaningful at sub-second resolution. -function PowerChart({ samples, loading }: { samples: MeterValueSample[]; loading: boolean }) { +function PowerChart({ + samples, + loading, + error, +}: { + samples: MeterValueSample[]; + loading: boolean; + error: unknown; +}) { const { data, phases, hasSum } = useMemo(() => buildPowerSeries(samples), [samples]); const empty = data.length === 0; return ( - + @@ -330,11 +400,19 @@ function PowerChart({ samples, loading }: { samples: MeterValueSample[]; loading // Import.Register is reported by the charger as a single (typically // Wh) value per sample. We render it as a step-monotone line because // it's monotone non-decreasing. -function EnergyChart({ samples, loading }: { samples: MeterValueSample[]; loading: boolean }) { +function EnergyChart({ + samples, + loading, + error, +}: { + samples: MeterValueSample[]; + loading: boolean; + error: unknown; +}) { const data = useMemo(() => buildEnergySeries(samples), [samples]); const empty = data.length === 0; return ( - + @@ -363,7 +441,13 @@ function EnergyChart({ samples, loading }: { samples: MeterValueSample[]; loadin ); } -function PhasesCard({ phases }: { phases: Record | null }) { +function PhasesCard({ + phases, + unavailable, +}: { + phases: Record | null; + unavailable: boolean; +}) { const entries = phases ? Object.entries(phases) : []; return ( @@ -372,7 +456,11 @@ function PhasesCard({ phases }: { phases: Record | null } {entries.length === 0 ? ( -

No phase telemetry available.

+

+ {unavailable + ? 'Archived phase readings could not be loaded.' + : 'No phase telemetry available.'} +

) : (
    {entries.map(([phase, p]) => ( diff --git a/apps/web/test/ChargerDetailPage.test.tsx b/apps/web/test/ChargerDetailPage.test.tsx index d96f320..213f8c6 100644 --- a/apps/web/test/ChargerDetailPage.test.tsx +++ b/apps/web/test/ChargerDetailPage.test.tsx @@ -50,6 +50,9 @@ vi.mock('@/components/StatisticsCard', () => ({ vi.mock('@/components/TransactionsHistory', () => ({ TransactionsHistory: () =>
    , })); +vi.mock('@/api/uptime-client', () => ({ + fetchCpUptime: vi.fn().mockRejectedValue(new Error('isolated uptime unavailable')), +})); let isPhone = false; vi.mock('@/lib/use-breakpoint', () => ({ @@ -91,7 +94,12 @@ function baseCp(over: Partial = {}): ChargePointSummary { last_heartbeat_at: '2026-05-10T11:48:00+00:00', last_status: 'Available', connectors: [ - { connector_id: 1, status: 'Available', error_code: 'NoError', last_changed_at: null }, + { + connector_id: 1, + status: 'Available', + error_code: 'NoError', + last_changed_at: '2026-05-10T11:48:00Z', + }, ], ...over, }; @@ -130,6 +138,21 @@ afterEach(() => { }); describe('ChargerDetailPage — snapshot / lastDelta merge', () => { + it('never renders another charger delta on this route', () => { + nextSubResult = { + snapshot: { + kind: 'charge-point', + row: baseCp({ cp_id: 'cp_TEST', firmware_version: 'right' }), + }, + lastDelta: { + kind: 'charge-point', + row: baseCp({ cp_id: 'OTHER', firmware_version: 'wrong' }), + }, + }; + renderPage(); + expect(screen.getByText(/firmware right/)).toBeInTheDocument(); + expect(screen.queryByText(/firmware wrong/)).toBeNull(); + }); // Regression: the page used to render `sub.snapshot.row` directly, // so a fresh cp.boot / cp.status delta never showed up until the // next snapshot refresh. The detail page now merges `lastDelta` in. @@ -160,6 +183,101 @@ describe('ChargerDetailPage — Commands tab', () => { }); }); +describe('ChargerDetailPage — data availability and connector identity', () => { + it('does not present a pre-boot controller report as current Available', () => { + nextSubResult = { + snapshot: { + kind: 'charge-point', + row: baseCp({ + connectors: [ + { + connector_id: 0, + status: 'Available', + error_code: 'NoError', + last_changed_at: '2026-05-10T09:59:00Z', + }, + ], + }), + }, + }; + renderPage(); + expect(screen.getByText('controller: Unknown')).toBeInTheDocument(); + expect(screen.queryByText('controller: Available')).toBeNull(); + }); + it('describes connector zero faults as a controller fault', () => { + nextSubResult = { + snapshot: { + kind: 'charge-point', + row: baseCp({ + connectors: [ + { + connector_id: 0, + status: 'Faulted', + error_code: 'InternalError', + last_changed_at: '2026-05-10T11:48:00Z', + }, + ], + }), + }, + }; + renderPage(); + expect(screen.getByText('Faulted — controller')).toBeInTheDocument(); + expect(screen.queryByText('Faulted — 1 connector')).toBeNull(); + }); + it('keeps the charger visible after a refresh failure', () => { + nextSubResult = { + error: 'Gateway refresh failed. Showing last known data.', + snapshot: { kind: 'charge-point', row: baseCp() }, + }; + renderPage(); + expect(screen.getByText(/firmware 1\.0\.0/)).toBeInTheDocument(); + expect(screen.getByText(/Showing last known data/)).toBeInTheDocument(); + }); + + it('shows unavailable connector data rather than a confirmed empty state', async () => { + const user = userEvent.setup(); + nextSubResult = { + snapshot: { + kind: 'charge-point', + row: baseCp({ + connectors: [], + connectors_state: 'unavailable', + connectors_source: 'clickhouse', + connectors_error: 'query_failed', + connectors_last_successful_at: null, + }), + }, + }; + renderPage(); + expect(screen.getByTestId('detail-tab-connectors')).toHaveTextContent('—'); + await user.click(screen.getByTestId('detail-tab-connectors')); + expect(screen.getAllByText(/Connector data unavailable/).length).toBeGreaterThan(0); + expect(screen.queryByText('No connectors reported.')).toBeNull(); + }); + + it('counts only physical connectors and displays connector zero as the controller', async () => { + const user = userEvent.setup(); + nextSubResult = { + snapshot: { + kind: 'charge-point', + row: baseCp({ + connectors: [0, 1, 2].map((connector_id) => ({ + connector_id, + status: connector_id === 0 ? 'Available' : 'Charging', + error_code: null, + last_changed_at: '2026-05-10T11:48:00Z', + })), + }), + }, + }; + renderPage(); + expect(screen.getByTestId('detail-tab-connectors')).toHaveTextContent('Connectors2'); + expect(screen.getByText('controller: Available')).toBeInTheDocument(); + await user.click(screen.getByTestId('detail-tab-connectors')); + expect(screen.getAllByRole('row')).toHaveLength(3); + }); +}); + describe('ChargerDetailPage — OCPP version badge', () => { it('renders an OCPP version badge when the row carries ocpp_version', () => { nextSubResult = { diff --git a/apps/web/test/CommandsDrawer.test.tsx b/apps/web/test/CommandsDrawer.test.tsx index 04538d6..71e266e 100644 --- a/apps/web/test/CommandsDrawer.test.tsx +++ b/apps/web/test/CommandsDrawer.test.tsx @@ -58,6 +58,25 @@ async function openDrawer() { } describe('CommandsDrawer', () => { + it.each([ + { reply: null, copy: 'Command result unknown' }, + { reply: { status: 'Rejected' }, copy: 'Rejected' }, + ])('never toasts acceptance for $copy', async ({ reply, copy }) => { + rpc.mockResolvedValueOnce(reply); + const user = await openDrawer(); + const card = screen.getByText('RemoteStop').closest('[data-testid="cmd-card"]')!; + await user.type(within(card).getByPlaceholderText('0'), '42'); + await user.click(within(card).getByRole('button', { name: /^Send$/i })); + expect(toast).toHaveBeenCalledWith( + expect.objectContaining({ + variant: 'destructive', + description: expect.stringContaining(copy), + }), + ); + expect(toast).not.toHaveBeenCalledWith( + expect.objectContaining({ description: 'Command accepted by charger' }), + ); + }); it('opens on trigger click and renders all section headings', async () => { await openDrawer(); expect(screen.getByRole('heading', { name: /diagnostics/i })).toBeInTheDocument(); diff --git a/apps/web/test/ConnectorFreshness.test.tsx b/apps/web/test/ConnectorFreshness.test.tsx new file mode 100644 index 0000000..019048c --- /dev/null +++ b/apps/web/test/ConnectorFreshness.test.tsx @@ -0,0 +1,68 @@ +import { cleanup, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { withConnectorFreshness } from '@eveys-console/protocol'; +import type { ChargePointSummary } from '@eveys-console/protocol'; +import { chargePointFaultLevel, faultedConnectors } from '@/lib/fault'; +import { computeAlerts } from '@/lib/alerts'; +import { ConnectorDataNotice, physicalConnectors } from '@/components/ConnectorDataNotice'; +import { canRemoteStart, canRemoteStop } from '@/lib/charger-state'; + +afterEach(cleanup); +const cp = (status = 'Charging'): ChargePointSummary => ({ + cp_id: 'CP_TEST', + online: true, + pod_id: 'test', + vendor: null, + model: null, + firmware_version: null, + serial_number: null, + last_status: 'Available', + last_boot_at: '2026-10-13T09:12:44Z', + last_heartbeat_at: '2026-10-13T14:00:00Z', + connectors_state: 'available', + connectors: [ + { + connector_id: 0, + status: 'Available', + error_code: 'NoError', + last_changed_at: '2026-10-13T09:13:00Z', + }, + { connector_id: 1, status, error_code: 'NoError', last_changed_at: '2026-10-13T08:47:04Z' }, + ], +}); + +describe('stale connector presentation and controls', () => { + it('presents pre-boot Charging as Unknown while retaining its reported value', () => { + expect(physicalConnectors(cp())[0]).toMatchObject({ + status: 'Unknown', + reported_status: 'Charging', + }); + }); + it('explains stale data even when the archive query succeeded', () => { + render(); + expect(screen.getByRole('status')).toHaveTextContent(/current connector status is unknown/i); + expect(screen.getByRole('status')).toHaveTextContent(/1: Charging/); + }); + it('does not enable Stop based on pre-boot Charging', () => { + expect(canRemoteStop(cp()).enabled).toBe(false); + }); + it('does not enable Start using connector zero or stale Available', () => { + expect(canRemoteStart(cp('Available')).enabled).toBe(false); + }); + it('does not present a stale Faulted report as a current fault', () => { + expect(chargePointFaultLevel(withConnectorFreshness(cp('Faulted')))).toBe('ok'); + }); + it('keeps stale fault evidence out of the current fault banner', () => { + expect(faultedConnectors(withConnectorFreshness(cp('Faulted')))).toEqual([]); + }); + it('does not derive a current charger fault alert from stale evidence', () => { + expect( + computeAlerts({ charge_points: [withConnectorFreshness(cp('Faulted'))], sys_status: null }), + ).toEqual([]); + }); + it('does not derive a current advisory alert from unknown evidence', () => { + const row = withConnectorFreshness(cp()); + row.connectors[1]!.error_code = 'OverCurrentFailure'; + expect(computeAlerts({ charge_points: [row], sys_status: null })).toEqual([]); + }); +}); diff --git a/apps/web/test/DeviceEventsPanel.test.tsx b/apps/web/test/DeviceEventsPanel.test.tsx index e5303af..c3ed3eb 100644 --- a/apps/web/test/DeviceEventsPanel.test.tsx +++ b/apps/web/test/DeviceEventsPanel.test.tsx @@ -97,6 +97,53 @@ describe('DeviceEventsPanel — wiring', () => { }); describe('DeviceEventsPanel — empty state', () => { + it('shows archive read failure while live events can still arrive', () => { + setSub({ + snapshot: { + kind: 'device-events', + rows: [], + history_state: 'unavailable', + history_error: 'read_failed', + }, + }); + const { rerender } = render(); + expect(screen.getByText(/Event history unavailable/i)).toBeInTheDocument(); + expect(screen.queryByText(/No recorded events/i)).not.toBeInTheDocument(); + setSub({ lastDelta: delta(makeEvent({ summary: 'live status after archive failure' })) }); + rerender(); + expect(screen.getByText('live status after archive failure')).toBeInTheDocument(); + expect(screen.getByText(/Event history unavailable/i)).toBeInTheDocument(); + }); + + it('shows a successfully read empty history without an endless loading spinner', () => { + setSub({ + snapshot: { + kind: 'device-events', + rows: [], + history_state: 'available', + history_error: null, + }, + }); + render(); + expect(screen.getByTestId('device-events-empty')).toHaveTextContent('No recorded events'); + }); + + it('keeps the last successful rows visible when live subscription later fails', () => { + setSub({ + snapshot: { + kind: 'device-events', + rows: [makeEvent({ summary: 'retained status' })], + history_state: 'available', + }, + }); + const { rerender } = render(); + expect(screen.getByText('retained status')).toBeInTheDocument(); + setSub({ error: 'Disconnected' }); + rerender(); + expect(screen.getByText(/Couldn't subscribe.*Disconnected/i)).toBeInTheDocument(); + expect(screen.getByText('retained status')).toBeInTheDocument(); + }); + it('renders the waiting copy when no events have arrived', () => { render(); expect(screen.getByTestId('device-events-empty')).toHaveTextContent('Waiting for events'); diff --git a/apps/web/test/FleetPage.test.tsx b/apps/web/test/FleetPage.test.tsx index 6150a13..6041ee5 100644 --- a/apps/web/test/FleetPage.test.tsx +++ b/apps/web/test/FleetPage.test.tsx @@ -156,7 +156,12 @@ const baseRow = ( last_heartbeat_at: '2026-05-09T11:00:00+00:00', last_status: 'Available', connectors: [ - { connector_id: 1, status: 'Available', error_code: 'NoError', last_changed_at: null }, + { + connector_id: 1, + status: 'Available', + error_code: 'NoError', + last_changed_at: '2026-05-09T11:00:00Z', + }, ], ...overrides, }); @@ -382,7 +387,7 @@ describe('FleetPage — client-side filters', () => { connector_id: 1, status: 'Faulted', error_code: 'GroundFailure', - last_changed_at: null, + last_changed_at: '2026-05-09T11:00:00Z', }, ], }), @@ -393,7 +398,7 @@ describe('FleetPage — client-side filters', () => { connector_id: 1, status: 'Available', error_code: 'WeakSignal', - last_changed_at: null, + last_changed_at: '2026-05-09T11:00:00Z', }, ], }), @@ -616,7 +621,12 @@ describe('FleetPage — delta application', () => { baseRow('CP_A', { last_status: 'Available', connectors: [ - { connector_id: 1, status: 'Faulted', error_code: 'NoError', last_changed_at: null }, + { + connector_id: 1, + status: 'Faulted', + error_code: 'NoError', + last_changed_at: '2026-05-09T11:00:00Z', + }, ], }), ], @@ -628,7 +638,12 @@ describe('FleetPage — delta application', () => { row: baseRow('CP_A', { last_status: 'Charging', connectors: [ - { connector_id: 1, status: 'Faulted', error_code: 'NoError', last_changed_at: null }, + { + connector_id: 1, + status: 'Faulted', + error_code: 'NoError', + last_changed_at: '2026-05-09T11:00:00Z', + }, ], }), }, @@ -683,12 +698,17 @@ describe('FleetPage — table-row connector drill-down', () => { rows: [ baseRow('CP_A', { connectors: [ - { connector_id: 1, status: 'Charging', error_code: 'NoError', last_changed_at: null }, + { + connector_id: 1, + status: 'Charging', + error_code: 'NoError', + last_changed_at: '2026-05-09T11:00:00Z', + }, { connector_id: 2, status: 'Faulted', error_code: 'GroundFailure', - last_changed_at: null, + last_changed_at: '2026-05-09T11:00:00Z', }, ], }), @@ -733,7 +753,7 @@ describe('FleetPage — ?faults=1 URL param', () => { connector_id: 1, status: 'Faulted', error_code: 'GroundFailure', - last_changed_at: null, + last_changed_at: '2026-05-09T11:00:00Z', }, ], }), diff --git a/apps/web/test/OcppLogPanel.test.tsx b/apps/web/test/OcppLogPanel.test.tsx index 233784b..8303830 100644 --- a/apps/web/test/OcppLogPanel.test.tsx +++ b/apps/web/test/OcppLogPanel.test.tsx @@ -48,7 +48,10 @@ beforeEach(() => { fetchCalls.length = 0; }); -afterEach(() => cleanup()); +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); function _response(frames: CpFramesResponse['frames'] = []): CpFramesResponse { return { cp_id: 'CP_001', frames, request_id: 'req-1' }; @@ -140,6 +143,45 @@ describe('OcppLogPanel — rendering', () => { }); describe('OcppLogPanel — filters', () => { + it('refreshes the time window at request time after the panel has stayed open', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date('2026-10-13T07:00:00Z')); + const user = userEvent.setup(); + nextResponse.value = _response(); + render(); + await waitFor(() => expect(fetchCalls.length).toBe(1)); + expect(fetchCalls[0].params.to).toBe('2026-10-13T07:00:00.000Z'); + + vi.setSystemTime(new Date('2026-10-13T09:00:00Z')); + await user.click(screen.getByTestId('ocpp-log-refresh')); + await waitFor(() => expect(fetchCalls.length).toBe(2)); + expect(fetchCalls[1].params.to).toBe('2026-10-13T09:00:00.000Z'); + expect(fetchCalls[1].params.from).toBe('2026-10-13T08:00:00.000Z'); + }); + + it('commits a trimmed action on blur without fetching each keystroke', async () => { + const user = userEvent.setup(); + nextResponse.value = _response(); + render(); + await waitFor(() => expect(fetchCalls.length).toBe(1)); + await user.type(screen.getByTestId('ocpp-log-action-input'), ' StatusNotification '); + expect(fetchCalls.length).toBe(1); + await user.tab(); + await waitFor(() => expect(fetchCalls.length).toBe(2)); + expect(fetchCalls[1].params.action).toBe('StatusNotification'); + }); + + it('does not repeat an Enter commit when the unchanged input later loses focus', async () => { + const user = userEvent.setup(); + nextResponse.value = _response(); + render(); + await waitFor(() => expect(fetchCalls.length).toBe(1)); + await user.type(screen.getByTestId('ocpp-log-action-input'), 'MeterValues{Enter}'); + await waitFor(() => expect(fetchCalls.length).toBe(2)); + await user.tab(); + expect(fetchCalls.length).toBe(2); + }); + it('refetches with direction=outbound when the select changes', async () => { const user = userEvent.setup(); nextResponse.value = _response(); diff --git a/apps/web/test/SystemPage.test.tsx b/apps/web/test/SystemPage.test.tsx index 77f1eba..6a100bd 100644 --- a/apps/web/test/SystemPage.test.tsx +++ b/apps/web/test/SystemPage.test.tsx @@ -356,6 +356,45 @@ describe('SystemPage — alerts summary', () => { }); describe('SystemPage — services placement', () => { + it('shows unobserved ingestor progress as unknown rather than a confirmed failure', async () => { + nextSysStatus = healthySys({ + gateway: { + ok: false, + detail: 'status=degraded', + components: { postgres: 'ok', redis: 'ok', clickhouse: 'ok', ingestor: 'unknown' }, + }, + }); + renderPage(); + const pill = await screen.findByTestId('service-pill-gw-ingestor'); + expect(pill).toHaveTextContent('unknown'); + expect(pill).toHaveAttribute('data-tone', 'warning'); + expect(pill).toHaveAttribute('title', 'unknown — ingestion progress is not observed'); + }); + it('shows degraded gateway and failed ClickHouse separately without turning diagnostics into a service', async () => { + nextSysStatus = healthySys({ + gateway: { + ok: false, + detail: 'status=degraded', + components: { + postgres: 'ok', + redis: 'ok', + clickhouse: 'error', + clickhouse_error_class: 'ConnectionError', + }, + }, + }); + renderPage(); + expect(await screen.findByTestId('service-pill-gateway')).toHaveAttribute( + 'data-tone', + 'warning', + ); + expect(screen.getByTestId('service-pill-gw-clickhouse')).toHaveTextContent('ClickHouse'); + expect(screen.getByTestId('service-pill-gw-clickhouse')).toHaveAttribute( + 'data-tone', + 'destructive', + ); + expect(screen.queryByTestId('service-pill-gw-clickhouse_error_class')).toBeNull(); + }); it('renders the Services pills above the alerts summary and metrics row', async () => { renderPage(); const services = await screen.findByTestId('service-status-row'); @@ -390,6 +429,8 @@ describe('SystemPage — headline metrics', () => { renderPage(); const tile = await screen.findByTestId('metric-sessions'); expect(within(tile).getByText('2')).toBeInTheDocument(); + expect(within(tile).queryByText(/chargers charging/)).toBeNull(); + expect(within(tile).getByText(/open transaction records/)).toBeInTheDocument(); }); it('renders faults tile counting cps with any Faulted connector', async () => { diff --git a/apps/web/test/TransactionDetailPage.test.tsx b/apps/web/test/TransactionDetailPage.test.tsx index 9dd0bd5..575771f 100644 --- a/apps/web/test/TransactionDetailPage.test.tsx +++ b/apps/web/test/TransactionDetailPage.test.tsx @@ -10,7 +10,7 @@ // heavy; we only check that renders the right href. import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; // ---- mocks --------------------------------------------------------------- @@ -41,6 +41,10 @@ vi.mock('@/api/transactions-client', () => ({ fetchMeterValues: (...args: unknown[]) => fetchMeterValues(...args), })); +vi.mock('@/api/frames-client', () => ({ + fetchTxFrames: async (_token: string, txId: number) => ({ transaction_id: txId, frames: [] }), +})); + let routeParams: { txId: string } = { txId: '42' }; vi.mock('@tanstack/react-router', () => ({ useParams: () => routeParams, @@ -99,10 +103,11 @@ import type { TransactionDetail, MeterValuesResponse } from '@/api/transactions- // ---- helpers ------------------------------------------------------------- -function renderPage() { - const qc = new QueryClient({ +function renderPage( + qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } }, - }); + }), +) { return render( @@ -297,6 +302,50 @@ describe('TransactionDetailPage — SoC card', () => { }); describe('TransactionDetailPage — charts', () => { + it('shows failed archive reads instead of claiming the two curves are empty', async () => { + fetchTransaction.mockResolvedValue(closedTx); + fetchMeterValues.mockRejectedValue(new Error('meter-values 503')); + renderPage(); + await waitFor(() => expect(screen.getAllByText(/Couldn't load samples/i)).toHaveLength(2)); + expect(screen.queryByText(/No samples in this window/i)).not.toBeInTheDocument(); + expect(screen.getByText('tx 42')).toBeInTheDocument(); + expect(screen.getByText('closed')).toBeInTheDocument(); + expect(screen.getByText(/kWh: 5\.500/)).toBeInTheDocument(); + }); + + it('retains a successful curve with a visible notice when its later read fails', async () => { + fetchTransaction.mockResolvedValue(closedTx); + fetchMeterValues.mockImplementation( + async (_token: string, _cp: string, params: { measurand: string }) => ({ + meter_values: [ + { + cp_id: 'CP_A', + connector_id: 1, + transaction_id: 42, + occurred_at: '2026-05-10T12:00:30Z', + measurand: params.measurand, + phase: params.measurand === 'Power.Active.Import' ? 'L1' : null, + unit: params.measurand === 'Power.Active.Import' ? 'W' : 'Wh', + value: params.measurand === 'Power.Active.Import' ? 2300 : 1000, + }, + ], + next_cursor: null, + }), + ); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + renderPage(qc); + await waitFor(() => expect(screen.getAllByTestId('line-chart')).toHaveLength(2)); + fetchMeterValues.mockRejectedValue(new Error('meter-values 503')); + await act(async () => { + await qc.invalidateQueries({ queryKey: ['meter-values'] }); + }); + await waitFor(() => expect(screen.getAllByText(/Couldn't load samples/i)).toHaveLength(2)); + expect(screen.getAllByTestId('line-chart')).toHaveLength(2); + expect( + JSON.parse(screen.getAllByTestId('line-chart')[0]!.getAttribute('data-points')!)[0].L1, + ).toBe(2.3); + }); + it('passes one Power.Active.Import data point per timestamp, with per-phase columns', async () => { fetchTransaction.mockResolvedValue(closedTx); fetchMeterValues.mockImplementation( @@ -441,6 +490,132 @@ describe('TransactionDetailPage — charts', () => { }); }); +describe('TransactionDetailPage — archive read state', () => { + for (const [state, message, error] of [ + ['unavailable', /Archived telemetry unavailable/i, 'ARCHIVE_UNAVAILABLE'], + ['unconfigured', /Telemetry archive is not configured/i, 'ARCHIVE_UNCONFIGURED'], + ] as const) { + it(`shows ${state} telemetry as a read limitation while retaining the PG transaction`, async () => { + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry: null, + telemetry_state: state, + telemetry_error: error, + }); + renderPage(); + await waitFor(() => expect(screen.getByText(message)).toBeInTheDocument()); + expect(screen.getByText('tx 42')).toBeInTheDocument(); + expect(screen.getByText('closed')).toBeInTheDocument(); + expect(screen.getByText(/kWh: 5\.500/)).toBeInTheDocument(); + expect(screen.queryByText(/No phase telemetry available/i)).not.toBeInTheDocument(); + }); + } + + it('shows a successful empty archive result as empty without an outage notice', async () => { + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry: { soc: { start: null, last: null, delta: null }, phases: {} }, + telemetry_state: 'available', + telemetry_error: null, + }); + renderPage(); + await waitFor(() => screen.getByText(/No phase telemetry available/i)); + expect( + screen.queryByText(/Archived telemetry unavailable|Telemetry archive is not configured/i), + ).not.toBeInTheDocument(); + }); + + it('retains successful phase readings if a later detail reports an unavailable archive', async () => { + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry_state: 'available', + telemetry_error: null, + }); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + renderPage(qc); + await waitFor(() => screen.getByTestId('phase-row-L1')); + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry: null, + telemetry_state: 'unavailable', + telemetry_error: 'ARCHIVE_UNAVAILABLE', + }); + await act(async () => { + await qc.invalidateQueries({ queryKey: ['transaction', 42] }); + }); + await waitFor(() => screen.getByText(/Archived telemetry unavailable/i)); + expect(screen.getByTestId('phase-row-L1')).toBeInTheDocument(); + expect(screen.getByText(/previously loaded readings/i)).toBeInTheDocument(); + }); + + it('keeps the successful PG header visible when a later detail refetch fails', async () => { + fetchTransaction.mockResolvedValue(closedTx); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + renderPage(qc); + await waitFor(() => screen.getByText('tx 42')); + fetchTransaction.mockRejectedValue(new Error('transaction 502')); + await act(async () => { + await qc.invalidateQueries({ queryKey: ['transaction', 42] }); + }); + await waitFor(() => screen.getByText(/Couldn't refresh transaction/i)); + expect(screen.getByText('tx 42')).toBeInTheDocument(); + expect(screen.getByText('closed')).toBeInTheDocument(); + }); + + it('clears retained readings when the route switches to another transaction', async () => { + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry_state: 'available', + telemetry_error: null, + }); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + const view = renderPage(qc); + await waitFor(() => screen.getByTestId('phase-row-L1')); + fetchTransaction.mockResolvedValue({ + ...closedTx, + transaction_id: 43, + cp_id: 'CP_B', + telemetry: null, + telemetry_state: 'unavailable', + telemetry_error: 'ARCHIVE_UNAVAILABLE', + }); + routeParams = { txId: '43' }; + view.rerender( + + + , + ); + await waitFor(() => screen.getByText('tx 43')); + expect(screen.getByText('CP_B')).toBeInTheDocument(); + expect(screen.queryByTestId('phase-row-L1')).not.toBeInTheDocument(); + expect(screen.queryByTestId('soc-card')).not.toBeInTheDocument(); + expect(screen.queryByText(/previously loaded readings/i)).not.toBeInTheDocument(); + }); + + it('replaces retained readings with a later successful empty archive snapshot', async () => { + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry_state: 'available', + telemetry_error: null, + }); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } }); + renderPage(qc); + await waitFor(() => screen.getByTestId('phase-row-L1')); + fetchTransaction.mockResolvedValue({ + ...closedTx, + telemetry: { soc: { start: null, last: null, delta: null }, phases: {} }, + telemetry_state: 'available', + telemetry_error: null, + }); + await act(async () => { + await qc.invalidateQueries({ queryKey: ['transaction', 42] }); + }); + await waitFor(() => screen.getByText(/No phase telemetry available/i)); + expect(screen.queryByTestId('phase-row-L1')).not.toBeInTheDocument(); + expect(screen.queryByTestId('soc-card')).not.toBeInTheDocument(); + }); +}); + describe('TransactionDetailPage — open-tx polling', () => { it('refetches the detail on the open-tx interval and stops once closed', async () => { vi.useFakeTimers(); diff --git a/apps/web/test/charger-state.test.ts b/apps/web/test/charger-state.test.ts index 6b09f44..1c0a7a6 100644 --- a/apps/web/test/charger-state.test.ts +++ b/apps/web/test/charger-state.test.ts @@ -16,7 +16,7 @@ const conn = (over: Partial = {}): Connector => ({ connector_id: 1, status: 'Available', error_code: 'NoError', - last_changed_at: null, + last_changed_at: '2026-10-13T09:13:00Z', ...over, }); @@ -31,7 +31,7 @@ const cp = ( model: 'X1', firmware_version: '1.0.0', serial_number: 'SN1', - last_boot_at: null, + last_boot_at: '2026-10-13T09:12:44Z', last_heartbeat_at: null, last_status: 'Available', connectors: [conn()], diff --git a/apps/web/test/setup.ts b/apps/web/test/setup.ts index 8c3aee4..ef4a593 100644 --- a/apps/web/test/setup.ts +++ b/apps/web/test/setup.ts @@ -3,6 +3,12 @@ import '@testing-library/jest-dom/vitest'; +// Every HTTP dependency must be explicitly faked by its test. The OS +// network-deny sandbox is a second barrier, including localhost. +globalThis.fetch = () => { + throw new Error('Unexpected fetch in isolated test'); +}; + // matchMedia: jsdom doesn't implement it. Our useIsBelow() hook reads // it on first render and subscribes to change events. Default to // "matches: false" so a fresh test renders the desktop layout diff --git a/apps/web/test/use-command-transcript.test.ts b/apps/web/test/use-command-transcript.test.ts index 7ae3ec3..9b9f1b8 100644 --- a/apps/web/test/use-command-transcript.test.ts +++ b/apps/web/test/use-command-transcript.test.ts @@ -13,7 +13,7 @@ import { function makeClient() { return { - rpc: vi.fn(async (_method: string, _params: Record) => { + rpc: vi.fn(async (_method: string, _params: Record): Promise => { return { status: 'Accepted' }; }), }; @@ -28,6 +28,83 @@ describe('useCommandTranscript', () => { __resetTranscriptStoresForTests(); }); + it.each([null, {}, { unexpected: true }, { status: 'invented-status' }])( + 'does not accept an unknown/malformed reset reply: %j', + async (response) => { + const client = makeClient(); + client.rpc.mockResolvedValueOnce(response); + const onResult = vi.fn(); + const { result } = renderHook(() => useCommandTranscript(client, 'cp_TEST')); + await act(async () => { + await result.current.send('reset', { type: 'Soft' }, onResult); + }); + expect(result.current.entries[0]!.outcome).toBe('unknown'); + expect(result.current.entries[0]!.status).toBe('Result unknown'); + expect(onResult).not.toHaveBeenCalled(); + }, + ); + + it('does not run a success callback for a rejected command', async () => { + const client = makeClient(); + client.rpc.mockResolvedValueOnce({ status: 'Rejected' }); + const onResult = vi.fn(); + const { result } = renderHook(() => useCommandTranscript(client, 'cp_TEST')); + await act(async () => { + await result.current.send('remote-stop', { transaction_id: 42 }, onResult); + }); + expect(onResult).not.toHaveBeenCalled(); + }); + + it('accepts valid status-less configuration keys and RebootRequired only for configuration changes', async () => { + const client = makeClient(); + const config = { + configuration_key: [ + { key: 'StopTransactionOnEVSideDisconnect', readonly: false, value: 'true' }, + ], + unknown_key: [], + }; + client.rpc.mockResolvedValueOnce(config).mockResolvedValueOnce({ status: 'RebootRequired' }); + const onResult = vi.fn(); + const { result } = renderHook(() => useCommandTranscript(client, 'cp_TEST')); + await act(async () => { + await result.current.send('get-configuration', {}, onResult); + await result.current.send('change-configuration', { key: 'k', value: 'v' }); + }); + expect(result.current.entries.map((entry) => entry.outcome)).toEqual(['accepted', 'accepted']); + expect(onResult).toHaveBeenCalledWith(config); + }); + + it.each([ + { method: 'unlock-connector', response: { status: 'Accepted' }, outcome: 'unknown' }, + { method: 'unknown-command', response: { status: 'Accepted' }, outcome: 'unknown' }, + { method: 'constructor', response: { status: 'Accepted' }, outcome: 'unknown' }, + { method: 'unlock-connector', response: { status: 'Unlocked' }, outcome: 'accepted' }, + { method: 'change-configuration', response: { status: 'Accepted' }, outcome: 'accepted' }, + { method: 'reset', response: { status: 'Unlocked' }, outcome: 'unknown' }, + { method: 'reset', response: { status: 'RebootRequired' }, outcome: 'unknown' }, + { + method: 'get-configuration', + response: { configuration_key: ['invalid'], unknown_key: [] }, + outcome: 'unknown', + }, + { method: 'get-diagnostics', response: { file_name: '' }, outcome: 'soft-reject' }, + { method: 'get-diagnostics', response: { file_name: 'diagnostics.log' }, outcome: 'accepted' }, + ])( + 'interprets $method replies using their own contract: $outcome', + async ({ method, response, outcome }) => { + const client = makeClient(); + client.rpc.mockResolvedValueOnce(response); + const onResult = vi.fn(); + const { result } = renderHook(() => useCommandTranscript(client, 'cp_TEST')); + await act(async () => { + await result.current.send(method, {}, onResult); + }); + expect(result.current.entries[0]!.outcome).toBe(outcome); + if (outcome === 'accepted') expect(onResult).toHaveBeenCalledWith(response); + else expect(onResult).not.toHaveBeenCalled(); + }, + ); + it('appends a pending entry on send and resolves to ok + accepted', async () => { const client = makeClient(); const { result } = renderHook(() => useCommandTranscript(client, 'cp_TEST')); diff --git a/apps/web/test/use-subscription.test.tsx b/apps/web/test/use-subscription.test.tsx new file mode 100644 index 0000000..eec91d4 --- /dev/null +++ b/apps/web/test/use-subscription.test.tsx @@ -0,0 +1,224 @@ +import { act, cleanup, renderHook } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ChargePointSummary, DeltaForQuery, SnapshotForQuery } from '@eveys-console/protocol'; + +const transport = vi.hoisted(() => ({ + status: 'open', + subscriptions: [] as Array<{ + onSnapshot: (snapshot: SnapshotForQuery, cursor: string) => void; + onDelta: (delta: DeltaForQuery, cursor: string) => void; + onError: (message: string) => void; + }>, + subscribe: vi.fn(), +})); +vi.mock('@/lib/ws-context', () => ({ + useConsoleClient: () => ({ client: transport, status: transport.status }), +})); +import { useSubscription } from '@/hooks/use-subscription'; + +const cp = (id: string, status = 'Available', at = '2026-10-13T10:00:00Z'): ChargePointSummary => ({ + cp_id: id, + online: true, + pod_id: 'fake', + vendor: null, + model: null, + firmware_version: null, + serial_number: null, + last_boot_at: null, + last_heartbeat_at: null, + last_status: status, + connectors: [{ connector_id: 1, status, error_code: null, last_changed_at: at }], +}); +beforeEach(() => { + transport.status = 'open'; + transport.subscriptions = []; + transport.subscribe.mockImplementation((_query, _params, handlers) => { + transport.subscriptions.push(handlers); + return Promise.resolve({ unsubscribe: vi.fn() }); + }); + vi.stubGlobal('fetch', () => { + throw new Error('Unexpected network'); + }); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('useSubscription scope and cumulative data', () => { + it('retains a successful connector snapshot on archive failure and marks it unavailable', () => { + const { result } = renderHook(() => useSubscription('charge-point', { cp_id: 'A' })); + const h = transport.subscriptions[0]!; + const successful = { + ...cp('A'), + connectors_state: 'available' as const, + connectors_last_successful_at: '2026-10-13T10:00:00Z', + }; + act(() => h.onSnapshot({ kind: 'charge-point', row: successful }, 'success')); + act(() => + h.onSnapshot( + { + kind: 'charge-point', + row: { + ...cp('A'), + connectors: [], + connectors_state: 'unavailable', + connectors_last_successful_at: null, + }, + }, + 'failed', + ), + ); + expect(result.current.snapshot).toMatchObject({ + row: { + connectors_state: 'unavailable', + connectors_last_successful_at: '2026-10-13T10:00:00Z', + connectors: [{ connector_id: 1 }], + }, + }); + act(() => + h.onSnapshot( + { + kind: 'charge-point', + row: { + ...cp('A'), + connectors: [], + connectors_state: 'available', + connectors_last_successful_at: '2026-10-13T10:02:00Z', + }, + }, + 'confirmed-empty', + ), + ); + expect(result.current.snapshot).toMatchObject({ + row: { connectors_state: 'available', connectors: [] }, + }); + }); + + it('keeps one subscription through reconnect and clears error and delta when its fresh snapshot arrives', () => { + const { result, rerender } = renderHook(() => useSubscription('charge-point', { cp_id: 'A' })); + const h = transport.subscriptions[0]!; + act(() => h.onSnapshot({ kind: 'charge-point', row: cp('A') }, 'initial')); + act(() => h.onDelta({ kind: 'charge-point', row: cp('A', 'Charging') }, 'delta')); + transport.status = 'closed'; + rerender(); + expect(result.current.error).toContain('Showing last known data'); + transport.status = 'open'; + rerender(); + act(() => h.onSnapshot({ kind: 'charge-point', row: cp('A', 'Faulted') }, 'replacement')); + expect(transport.subscriptions).toHaveLength(1); + expect(result.current).toMatchObject({ + error: null, + lastDelta: null, + cursor: 'replacement', + snapshot: { row: { last_status: 'Faulted' } }, + }); + }); + it('retains updates for both fleet rows after consecutive events', () => { + const { result } = renderHook(() => useSubscription('charge-points', {})); + const handlers = transport.subscriptions[0]!; + act(() => handlers.onSnapshot({ kind: 'charge-points', rows: [cp('A'), cp('B')] }, 'snapshot')); + act(() => + handlers.onDelta({ kind: 'charge-points', op: 'upsert', row: cp('A', 'Charging') }, 'a'), + ); + act(() => + handlers.onDelta({ kind: 'charge-points', op: 'upsert', row: cp('B', 'Faulted') }, 'b'), + ); + const snapshot = result.current.snapshot; + expect(snapshot?.kind).toBe('charge-points'); + if (snapshot?.kind === 'charge-points') + expect(snapshot.rows.map((row) => row.last_status)).toEqual(['Charging', 'Faulted']); + }); + + it('resets all old scope data before the next charger snapshot arrives', () => { + const { result, rerender } = renderHook( + ({ id }) => useSubscription('charge-point', { cp_id: id }), + { initialProps: { id: 'A' } }, + ); + const old = transport.subscriptions[0]!; + act(() => old.onSnapshot({ kind: 'charge-point', row: cp('A') }, 'a')); + act(() => old.onDelta({ kind: 'charge-point', row: cp('A', 'Charging') }, 'a2')); + act(() => old.onError('upstream unavailable')); + rerender({ id: 'B' }); + expect(result.current).toMatchObject({ + loading: true, + error: null, + snapshot: null, + lastDelta: null, + cursor: null, + }); + act(() => old.onDelta({ kind: 'charge-point', row: cp('A', 'Faulted') }, 'late-a')); + expect(result.current.snapshot).toBeNull(); + }); + + it('ignores a delta for another charger and clears old error on a fresh snapshot', () => { + const { result } = renderHook(() => useSubscription('charge-point', { cp_id: 'A' })); + const h = transport.subscriptions[0]!; + act(() => h.onSnapshot({ kind: 'charge-point', row: cp('A') }, 'a')); + act(() => h.onDelta({ kind: 'charge-point', row: cp('B', 'Charging') }, 'wrong')); + expect(result.current.lastDelta).toBeNull(); + act(() => h.onError('failed refetch')); + act(() => h.onSnapshot({ kind: 'charge-point', row: cp('A', 'Charging') }, 'fresh')); + expect(result.current.error).toBeNull(); + expect(result.current.lastDelta).toBeNull(); + }); + + it('compares connector timestamps by UTC instant and retains other known connectors', () => { + const { result } = renderHook(() => useSubscription('charge-point', { cp_id: 'A' })); + const h = transport.subscriptions[0]!; + const row = cp('A', 'Charging', '2026-10-13T10:00:00Z'); + row.connectors.push({ + connector_id: 2, + status: 'Available', + error_code: null, + last_changed_at: '2026-10-13T10:00:00Z', + }); + act(() => h.onSnapshot({ kind: 'charge-point', row }, 's')); + act(() => + h.onDelta( + { kind: 'charge-point', row: cp('A', 'SuspendedEV', '2026-10-13T13:01:00+03:00') }, + 'new', + ), + ); + expect(result.current.snapshot).toMatchObject({ + row: { + connectors: [ + { connector_id: 1, status: 'SuspendedEV' }, + { connector_id: 2, status: 'Available' }, + ], + }, + }); + act(() => + h.onDelta( + { kind: 'charge-point', row: cp('A', 'Faulted', '2026-10-13T11:00:00+03:00') }, + 'old', + ), + ); + const snapshot = result.current.snapshot; + if (snapshot?.kind === 'charge-point') + expect(snapshot.row.connectors.map((c) => c.status)).toEqual(['SuspendedEV', 'Available']); + else throw new Error('Missing charger snapshot'); + }); + + it('removes a stopped transaction from the active snapshot', () => { + const { result } = renderHook(() => useSubscription('transactions-active', {})); + const h = transport.subscriptions[0]!; + const row = { + transaction_id: 7, + cp_id: 'A', + connector_id: 1, + id_tag: 'fake', + meter_start_wh: 0, + meter_stop_wh: null, + consumed_wh: null, + started_reported_at: '2026-10-13T10:00:00Z', + started_received_at: '2026-10-13T10:00:00Z', + stopped_reported_at: null, + stopped_received_at: null, + stop_reason: null, + }; + act(() => h.onSnapshot({ kind: 'transactions-active', rows: [row] }, 's')); + act(() => h.onDelta({ kind: 'transactions-active', op: 'remove', transaction_id: 7 }, 'stop')); + expect(result.current.snapshot).toMatchObject({ rows: [] }); + }); +}); diff --git a/apps/web/test/ws-client.test.ts b/apps/web/test/ws-client.test.ts index 7939be2..5af4702 100644 --- a/apps/web/test/ws-client.test.ts +++ b/apps/web/test/ws-client.test.ts @@ -53,6 +53,91 @@ afterEach(() => { }); describe('ConsoleClient', () => { + it('delivers a scoped refresh error only to its active subscription', async () => { + const client = new ConsoleClient({ url: 'ws://fake/ws', token: 'fake' }); + client.connect(); + lastSocket?.onopen?.({}); + const onError = vi.fn(); + const pending = client.subscribe( + 'charge-point', + { cp_id: 'A' }, + { onSnapshot: vi.fn(), onDelta: vi.fn(), onError }, + ); + const request = JSON.parse(lastSocket!.send.mock.calls.at(-1)![0]); + lastSocket?.onmessage?.({ + data: JSON.stringify({ + v: 1, + type: 'subscription.accepted', + inReplyTo: request.id, + subscriptionId: 'sub-A', + }), + }); + await pending; + lastSocket?.onmessage?.({ + data: JSON.stringify({ + v: 1, + type: 'error', + subscriptionId: 'other', + error: { code: 'upstream_unavailable', message: 'ignore' }, + }), + }); + lastSocket?.onmessage?.({ + data: JSON.stringify({ + v: 1, + type: 'error', + subscriptionId: 'sub-A', + error: { code: 'upstream_unavailable', message: 'refresh failed' }, + }), + }); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith('refresh failed'); + client.close(); + }); + + it('reissues a subscription once and keeps its unsubscribe handle valid across reconnect', async () => { + vi.useFakeTimers(); + const client = new ConsoleClient({ url: 'ws://fake/ws', token: 'fake' }); + client.connect(); + lastSocket?.onopen?.({}); + const pending = client.subscribe( + 'charge-point', + { cp_id: 'A' }, + { onSnapshot: vi.fn(), onDelta: vi.fn() }, + ); + const request = JSON.parse(lastSocket!.send.mock.calls.at(-1)![0]); + lastSocket?.onmessage?.({ + data: JSON.stringify({ + v: 1, + type: 'subscription.accepted', + inReplyTo: request.id, + subscriptionId: 'old-A', + }), + }); + const handle = await pending; + lastSocket?.onclose?.({ code: 1001, reason: 'restart' }); + vi.advanceTimersByTime(1000); + lastSocket?.onopen?.({}); + expect(lastSocket!.send).toHaveBeenCalledTimes(1); + const replacement = JSON.parse(lastSocket!.send.mock.calls[0]![0]); + lastSocket?.onmessage?.({ + data: JSON.stringify({ + v: 1, + type: 'subscription.accepted', + inReplyTo: replacement.id, + subscriptionId: 'new-A', + }), + }); + handle.unsubscribe(); + expect(JSON.parse(lastSocket!.send.mock.calls.at(-1)![0])).toMatchObject({ + type: 'unsubscribe', + subscriptionId: 'new-A', + }); + lastSocket?.onclose?.({ code: 1001, reason: 'restart' }); + vi.advanceTimersByTime(1000); + lastSocket?.onopen?.({}); + expect(lastSocket!.send).not.toHaveBeenCalled(); + client.close(); + }); it('fires onAuthRejected and stops reconnecting when server closes with 4401', () => { const onAuthRejected = vi.fn(); const onStatus = vi.fn<(s: ConnectionStatus) => void>(); diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 8b1a8a0..5735c42 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -58,6 +58,10 @@ services: PORT: 8090 LOG_LEVEL: ${LOG_LEVEL:-info} LOG_PRETTY: 'false' + # These stores otherwise default to /app/data, outside the named volume. + # Copy existing /app/data state before recreating a deployed server. + DIAGNOSTICS_DATA_DIR: /data + EVENT_LOG_DIR: /data/event-log JWT_SECRET: ${JWT_SECRET:?set JWT_SECRET in .env or the host env} JWT_AUDIENCE: ${JWT_AUDIENCE:-eveys-console} JWT_ISSUER: ${JWT_ISSUER:-eveys-console} diff --git a/packages/protocol/src/envelope.ts b/packages/protocol/src/envelope.ts index 58fa01a..ec80c52 100644 --- a/packages/protocol/src/envelope.ts +++ b/packages/protocol/src/envelope.ts @@ -72,6 +72,7 @@ export const rpcResultMessage = baseServer.extend({ export const errorMessage = baseServer.extend({ type: z.literal('error'), inReplyTo: z.string().optional(), + subscriptionId: z.string().optional(), error: errorPayload, }); diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index bafedf1..99d4837 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -1,3 +1,4 @@ export * from './envelope.js'; export * from './queries.js'; export * from './errors.js'; +export * from './subscription-state.js'; diff --git a/packages/protocol/src/queries.ts b/packages/protocol/src/queries.ts index a1a9c0f..e3749ac 100644 --- a/packages/protocol/src/queries.ts +++ b/packages/protocol/src/queries.ts @@ -23,6 +23,11 @@ export const connectorState = z status: z.string(), error_code: z.string().nullable(), last_changed_at: isoTimestamp.nullable(), + status_freshness: z.enum(['current', 'stale', 'unknown']).optional(), + stale_reason: z + .enum(['before_boot', 'stopped_after_status', 'unverified_timestamp']) + .nullable() + .optional(), /** Vendor-specific error code (OCPP 1.6 StatusNotification). */ vendor_error_code: z.string().nullable().optional(), /** Free-text human-readable detail line on the StatusNotification. */ @@ -83,6 +88,10 @@ export const chargePointSummary = z last_diagnostics_status: z.string().nullable().optional(), last_firmware_status: z.string().nullable().optional(), connectors: z.array(connectorState), + connectors_state: z.enum(['available', 'unavailable']).optional(), + connectors_source: z.literal('clickhouse').optional(), + connectors_error: z.enum(['query_failed', 'not_configured']).nullable().optional(), + connectors_last_successful_at: isoTimestamp.nullable().optional(), /** Currently-Active reservations on this charger, inlined by the * gateway's detail endpoint so the Commands tab can populate * the CancelReservation dropdown without a second round-trip. @@ -186,7 +195,13 @@ export const snapshotForQuery = z.union([ z.object({ kind: z.literal('transactions-active'), rows: z.array(transactionSummary) }), z.object({ kind: z.literal('meter-history'), rows: z.array(meterSample) }), z.object({ kind: z.literal('status-history'), rows: z.array(statusEvent) }), - z.object({ kind: z.literal('device-events'), rows: z.array(deviceEvent) }), + z.object({ + kind: z.literal('device-events'), + rows: z.array(deviceEvent), + // This reports the local log read only, not archive completeness. + history_state: z.enum(['available', 'unavailable', 'unconfigured']).optional(), + history_error: z.literal('read_failed').nullable().optional(), + }), ]); export type SnapshotForQuery = z.infer; diff --git a/packages/protocol/src/subscription-state.ts b/packages/protocol/src/subscription-state.ts new file mode 100644 index 0000000..430d096 --- /dev/null +++ b/packages/protocol/src/subscription-state.ts @@ -0,0 +1,117 @@ +import type { ChargePointSummary, DeltaForQuery, SnapshotForQuery } from './queries.js'; + +// A successful archive read does not make a pre-boot notification current. +// Retain the reported value for diagnosis, but mark its usability separately. +export function withConnectorFreshness(row: ChargePointSummary): ChargePointSummary { + const boot = row.last_boot_at ? Date.parse(row.last_boot_at) : NaN; + return { + ...row, + connectors: row.connectors.map((connector) => { + const observed = connector.last_changed_at ? Date.parse(connector.last_changed_at) : NaN; + if (Number.isFinite(boot) && Number.isFinite(observed) && observed < boot) { + return { + ...connector, + status_freshness: 'stale' as const, + stale_reason: 'before_boot' as const, + }; + } + if (!Number.isFinite(boot) || !Number.isFinite(observed)) { + return { + ...connector, + status_freshness: 'unknown' as const, + stale_reason: 'unverified_timestamp' as const, + }; + } + // Preserve additional server evidence (for example a later physical Stop). + if (connector.status_freshness === 'stale' || connector.status_freshness === 'unknown') + return connector; + return { ...connector, status_freshness: 'current' as const, stale_reason: null }; + }), + }; +} + +// Gateway refetches can lag the Kafka tail. Keep each connector's newest +// observed value, comparing ISO offsets by their UTC instant. +export function mergeChargePoint( + previous: ChargePointSummary | undefined, + incoming: ChargePointSummary, +): ChargePointSummary { + if (!previous || previous.cp_id !== incoming.cp_id) return withConnectorFreshness(incoming); + const connectors = new Map( + previous.connectors.map((connector) => [connector.connector_id, connector]), + ); + let accepted = false; + for (const connector of incoming.connectors) { + const old = connectors.get(connector.connector_id); + const oldTime = old?.last_changed_at ? Date.parse(old.last_changed_at) : NaN; + const newTime = connector.last_changed_at ? Date.parse(connector.last_changed_at) : NaN; + if (old && Number.isFinite(oldTime) && (!Number.isFinite(newTime) || newTime < oldTime)) + continue; + connectors.set(connector.connector_id, connector); + accepted = true; + } + return withConnectorFreshness({ + ...incoming, + last_status: + incoming.connectors.length > 0 && !accepted ? previous.last_status : incoming.last_status, + connectors: [...connectors.values()].sort((a, b) => a.connector_id - b.connector_id), + ...(incoming.connectors_state === 'unavailable' && previous.connectors_last_successful_at + ? { connectors_last_successful_at: previous.connectors_last_successful_at } + : {}), + }); +} + +// Histories keep their existing append consumers. Entity snapshots accumulate +// all upserts/removes here so callers cannot accidentally apply only one delta. +export function applySubscriptionDelta( + snapshot: SnapshotForQuery | null, + delta: DeltaForQuery, +): SnapshotForQuery | null { + if (!snapshot || snapshot.kind !== delta.kind) return snapshot; + if (snapshot.kind === 'charge-point' && delta.kind === 'charge-point') { + if (snapshot.row.cp_id !== delta.row.cp_id) return snapshot; + return { ...snapshot, row: mergeChargePoint(snapshot.row, delta.row) }; + } + if (snapshot.kind === 'charge-points' && delta.kind === 'charge-points') { + const rows = new Map(snapshot.rows.map((row) => [row.cp_id, row])); + if (delta.op === 'remove' && delta.cp_id) rows.delete(delta.cp_id); + if (delta.op === 'upsert' && delta.row) + rows.set(delta.row.cp_id, mergeChargePoint(rows.get(delta.row.cp_id), delta.row)); + return { ...snapshot, rows: [...rows.values()] }; + } + if (snapshot.kind === 'transactions-active' && delta.kind === 'transactions-active') { + const rows = new Map(snapshot.rows.map((row) => [row.transaction_id, row])); + if (delta.op === 'remove' && delta.transaction_id !== undefined) + rows.delete(delta.transaction_id); + if (delta.op === 'upsert' && delta.row) rows.set(delta.row.transaction_id, delta.row); + return { ...snapshot, rows: [...rows.values()] }; + } + return snapshot; +} + +// A new successful snapshot is authoritative. An unavailable archive cannot +// erase the last successful connector snapshot on reconnect. +export function retainUnavailableConnectors( + previous: SnapshotForQuery | null, + incoming: SnapshotForQuery, +): SnapshotForQuery { + if ( + previous?.kind === 'charge-point' && + incoming.kind === 'charge-point' && + incoming.row.connectors_state === 'unavailable' + ) { + return { ...incoming, row: mergeChargePoint(previous.row, incoming.row) }; + } + if (previous?.kind === 'charge-points' && incoming.kind === 'charge-points') { + const oldRows = new Map(previous.rows.map((row) => [row.cp_id, row])); + return { + ...incoming, + rows: incoming.rows.map((row) => + row.connectors_state === 'unavailable' + ? mergeChargePoint(oldRows.get(row.cp_id), row) + : row, + ), + }; + } + return incoming; +} diff --git a/packages/protocol/test/connector-freshness.test.ts b/packages/protocol/test/connector-freshness.test.ts new file mode 100644 index 0000000..deba9c8 --- /dev/null +++ b/packages/protocol/test/connector-freshness.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest'; +import { chargePointSummary, mergeChargePoint } from '../src/index.js'; + +const row = (at: string | null, boot = '2026-10-13T09:12:44Z') => + chargePointSummary.parse({ + cp_id: 'CP_TEST', + online: true, + pod_id: 'test', + vendor: null, + model: null, + firmware_version: null, + serial_number: null, + last_status: 'Available', + last_boot_at: boot, + last_heartbeat_at: '2026-10-13T14:00:00Z', + connectors: [ + { connector_id: 1, status: 'Charging', error_code: 'NoError', last_changed_at: at }, + ], + }); + +describe('connector status across reboot', () => { + it('marks a successful archive row from before the latest boot as stale', () => { + const result = mergeChargePoint(undefined, row('2026-10-13T08:47:04Z')); + expect(result.connectors[0]).toMatchObject({ + status: 'Charging', + status_freshness: 'stale', + stale_reason: 'before_boot', + }); + }); + it('invalidates retained last-known data when boot changes during a subscription', () => { + const old = row('2026-10-13T08:47:04Z', '2026-10-13T08:46:53Z'); + const update = { + ...row('2026-10-13T08:47:04Z'), + connectors: [], + connectors_state: 'unavailable' as const, + }; + expect(mergeChargePoint(old, update).connectors[0]).toMatchObject({ + status_freshness: 'stale', + stale_reason: 'before_boot', + }); + }); + it('compares UTC instants and accepts a notification at the current boot', () => { + expect( + mergeChargePoint(undefined, row('2026-10-13T12:12:44+03:00')).connectors[0], + ).toMatchObject({ status_freshness: 'current' }); + }); + it('does not assert current status without an observation timestamp after a known boot', () => { + expect(mergeChargePoint(undefined, row(null)).connectors[0]).toMatchObject({ + status_freshness: 'unknown', + stale_reason: 'unverified_timestamp', + }); + }); + it('never marks nullable boot and observation timestamps current', () => { + const input = { ...row(null), last_boot_at: null }; + expect(mergeChargePoint(undefined, input).connectors[0]).toMatchObject({ + status_freshness: 'unknown', + stale_reason: 'unverified_timestamp', + }); + }); + it('does not attest the active boot epoch when the boot time is absent', () => { + const input = { ...row('2026-10-13T14:00:00Z'), last_boot_at: null }; + expect(mergeChargePoint(undefined, input).connectors[0]).toMatchObject({ + status_freshness: 'unknown', + }); + }); +});