diff --git a/src/web/api/index.js b/src/web/api/index.js index 7705500..f656efa 100644 --- a/src/web/api/index.js +++ b/src/web/api/index.js @@ -1,4 +1,6 @@ +import { ACCESS_LEVELS } from '../../config/constants.js'; import { registerAuthRoutes } from '../auth/routes.js'; +import { openEventStream } from '../events.js'; import { registerCommunityRoutes } from './community.js'; import { registerConfigurationRoutes } from './configuration.js'; import { registerDeploymentRoutes } from './deployments.js'; @@ -30,6 +32,15 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) { registerAuthRoutes(router); registerConfigurationRoutes(router); + // Long-lived stream the pages listen to instead of polling (M16-T12). + router.get( + '/api/events', + ({ request, response, actor }) => { + openEventStream(request, response, actor); + }, + { access: ACCESS_LEVELS.STAFF }, + ); + // In bootstrap mode the bot is not connected and the database may be empty: // only the wizard makes sense. if (setupOnly) return router; diff --git a/src/web/events.js b/src/web/events.js new file mode 100644 index 0000000..1cf81af --- /dev/null +++ b/src/web/events.js @@ -0,0 +1,135 @@ +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 'discord': + return 'discord'; + case 'community': + return 'community'; + case 'settings': + case 'configuration': + return 'settings'; + default: + return 'mutation'; + } +} diff --git a/src/web/server.js b/src/web/server.js index e58550f..76fda41 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -8,6 +8,7 @@ import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js'; import { registerApiRoutes } from './api/index.js'; import { authenticate, assertSameOrigin } from './auth/session.js'; import { authorize } from './auth/guard.js'; +import { broadcast, closeEventStreams, topicForPath } from './events.js'; import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js'; import { createRouter } from './router.js'; @@ -102,8 +103,15 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da context, }); - // A handler that wrote the response itself (a redirect) returns nothing. + // A handler that wrote the response itself (a redirect, an event stream) + // returns nothing. if (!response.headersSent) sendJson(response, 200, result ?? { ok: true }); + + // Announce the change only once it has gone through, so a dashboard never + // refreshes on a write that was rejected. + if (request.method !== 'GET') { + broadcast(topicForPath(pathname), { path: pathname, method: request.method }); + } } catch (error) { const status = statusOf(error); if (status >= 500) log.error(`${request.method} ${pathname} failed`, error); @@ -127,6 +135,8 @@ export function startWebServer({ client = null, setupOnly = false } = {}) { log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly }); }); server.on('error', (error) => log.error('Dashboard server error', error)); + // Open event streams would otherwise keep the server from closing. + server.on('close', closeEventStreams); return server; } diff --git a/src/web/services/deploy-service.js b/src/web/services/deploy-service.js index 3fb62d9..b780fca 100644 --- a/src/web/services/deploy-service.js +++ b/src/web/services/deploy-service.js @@ -12,6 +12,7 @@ import { import { logEvent } from '../../database/repositories/event-log-repository.js'; import { notify } from '../../services/notifications/notification-service.js'; import { splitRepository, repos } from '../../services/gitea/gitea-admin.js'; +import { broadcast } from '../events.js'; import { HttpError, badRequest, forbidden } from '../http.js'; /** Runs a deployment for a target and records its outcome (M16-T07). */ @@ -156,6 +157,7 @@ export async function runDeployment( triggeredBy, }); markRunning(deployment.id); + broadcast('deployments', { id: deployment.id, status: 'running', target: target.name }); const payload = { deploymentId: deployment.id, @@ -177,12 +179,14 @@ export async function runDeployment( else output = await runGiteaAction(target, payload); finishDeployment(deployment.id, { status: 'success', log: output }); + broadcast('deployments', { id: deployment.id, status: 'success', target: target.name }); logEvent({ guildId, type: 'deploy.success', actorId: triggeredBy, payload }); await announce(client, { ...payload, status: 'success' }); return { ...deployment, status: 'success', log: output }; } catch (error) { const details = error.details ?? error.message; finishDeployment(deployment.id, { status: 'failed', log: details, error: error.message }); + broadcast('deployments', { id: deployment.id, status: 'failed', target: target.name }); log.error('Deployment failed', error); logEvent({ guildId, type: 'deploy.failed', actorId: triggeredBy, payload }); await announce(client, { ...payload, status: 'failed', error: error.message }); diff --git a/src/webhooks/gitea-webhook.js b/src/webhooks/gitea-webhook.js index 12dd1bc..70bae6e 100644 --- a/src/webhooks/gitea-webhook.js +++ b/src/webhooks/gitea-webhook.js @@ -5,6 +5,7 @@ import { getDatabase } from '../database/index.js'; import { logEvent } from '../database/repositories/event-log-repository.js'; import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js'; import { notify } from '../services/notifications/notification-service.js'; +import { broadcast } from '../web/events.js'; const log = createLogger('webhooks'); @@ -60,6 +61,8 @@ export async function handleGiteaWebhook(client, headers, rawBody) { payload: { deliveryId, type: notification.type }, }); + broadcast('gitea', { event, repository: payload.repository?.full_name ?? null }); + await notify(client, notification.type, { embeds: [notification.embed], content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined, diff --git a/tests/web-events.test.js b/tests/web-events.test.js new file mode 100644 index 0000000..cd6bf8c --- /dev/null +++ b/tests/web-events.test.js @@ -0,0 +1,187 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { createApiToken } from '../src/database/repositories/web-session-repository.js'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { hashToken } from '../src/web/auth/session.js'; +import { broadcast, closeEventStreams, subscriberCount, topicForPath } from '../src/web/events.js'; +import { createHandler } from '../src/web/server.js'; + +/** Live updates pushed over server-sent events (M16-T12). */ + +const TOKEN = 'fws_events-test-token'; + +/** Reads SSE frames off the socket until `stop()` is called. */ +function openStream(url) { + const controller = new AbortController(); + const frames = []; + let resolveReady; + const ready = new Promise((resolve) => (resolveReady = resolve)); + + const done = fetch(url, { + headers: { Authorization: `Bearer ${TOKEN}`, Accept: 'text/event-stream' }, + signal: controller.signal, + }).then(async (response) => { + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /text\/event-stream/); + resolveReady(response); + + const decoder = new TextDecoder(); + try { + for await (const chunk of response.body) frames.push(decoder.decode(chunk, { stream: true })); + } catch { + // Aborting the request is how the test ends the stream. + } + }); + + return { ready, frames, stop: () => controller.abort(), done }; +} + +/** Events land asynchronously; give the socket a moment to deliver. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 120)); + +describe('event topics', () => { + it('routes a write to the pages that care about it', () => { + assert.equal(topicForPath('/api/deploy/targets/3/run'), 'deployments'); + assert.equal(topicForPath('/api/deployments'), 'deployments'); + assert.equal(topicForPath('/api/repositories/FWS/Arch/issues'), 'gitea'); + assert.equal(topicForPath('/api/organization'), 'gitea'); + assert.equal(topicForPath('/api/discord/announce'), 'discord'); + assert.equal(topicForPath('/api/community/tickets/1/close'), 'community'); + assert.equal(topicForPath('/api/settings/values/x'), 'settings'); + assert.equal(topicForPath('/api/auth/logout'), 'mutation'); + }); + + it('does nothing when nobody is listening', () => { + assert.equal(broadcast('tick', {}), 0); + }); +}); + +describe('event stream', () => { + let server; + let base; + + before(async () => { + initDatabase(':memory:'); + createApiToken({ + name: 'events', + tokenHash: hashToken(TOKEN), + prefix: TOKEN.slice(0, 12), + accessLevel: ACCESS_LEVELS.OWNER, + }); + + server = createServer(createHandler({ client: null, setupOnly: false })); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + base = `http://127.0.0.1:${server.address().port}`; + }); + + after(async () => { + closeEventStreams(); + await new Promise((resolve) => server.close(resolve)); + closeDatabase(); + }); + + beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;')); + + it('refuses an anonymous listener', async () => { + const response = await fetch(`${base}/api/events`); + assert.equal(response.status, 401); + }); + + it('greets a subscriber and counts it', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + assert.equal(subscriberCount(), 1); + assert.match(stream.frames.join(''), /event: ready/); + assert.match(stream.frames.join(''), /retry: 5000/); + + stream.stop(); + await settle(); + assert.equal(subscriberCount(), 0); + }); + + it('pushes a broadcast to the open streams', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + assert.equal(broadcast('deployments', { id: 7, status: 'running' }), 1); + await settle(); + + const received = stream.frames.join(''); + assert.match(received, /event: deployments/); + assert.match(received, /"id":7/); + assert.match(received, /"topic":"deployments"/); + + stream.stop(); + await settle(); + }); + + it('announces a successful write, and only once it succeeded', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + const write = (body) => + fetch(`${base}/api/deploy/targets`, { + method: 'POST', + headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + + const rejected = await write({ name: '', repository: 'nope', kind: 'webhook' }); + assert.equal(rejected.status, 400); + await settle(); + assert.doesNotMatch(stream.frames.join(''), /event: deployments/); + + const accepted = await write({ + name: 'production', + repository: 'FWS/FWS-Arch', + kind: 'webhook', + config: { url: 'https://deploy.example/hook' }, + }); + assert.equal(accepted.status, 200); + await settle(); + + const received = stream.frames.join(''); + assert.match(received, /event: deployments/); + assert.match(received, /"method":"POST"/); + + stream.stop(); + await settle(); + }); + + it('stays silent on a read', async () => { + const stream = openStream(`${base}/api/events`); + await stream.ready; + await settle(); + + await fetch(`${base}/api/deployments`, { headers: { Authorization: `Bearer ${TOKEN}` } }); + await settle(); + assert.doesNotMatch(stream.frames.join(''), /event: deployments/); + + stream.stop(); + await settle(); + }); + + it('serves several dashboards at once', async () => { + const first = openStream(`${base}/api/events`); + const second = openStream(`${base}/api/events`); + await Promise.all([first.ready, second.ready]); + await settle(); + + assert.equal(broadcast('gitea', { event: 'push' }), 2); + await settle(); + + assert.match(first.frames.join(''), /event: gitea/); + assert.match(second.frames.join(''), /event: gitea/); + + first.stop(); + second.stop(); + await settle(); + assert.equal(subscriberCount(), 0); + }); +});