Files
continuum-backend/tests/edge_protocol.test.ts
T
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

112 lines
4.6 KiB
TypeScript

import { describe, expect, it } from "bun:test";
import { Value } from "@sinclair/typebox/value";
import { EdgeClientMessageSchema, EdgeServerMessageSchema } from "@continuum/ts-types";
import currentCapture from "./fixtures/gateway_frames.json";
import legacyCapture from "./fixtures/gateway_frames_legacy_nulls.json";
/**
* A contract test, not a unit test: it checks that what continuum-proxy
* actually puts on the wire is what this backend's validator accepts.
*
* The fixtures are real captures from a live gateway talking to a real P1P and
* H2C, not hand-written examples - which is the whole point. The two ends of
* /ws/edge/v1 had silently drifted into completely different protocols
* (different handshake, different telemetry shape, printer ids the gateway
* could not know), and every hand-written example agreed with whichever side
* wrote it. Re-capture with scripts/capture-gateway-frames.js when the protocol
* changes, rather than editing these by hand.
*/
function check(schema: Parameters<typeof Value.Check>[0], value: unknown) {
const ok = Value.Check(schema, value);
if (!ok) {
// Surface *why*, or a failure here is just "false !== true".
const errors = [...Value.Errors(schema, value)].map(
(e) => `${e.path || "/"}: ${e.message} (got ${JSON.stringify(e.value)})`,
);
throw new Error(`validation failed:\n ${errors.join("\n ")}`);
}
}
describe("gateway -> backend frames", () => {
for (const frame of currentCapture.frames) {
it(`accepts a real '${frame.type}' frame`, () => {
check(EdgeClientMessageSchema, frame);
});
}
it("accepts the pre-fix capture, where empty fields were explicit nulls", () => {
// Liberal reader: the gateway now omits these, but a serde-derived
// producer emits null by default and one such field must not cost us a
// whole farm's telemetry batch.
for (const frame of legacyCapture.frames) {
check(EdgeClientMessageSchema, frame);
}
});
it("carries the live telemetry this was captured from", () => {
const telemetry = currentCapture.frames.find((f) => f.type === "telemetry");
expect(telemetry).toBeDefined();
const printers = (telemetry as { printers: Array<{ printer_id: string }> }).printers;
expect(printers.length).toBeGreaterThan(0);
// Guards against a fixture that validates because it is empty.
expect(printers.every((p) => typeof p.printer_id === "string" && p.printer_id.length > 0)).toBe(true);
});
it("rejects a telemetry batch whose printer has no id", () => {
// printer_id and name are the only required fields; everything else is
// genuinely unknowable for a printer that has only just connected.
check(EdgeClientMessageSchema, { type: "telemetry", printers: [{ printer_id: "p1p", name: "P1P" }] });
expect(Value.Check(EdgeClientMessageSchema, { type: "telemetry", printers: [{ name: "P1P" }] })).toBe(false);
});
it("rejects an unknown message type", () => {
// The old protocol's handshake, which no gateway ever sent.
expect(Value.Check(EdgeClientMessageSchema, { type: "auth", token: "x" })).toBe(false);
});
});
describe("backend -> gateway frames", () => {
// Exactly what src/routes/ws/edge.ts sends. If one of these stops
// validating, the gateway's serde enum will have stopped accepting it too -
// see the mirror of this test in continuum-proxy/tests/uplink_protocol.rs.
const outbound = [
{ type: "hello_ack", session_id: "3f2b1c5e-0000-4000-8000-000000000000" },
{ type: "hello_error", message: "invalid edge token" },
{ type: "heartbeat_ack", seq: 7 },
{
type: "command",
command_id: "9a7d2f10-0000-4000-8000-000000000000",
printer_id: "p1p",
command: { action: "set_fan_speed", percent: 40 },
},
{
type: "command",
command_id: "9a7d2f11-0000-4000-8000-000000000000",
printer_id: "p1p",
command: { action: "send_gcode_line", line: "M106 S0" },
},
];
for (const frame of outbound) {
it(`emits a valid '${frame.type}' (${(frame as { command?: { action: string } }).command?.action ?? "no command"})`, () => {
check(EdgeServerMessageSchema, frame);
});
}
it("has no start-print command to send", () => {
// Deliberate: the gateway can start an uploaded file, but that path has
// never been run against real hardware. Delete this test when it has been,
// and add the variant to the schema.
expect(
Value.Check(EdgeServerMessageSchema, {
type: "command",
command_id: "x",
printer_id: "p1p",
command: { action: "start_print", file_name: "plate_1.3mf" },
}),
).toBe(false);
});
});