// A host with several routes connects through the first one that answers. import { afterEach, describe, expect, it } from "bun:test"; import type { Server } from "bun"; import { T3Host } from "../src/t3/host.ts"; const ENVIRONMENT_ID = "env-laptop"; let server: Server | undefined; afterEach(() => server?.stop(true)); /** Just enough of a T3 server: the descriptor, a ticket, config, and an empty shell snapshot. */ function fakeT3() { server = Bun.serve({ port: 0, fetch(req, srv) { const { pathname } = new URL(req.url); if (pathname === "/.well-known/t3/environment") { return Response.json({ environmentId: ENVIRONMENT_ID, label: "framework-gib", serverVersion: "0.1.5", orchestrationProtocolVersion: 2 }); } if (pathname === "/api/auth/websocket-ticket/rpc") return Response.json({ ticket: "t" }); if (pathname === "/ws" && srv.upgrade(req)) return undefined; return new Response("not found", { status: 404 }); }, websocket: { message(ws, data) { const frame = JSON.parse(String(data)) as { _tag: string; id: string; tag: string }; if (frame._tag !== "Request") return; if (frame.tag === "server.getConfig") { ws.send(JSON.stringify({ _tag: "Exit", requestId: frame.id, exit: { _tag: "Success", value: {} } })); } else if (frame.tag === "orchestration.subscribeShell") { const snapshot = { snapshotSequence: 1, projects: [], threads: [] }; ws.send(JSON.stringify({ _tag: "Chunk", requestId: frame.id, values: [{ kind: "snapshot", snapshot }] })); } }, }, }); return `http://localhost:${server.port}`; } describe("T3Host routes", () => { it("falls back to the next route when the preferred one does not answer", async () => { const working = fakeT3(); // Port 9 (discard) refuses connections, standing in for a LAN route that is down. const host = new T3Host({ id: ENVIRONMENT_ID, label: "Laptop", urls: ["http://127.0.0.1:9", working], token: "x", environmentId: ENVIRONMENT_ID }); const online = new Promise((resolve) => { const check = setInterval(() => { if (host.status === "online") { clearInterval(check); resolve(); } }, 5); }); host.start(); await online; expect(host.url).toBe(working); host.stop(); }); });