Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions e2e/gateway-smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,184 @@ describe("gateway smoke", () => {

await fetch(`${baseUrl}/v1/leases/${leaseId}`, { headers: auth, method: "DELETE" });
});

// #186: the gateway issued this lease and still holds it, so its single-lease read answers it
// rather than `404 UNKNOWN_LEASE`, in the shape `docs/HTTP-API.md` gives a gateway lease: the
// lease the request resource reports, plus `workerId`/`worker` naming the machine it lives on.
it("serves GET /v1/leases/{id} for a lease the gateway granted over HTTP: the granted lease, naming its worker (#186)", async () => {
const { baseUrl, gateway } = await startFleet(
[{ label: "worker-a", models: ["Pixel 8"] }],
"smoke-agent",
);
const auth = await agentAuth(gateway);
await waitFor(
async () => {
try {
return (await fetch(`${baseUrl}/v1/healthz`)).ok;
} catch {
return false;
}
},
{ label: "the gateway's HTTP port accepting connections" },
);

const created = await fetch(`${baseUrl}/v1/lease-requests`, {
body: JSON.stringify({ device: "Pixel 8", platform: "android" }),
headers: auth,
method: "POST",
});
expect(created.status).toBe(201);
const requestId = ((await created.json()) as { request: { id: string } }).request.id;

let grantedLease: { id: string } | undefined;
await waitFor(
async () => {
const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, {
headers: auth,
});
const view = (await polled.json()) as {
request: { state: string; lease?: { id: string } };
};
grantedLease = view.request.lease;
return view.request.state === "granted";
},
{ label: "the fleet granted the lease request", timeout: 30_000 },
);
if (grantedLease === undefined)
throw new Error("expected the granted request to carry a lease");

const listed = await gateway.cli(["worker", "list", "--json"]);
expect(listed.code).toBe(0);
const workerA = (listed.json as { workers: WorkerView[] }).workers.find(
(view) => view.label === "worker-a",
);
if (workerA === undefined) throw new Error("expected worker-a in the gateway's worker list");

const fetched = await fetch(`${baseUrl}/v1/leases/${grantedLease.id}`, { headers: auth });
expect({ body: await fetched.json(), status: fetched.status }).toEqual({
body: {
lease: {
...grantedLease,
worker: { id: workerA.id, label: "worker-a" },
workerId: workerA.id,
},
},
status: 200,
});

await fetch(`${baseUrl}/v1/leases/${grantedLease.id}`, { headers: auth, method: "DELETE" });
});

// #253: `docs/HTTP-API.md` ("The lease object") gives a gateway-issued lease `workerId` and
// `worker`, and the request resource embeds that object once `granted`. It is handed out in
// two places: the `201` when the grant lands before any progress, and the stored request read
// back. The first request provisions, so its `201` is not granted; it warms the device. The
// second finds that device free and is granted inside its own `201`. All three lease objects count.
it("returns workerId and worker on a gateway-granted lease, in POST /v1/lease-requests' 201 and in GET /v1/lease-requests/{id} (#253)", async () => {
const { baseUrl, gateway } = await startFleet(
[{ label: "worker-a", models: ["Pixel 8"] }],
"smoke-agent",
);
const auth = await agentAuth(gateway);
await waitFor(
async () => {
try {
return (await fetch(`${baseUrl}/v1/healthz`)).ok;
} catch {
return false;
}
},
{ label: "the gateway's HTTP port accepting connections" },
);

const listed = await gateway.cli(["worker", "list", "--json"]);
expect(listed.code).toBe(0);
const workerA = (listed.json as { workers: WorkerView[] }).workers.find(
(view) => view.label === "worker-a",
);
if (workerA === undefined) throw new Error("expected worker-a in the gateway's worker list");

interface RequestBody {
readonly request: {
readonly id: string;
readonly state: string;
readonly lease?: Record<string, unknown>;
};
}
const submit = async (): Promise<RequestBody> => {
const created = await fetch(`${baseUrl}/v1/lease-requests`, {
body: JSON.stringify({ device: "Pixel 8", platform: "android" }),
headers: auth,
method: "POST",
});
expect(created.status).toBe(201);
return (await created.json()) as RequestBody;
};
const readGranted = async (requestId: string): Promise<RequestBody> => {
let body: RequestBody | undefined;
await waitFor(
async () => {
const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, {
headers: auth,
});
body = (await polled.json()) as RequestBody;
return body.request.state === "granted";
},
{ label: "the fleet granted the lease request", timeout: 30_000 },
);
if (body === undefined) throw new Error("expected the granted request to be read back");
return body;
};
const release = async (body: RequestBody): Promise<void> => {
const leaseId = body.request.lease?.id;
if (typeof leaseId !== "string") throw new Error("expected the granted lease to have an id");
const released = await fetch(`${baseUrl}/v1/leases/${leaseId}`, {
headers: auth,
method: "DELETE",
});
expect(released.status).toBe(202);
};

const first = await submit();
const firstRead = await readGranted(first.request.id);
await release(firstRead);
// The release answers before the worker has reclaimed the device. The second request is
// granted inside its own `201` only once the gateway's view shows that device ready again.
await waitFor(
async () => {
const status = (await (await fetch(`${baseUrl}/v1/status`, { headers: auth })).json()) as {
devices: { state: string }[];
leases: unknown[];
};
return (
status.leases.length === 0 &&
status.devices.length > 0 &&
status.devices.every((device) => device.state === "ready")
);
},
{ label: "the released device ready again in the gateway's view", timeout: 30_000 },
);

const second = await submit();
const secondRead = await readGranted(second.request.id);

const namesWorkerA = expect.objectContaining({
worker: { id: workerA.id, label: "worker-a" },
workerId: workerA.id,
});
expect({
firstRequestRead: firstRead.request.lease,
secondRequestCreated: { lease: second.request.lease, state: second.request.state },
secondRequestRead: secondRead.request.lease,
}).toEqual({
firstRequestRead: namesWorkerA,
secondRequestCreated: { lease: namesWorkerA, state: "granted" },
secondRequestRead: namesWorkerA,
});

await release(secondRead);
});

it("queues a fleet-wide FIFO behind a full worker, refuses --no-wait, and serves the waiter on release", async () => {
// One worker that can run exactly one device, so the fleet's whole capacity is one lease.
// ADR §10: the gateway keeps a single fleet-wide queue and reports the same codes and
Expand Down
13 changes: 9 additions & 4 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -759,10 +759,15 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise<Daemon
// Inert in gateway mode: the gateway issues no leases of its own in this PR, so there
// are no owner-routed facts to buffer (see `DaemonServer`'s constructor).
ownerRoutedFacts: daemon.ownerRoutedFacts,
// A gateway owns no devices, so there is no registry to read one from. The routes that
// decorate a response with a device record are lease routes, which answer
// `UNSUPPORTED_IN_GATEWAY_MODE` here anyway; the fleet's devices come from `status.get`.
registry: { snapshot: { devices: [] } },
// A gateway owns no devices, so it has no registry. `GET /v1/leases/{id}` builds its lease
// payload from the devices each worker view's refresh read in the grant shape, matched on
// the lease's own worker. They carry no state, so `DELETE /v1/leases/{id}` reports its
// `reclaiming` default.
registry: {
get snapshot() {
return { devices: gatewayService.workers.grantedDevices() };
},
},
tokens,
});
const gateway = new HttpGateway(app, {
Expand Down
33 changes: 33 additions & 0 deletions src/gateway/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,39 @@ describe("GatewayService", () => {
await harness.service.stop();
});

it("keeps a worker's devices in the grant shape beside its view, with driverDeviceId, leaving out one that has none", async () => {
const harness = fleet();
await harness.service.start();
const worker = new ScriptedWorkerClient();
worker.devices = [
{
...deviceFixture("dev_1"),
createdAt: 1,
driverData: { secret: "a driver's private blob" },
driverDeviceId: "UDID-1",
},
{ ...deviceFixture("dev_2"), createdAt: 1, driverData: {} },
];

await harness.join("wrk_1", worker);
await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.devices).toHaveLength(2));

for (const device of harness.service.workers.view("wrk_1")?.devices ?? []) {
expect(device).not.toHaveProperty("driverDeviceId");
}
expect(harness.service.workers.grantedDevices()).toEqual([
{
driverDeviceId: "UDID-1",
id: "dev_1",
mode: "full",
spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" },
workerId: "wrk_1",
},
]);

await harness.service.stop();
});

it("keeps each worker device's mode in the view", async () => {
const harness = fleet();
await harness.service.start();
Expand Down
21 changes: 19 additions & 2 deletions src/gateway/worker-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
import { z } from "zod";

import type { EventBus, EventName } from "../bus/index.js";
import { isSimlockError, statusDeviceSchema } from "../contract/index.js";
import { grantedDeviceSchema, isSimlockError, statusDeviceSchema } from "../contract/index.js";
import type { SimlockAdminClient } from "../admin/index.js";
import { connectSimlockAdmin } from "../admin/index.js";
import type { AcceptedUplink, Clock, IpcConnection, Logger } from "../ports/index.js";
import { NoopLogger } from "../ports/index.js";
import type { WorkerRegistry, WorkerViewSnapshot } from "./worker-registry.js";
import type { WorkerGrantedDevice, WorkerRegistry, WorkerViewSnapshot } from "./worker-registry.js";

/**
* How long the gateway waits for one round trip to a worker before giving up on it.
Expand Down Expand Up @@ -109,6 +109,18 @@ export interface WorkerLinkOptions {
* client's `status.get`. */
const viewDevicesSchema = z.array(statusDeviceSchema);

/** The same `list.get` answer narrowed to the grant shape instead, which keeps `driverDeviceId`
* for the lease payload a gateway serves its holder (`GET /v1/leases/{id}`). Kept off the view,
* in the registry beside it: see `WorkerGrantedDevice`. `list.get`'s contract also admits a
* device without `driverDeviceId`, so one that does not parse is left out on its own rather than
* failing the view's refresh; its lease then answers `UNKNOWN_LEASE` rather than a made-up udid. */
function grantedDevices(devices: readonly unknown[]): WorkerGrantedDevice[] {
return devices.flatMap((device) => {
const parsed = grantedDeviceSchema.safeParse(device);
return parsed.success ? [parsed.data] : [];
});
}

export class WorkerLink {
readonly workerId: string;
readonly #logger: Logger;
Expand Down Expand Up @@ -364,9 +376,14 @@ export class WorkerLink {
// this re-check the write below would land after the successor's own, more recent refresh,
// overwriting a fresh view with a stale one for up to `WORKER_CALL_TIMEOUT_MS`.
if (this.#closed || (this.options.isCurrentLink?.() ?? true) === false) return;
// The leases come from `status.get` and the devices from the `list.get` after it, and a
// worker keeps a device while a lease holds it, so a lease reported here names a device in
// `devices` unless it ended in between. One `refresh` call commits both, so a lease is
// never visible before its device.
this.options.registry.refresh(this.workerId, {
...viewStatus(status),
devices: viewDevicesSchema.parse(devices),
grantedDevices: grantedDevices(devices),
version: client.daemonVersion,
...(catalog === undefined ? {} : { catalog: catalog.platforms }),
...(config === undefined ? {} : viewConfig(config)),
Expand Down
48 changes: 48 additions & 0 deletions src/gateway/worker-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,54 @@ describe("WorkerRegistry", () => {
expect(workers.view("wrk_1")).toBeUndefined();
});

it("lists each worker's granted devices under that worker's id, and keeps them through a refresh that carries none", () => {
const { workers } = registry();
const granted = (udid: string) => ({
driverDeviceId: udid,
id: "dev_1",
mode: "full" as const,
spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const },
});
workers.connected("wrk_a", undefined, "0.3.0");
workers.connected("wrk_b", undefined, "0.3.0");
workers.refresh("wrk_a", { grantedDevices: [granted("UDID-A")] });
workers.refresh("wrk_b", { grantedDevices: [granted("UDID-B")] });
workers.refresh("wrk_b", { queueDepth: 1 });

expect(
workers
.grantedDevices()
.map(({ driverDeviceId, workerId }) => ({ driverDeviceId, workerId })),
).toEqual([
{ driverDeviceId: "UDID-A", workerId: "wrk_a" },
{ driverDeviceId: "UDID-B", workerId: "wrk_b" },
]);
});

it("forgets a worker's granted devices with its view, so a worker re-added under that id lists none of them", async () => {
const { workers } = registry();
workers.connected("wrk_1", undefined, "0.3.0");
workers.refresh("wrk_1", {
grantedDevices: [
{
driverDeviceId: "UDID-1",
id: "dev_1",
mode: "full",
spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" },
},
],
});
expect(workers.grantedDevices().map(({ id, workerId }) => ({ id, workerId }))).toEqual([
{ id: "dev_1", workerId: "wrk_1" },
]);

workers.disconnected("wrk_1");
await workers.remove("wrk_1");
workers.connected("wrk_1", undefined, "0.3.0");

expect(workers.grantedDevices()).toEqual([]);
});

describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => {
it("warns once a worker's own cap is refreshed in below the gateway's", () => {
const logger = new RecordingLogger();
Expand Down
Loading
Loading