- 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
277 lines
7.8 KiB
TypeScript
277 lines
7.8 KiB
TypeScript
import {
|
|
LIVE_LABELS,
|
|
liveStatus,
|
|
parseScenarioEvent,
|
|
scenarioChanged,
|
|
SCENARIO_POLL_MS,
|
|
SSE_FAILURES_BEFORE_POLLING,
|
|
SSE_STALE_MS,
|
|
} from '#shared/live'
|
|
import type { LiveConnection } from '#shared/live'
|
|
import type { ScenarioState } from '#shared/types'
|
|
|
|
interface LiveStore {
|
|
status: LiveConnection
|
|
serverScenario: ScenarioState | null
|
|
lastEventAt: string
|
|
lastPollAt: string
|
|
sseFailures: number
|
|
pollFailures: number
|
|
revision: number
|
|
error: string
|
|
}
|
|
|
|
// One stream per browser tab. The module-level store survives page navigation
|
|
// and is only mutated from onMounted/EventSource callbacks (never during SSR).
|
|
const store = reactive<LiveStore>({
|
|
status: 'connecting',
|
|
serverScenario: null,
|
|
lastEventAt: '',
|
|
lastPollAt: '',
|
|
sseFailures: 0,
|
|
pollFailures: 0,
|
|
revision: 0,
|
|
error: '',
|
|
})
|
|
|
|
let source: EventSource | null = null
|
|
let pollTimer: ReturnType<typeof setInterval> | null = null
|
|
let staleTimer: ReturnType<typeof setInterval> | null = null
|
|
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
|
let subscribers = 0
|
|
let started = false
|
|
let lastStaleRetry = 0
|
|
|
|
function nowIso(): string {
|
|
return new Date().toISOString()
|
|
}
|
|
|
|
function refreshStatus() {
|
|
store.status = liveStatus({
|
|
online: import.meta.client ? navigator.onLine !== false : true,
|
|
sseOpen: source?.readyState === EventSource.OPEN,
|
|
sseFailures: store.sseFailures,
|
|
polling: pollTimer !== null,
|
|
pollFailures: store.pollFailures,
|
|
})
|
|
}
|
|
|
|
function clearPolling() {
|
|
if (pollTimer) clearInterval(pollTimer)
|
|
pollTimer = null
|
|
}
|
|
|
|
function applyScenario(next: ScenarioState, origin: 'sse' | 'poll') {
|
|
const changed = scenarioChanged(store.serverScenario, next)
|
|
store.serverScenario = next
|
|
store.lastEventAt = nowIso()
|
|
store.error = ''
|
|
if (origin === 'poll') store.lastPollAt = store.lastEventAt
|
|
if (changed) store.revision += 1
|
|
}
|
|
|
|
async function pollScenario(): Promise<void> {
|
|
if (!import.meta.client) return
|
|
try {
|
|
const next = await $fetch<ScenarioState>('/api/scenario', {
|
|
headers: { accept: 'application/json' },
|
|
timeout: 5000,
|
|
})
|
|
store.pollFailures = 0
|
|
applyScenario(next, 'poll')
|
|
// A successful poll proves the API is reachable; stay "Polling" until SSE
|
|
// opens again, so the audience can see the fallback is active.
|
|
if (store.status === 'offline') store.status = 'polling'
|
|
} catch (error) {
|
|
store.pollFailures += 1
|
|
store.error = (error as { statusMessage?: string })?.statusMessage ?? 'Scenario polling failed'
|
|
}
|
|
refreshStatus()
|
|
}
|
|
|
|
function startPolling() {
|
|
if (!import.meta.client || pollTimer) return
|
|
void pollScenario()
|
|
pollTimer = setInterval(() => void pollScenario(), SCENARIO_POLL_MS)
|
|
refreshStatus()
|
|
}
|
|
|
|
function closeSource() {
|
|
if (source) {
|
|
source.close()
|
|
source = null
|
|
}
|
|
if (reconnectTimer) clearTimeout(reconnectTimer)
|
|
reconnectTimer = null
|
|
}
|
|
|
|
function connectSse() {
|
|
if (!import.meta.client) return
|
|
closeSource()
|
|
|
|
if (navigator.onLine === false) {
|
|
store.status = 'offline'
|
|
startPolling()
|
|
return
|
|
}
|
|
|
|
const eventSource = new EventSource('/api/stream')
|
|
source = eventSource
|
|
|
|
eventSource.onopen = () => {
|
|
if (source !== eventSource) return
|
|
store.sseFailures = 0
|
|
store.pollFailures = 0
|
|
store.error = ''
|
|
// Start the stale watchdog now: a proxy can accept the SSE headers and
|
|
// then buffer the body, so "open" does not prove events are flowing.
|
|
store.lastEventAt = nowIso()
|
|
clearPolling()
|
|
refreshStatus()
|
|
}
|
|
|
|
eventSource.addEventListener('scenario', (event) => {
|
|
if (source !== eventSource) return
|
|
const parsed = parseScenarioEvent((event as MessageEvent).data)
|
|
if (!parsed) {
|
|
store.error = 'Ignored a malformed scenario event'
|
|
return
|
|
}
|
|
store.sseFailures = 0
|
|
applyScenario(parsed, 'sse')
|
|
refreshStatus()
|
|
})
|
|
|
|
eventSource.addEventListener('ping', () => {
|
|
if (source !== eventSource) return
|
|
store.sseFailures = 0
|
|
store.lastEventAt = nowIso()
|
|
if (pollTimer && eventSource.readyState === EventSource.OPEN) clearPolling()
|
|
refreshStatus()
|
|
})
|
|
|
|
eventSource.onerror = () => {
|
|
if (source !== eventSource) return
|
|
store.sseFailures += 1
|
|
|
|
// A non-200 response (Nitro 502/503, proxy error) leaves EventSource in
|
|
// CLOSED and the browser will not retry it. Treat that as a definitive
|
|
// failure: start polling now and try the stream again on a timer. Network
|
|
// errors while CONNECTING still use the browser's own retry loop.
|
|
const fatal = eventSource.readyState === EventSource.CLOSED
|
|
if (fatal) {
|
|
store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING)
|
|
if (!reconnectTimer) {
|
|
reconnectTimer = setTimeout(() => {
|
|
if (!started) return
|
|
connectSse()
|
|
}, 5000)
|
|
}
|
|
}
|
|
|
|
if (store.sseFailures >= SSE_FAILURES_BEFORE_POLLING) startPolling()
|
|
refreshStatus()
|
|
}
|
|
}
|
|
|
|
function checkStale() {
|
|
if (!import.meta.client || !started) return
|
|
const sseOpen = source?.readyState === EventSource.OPEN
|
|
if (sseOpen && store.lastEventAt) {
|
|
const age = Date.now() - Date.parse(store.lastEventAt)
|
|
if (age > SSE_STALE_MS) {
|
|
// Connection is open but no ping arrived: Cloudflare/path buffering.
|
|
// Polling is the contract fallback; retry SSE once a minute.
|
|
store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING)
|
|
startPolling()
|
|
refreshStatus()
|
|
if (Date.now() - lastStaleRetry > 60000) {
|
|
lastStaleRetry = Date.now()
|
|
connectSse()
|
|
}
|
|
}
|
|
}
|
|
if (store.pollFailures > 0) refreshStatus()
|
|
}
|
|
|
|
function start() {
|
|
if (!import.meta.client || started) return
|
|
started = true
|
|
store.sseFailures = 0
|
|
store.pollFailures = 0
|
|
store.lastEventAt = ''
|
|
store.error = ''
|
|
store.status = 'connecting'
|
|
window.addEventListener('online', handleOnline)
|
|
window.addEventListener('offline', handleOffline)
|
|
staleTimer = setInterval(checkStale, 5000)
|
|
connectSse()
|
|
}
|
|
|
|
function stop() {
|
|
if (!import.meta.client) return
|
|
started = false
|
|
closeSource()
|
|
clearPolling()
|
|
if (staleTimer) clearInterval(staleTimer)
|
|
staleTimer = null
|
|
window.removeEventListener('online', handleOnline)
|
|
window.removeEventListener('offline', handleOffline)
|
|
store.status = 'connecting'
|
|
}
|
|
|
|
function handleOnline() {
|
|
if (!started) return
|
|
store.pollFailures = 0
|
|
connectSse()
|
|
void pollScenario()
|
|
}
|
|
|
|
function handleOffline() {
|
|
if (!started) return
|
|
store.status = 'offline'
|
|
if (pollTimer) clearInterval(pollTimer)
|
|
pollTimer = null
|
|
}
|
|
|
|
/**
|
|
* Subscribe the current page to the Go scenario stream through Nitro.
|
|
*
|
|
* The first render uses `initial` from SSR; after mount the composable opens
|
|
* `/api/stream`, shows Live/Polling/Offline, and falls back to GET
|
|
* /api/scenario every 5 s when SSE fails or is buffered.
|
|
*/
|
|
export function useLiveScenario(initial?: ScenarioState | null) {
|
|
const initialScenario = initial ?? null
|
|
|
|
const current = computed<ScenarioState | null>(() => store.serverScenario ?? initialScenario)
|
|
const scenarioId = computed(() => current.value?.scenario.scenario ?? 'base')
|
|
const status = computed(() => store.status)
|
|
const statusLabel = computed(() => LIVE_LABELS[store.status])
|
|
|
|
onMounted(() => {
|
|
// Seed after hydration so the first client paint matches the SSR HTML.
|
|
if (initialScenario && !store.serverScenario) store.serverScenario = initialScenario
|
|
subscribers += 1
|
|
start()
|
|
})
|
|
onBeforeUnmount(() => {
|
|
subscribers = Math.max(0, subscribers - 1)
|
|
if (subscribers === 0) stop()
|
|
})
|
|
|
|
return reactive({
|
|
scenario: current,
|
|
scenarioId,
|
|
version: computed(() => current.value?.version ?? 0),
|
|
scenarioAt: computed(() => current.value?.at ?? ''),
|
|
status,
|
|
statusLabel,
|
|
lastEventAt: computed(() => store.lastEventAt),
|
|
lastPollAt: computed(() => store.lastPollAt),
|
|
error: computed(() => store.error),
|
|
revision: computed(() => store.revision),
|
|
pollNow: pollScenario,
|
|
})
|
|
}
|