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:
1 parent
5cbea49349
commit
9b85deca8f
8 files changed
+517
No files matched your search
@@ -45,6 +45,8 @@ The agent has two parts: the box within reach of the couch, with an IR emitter o
|
|||||||
5. With the same `speech` capability, the box has the speech server voice the brain's reply (piper), and plays the WAV.
|
5. With the same `speech` capability, the box has the speech server voice the brain's reply (piper), and plays the WAV.
|
||||||
6. When the brain can't fix something, `report_problem` opens an issue on one repository, using a fine-grained token that can do nothing else, so the person who looks after the box gets mail.
|
6. When the brain can't fix something, `report_problem` opens an issue on one repository, using a fine-grained token that can do nothing else, so the person who looks after the box gets mail.
|
||||||
|
|
||||||
|
Whoever looks after the box can check a [status page](status/status.js) from a phone: whether the box, speech, and the brain are up, and counts of conversations, turns, IR presses, and looks. No transcripts.
|
||||||
|
|
||||||
The brain is Claude Code today, by way of its channels feature; the capabilities don't depend on it, and another harness that speaks MCP could take its place. Its [instructions](brain/instructions.md) say how to work the TV; a household file says who's who.
|
The brain is Claude Code today, by way of its channels feature; the capabilities don't depend on it, and another harness that speaks MCP could take its place. Its [instructions](brain/instructions.md) say how to work the TV; a household file says who's who.
|
||||||
|
|
||||||
## Capabilities and confinement
|
## Capabilities and confinement
|
||||||
|
|||||||
@@ -43,6 +43,7 @@
|
|||||||
earcons = pkgs.callPackage ./box/earcons.nix { };
|
earcons = pkgs.callPackage ./box/earcons.nix { };
|
||||||
brain = pkgs.callPackage ./brain/brain.nix { src = self; };
|
brain = pkgs.callPackage ./brain/brain.nix { src = self; };
|
||||||
brain-js = pkgs.callPackage ./brain/default.nix { };
|
brain-js = pkgs.callPackage ./brain/default.nix { };
|
||||||
|
status = pkgs.callPackage ./status/default.nix { };
|
||||||
});
|
});
|
||||||
|
|
||||||
# nix develop --command make test
|
# nix develop --command make test
|
||||||
@@ -63,6 +64,7 @@
|
|||||||
brain-js = self.packages.${pkgs.stdenv.hostPlatform.system}.brain-js;
|
brain-js = self.packages.${pkgs.stdenv.hostPlatform.system}.brain-js;
|
||||||
# The channel, its unit, and its instructions, put together.
|
# The channel, its unit, and its instructions, put together.
|
||||||
brain = self.packages.${pkgs.stdenv.hostPlatform.system}.brain;
|
brain = self.packages.${pkgs.stdenv.hostPlatform.system}.brain;
|
||||||
|
status = self.packages.${pkgs.stdenv.hostPlatform.system}.status;
|
||||||
# Doctests, and pyflakes for the names doctests don't reach.
|
# Doctests, and pyflakes for the names doctests don't reach.
|
||||||
box-py = pkgs.runCommand "box-py-doctests" { nativeBuildInputs = [ (python pkgs) ]; } ''
|
box-py = pkgs.runCommand "box-py-doctests" { nativeBuildInputs = [ (python pkgs) ]; } ''
|
||||||
cd ${./box/body}
|
cd ${./box/body}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# status: the agent's status page, for a phone, on the home server: is the box up, are speech and the
|
||||||
|
# brain, and how many conversations, turns, IR presses, and looks. The box reports to it when its
|
||||||
|
# system sets pdtv26.box.statusUrl.
|
||||||
|
# Tools come from the flake: nix develop --command make test
|
||||||
|
# sudo make install BOX=... # on the home server
|
||||||
|
|
||||||
|
FLAKE = ..
|
||||||
|
NAME = $(BOX)
|
||||||
|
BOX = box
|
||||||
|
PORT = 8027
|
||||||
|
# What it checks, host:port. Use addresses where this host can't resolve the names.
|
||||||
|
BOX_IR = $(BOX):8026
|
||||||
|
SPEECH = localhost:8024
|
||||||
|
BRAIN = localhost:8025
|
||||||
|
# The private network's addresses: the only ones it answers or checks. A tailnet's, by default.
|
||||||
|
RANGES = 100.64.0.0/10 fd7a:115c:a1e0::/48
|
||||||
|
APP = /usr/local/lib/pdtv26-status/app
|
||||||
|
UNIT = /etc/systemd/system/pdtv26-status.service
|
||||||
|
TARGETS = /etc/pdtv26-status/targets
|
||||||
|
|
||||||
|
.PHONY: help test app install
|
||||||
|
|
||||||
|
## list targets
|
||||||
|
help:
|
||||||
|
@awk -f ../make-help.awk $(MAKEFILE_LIST)
|
||||||
|
|
||||||
|
## the unit tests, in Nix's build sandbox
|
||||||
|
test:
|
||||||
|
nix build -L --no-link ..#status
|
||||||
|
|
||||||
|
## the server, as a GC root
|
||||||
|
app:
|
||||||
|
install -d $(dir $(APP))
|
||||||
|
nix build --out-link $(APP) '$(FLAKE)#status'
|
||||||
|
|
||||||
|
$(UNIT): pdtv26-status.service Makefile
|
||||||
|
sed 's|@ranges@|$(RANGES)|' $< > $@
|
||||||
|
|
||||||
|
$(TARGETS): Makefile
|
||||||
|
install -d $(dir $@)
|
||||||
|
printf 'PORT=%s\nNAME=%s\nBOX=%s\nSPEECH=%s\nBRAIN=%s\n' $(PORT) $(NAME) $(BOX_IR) $(SPEECH) $(BRAIN) > $@
|
||||||
|
|
||||||
|
## build, install the unit and its targets, and (re)start it: sudo make install BOX=...
|
||||||
|
install: app $(UNIT) $(TARGETS)
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable pdtv26-status
|
||||||
|
systemctl restart pdtv26-status
|
||||||
|
sleep 2; systemctl --no-pager status pdtv26-status | grep -E '●|Active|listening'
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# The status page: bin/status-server HOST PORT STATE_DIR NAME BOX SPEECH BRAIN, with node.
|
||||||
|
# No npm dependencies: node's own http and net. The tests run as the package builds.
|
||||||
|
{ lib, stdenvNoCC, nodejs-slim }:
|
||||||
|
stdenvNoCC.mkDerivation {
|
||||||
|
pname = "pdtv26-status";
|
||||||
|
version = "0.1.0";
|
||||||
|
src = lib.fileset.toSource {
|
||||||
|
root = ./.;
|
||||||
|
fileset = lib.fileset.unions [ ./status.js ./status.test.js ./status-server.js ./pdtv26-status.service ];
|
||||||
|
};
|
||||||
|
nativeCheckInputs = [ nodejs-slim ];
|
||||||
|
doCheck = true;
|
||||||
|
checkPhase = ''
|
||||||
|
runHook preCheck
|
||||||
|
node --check status-server.js
|
||||||
|
node --test
|
||||||
|
# With DynamicUser, systemd makes /var/lib/<StateDirectory> its own symlink, so nothing else
|
||||||
|
# can live there: the app (make install's GC root) goes elsewhere.
|
||||||
|
state=$(sed -n 's/^StateDirectory=//p' pdtv26-status.service)
|
||||||
|
if grep -q "^ExecStart=/var/lib/$state/" pdtv26-status.service; then
|
||||||
|
echo "pdtv26-status.service runs a program from its own StateDirectory, /var/lib/$state" >&2; exit 1
|
||||||
|
fi
|
||||||
|
runHook postCheck
|
||||||
|
'';
|
||||||
|
installPhase = ''
|
||||||
|
runHook preInstall
|
||||||
|
mkdir -p $out/lib/pdtv26-status $out/bin
|
||||||
|
cp status.js status-server.js $out/lib/pdtv26-status/
|
||||||
|
printf '#!/bin/sh\nexec %s %s/lib/pdtv26-status/status-server.js "$@"\n' ${nodejs-slim}/bin/node $out > $out/bin/status-server
|
||||||
|
chmod +x $out/bin/status-server
|
||||||
|
runHook postInstall
|
||||||
|
'';
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=pdtv26-status: the agent's status page, on the private network
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
# GET / is the page; the box POSTs /event and /heartbeat. It checks the box's ir capability, the
|
||||||
|
# speech server, and the brain's channel; make install writes them, host:port, to the targets file.
|
||||||
|
# The private network is the boundary: no key.
|
||||||
|
EnvironmentFile=/etc/pdtv26-status/targets
|
||||||
|
ExecStart=/usr/local/lib/pdtv26-status/app/bin/status-server :: ${PORT} /var/lib/pdtv26-status ${NAME} ${BOX} ${SPEECH} ${BRAIN}
|
||||||
|
DynamicUser=yes
|
||||||
|
StateDirectory=pdtv26-status
|
||||||
|
IPAddressDeny=any
|
||||||
|
IPAddressAllow=localhost @ranges@
|
||||||
|
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateDevices=yes
|
||||||
|
MemoryMax=200M
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
Executable
+122
@@ -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;
|
||||||
|
});
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
/**
|
||||||
|
* @file The agent's status, for a page whoever looks after the box can check from a phone: is it up,
|
||||||
|
* is it ready, and how many burgers sold (conversations, turns, IR presses, looks).
|
||||||
|
* Events come from the box (its button and ir services); checks are TCP connects to the box's ir
|
||||||
|
* capability, the speech server, and the brain's channel. No transcripts here: just counts and times.
|
||||||
|
* @see status-server.js
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** What the box may report, and what each counts toward. */
|
||||||
|
export const KINDS = ['ready', 'conversation', 'turn', 'huh', 'interrupt', 'end', 'ir', 'look'];
|
||||||
|
|
||||||
|
/** The button service says it's alive this often; three missed and it's not responding. */
|
||||||
|
export const HEARTBEAT_MS = 60_000;
|
||||||
|
|
||||||
|
/** The parts the page checks, in order, with what to say when one is down. */
|
||||||
|
export const CHECKS = [
|
||||||
|
{ name: 'box', label: 'the box (its IR port)', down: 'unplugged, booting, or off the network' },
|
||||||
|
{ name: 'speech', label: 'ears and voice (the speech server)', down: 'the speech server is down: no transcripts, no voice' },
|
||||||
|
{ name: 'brain', label: 'the brain (its channel)', down: 'the channel is not listening: is it waiting at its prompt?' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** The button service's events, whatever its name before the source names were pdtv26's. @param {string} source */
|
||||||
|
const fromButton = (source) => source.endsWith('-button');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {{ at: number, kind: string, source: string, reason?: string, code?: string, times?: number }} Event
|
||||||
|
* @typedef {{ name: string, up: boolean, at: number, since: number, outage?: number }} Check outage: when the latest outage we saw began
|
||||||
|
* @typedef {{ conversations: number, turns: number, huh: number, interrupts: number, irPresses: number, looks: number }} Tally
|
||||||
|
* @typedef {{ word: string, since?: number, why?: string }} State
|
||||||
|
* @typedef {{ state: State, heartbeat?: number, checks: (typeof CHECKS[number] & Partial<Check>)[], today: Tally, total: Tally, recent: Event[] }} Summary
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {any} raw an event as the box sent it, stamped with our time
|
||||||
|
* @returns {Event | undefined} the parts we keep, or undefined if it's not one of ours
|
||||||
|
*/
|
||||||
|
export const cleanEvent = (raw) => {
|
||||||
|
if (!raw || typeof raw !== 'object' || !KINDS.includes(raw.kind)) return undefined;
|
||||||
|
/** @type {Event} */
|
||||||
|
const ev = { at: Number(raw.at), kind: raw.kind, source: String(raw.source ?? '').slice(0, 20) };
|
||||||
|
if (typeof raw.reason === 'string') ev.reason = raw.reason.slice(0, 40);
|
||||||
|
if (typeof raw.code === 'string' && /^[0-9A-F ]{2,47}$/.test(raw.code)) ev.code = raw.code;
|
||||||
|
if (Number.isInteger(raw.times) && raw.times > 0 && raw.times <= 20) ev.times = raw.times;
|
||||||
|
return ev;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @param {Event[]} evs @returns {Tally} */
|
||||||
|
const tally = (evs) => {
|
||||||
|
/** @param {string} kind */
|
||||||
|
const n = (kind) => evs.filter((e) => e.kind === kind).length;
|
||||||
|
return {
|
||||||
|
conversations: n('conversation'),
|
||||||
|
turns: n('turn'),
|
||||||
|
huh: n('huh'),
|
||||||
|
interrupts: n('interrupt'),
|
||||||
|
irPresses: evs.filter((e) => e.kind === 'ir').reduce((sum, e) => sum + (e.times ?? 1), 0),
|
||||||
|
looks: n('look'),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Events, checks, and the latest heartbeat; summary(now) says what they add up to. */
|
||||||
|
export class Status {
|
||||||
|
#dayOf;
|
||||||
|
/** @type {Event[]} */
|
||||||
|
#events = [];
|
||||||
|
/** @type {Map<string, Check>} */
|
||||||
|
#checks = new Map();
|
||||||
|
/** @type {number | undefined} when the button service last said it's alive: kept in memory, not in the event log */
|
||||||
|
#heartbeat;
|
||||||
|
|
||||||
|
/** @param {(t: number) => string} dayOf names the local day t falls on */
|
||||||
|
constructor(dayOf) {
|
||||||
|
this.#dayOf = dayOf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {Event} ev */
|
||||||
|
record(ev) { this.#events.push(ev); }
|
||||||
|
|
||||||
|
/** @param {number} at */
|
||||||
|
beat(at) { this.#heartbeat = at; }
|
||||||
|
|
||||||
|
/** @param {string} name @param {boolean} up @param {number} at */
|
||||||
|
check(name, up, at) {
|
||||||
|
const prev = this.#checks.get(name);
|
||||||
|
const since = prev && prev.up === up ? prev.since : at;
|
||||||
|
const outage = up ? prev?.outage : since;
|
||||||
|
this.#checks.set(name, { name, up, at, since, ...(outage === undefined ? {} : { outage }) });
|
||||||
|
}
|
||||||
|
|
||||||
|
size() { return this.#events.length; }
|
||||||
|
|
||||||
|
/** The box's state, from its checks and events. @param {number} now @returns {State} */
|
||||||
|
#state(now) {
|
||||||
|
const up = this.#checks.get('box');
|
||||||
|
if (!up) return { word: 'not checked yet' };
|
||||||
|
if (!up.up) return { word: 'unreachable', since: up.since };
|
||||||
|
const ready = this.#events.findLast((e) => e.kind === 'ready');
|
||||||
|
// Services restart together, so ready can come before the check sees the box up again: a ready
|
||||||
|
// counts unless it's from before the latest outage we saw.
|
||||||
|
if (!ready || ready.at < (up.outage ?? -Infinity)) return { word: 'booting', since: up.since };
|
||||||
|
const alive = Math.max(this.#heartbeat ?? 0, this.#events.findLast((e) => fromButton(e.source))?.at ?? 0);
|
||||||
|
if (now - alive > 3 * HEARTBEAT_MS) return { word: 'not responding', since: alive, why: 'no heartbeat from its button service' };
|
||||||
|
const last = this.#events.findLast((e) => e.kind === 'conversation' || e.kind === 'end');
|
||||||
|
if (last?.kind === 'conversation' && now - last.at < 10 * 60_000) return { word: 'in a conversation', since: last.at };
|
||||||
|
return { word: 'ready for duty', since: ready.at };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {number} now @returns {Summary} */
|
||||||
|
summary(now) {
|
||||||
|
const today = this.#dayOf(now);
|
||||||
|
return {
|
||||||
|
state: this.#state(now),
|
||||||
|
heartbeat: this.#heartbeat,
|
||||||
|
checks: CHECKS.map((c) => ({ ...c, ...this.#checks.get(c.name) })),
|
||||||
|
today: tally(this.#events.filter((e) => this.#dayOf(e.at) === today)),
|
||||||
|
total: tally(this.#events),
|
||||||
|
recent: this.#events.slice(-12).reverse(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {unknown} s */
|
||||||
|
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The page: phone-sized, no script, refreshes itself.
|
||||||
|
* @param {Summary} s
|
||||||
|
* @param {(t: number) => string} clock formats a time for people
|
||||||
|
* @param {string} name the box's name, for the title
|
||||||
|
*/
|
||||||
|
export const render = (s, clock, name) => {
|
||||||
|
/** @param {number | undefined} t */
|
||||||
|
const since = (t) => (t ? ` since ${esc(clock(t))}` : '');
|
||||||
|
// One row per count, so the table stays phone-narrow however many counts there are.
|
||||||
|
/** @type {[string, keyof Tally][]} */
|
||||||
|
const COUNTS = [['talks', 'conversations'], ['turns', 'turns'], ['huh?', 'huh'],
|
||||||
|
['interrupted', 'interrupts'], ['IR presses', 'irPresses'], ['looks', 'looks']];
|
||||||
|
/** @param {[string, keyof Tally]} count */
|
||||||
|
const row = ([label, key]) => `<tr><td>${label}</td><td>${s.today[key]}</td><td>${s.total[key]}</td></tr>`;
|
||||||
|
/** @param {Event} e */
|
||||||
|
const describe = (e) => [e.kind, e.reason, e.code && `${e.code}${(e.times ?? 1) > 1 ? ` ×${e.times}` : ''}`].filter(Boolean).join(' ');
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="en"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta http-equiv="refresh" content="15">
|
||||||
|
<title>${esc(name)} status</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light dark; --ok: #1a7f37; --bad: #cf222e; --muted: #6e7781; }
|
||||||
|
body { font: 17px/1.4 system-ui, sans-serif; margin: 0 auto; max-width: 32rem; padding: 1rem; }
|
||||||
|
h1 { font-size: 1.6rem; margin: 0 0 .25rem; }
|
||||||
|
.state { font-size: 1.3rem; margin-bottom: 1rem; }
|
||||||
|
.up { color: var(--ok); } .down { color: var(--bad); } .muted { color: var(--muted); font-size: .9rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%; margin: .5rem 0 1rem; }
|
||||||
|
td, th { padding: .25rem .4rem; text-align: right; } td:first-child, th:first-child { text-align: left; }
|
||||||
|
ul { padding-left: 1.2rem; margin: .25rem 0 1rem; }
|
||||||
|
</style></head><body>
|
||||||
|
<h1>${esc(name)}</h1>
|
||||||
|
<div class="state"><b>${esc(s.state.word)}</b>${since(s.state.since)}${s.state.why ? `<br><span class="muted">${esc(s.state.why)}</span>` : ''}</div>
|
||||||
|
<ul>
|
||||||
|
${s.checks.map((c) => c.at === undefined
|
||||||
|
? `<li class="muted">${esc(c.label)}: not checked yet</li>`
|
||||||
|
: `<li class="${c.up ? 'up' : 'down'}">${c.up ? '✓' : '✗'} ${esc(c.label)}${since(c.since)}${c.up ? '' : `<br><span class="muted">${esc(c.down)}</span>`}</li>`).join('\n')}
|
||||||
|
</ul>
|
||||||
|
<table>
|
||||||
|
<tr><th></th><th>today</th><th>all time</th></tr>
|
||||||
|
${COUNTS.map(row).join('\n')}
|
||||||
|
</table>
|
||||||
|
<div class="muted">last heartbeat: ${s.heartbeat ? esc(clock(s.heartbeat)) : 'none yet'}</div>
|
||||||
|
<div class="muted">recent</div>
|
||||||
|
<ul class="muted">
|
||||||
|
${s.recent.map((e) => `<li>${esc(clock(e.at))} ${esc(describe(e))}</li>`).join('\n') || '<li>nothing yet</li>'}
|
||||||
|
</ul>
|
||||||
|
</body></html>
|
||||||
|
`;
|
||||||
|
};
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// Tests for the status page: no network, no clock.
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Status, cleanEvent, render } from './status.js';
|
||||||
|
|
||||||
|
const MIN = 60_000;
|
||||||
|
const dayOf = (t) => String(Math.floor(t / (24 * 60 * MIN)));
|
||||||
|
|
||||||
|
test('unreachable, then booting, then ready, then in a conversation, then ready again', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
assert.equal(s.summary(0).state.word, 'not checked yet');
|
||||||
|
s.check('box', false, 1 * MIN);
|
||||||
|
assert.deepEqual(s.summary(2 * MIN).state, { word: 'unreachable', since: 1 * MIN });
|
||||||
|
s.check('box', true, 3 * MIN);
|
||||||
|
assert.deepEqual(s.summary(3 * MIN).state, { word: 'booting', since: 3 * MIN });
|
||||||
|
s.record({ at: 3.5 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
assert.deepEqual(s.summary(4 * MIN).state, { word: 'ready for duty', since: 3.5 * MIN });
|
||||||
|
s.record({ at: 5 * MIN, kind: 'conversation', source: 'pdtv26-button' });
|
||||||
|
assert.equal(s.summary(6 * MIN).state.word, 'in a conversation');
|
||||||
|
s.record({ at: 7 * MIN, kind: 'end', source: 'pdtv26-button', reason: 'goodbye' });
|
||||||
|
assert.equal(s.summary(8 * MIN).state.word, 'ready for duty');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('heartbeats keep it ready; three missed and it is not responding', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.check('box', true, 0);
|
||||||
|
s.record({ at: 1 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.beat(10 * MIN);
|
||||||
|
assert.equal(s.summary(12 * MIN).state.word, 'ready for duty');
|
||||||
|
assert.deepEqual(s.summary(14 * MIN).state,
|
||||||
|
{ word: 'not responding', since: 10 * MIN, why: 'no heartbeat from its button service' });
|
||||||
|
assert.match(render(s.summary(14 * MIN), (t) => `t${t}`, 'box'), /last heartbeat: t600000/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a ready from before the box went away does not count: booting', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.check('box', true, 0);
|
||||||
|
s.record({ at: 1 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', false, 2 * MIN);
|
||||||
|
s.check('box', true, 3 * MIN);
|
||||||
|
assert.equal(s.summary(4 * MIN).state.word, 'booting');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a ready during the outage counts: services restart together, and the check sees the box up last', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.check('box', true, 0);
|
||||||
|
s.record({ at: 1 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', false, 2 * MIN);
|
||||||
|
s.record({ at: 2.5 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', true, 3 * MIN);
|
||||||
|
assert.deepEqual(s.summary(4 * MIN).state, { word: 'ready for duty', since: 2.5 * MIN });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a ready from before the server started counts, if the server saw no outage', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.record({ at: 1 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', true, 10 * MIN);
|
||||||
|
s.beat(10.5 * MIN);
|
||||||
|
assert.deepEqual(s.summary(11 * MIN).state, { word: 'ready for duty', since: 1 * MIN });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('checks keep when they last changed', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.check('brain', true, 1 * MIN);
|
||||||
|
s.check('brain', true, 2 * MIN);
|
||||||
|
s.check('brain', false, 3 * MIN);
|
||||||
|
const brain = s.summary(4 * MIN).checks.find((c) => c.name === 'brain');
|
||||||
|
assert.deepEqual([brain.up, brain.since, brain.at], [false, 3 * MIN, 3 * MIN]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('burgers sold: today and all time, IR presses counted by times', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
const day = 24 * 60 * MIN;
|
||||||
|
s.record({ at: 1, kind: 'conversation', source: 'pdtv26-button' });
|
||||||
|
s.record({ at: day + 1, kind: 'conversation', source: 'pdtv26-button' });
|
||||||
|
s.record({ at: day + 2, kind: 'turn', source: 'pdtv26-button' });
|
||||||
|
s.record({ at: day + 3, kind: 'huh', source: 'pdtv26-button' });
|
||||||
|
s.record({ at: day + 4, kind: 'ir', source: 'pdtv26-ir', code: '20 DF F4 0B', times: 3 });
|
||||||
|
s.record({ at: day + 5, kind: 'ir', source: 'pdtv26-ir', code: '20 DF 10 EF' });
|
||||||
|
const { today, total } = s.summary(day + 10);
|
||||||
|
assert.deepEqual(today, { conversations: 1, turns: 1, huh: 1, interrupts: 0, irPresses: 4, looks: 0 });
|
||||||
|
assert.equal(total.conversations, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('only our kinds of events, and only their tame parts, are kept', () => {
|
||||||
|
assert.equal(cleanEvent({ kind: 'transcript', text: 'secrets' }), undefined);
|
||||||
|
assert.equal(cleanEvent(null), undefined);
|
||||||
|
assert.deepEqual(cleanEvent({ at: 5, kind: 'ir', source: 'pdtv26-ir', code: '20 DF 10 EF', times: 2, text: 'x' }),
|
||||||
|
{ at: 5, kind: 'ir', source: 'pdtv26-ir', code: '20 DF 10 EF', times: 2 });
|
||||||
|
assert.deepEqual(cleanEvent({ at: 5, kind: 'ir', source: 'x', code: '<script>', times: 99 }),
|
||||||
|
{ at: 5, kind: 'ir', source: 'x' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the page says what is down, and why, and escapes what it shows', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.check('box', true, 0);
|
||||||
|
s.check('speech', true, 0);
|
||||||
|
s.check('brain', false, 0);
|
||||||
|
s.record({ at: 1, kind: 'end', source: 'pdtv26-button', reason: '<b>quiet</b>' });
|
||||||
|
const html = render(s.summary(MIN), (t) => `t${t}`, 'box');
|
||||||
|
assert.match(html, /<tr><td>IR presses<\/td><td>\d+<\/td><td>\d+<\/td><\/tr>/);
|
||||||
|
assert.match(html, /<b>booting<\/b>/);
|
||||||
|
assert.match(html, /✗ the brain \(its channel\)/);
|
||||||
|
assert.match(html, /<title>box status<\/title>/);
|
||||||
|
assert.match(html, /waiting at its prompt/);
|
||||||
|
assert.match(html, /end <b>quiet<\/b>/);
|
||||||
|
assert.match(html, /name="viewport"/);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user