Files
Noel Sabia 233fdbf66c feat: live SSE stage, phone view and presenter control
- proxy Go /api/stream through Nitro; drive /stage, /live, /plan and /forecast from scenario events
- fall back to 5 s polling after SSE failures or heartbeat silence; show Live/Polling/Offline
- authenticate /control and POST /api/scenario in Nitro with server-side control credentials
- add big-screen stage with local QR and a no-login phone recommendation view
- add SSE unit tests and a live smoke test; refresh README/Makefile
2026-11-14 06:59:07 +01:00

388 lines
14 KiB
JavaScript

#!/usr/bin/env node
/**
* End-to-end live smoke test.
*
* Prerequisites (read-only use of the Go/ML worktrees):
* - Go API on http://127.0.0.1:18080 with CONTROL_USER/CONTROL_PASS
* - FastAPI ML on http://127.0.0.1:18000 (so Go can answer /api/readyz)
* - Built Nuxt server on http://127.0.0.1:13000 with
* NUXT_API_INTERNAL_BASE=http://127.0.0.1:18080
* CONTROL_USER=control CONTROL_PASS=secret
*
* What it proves: the presenter POST reaches Go through Nitro, a `scenario`
* SSE event arrives through the Nitro stream proxy, and the staffing/forecast
* APIs return the new scenario. It also checks /stage, /live, the QR route and
* the control-auth boundary.
*/
import assert from 'node:assert/strict'
const WEB_URL = (process.env.WEB_URL ?? 'http://127.0.0.1:13000').replace(/\/+$/, '')
const CONTROL_USER = process.env.CONTROL_USER ?? 'control'
const CONTROL_PASS = process.env.CONTROL_PASS ?? 'secret'
const SENSOR = process.env.SENSOR ?? 'hn-stadtgalerie-01'
const SSE_TIMEOUT_MS = Number(process.env.SSE_TIMEOUT_MS ?? 8000)
const EXPECT_HEARTBEAT = process.env.EXPECT_HEARTBEAT === '1'
const verbose = process.env.VERBOSE === '1'
const AUTHORIZATION = `Basic ${Buffer.from(`${CONTROL_USER}:${CONTROL_PASS}`).toString('base64')}`
function url(path) {
return new URL(path, `${WEB_URL}/`).toString()
}
function log(message) {
console.log(` ${message}`)
}
function pass(message) {
console.log(`PASS ${message}`)
}
function fail(message) {
console.error(`FAIL ${message}`)
}
async function fetchText(path, options = {}) {
const response = await fetch(url(path), options)
const text = await response.text()
if (verbose) log(`${options.method ?? 'GET'} ${path} -> ${response.status}`)
return { response, text }
}
async function fetchJson(path, options = {}) {
const { response, text } = await fetchText(path, {
...options,
headers: { accept: 'application/json', ...(options.headers ?? {}) },
})
let body
try {
body = JSON.parse(text)
} catch {
throw new Error(`${path} returned non-JSON (${response.status}): ${text.slice(0, 200)}`)
}
return { response, body }
}
async function expectJson(path, options, status = 200) {
const { response, body } = await fetchJson(path, options)
assert.equal(response.status, status, `${path} status ${response.status}, expected ${status}: ${JSON.stringify(body)}`)
return body
}
function parseFrame(frame) {
let name = 'message'
let id = ''
let retry = ''
const data = []
for (const line of frame.split('\n')) {
if (!line || line.startsWith(':')) continue
const separator = line.indexOf(':')
const field = separator < 0 ? line : line.slice(0, separator)
const value = separator < 0 ? '' : line.slice(separator + 1).replace(/^ /, '')
if (field === 'event') name = value
else if (field === 'id') id = value
else if (field === 'data') data.push(value)
else if (field === 'retry') retry = value
}
if (!data.length && name === 'message' && !retry) return null
return { name: data.length || name !== 'message' ? name : 'retry', id, retry, data: data.join('\n') }
}
/** Minimal incremental SSE reader over fetch (Node has no EventSource). */
function openSse(path) {
const controller = new AbortController()
const events = []
const waiters = new Set()
let raw = ''
let buffer = ''
let finished = false
const notify = () => {
for (const waiter of [...waiters]) waiter()
}
const consume = () => {
while (true) {
const match = buffer.match(/\r?\n\r?\n/)
if (!match || match.index === undefined) break
const frame = buffer.slice(0, match.index)
buffer = buffer.slice(match.index + match[0].length)
const event = parseFrame(frame)
if (event) {
events.push(event)
notify()
}
}
}
const responsePromise = fetch(url(path), {
headers: { accept: 'text/event-stream' },
signal: controller.signal,
}).then(async (response) => {
assert.equal(response.status, 200, `SSE status ${response.status}`)
const contentType = response.headers.get('content-type') ?? ''
assert.match(contentType, /text\/event-stream/, `SSE content-type: ${contentType}`)
const reader = response.body.getReader()
const decoder = new TextDecoder()
;(async () => {
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value, { stream: true })
raw += chunk
buffer += chunk.replace(/\r\n/g, '\n')
consume()
}
} catch (error) {
if (error?.name !== 'AbortError') throw error
} finally {
finished = true
notify()
}
})()
return response
})
function waitFor(predicate, timeoutMs, label) {
const existing = events.find(predicate)
if (existing) return Promise.resolve(existing)
if (finished) return Promise.reject(new Error(`SSE closed before ${label}`))
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
waiters.delete(check)
reject(new Error(`Timed out after ${timeoutMs} ms waiting for ${label}`))
}, timeoutMs)
const check = () => {
const match = events.find(predicate)
if (!match) return
clearTimeout(timer)
waiters.delete(check)
resolve(match)
}
waiters.add(check)
})
}
return {
responsePromise,
waitFor,
get raw() {
return raw
},
close() {
controller.abort()
},
}
}
function decisionShape(plan) {
return JSON.stringify({
scenario: plan.scenario,
summary: plan.summary,
footfall: plan.hours.map((hour) => [hour.t, hour.footfall, hour.required_staff, hour.scheduled_staff]),
})
}
async function main() {
console.log(`PulseCast live smoke test -> ${WEB_URL}`)
const health = await expectJson('/api/healthz')
assert.equal(health.ok, true, 'healthz.ok')
pass('Nitro health endpoint')
const ready = await expectJson('/api/readyz')
assert.equal(ready.ok, true, 'readyz.ok')
assert.equal(ready.data, true, 'readyz.data (Go bootstrap snapshot)')
assert.equal(ready.model, true, 'readyz.model (FastAPI)')
pass('Go API ready with ML snapshot')
const initial = await expectJson('/api/scenario')
assert.equal(typeof initial.version, 'number', 'scenario.version')
assert.ok(initial.scenario?.scenario, 'scenario.scenario')
pass(`scenario state v${initial.version} (${initial.scenario.scenario})`)
const basePlan = await expectJson(
`/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=base&standard=standard`,
)
assert.equal(basePlan.sensor, SENSOR)
assert.equal(basePlan.scenario, 'base')
assert.ok(basePlan.hours.length > 0, 'base plan has open hours')
assert.ok(basePlan.shifts.length > 0, 'base plan has shift blocks')
pass(`base plan: ${basePlan.hours.length} hours, ${basePlan.shifts.length} shifts`)
const baseForecast = await expectJson(
`/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=base`,
)
assert.ok(baseForecast.points.length > 0, 'base forecast has points')
pass(`base forecast: ${baseForecast.points.length} hourly points`)
const unauthenticated = await fetchJson('/api/scenario', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scenario: 'rainy-saturday' }),
})
assert.equal(unauthenticated.response.status, 401, 'POST without presenter auth must be 401')
pass('unauthenticated scenario POST is rejected')
const controlPage = await fetchText('/control')
assert.equal(controlPage.response.status, 401, '/control without auth must be 401')
assert.match(controlPage.response.headers.get('www-authenticate') ?? '', /Basic/i)
pass('/control is presenter-protected')
const controlAuthed = await fetchText('/control', { headers: { authorization: AUTHORIZATION } })
assert.equal(controlAuthed.response.status, 200, '/control with auth')
assert.match(controlAuthed.text, /Presenter control/i)
pass('/control authenticates and renders')
for (const [path, needle] of [
['/stage', 'Scan for the phone view'],
['/live', 'The plan on your phone'],
]) {
const page = await fetchText(path)
assert.equal(page.response.status, 200, `${path} status`)
assert.match(page.response.headers.get('content-type') ?? '', /text\/html/i, `${path} content-type`)
assert.ok(page.text.includes(needle), `${path} contains "${needle}"`)
assert.ok(page.text.includes('PulseCast'), `${path} contains the app shell`)
pass(`${path} renders server-side`)
}
const qr = await fetchText(`/api/qr?text=${encodeURIComponent(`${WEB_URL}/live`)}`)
assert.equal(qr.response.status, 200, 'QR status')
assert.match(qr.response.headers.get('content-type') ?? '', /image\/svg\+xml/i, 'QR content-type')
assert.match(qr.text, /<svg/i, 'QR is SVG')
pass('QR route returns SVG locally')
const sse = openSse('/api/stream')
try {
await sse.responsePromise
const initialEvent = await sse.waitFor(
(event) => event.name === 'scenario' || event.name === 'retry',
5000,
'the initial SSE frame',
)
assert.ok(initialEvent, 'initial SSE frame')
if (EXPECT_HEARTBEAT) {
await sse.waitFor((event) => event.name === 'ping', SSE_TIMEOUT_MS, 'a heartbeat ping')
pass('SSE heartbeat observed')
}
assert.match(sse.raw, /retry:\s*3000/, 'SSE retry hint')
const initialScenarioEvent = await sse.waitFor(
(event) => event.name === 'scenario',
5000,
'the initial scenario event',
)
const initialPayload = JSON.parse(initialScenarioEvent.data)
assert.equal(typeof initialPayload.version, 'number', 'SSE initial version')
pass(`SSE connected: retry:3000, initial scenario v${initialPayload.version}`)
const target = initialPayload.scenario === 'rainy-saturday' ? 'sunny-saturday-market' : 'rainy-saturday'
const body =
target === 'sunny-saturday-market'
? {
scenario: target,
weather: { temp_delta_c: 4, precip_mm: 0 },
event: { type: 'market', uplift: 0.2 },
}
: {
scenario: target,
weather: { temp_delta_c: -2, precip_mm: 3.2 },
}
const started = performance.now()
const posted = await expectJson('/api/scenario', {
method: 'POST',
headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' },
body: JSON.stringify(body),
})
assert.equal(posted.scenario.scenario, target, 'POST response scenario')
const postMs = performance.now() - started
const event = await sse.waitFor(
(candidate) => {
if (candidate.name !== 'scenario') return false
try {
const payload = JSON.parse(candidate.data)
return payload.version >= posted.version && payload.scenario?.scenario === target
} catch {
return false
}
},
5000,
`a scenario SSE event for ${target}`,
)
const elapsed = performance.now() - started
const payload = JSON.parse(event.data)
assert.equal(payload.scenario.scenario, target, 'SSE scenario id')
assert.equal(event.id, String(payload.version), 'SSE id equals the scenario version')
assert.ok(elapsed < 5000, `scenario event took ${elapsed.toFixed(0)} ms (max 5000)`)
if (elapsed >= 2000) {
console.warn(`WARN scenario propagated in ${elapsed.toFixed(0)} ms; contract target is <2000 ms`)
}
pass(`scenario POST -> SSE event in ${elapsed.toFixed(0)} ms (POST ${postMs.toFixed(0)} ms)`)
const polled = await expectJson('/api/scenario')
assert.equal(polled.version, posted.version, 'GET /api/scenario polling version')
assert.equal(polled.scenario.scenario, target, 'GET /api/scenario polling scenario')
pass(`polling fallback reads v${polled.version} (${target})`)
const targetPlan = await expectJson(
`/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=${target}&standard=standard`,
)
assert.equal(targetPlan.scenario, target, 'target plan scenario')
assert.ok(targetPlan.hours.length > 0, 'target plan has hours')
assert.notEqual(
decisionShape(targetPlan),
decisionShape(basePlan),
`${target} plan must differ from base`,
)
if (targetPlan.cached) {
console.warn('WARN Go served a cached plan; ML was not used for this request')
} else {
pass('target plan is live and differs from base')
}
const targetForecast = await expectJson(
`/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=${target}`,
)
assert.equal(targetForecast.scenario, target, 'target forecast scenario')
assert.ok(targetForecast.points.length > 0, 'target forecast has points')
assert.notEqual(
JSON.stringify(targetForecast.points),
JSON.stringify(baseForecast.points),
`${target} forecast must differ from base`,
)
pass('target forecast is live and differs from base')
const stageAfter = await fetchText('/stage')
assert.equal(stageAfter.response.status, 200, 'stage after scenario')
const expectedLabel = target === 'rainy-saturday' ? 'Rainy Saturday' : 'Sunny Saturday'
assert.ok(stageAfter.text.includes(expectedLabel), `stage renders ${expectedLabel}`)
pass(`/stage server-renders the new scenario (${expectedLabel})`)
const liveAfter = await fetchText('/live')
assert.equal(liveAfter.response.status, 200, 'live after scenario')
assert.ok(liveAfter.text.includes(expectedLabel), `live renders ${expectedLabel}`)
pass(`/live server-renders the new scenario (${expectedLabel})`)
// Leave the demo in the base state so the next run is deterministic.
const restored = await expectJson('/api/scenario', {
method: 'POST',
headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' },
body: JSON.stringify({ scenario: 'base', weather: { temp_delta_c: 0, precip_mm: 0 } }),
})
assert.equal(restored.scenario.scenario, 'base')
pass(`restored base (v${restored.version})`)
} finally {
sse.close()
}
console.log('\nAll live smoke checks passed.')
}
main().catch((error) => {
fail(error?.stack ?? String(error))
process.exitCode = 1
})