diff --git a/e2e/component-install.test.ts b/e2e/component-install.test.ts index 2bece2cb3..213a22999 100644 --- a/e2e/component-install.test.ts +++ b/e2e/component-install.test.ts @@ -3,10 +3,10 @@ import { describe, expect, it } from "vitest"; import { type CliResult, events, - freeLoopbackPort, type TestEnv, waitFor, withDaemon, + withHttpDaemon, } from "./helpers/index.js"; const MISSING = ["lease", "--platform", "ios", "--device", "iPhone 16", "--os", "19.0"] as const; @@ -263,10 +263,9 @@ interface HttpDaemon { } async function httpDaemon(): Promise { - const port = await freeLoopbackPort(); - const env = await withDaemon({ + const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - }); + })); const baseUrl = `http://127.0.0.1:${port}`; await waitFor( async () => { diff --git a/e2e/console-serving.test.ts b/e2e/console-serving.test.ts index 35229e575..a2acf509e 100644 --- a/e2e/console-serving.test.ts +++ b/e2e/console-serving.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; /** * The daemon serves the built web console at `/` whenever HTTP is enabled, at the address @@ -33,10 +33,9 @@ async function fetchWhenListening(url: string): Promise { describe("the web console", () => { it("GET / answers the console page when HTTP is enabled", async () => { - const port = await freeLoopbackPort(); - const worker = await withDaemon({ + const { env: worker, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - }); + })); const url = await consoleUrl(worker); expect(url).toBe(`http://127.0.0.1:${port}/`); @@ -58,11 +57,10 @@ describe("the web console", () => { }); it("a gateway serves the console page at the address simlock status prints", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const url = await consoleUrl(gateway); expect(url).toBe(`http://127.0.0.1:${port}/`); diff --git a/e2e/contract-surface.test.ts b/e2e/contract-surface.test.ts index e51a0dfc1..607082472 100644 --- a/e2e/contract-surface.test.ts +++ b/e2e/contract-surface.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { OPERATIONS, type OperationName } from "../src/contract/index.js"; import { NodeIpcTransport } from "../src/ports/index.js"; import { SimlockWire, WireCallError } from "../src/simlock-client/wire.js"; -import { freeLoopbackPort, withDaemon } from "./helpers/index.js"; +import { withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; /** @@ -106,11 +106,10 @@ describe("contract surface", () => { // its input before deciding anything, so even the ones a gateway answers // `UNSUPPORTED_IN_GATEWAY_MODE` reject an unparseable payload with `BAD_REQUEST` first. // Anything that came back `UNKNOWN_REQUEST` here would be an operation a gateway forgot. - const port = await freeLoopbackPort(); - const env = await withDaemon({ + const { env } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); expect((await env.startDaemon()).code).toBe(0); expect(await sweep(env)).toEqual( diff --git a/e2e/gateway-component-install.test.ts b/e2e/gateway-component-install.test.ts index 01cba3f67..27be953e0 100644 --- a/e2e/gateway-component-install.test.ts +++ b/e2e/gateway-component-install.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; interface WorkerView { readonly id: string; @@ -44,11 +44,10 @@ async function androidRuntimeWorkers(gateway: TestEnv, runtime: string): Promise describe("simlock component install through a gateway", () => { it("asks every worker, shows the install in worker list while it runs, reports each by id, refuses on the worker set to never, the gateway's catalog lists the component for the one that installed it, and an agent token gets 403 over HTTP", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); const { secret } = minted.json as { secret: string }; @@ -150,11 +149,10 @@ describe("simlock component install through a gateway", () => { }); it("refuses component install with no worker flag on a gateway with exit 2, telling the operator to name workers", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const result = await gateway.cli(["component", "install", "ios", "26.4"]); diff --git a/e2e/gateway-event-relay.test.ts b/e2e/gateway-event-relay.test.ts index e52502257..7cb9f2393 100644 --- a/e2e/gateway-event-relay.test.ts +++ b/e2e/gateway-event-relay.test.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { RecordedEvent } from "./helpers/events.js"; /** @@ -15,11 +15,10 @@ import type { RecordedEvent } from "./helpers/events.js"; */ async function gatewayWithWorker() { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const worker = await withDaemon({ diff --git a/e2e/gateway-fast-fail.test.ts b/e2e/gateway-fast-fail.test.ts index 5ec1dab6c..04c063608 100644 --- a/e2e/gateway-fast-fail.test.ts +++ b/e2e/gateway-fast-fail.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { CliResult, TestEnv } from "./helpers/index.js"; import type { FakeDriverScript } from "./fake-driver/types.js"; @@ -26,12 +26,11 @@ interface WorkerView { } async function startGateway() { - const port = await freeLoopbackPort(); // `driver: "none"`: a gateway starts no drivers (ADR 0005 §2). - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); const { secret } = minted.json as { secret: string }; diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index eb6d158bc..65897f66f 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, waitForDeviceState, withDaemon } from "./helpers/index.js"; +import { waitFor, waitForDeviceState, withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; /** @@ -132,13 +132,12 @@ function expectSameView( describe("gateway fleet", () => { it("two workers join, status aggregates them, a kill disconnects one, drain flags the other", async () => { - const port = await freeLoopbackPort(); // `driver: "none"`: a gateway starts no drivers and warns about every worker-only key in // its config (ADR 0005 §2), so it gets no fake-driver wiring and no capacity seeding. - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); // 1. The gateway mints a join token. `--role worker` is what makes it a join token and // nothing else: it opens an uplink and no `/v1` route. @@ -280,11 +279,10 @@ describe("gateway fleet", () => { }); it("shows each worker's own pairings, other names, and images in the worker list and their union in the catalog", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; @@ -397,11 +395,10 @@ describe("gateway fleet", () => { }); it("shows each worker's own custom models in the worker list, and marks a model custom in the catalog when any worker does", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; @@ -452,11 +449,10 @@ describe("gateway fleet", () => { }); it("gives a request with a mode that mode on either worker, and a request with none the default of the worker it landed on", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; @@ -529,11 +525,10 @@ describe("gateway fleet", () => { }); it("grants --device 'iphone 16 pro' and --device pixel_7 through a gateway by the worker's own names", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; // The fake driver resolves model names exactly, so a grant proves the gateway sent the @@ -577,11 +572,10 @@ describe("gateway fleet", () => { }); it("grants an Android --class phone request on the worker holding a warm Pixel, not on one with free capacity", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const pixels = { @@ -654,11 +648,10 @@ describe("gateway fleet", () => { }); it("grants --class phone with --os '>=18' through a gateway on a worker whose runtime is in the range, and nothing else", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const join = (label: string, osVersion: string) => @@ -702,11 +695,10 @@ describe("gateway fleet", () => { }); it("refuses an uplink whose token is not a worker join token", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); // An operator token is a real credential that opens no uplink (ADR 0005 §25). The worker // keeps retrying at its backoff cap rather than giving up, so what this asserts is the // gateway's side: it never becomes a worker. @@ -736,11 +728,10 @@ describe("gateway fleet", () => { }); it("through a gateway, a caller-chosen lease ID comes back with no worker prefix, renews and releases by that ID, and a second request for it is LEASE_ID_TAKEN", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const { secret } = (await gateway.cli(["token", "create", "--role", "worker"])).json as { secret: string; }; diff --git a/e2e/gateway-lease-limit.test.ts b/e2e/gateway-lease-limit.test.ts index e74ac5375..31f69b2da 100644 --- a/e2e/gateway-lease-limit.test.ts +++ b/e2e/gateway-lease-limit.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import type { FakeDriverScript } from "./fake-driver/types.js"; -import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import type { CliResult, TestEnv } from "./helpers/index.js"; const FAST = { timeout: 20_000 }; @@ -11,15 +11,14 @@ const IPHONE_16: FakeDriverScript = { const TWO_DEVICES = { limits: { maxRunning: 2, ios: { maxDevices: 2, maxRunning: 2 } } }; async function startGateway(maxPerRequester: number) { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, lease: { maxPerRequester }, mode: "gateway", }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); const { secret } = minted.json as { secret: string }; diff --git a/e2e/gateway-physical-routing.test.ts b/e2e/gateway-physical-routing.test.ts index 454c3f8b3..7a71b82ee 100644 --- a/e2e/gateway-physical-routing.test.ts +++ b/e2e/gateway-physical-routing.test.ts @@ -3,12 +3,12 @@ import { describe, expect, it } from "vitest"; import type { CliBackgroundHandle } from "./helpers/cli.js"; import type { FakeDriverPlatformScript, ScriptedPhysicalDevice } from "./fake-driver/types.js"; import { - freeLoopbackPort, + type CliResult, + type TestEnv, waitFor, waitForDeviceState, withDaemon, - type CliResult, - type TestEnv, + withHttpDaemon, } from "./helpers/index.js"; const FAST = { timeout: 20_000 }; @@ -70,12 +70,11 @@ interface Fleet { } async function startFleet(specs: readonly WorkerSpec[]): Promise { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ agentId: "fleet-agent", configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); const { secret } = minted.json as { secret: string }; diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index c877286b6..0f2ff5ab2 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; /** * ADR 0005's happy path, over real transports: a real gateway process, real worker processes @@ -59,14 +59,13 @@ interface Fleet { * these tests are about. */ async function startFleet(specs: readonly WorkerSpec[], agentId: string): Promise { - const port = await freeLoopbackPort(); // `driver: "none"`: a gateway starts no drivers and warns about every worker-only key in its // config (ADR 0005 §2), so it gets no fake-driver wiring and no capacity seeding. - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ agentId, configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code).toBe(0); diff --git a/e2e/helpers/http-daemon.test.ts b/e2e/helpers/http-daemon.test.ts new file mode 100644 index 000000000..759f68d4e --- /dev/null +++ b/e2e/helpers/http-daemon.test.ts @@ -0,0 +1,37 @@ +import { createServer } from "node:net"; +import { describe, expect, it } from "vitest"; + +import { withHttpDaemon } from "./http-daemon.js"; +import { freeLoopbackPort } from "./port.js"; + +describe("withHttpDaemon", () => { + it("when the first port it picks is already taken, returns a daemon whose HTTP listener answers on the next one", async () => { + const holder = createServer(); + const taken = await new Promise((resolve) => { + holder.listen(0, "127.0.0.1", () => { + const address = holder.address(); + resolve(typeof address === "object" && address !== null ? address.port : 0); + }); + }); + try { + const picked: number[] = []; + const { env, port } = await withHttpDaemon( + (pickedPort) => ({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port: pickedPort } }, + }), + async () => { + const next = picked.length === 0 ? taken : await freeLoopbackPort(); + picked.push(next); + return next; + }, + ); + + expect(picked[0]).toBe(taken); + expect(port).toBe(picked[1]); + expect((await fetch(`http://127.0.0.1:${String(port)}/v1/healthz`)).ok).toBe(true); + expect((await env.cli(["status"])).code).toBe(0); + } finally { + await new Promise((resolve) => holder.close(() => resolve())); + } + }); +}); diff --git a/e2e/helpers/http-daemon.ts b/e2e/helpers/http-daemon.ts new file mode 100644 index 000000000..ea410b01e --- /dev/null +++ b/e2e/helpers/http-daemon.ts @@ -0,0 +1,50 @@ +import { readFile } from "node:fs/promises"; + +import { withDaemon, type TestEnv, type WithDaemonOptions } from "./env.js"; +import { freeLoopbackPort } from "./port.js"; +import { waitFor } from "./wait.js"; + +const ATTEMPTS = 5; + +// why: `freeLoopbackPort` releases the port it picked, so another process can take it before +// the daemon binds it. The daemon then stops with `EADDRINUSE` a moment after it claimed its +// socket, so a `daemon start` can exit 0 and the next CLI call times out auto-starting a daemon +// that fails the same way (#553). So this waits for the daemon's own "HTTP gateway listening" +// line, and on `EADDRINUSE` starts a fresh env on a new port. `pickPort` lets this helper's own +// test hand it a taken port first. +export async function withHttpDaemon( + options: (port: number) => WithDaemonOptions, + pickPort: () => Promise = freeLoopbackPort, +): Promise<{ readonly env: TestEnv; readonly port: number }> { + for (let attempt = 1; attempt <= ATTEMPTS; attempt += 1) { + const port = await pickPort(); + const env = await withDaemon({ ...options(port), mode: "auto" }); + const started = await env.startDaemon(); + if (started.code !== 0) { + if ((await readLog(env)).includes("EADDRINUSE")) continue; + throw new Error(`daemon start exited ${String(started.code)}: ${started.stderr}`); + } + let outcome: "listening" | "port-taken" | undefined; + await waitFor( + async () => { + const log = await readLog(env); + if (log.includes("EADDRINUSE")) outcome = "port-taken"; + else if (log.includes('"HTTP gateway listening"')) outcome = "listening"; + return outcome !== undefined; + }, + { label: `the daemon's HTTP listener on port ${String(port)}` }, + ); + if (outcome === "listening") return { env, port }; + } + throw new Error( + `every one of ${String(ATTEMPTS)} free loopback ports was taken before the daemon bound it`, + ); +} + +async function readLog(env: TestEnv): Promise { + try { + return await readFile(env.logPath, "utf8"); + } catch { + return ""; + } +} diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index 99d367974..589b32aa7 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -12,6 +12,7 @@ export { } from "./agent-device.js"; export type { Agent, AgentDeviceResult } from "./agent-device.js"; export { freeLoopbackPort } from "./port.js"; +export { withHttpDaemon } from "./http-daemon.js"; // A flow that factors its own setup out of a test body needs to name what `withDaemon` hands // back; every other flow keeps it inferred. export type { SharedTestEnv, TestEnv } from "./env.js"; diff --git a/e2e/installs-in-progress.test.ts b/e2e/installs-in-progress.test.ts index b19bd040e..867bbcd1e 100644 --- a/e2e/installs-in-progress.test.ts +++ b/e2e/installs-in-progress.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; interface Install { readonly platform: string; @@ -29,11 +29,10 @@ async function viewInstalls(gateway: TestEnv): Promise { it("shows an install on the worker's status and on its gateway's worker list while it runs, and on neither after it ends", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); const { secret } = minted.json as { secret: string }; diff --git a/e2e/physical-devices-core.test.ts b/e2e/physical-devices-core.test.ts index 89663dade..53fa94089 100644 --- a/e2e/physical-devices-core.test.ts +++ b/e2e/physical-devices-core.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import { HELD_LEASE, LEASED, @@ -493,11 +493,10 @@ interface Fleet { } async function fleetWithPhysicalWorker(physical: readonly PhysicalSeed[]): Promise { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const worker = await withDaemon({ diff --git a/e2e/physical-enrollment.test.ts b/e2e/physical-enrollment.test.ts index 86852d004..a641a5913 100644 --- a/e2e/physical-enrollment.test.ts +++ b/e2e/physical-enrollment.test.ts @@ -7,7 +7,7 @@ import { PROTOCOL_VERSION_RANGE } from "../src/contract/index.js"; import { NodeIpcTransport } from "../src/ports/index.js"; import { SimlockWire, WireCallError } from "../src/simlock-client/wire.js"; import type { FakeDriverRefusalReason, ScriptedPhysicalDevice } from "./fake-driver/types.js"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; const UDID = "00008110-001A2B3C4D5E"; const ALIAS = "7A1C0E52-6B7D-4F1E-9C1A-2D3E4F5A6B7C"; @@ -84,7 +84,11 @@ async function startDaemon( readonly http?: number; } = {}, ): Promise { - return withDaemon({ + return withDaemon(daemonOptions(options)); +} + +function daemonOptions(options: Parameters[0] = {}) { + return { ...(options.platforms === undefined ? {} : { fakeDriverPlatforms: options.platforms }), ...(options.http === undefined ? {} @@ -93,7 +97,7 @@ async function startDaemon( android: { ...ANDROID_BASE, ...options.android }, ios: { ...IOS_BASE, ...options.ios }, }, - }); + }; } async function rows(env: TestEnv): Promise { @@ -135,8 +139,7 @@ async function httpDaemon(options: { readonly ios?: Record; readonly android?: Record; }): Promise { - const port = await freeLoopbackPort(); - const env = await startDaemon({ ...options, http: port }); + const { env, port } = await withHttpDaemon((port) => daemonOptions({ ...options, http: port })); const base = `http://127.0.0.1:${String(port)}`; await waitFor( async () => { @@ -594,11 +597,10 @@ describe("device add over HTTP", () => { describe("device add through a gateway", () => { async function fleet(): Promise<{ gateway: TestEnv; worker: TestEnv; workerId: string }> { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); const { secret } = minted.json as { secret: string }; diff --git a/e2e/physical-gateway.test.ts b/e2e/physical-gateway.test.ts index b84c0c063..ae53bf98d 100644 --- a/e2e/physical-gateway.test.ts +++ b/e2e/physical-gateway.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import type { ScriptedPhysicalDevice } from "./fake-driver/types.js"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; import { PHYSICAL_AGENT, PHYSICAL_MODEL, @@ -39,11 +39,10 @@ interface Row { } async function fleetWithIphone(): Promise<{ gateway: TestEnv; worker: TestEnv }> { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); const { secret } = minted.json as { secret: string }; const worker = await withDaemon({ diff --git a/e2e/renew-ttl.test.ts b/e2e/renew-ttl.test.ts index 96ac1b334..65be2ae92 100644 --- a/e2e/renew-ttl.test.ts +++ b/e2e/renew-ttl.test.ts @@ -1,4 +1,4 @@ -import { readFile } from "node:fs/promises"; +import { existsSync } from "node:fs"; import { describe, expect, it } from "vitest"; import { waitFor, withDaemon } from "./helpers/index.js"; @@ -24,25 +24,12 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { configOverrides: { lease: { defaultTtlMs: 60_000, maxTtlMs: 30_000 } }, }); - // Every command auto-starts on demand; the daemon process fails the config load before - // it ever opens its socket, so the CLI retries for its startup window and then gives up - // -- surfaced as an INTERNAL timeout, not a specific config error code (the CLI never - // got a response to relay). - const result = await env.cli(["catalog", "--json"], { timeout: 15_000 }); + // why: the CLI loads the config before it launches a daemon, so no daemon.log is written. + const result = await env.cli(["catalog", "--json"]); expect(result.code).toBe(1); expect(result.error?.code).toBe("INTERNAL"); - - await waitFor( - async () => { - try { - const log = await readFile(env.logPath, "utf8"); - return log.includes("lease.defaultTtlMs"); - } catch { - return false; - } - }, - { timeout: 10_000, label: "daemon.log names the offending config key" }, - ); + expect(result.error?.message).toContain("lease.defaultTtlMs"); + expect(existsSync(env.logPath)).toBe(false); }); it("keeps a renewing holder's lease alive (MCP and CLI) while a SIGKILLed holder's lease stays until its TTL, then expires", async () => { diff --git a/e2e/single-host-fleet.test.ts b/e2e/single-host-fleet.test.ts index 615c84bc6..32eea15ea 100644 --- a/e2e/single-host-fleet.test.ts +++ b/e2e/single-host-fleet.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; /** * A worker answers the fleet operations as a fleet of one: `worker list` and `GET /v1/workers` @@ -28,10 +28,9 @@ interface HttpHost { /** A single host with HTTP on, an operator token and an agent token, once it answers. */ async function httpHost(): Promise { - const port = await freeLoopbackPort(); - const env = await withDaemon({ + const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - }); + })); const baseUrl = `http://127.0.0.1:${port}`; const bearer = async (role: string) => { const minted = await env.cli(["token", "create", "--role", role]); diff --git a/e2e/slow-android-physical.test.ts b/e2e/slow-android-physical.test.ts index aa6875d44..ee1709442 100644 --- a/e2e/slow-android-physical.test.ts +++ b/e2e/slow-android-physical.test.ts @@ -2,13 +2,7 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; -import { - freeLoopbackPort, - waitFor, - waitForDeviceState, - withDaemon, - type TestEnv, -} from "./helpers/index.js"; +import { type TestEnv, waitFor, waitForDeviceState, withHttpDaemon } from "./helpers/index.js"; const execFileAsync = promisify(execFile); @@ -76,15 +70,14 @@ async function serverPid(): Promise { } async function rig(execTimeoutMs?: number): Promise { - const port = await freeLoopbackPort(); - const env = await withDaemon({ + const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { ...(execTimeoutMs === undefined ? {} : { exec: { timeoutMs: execTimeoutMs } }), health: { probeIntervalMs: PROBE_INTERVAL_MS, stableObservations: 2 }, http: { enabled: true, host: "127.0.0.1", port }, }, driver: "real", - }); + })); const base = `http://127.0.0.1:${String(port)}`; await waitFor( async () => { diff --git a/e2e/slow-ios-physical.test.ts b/e2e/slow-ios-physical.test.ts index 0710275cf..a46d569e0 100644 --- a/e2e/slow-ios-physical.test.ts +++ b/e2e/slow-ios-physical.test.ts @@ -5,13 +5,7 @@ import { join } from "node:path"; import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; -import { - freeLoopbackPort, - waitFor, - waitForDeviceState, - withDaemon, - type TestEnv, -} from "./helpers/index.js"; +import { type TestEnv, waitFor, waitForDeviceState, withHttpDaemon } from "./helpers/index.js"; const execFileAsync = promisify(execFile); @@ -106,14 +100,13 @@ async function uninstallDirect(udid: string, bundle: string): Promise { } async function rig(): Promise { - const port = await freeLoopbackPort(); - const env = await withDaemon({ + const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { health: { probeIntervalMs: PROBE_INTERVAL_MS, stableObservations: 2 }, http: { enabled: true, host: "127.0.0.1", port }, }, driver: "real", - }); + })); const base = `http://127.0.0.1:${String(port)}`; await waitFor( async () => { diff --git a/e2e/status-while-starting.test.ts b/e2e/status-while-starting.test.ts index 726383d3e..1d8b695b4 100644 --- a/e2e/status-while-starting.test.ts +++ b/e2e/status-while-starting.test.ts @@ -1,14 +1,13 @@ import { existsSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import { waitFor, withHttpDaemon } from "./helpers/index.js"; describe("status while the daemon is starting", () => { it("a daemon held in starting answers simlock status with the starting line, and GET /v1/status with daemon and host only", async () => { - const port = await freeLoopbackPort(); - const env = await withDaemon({ + const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - }); + })); // Minting a token is an operation that waits for a started daemon, so it comes first. const minted = await env.cli(["token", "create", "--role", "agent"]); expect(minted.code, minted.stderr).toBe(0); diff --git a/e2e/token-route.test.ts b/e2e/token-route.test.ts index 9a2556b5b..e080fe28b 100644 --- a/e2e/token-route.test.ts +++ b/e2e/token-route.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { waitFor, withHttpDaemon, type TestEnv } from "./helpers/index.js"; /** * `GET /v1/tokens` answers `token.list` over HTTP, so the console can name a lease's holder by @@ -30,16 +30,13 @@ interface HttpDaemon { /** A daemon in `mode` with HTTP on, once its listener answers. */ async function httpDaemon(mode: "worker" | "gateway"): Promise { - const port = await freeLoopbackPort(); - const http = { enabled: true, host: "127.0.0.1", port }; - const env = await withDaemon( - mode === "gateway" + const { env, port } = await withHttpDaemon((port) => { + const http = { enabled: true, host: "127.0.0.1", port }; + return mode === "gateway" ? { configOverrides: { http, mode: "gateway" }, driver: "none" } - : { configOverrides: { http } }, - ); + : { configOverrides: { http } }; + }); const baseUrl = `http://127.0.0.1:${port}`; - // Any CLI call starts the daemon; the listener comes up with it. - expect((await env.cli(["status", "--json"])).code).toBe(0); await waitFor( async () => { try { diff --git a/e2e/waiting-requests.test.ts b/e2e/waiting-requests.test.ts index 78ac21960..09809e1bd 100644 --- a/e2e/waiting-requests.test.ts +++ b/e2e/waiting-requests.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; +import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js"; /** * `simlock list --requests`: every request waiting for a device, one line each, on a single host @@ -55,11 +55,10 @@ describe("simlock list --requests", () => { }); it("on a gateway, lists the fleet queue and a request in a worker's own queue with that worker", async () => { - const port = await freeLoopbackPort(); - const gateway = await withDaemon({ + const { env: gateway, port } = await withHttpDaemon((port) => ({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, driver: "none", - }); + })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code).toBe(0); const worker = await withDaemon({