Files
continuum-backend/scripts/capture-gateway-frames.js
octoturge 42d4b3820a Add a runnable dev environment, and fix the pins that stopped it booting
The edge route had never been run. Adding a way to run it turned up that the
server could not start at all, for two independent dependency reasons that
typechecking could not see:

- `elysia: ^1.1.26` had resolved to 1.4.30, which calls `t.Module` - a TypeBox
  0.34 API - while this repo pinned TypeBox 0.33. `t.Module is not a function`.
- `drizzle-typebox: ^0.2.1` resolved to a version whose peers demand
  `drizzle-orm >= 0.36`, against the `^0.33.0` pinned here. Importing it threw
  `Export named 'getViewSelectedFields' not found`.

Both are caret ranges that drifted into combinations nobody chose. elysia,
@sinclair/typebox and the drizzle packages are now pinned tightly, TypeBox
forward to 0.34.52 (which satisfies Elysia and drizzle-typebox 0.1.1 alike),
and tests/dependency_identity.test.ts fails if the TypeBox version ever differs
between here and @continuum/ts-types - the skew that made every shared schema
invalid, with an error message pointing at Standard Schema instead.

Dropping to drizzle-typebox 0.1.1 widens `jsonb` in the generated validators,
so `metadata` needs an explicit object shape in validators.ts; the column is
declared `$type<Record<string, unknown>>()` and a validated body otherwise is
not assignable to `.values()`.

scripts/:

- `install-docker.sh` - one-time host setup, kept separate because it touches
  the machine rather than containers.
- `dev-env.sh up|down|reset|status|psql|schema|env` - Valkey + Postgres/pgvector.
  Uses docker-compose.yml when a daemon answers, and otherwise runs the same two
  services from apt. That fallback is not hypothetical: Docker cannot run in this
  sandbox at all. dockerd needs CAP_NET_ADMIN to build its bridge; with
  `--bridge=none --iptables=false` it starts but cannot unpack an image without
  CAP_SYS_ADMIN; with `--storage-driver=vfs` it still fails because registering a
  layer needs user namespaces, which are blocked outright. All three are
  host-level grants, so no script can work around them - hence a second path
  rather than a broken first one.
- `e2e-edge.sh` - the test the unit tests cannot be. Seeds a farm, claims its
  printers, mints an edge token, runs the real continuum-proxy, and asserts live
  telemetry reached Postgres and a command reached a printer. It only sends a fan
  speed, only to a printer reporting IDLE, and puts it back afterwards.
- `capture-gateway-frames.js` - records what a gateway really sends, for
  refreshing tests/fixtures/. Read-only unless FAN_TEST_PRINTER is set. The test
  comment referred to this before it existed.

Verified end to end, from a dropped and freshly migrated database: `h2c`
persisted as printing/RUNNING 22% layer 2/25 nozzle 230 bed 35 with 3 HMS
alerts, `p1p` as idle/IDLE, and `POST /printers/:id/commands` reached the P1P's
fan and came back ok:true. An unclaimed printer is refused 409
PRINTER_UNREACHABLE rather than guessed at.

Two things the e2e script got wrong first, both now fixed in it: it waited for
the first printer row instead of all of them, which silently tested only the v2
printer (a v1 Bambu reports one tick later); and `$!` after `( cd ... ) &` is
the subshell, so cleanup left an orphaned gateway reconnecting with a token for
a deleted farm and polluting the next run.

Note: `drizzle/` is gitignored, so the generated migration is not committed and
there is no migration history in the repo. Left as-is deliberately - that is a
workflow call, flagged in PLAN.md.
2026-10-03 12:17:10 +00:00

109 lines
4.2 KiB
JavaScript

// Stands in for this backend's /ws/edge/v1 and records every frame a real
// gateway sends, one JSON object per line.
//
// What it is for: refreshing tests/fixtures/gateway_frames.json. Those fixtures
// are deliberately real captures rather than hand-written examples - a
// hand-written example agrees with whoever wrote it, which is how the two ends
// of this protocol drifted into incompatible shapes without anything failing.
// So when the protocol changes, re-capture rather than editing the fixture.
//
// It needs no database and no auth, which is the point: it isolates the
// gateway's side of the wire from everything else. For the full path through a
// real database and real printers, use e2e-edge.sh instead.
//
// Usage:
// bun run scripts/capture-gateway-frames.js > frames.jsonl
// # then, in continuum-proxy, with its CONTINUUM_* env set:
// CONTINUUM_UPLINK_URL=ws://localhost:59999/ws/edge/v1 cargo run
//
// PORT=59999 where to listen
// FAN_TEST_PRINTER=p1p send one set_fan_speed to this printer, to capture a
// command_result. Leave unset to stay read-only.
//
// SAFETY: with FAN_TEST_PRINTER set this writes to a real printer. Only ever a
// fan speed, and only to the printer you name - but name an idle one.
const PORT = Number(process.env.PORT ?? 59999);
const FAN_TEST_PRINTER = process.env.FAN_TEST_PRINTER;
let commandSent = false;
Bun.serve({
port: PORT,
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("this endpoint only speaks WebSocket\n", { status: 400 });
},
websocket: {
open() {
console.error(`[capture] gateway connected`);
},
message(ws, raw) {
// stdout is the capture, stderr is the commentary, so the two can be
// redirected separately.
console.log(typeof raw === "string" ? raw : raw.toString());
let msg;
try {
msg = JSON.parse(typeof raw === "string" ? raw : raw.toString());
} catch (err) {
console.error(`[capture] not JSON, recorded anyway: ${err}`);
return;
}
switch (msg.type) {
case "hello":
// No token check: this is not the backend, it is a recorder.
console.error(`[capture] hello from ${msg.gateway_id} (farm ${msg.farm_id})`);
ws.send(JSON.stringify({ type: "hello_ack", session_id: "capture" }));
break;
case "heartbeat":
ws.send(JSON.stringify({ type: "heartbeat_ack", seq: msg.seq }));
break;
case "telemetry":
console.error(
`[capture] telemetry: ${msg.printers
.map((p) => `${p.printer_id}=${p.state ?? "?"}`)
.join(" ")}`,
);
if (FAN_TEST_PRINTER && !commandSent) {
commandSent = true;
const reported = msg.printers.find((p) => p.printer_id === FAN_TEST_PRINTER);
// Refuse to touch a printer that is not idle, and refuse to guess
// at one the gateway has not reported at all.
if (!reported) {
console.error(`[capture] '${FAN_TEST_PRINTER}' not in this batch, not sending`);
} else if (reported.state !== "IDLE" && reported.state !== "FINISH") {
console.error(`[capture] '${FAN_TEST_PRINTER}' is ${reported.state}, not sending`);
} else {
console.error(`[capture] -> set_fan_speed 0 to ${FAN_TEST_PRINTER}`);
ws.send(JSON.stringify({
type: "command",
command_id: "capture-1",
printer_id: FAN_TEST_PRINTER,
command: { action: "set_fan_speed", percent: 0 },
}));
}
}
break;
case "command_result":
console.error(`[capture] command_result ${msg.command_id}: ok=${msg.ok}`);
break;
default:
console.error(`[capture] ${msg.type}`);
}
},
close() {
console.error("[capture] gateway disconnected");
},
},
});
console.error(`[capture] listening on :${PORT} - frames to stdout, commentary to stderr`);
if (!FAN_TEST_PRINTER) {
console.error("[capture] read-only (set FAN_TEST_PRINTER to also capture a command_result)");
}