feat(status): a status page, for the phone of whoever looks after the box

Is the box up, and speech, and the brain; how many conversations,
turns, IR presses, and looks, today and all time. Counts and times
only: no transcripts.

- status/status.js: what the events and checks add up to, and the page
- status/status-server.js: the page, the box's events and heartbeat,
  and a TCP check of each part every 30 s; events kept in a file
- status/pdtv26-status.service and Makefile: sudo make install on the
  home server, answering only the private network
- checks: status (its tests)

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-12-02 18:57:08 -06:00
1 parent 5cbea49349
commit 9b85deca8f
8 files changed
+517

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env node
/**
* @file status-server: the agent's status page, for a phone, on the private network.
* usage: status-server.js HOST PORT STATE_DIR NAME BOX SPEECH BRAIN
* NAME: the box's name, for the page's title.
* BOX, SPEECH, BRAIN: host:port to check with a TCP connect (the box's ir capability, the speech
* server, the brain's channel).
* GET / is the page. The box POSTs /event ({kind, source, ...}: status.js KINDS) and /heartbeat.
* Events are kept in STATE_DIR/events.jsonl, so the counts survive a restart.
* No key: the private network is the boundary, and nothing here is more than counts and times.
*/
import { appendFile, readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { connect as connectTcp } from 'node:net';
import process from 'node:process';
import { buffer } from 'node:stream/consumers';
import { cleanEvent, render, Status } from './status.js';
/**
* Can we open a TCP connection to host:port within ms?
* @param {typeof connectTcp} connect
* @param {string} hostPort
* @param {number} [ms]
* @returns {Promise<boolean>}
*/
const reachable = (connect, hostPort, ms = 3000) => new Promise((resolve) => {
const i = hostPort.lastIndexOf(':');
const sock = connect({ host: hostPort.slice(0, i), port: Number(hostPort.slice(i + 1)) });
/** @param {boolean} up */
const done = (up) => { sock.destroy(); resolve(up); };
sock.setTimeout(ms, () => done(false));
sock.once('connect', () => done(true));
sock.once('error', () => done(false));
});
/**
* Serve the status page at HOST:PORT, and check on the parts every 30 s.
*
* @param {object} [io] what it reaches; the process's own, by default
* @param {string[]} [io.argv] HOST PORT STATE_DIR NAME BOX SPEECH BRAIN
* @param {typeof readFile} [io.read] reads STATE_DIR/events.jsonl
* @param {typeof appendFile} [io.append] adds to it
* @param {typeof connectTcp} [io.connect] checks BOX, SPEECH, and BRAIN
* @param {typeof createServer} [io.serve]
* @param {() => number} [io.now]
* @param {typeof setInterval} [io.every]
*/
const main = async ({
argv = process.argv.slice(2),
read = readFile,
append = appendFile,
connect = connectTcp,
serve = createServer,
now = Date.now,
every = setInterval,
} = {}) => {
const [host, port, stateDir, name, box, speech, brain] = argv;
/** @param {string} msg */
const log = (msg) => console.log(msg);
/** @param {number} t */
const dayOf = (t) => new Date(t).toLocaleDateString('en-CA');
/** @param {number} t */
const clock = (t) => new Date(t).toLocaleString('en-US', { weekday: 'short', hour: 'numeric', minute: '2-digit' });
const status = new Status(dayOf);
const file = `${stateDir}/events.jsonl`;
const saved = await read(file, 'utf8').catch((err) => (err.code === 'ENOENT' ? '' : Promise.reject(err)));
for (const line of saved.split('\n').filter(Boolean)) {
try {
const ev = cleanEvent(JSON.parse(line));
if (ev) status.record(ev);
} catch (err) {
log(`skipping a bad line in ${file}: ${err.message}`);
}
}
log(`status-server: ${status.size()} events from ${file}`);
const targets = { box, speech, brain };
const checkAll = async () => {
await Promise.all(Object.entries(targets).map(async ([part, hostPort]) => {
const up = await reachable(connect, hostPort);
const before = status.summary(now()).checks.find((c) => c.name === part);
if (before?.up !== up) log(`${part} (${hostPort}) ${up ? 'up' : 'down'}`);
status.check(part, up, now());
}));
};
await checkAll();
every(() => { checkAll().catch((err) => log(`checks failed: ${err.message}`)); }, 30_000);
const server = serve(async (req, res) => {
try {
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(render(status.summary(now()), clock, name));
} else if (req.method === 'POST' && req.url === '/heartbeat') {
status.beat(now());
res.writeHead(204).end();
} else if (req.method === 'POST' && req.url === '/event') {
const body = await buffer(req);
if (body.length > 1024) { res.writeHead(413).end(); return; }
const ev = cleanEvent({ ...JSON.parse(body.toString()), at: now() });
if (!ev) { res.writeHead(400).end('not an event I keep\n'); return; }
status.record(ev);
await append(file, `${JSON.stringify(ev)}\n`);
log(`event: ${ev.source} ${ev.kind}${ev.reason ? ` ${ev.reason}` : ''}`);
res.writeHead(204).end();
} else {
res.writeHead(404).end();
}
} catch (err) {
log(`${req.method} ${req.url} failed: ${err.message}`);
if (!res.headersSent) res.writeHead(400);
res.end();
}
});
server.listen(Number(port), host, () => log(`status-server: listening on ${host}:${port}`));
};
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});