feat(web): push live updates to the dashboard

Reading a page and wondering whether it is still true is a poor way to watch
a deployment, and polling every page on a timer costs far more than it
returns.

The server keeps one `text/event-stream` per open tab and publishes on it:
a write once it has actually succeeded, tagged with the page it concerns, a
deployment when it starts and when it ends, an incoming Gitea webhook, plus
a tick and a heartbeat that stops proxies closing an idle stream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 20:39:59 +02:00
1 parent 9c6297e00e
commit df89cc5893
6 files changed
+351 -1

No files matched your search

+11
View File
@@ -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;
+135
View File
@@ -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';
}
}
+11 -1
View File
@@ -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;
}
+4
View File
@@ -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 });