import { createLogger } from '../core/logger.js'; /** * Server-sent events feeding the dashboard live (M16-T12). * * One long-lived GET per open tab, pushed to rather than polled: a browser that * nobody is looking at costs a heartbeat every 25 seconds, and a change shows up * as soon as it happens instead of on the next timer. */ const log = createLogger('web:events'); const HEARTBEAT_MS = 25_000; const TICK_MS = 15_000; /** Past this, something is wrong: refuse rather than pile up dead sockets. */ const MAX_SUBSCRIBERS = 64; const subscribers = new Set(); let heartbeat = null; let tick = null; function write(subscriber, payload) { try { subscriber.response.write(payload); } catch (error) { log.debug('Dropping a closed event subscriber', error); remove(subscriber); } } function remove(subscriber) { if (!subscribers.delete(subscriber)) return; try { subscriber.response.end(); } catch { // The socket is already gone, which is exactly why we are here. } if (subscribers.size === 0) stopTimers(); } function startTimers() { if (heartbeat) return; // Comment frames keep proxies from closing an idle stream. heartbeat = setInterval(() => { for (const subscriber of subscribers) write(subscriber, ': ping\n\n'); }, HEARTBEAT_MS); tick = setInterval(() => broadcast('tick', { at: new Date().toISOString() }), TICK_MS); // Timers must never be the reason the process stays alive. heartbeat.unref?.(); tick.unref?.(); } function stopTimers() { clearInterval(heartbeat); clearInterval(tick); heartbeat = null; tick = null; } /** Publishes an event to every open dashboard. Never throws. */ export function broadcast(topic, payload = {}) { if (subscribers.size === 0) return 0; const frame = `event: ${topic}\ndata: ${JSON.stringify({ topic, ...payload })}\n\n`; for (const subscriber of subscribers) write(subscriber, frame); return subscribers.size; } /** * Registers a subscriber and keeps the response open. * Returns nothing: the router must not try to serialise a body onto it. */ export function openEventStream(request, response, actor) { if (subscribers.size >= MAX_SUBSCRIBERS) { response.writeHead(503).end(); return; } response.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', // `no-transform` and the nginx hint both matter: a buffering proxy turns a // live stream into a stream that arrives all at once, much later. 'Cache-Control': 'no-cache, no-transform', 'X-Accel-Buffering': 'no', Connection: 'keep-alive', 'X-Content-Type-Options': 'nosniff', }); response.flushHeaders?.(); const subscriber = { response, userId: actor?.userId ?? null }; subscribers.add(subscriber); startTimers(); write(subscriber, `retry: 5000\nevent: ready\ndata: ${JSON.stringify({ topic: 'ready' })}\n\n`); request.on('close', () => remove(subscriber)); request.on('error', () => remove(subscriber)); log.debug('Event subscriber connected', { subscribers: subscribers.size }); } export function subscriberCount() { return subscribers.size; } /** Closes every stream, so a shutdown does not hang on open sockets. */ export function closeEventStreams() { for (const subscriber of [...subscribers]) remove(subscriber); stopTimers(); } /** * Turns an API path into the topic a view can filter on, so a write made * anywhere refreshes the pages that care and only those. */ export function topicForPath(pathname) { const [, , section] = pathname.split('/'); switch (section) { case 'deploy': case 'deployments': return 'deployments'; case 'repositories': case 'organization': return 'gitea'; case 'projects': return 'projects'; case 'discord': return 'discord'; case 'community': return 'community'; case 'settings': case 'configuration': return 'settings'; default: return 'mutation'; } }