Files
pipelines/app/tool/pipelines_wiring_probe_server.mjs
T
alan 8476cfd740 feat(app): wire the native pipelines browser on the shared session
Register the landed PipelinesScreen at /pipelines through AppSession, with
an honest first-connection gate, a native reconnect banner that retains the
open list and detail, and an in-place refresh on reconnect. Move the shared
connection chrome out of RunsDestination so both destinations use one
implementation and one wording.

Add destination, registration and reconnect coverage plus an isolated
loopback Chrome probe that drives the real runPipelinesApp() composition.
2026-10-21 19:47:08 +01:00

395 lines
11 KiB
JavaScript

import { createHash } from 'node:crypto';
import { createServer } from 'node:http';
import { readFile, realpath, stat } from 'node:fs/promises';
import { extname, join, resolve, sep } from 'node:path';
import { once } from 'node:events';
// Isolated loopback fixture for the Pipelines wiring probe. It serves the
// normal application composition and answers the read-only protocol with
// deterministic data. No production server, database or operator data.
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
const PIPELINES = [
{
id: 3,
name: 'Release verification',
version: 3,
stages: 4,
created_at: '2026-09-28T10:12:00',
updated_at: '2026-10-21T09:40:00',
scheduled: true,
schedule_count: 2,
enabled_schedule_count: 1,
},
{
id: 7,
name: 'Nightly documentation',
version: 1,
stages: 2,
created_at: '2026-10-02T18:20:00',
updated_at: '2026-10-20T22:05:00',
scheduled: true,
schedule_count: 1,
enabled_schedule_count: 1,
},
];
const RUNS = [
{
id: 488,
pipeline_id: 3,
status: 'succeeded',
created_at: '2026-10-21T09:30:00',
finished_at: '2026-10-21T09:34:12',
executing: false,
},
{
id: 487,
pipeline_id: 7,
status: 'running',
created_at: '2026-10-21T09:20:00',
finished_at: '',
executing: true,
},
];
const VERSIONS = [
{ version: 1, stages: 2, created_at: '2026-09-28T10:12:00' },
{ version: 2, stages: 3, created_at: '2026-10-08T15:44:00' },
{ version: 3, stages: 4, created_at: '2026-10-21T09:12:00' },
];
const SOURCE = `name: Release verification
stages:
inspect:
type: model
output: report
verify:
type: model
output: verdict
`;
const SOURCE_V2 = `${SOURCE} # selected version 2
`;
function detail(id, requestedVersion) {
const summary = PIPELINES.find((pipeline) => pipeline.id === id) ?? PIPELINES[0];
const versions = id === 3 ? VERSIONS : VERSIONS.slice(0, 1);
const latest = versions[versions.length - 1].version;
const version = requestedVersion > 0 ? requestedVersion : latest;
return {
...summary,
version,
stages: versions.find((row) => row.version === version)?.stages ?? summary.stages,
latest_version: id === 3 ? latest : 1,
version_created_at:
versions.find((row) => row.version === version)?.created_at ?? summary.created_at,
content_hash: `sha256:fixture-${id}-v${version}`,
source: id === 3 && version === 2 ? SOURCE_V2 : SOURCE,
versions,
};
}
function accept(key) {
return createHash('sha1')
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
.digest('base64');
}
function frame(opcode, payload) {
const length = payload.length;
let header;
if (length < 126) {
header = Buffer.from([0x80 | opcode, length]);
} else if (length < 65536) {
header = Buffer.alloc(4);
header[0] = 0x80 | opcode;
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[0] = 0x80 | opcode;
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
return Buffer.concat([header, payload]);
}
class Connection {
constructor(socket, owner) {
this.socket = socket;
this.owner = owner;
this.buffer = Buffer.alloc(0);
this.fragments = [];
this.fragmentOpcode = 0;
}
push(chunk) {
if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]);
this.parse();
}
parse() {
while (this.buffer.length >= 2) {
const first = this.buffer[0];
const second = this.buffer[1];
const fin = (first & 0x80) !== 0;
const opcode = first & 0x0f;
const masked = (second & 0x80) !== 0;
let length = second & 0x7f;
let offset = 2;
if (length === 126) {
if (this.buffer.length < 4) return;
length = this.buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (this.buffer.length < 10) return;
length = Number(this.buffer.readBigUInt64BE(2));
offset = 10;
}
const maskOffset = offset;
if (masked) {
if (this.buffer.length < offset + 4) return;
offset += 4;
}
if (this.buffer.length < offset + length) return;
let payload = Buffer.from(this.buffer.subarray(offset, offset + length));
if (masked) {
const mask = this.buffer.subarray(maskOffset, maskOffset + 4);
for (let index = 0; index < payload.length; index++) {
payload[index] ^= mask[index % 4];
}
}
this.buffer = this.buffer.subarray(offset + length);
this.handleFrame(fin, opcode, payload);
}
}
handleFrame(fin, opcode, payload) {
if (opcode === 0x8) return this.close();
if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload));
if (opcode === 0x0a) return;
if (opcode === 0x0) {
this.fragments.push(payload);
if (fin) {
const data = Buffer.concat(this.fragments);
this.fragments = [];
this.message(this.fragmentOpcode, data);
}
return;
}
if (opcode !== 0x1) return;
if (!fin) {
this.fragmentOpcode = opcode;
this.fragments = [payload];
return;
}
this.message(opcode, payload);
}
message(_opcode, payload) {
let request;
try {
request = JSON.parse(payload.toString('utf8'));
} catch {
return;
}
this.owner.onMessage(this, request);
}
send(value) {
if (!this.socket.destroyed) {
this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value))));
}
}
close() {
if (!this.socket.destroyed) this.socket.end();
}
}
async function staticFile(base, pathname, req, res) {
let file = resolve(base, `.${pathname}`);
if (file !== base && !file.startsWith(base + sep)) {
res.writeHead(403).end();
return;
}
try {
if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
} catch {
if (extname(pathname)) {
res.writeHead(404).end('not found');
return;
}
file = join(base, 'index.html');
}
try {
const body = await readFile(file);
res
.writeHead(200, {
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
.end(req.method === 'HEAD' ? undefined : body);
} catch {
res.writeHead(404).end('not found');
}
}
export async function startWiringFixture({ root, refuse = false }) {
const base = await realpath(root);
const connections = new Set();
const sockets = new Set();
const counts = { subscribed: 0, listPipelines: 0, listRuns: 0, getPipeline: 0, dropped: 0 };
let refusing = refuse;
const dropConnections = () => {
for (const connection of connections) connection.close();
connections.clear();
counts.dropped++;
};
const server = createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://fixture').pathname;
if (pathname === '/fixture/drop' && req.method === 'POST') {
dropConnections();
res.writeHead(200).end('{"ok":true}');
return;
}
if (pathname === '/fixture/refuse' && req.method === 'POST') {
refusing = true;
dropConnections();
res.writeHead(200).end('{"ok":true}');
return;
}
if (pathname === '/fixture/accept' && req.method === 'POST') {
refusing = false;
res.writeHead(200).end('{"ok":true}');
return;
}
if (pathname === '/fixture/state') {
res
.writeHead(200, { 'content-type': 'application/json' })
.end(JSON.stringify({ ...counts, connections: connections.size, refusing }));
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405).end();
return;
}
await staticFile(base, pathname, req, res);
});
server.on('upgrade', (req, socket, head) => {
if (refusing) {
socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
return;
}
const url = new URL(req.url, 'http://fixture');
if (
url.pathname !== '/connect' ||
req.headers.upgrade?.toLowerCase() !== 'websocket' ||
!req.headers['sec-websocket-key']
) {
socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
return;
}
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`,
);
const connection = new Connection(socket, {
onMessage: (client, request) => {
switch (request.type) {
case 'subscribe':
counts.subscribed++;
return;
case 'unsubscribe':
return;
case 'list_pipelines':
counts.listPipelines++;
client.send({ id: request.id, type: 'pipelines', pipelines: PIPELINES });
return;
case 'list_runs':
counts.listRuns++;
client.send({ id: request.id, type: 'runs', runs: RUNS });
return;
case 'get_pipeline': {
counts.getPipeline++;
const id = request.pipeline_id;
if (!PIPELINES.some((pipeline) => pipeline.id === id)) {
client.send({
id: request.id,
type: 'error',
error: `Fixture pipeline ${id} is unavailable`,
});
return;
}
client.send({
id: request.id,
type: 'pipeline',
detail: detail(id, request.version),
});
return;
}
case 'ping':
client.send({
id: request.id,
type: 'pong',
build: { version: 'Fixture wiring build' },
time: '2026-10-21T12:00:00Z',
});
return;
default:
client.send({
id: request.id,
type: 'error',
error: `Fixture does not implement ${request.type}`,
});
}
},
});
connections.add(connection);
socket.on('data', (chunk) => connection.push(chunk));
socket.on('close', () => connections.delete(connection));
socket.on('error', () => connections.delete(connection));
connection.push(head);
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
server.on('connection', (socket) => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
});
return {
server,
url: `http://127.0.0.1:${server.address().port}`,
state: async () => (await fetch(`http://127.0.0.1:${server.address().port}/fixture/state`)).json(),
close: () =>
new Promise((resolveClose) => {
for (const connection of connections) connection.close();
server.close(() => resolveClose());
for (const socket of sockets) socket.destroy();
}),
};
}