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:
6 files changed
+351
-1
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user