diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 03fb76964..c877286b6 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -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; + }; + } + const submit = async (): Promise => { + 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 => { + 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 => { + 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 diff --git a/src/daemon/main.ts b/src/daemon/main.ts index cc670f999..2e9846b66 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -759,10 +759,15 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { 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(); diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 9a4155ca5..4330d8062 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -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. @@ -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; @@ -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)), diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index d584ecfef..6c84ae862 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -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(); diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index f9b10d1cc..f95af493b 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -12,7 +12,11 @@ import type { z } from "zod"; import type { EventBus } from "../bus/index.js"; -import { workerViewSchema, type ProtocolRange } from "../contract/index.js"; +import { + type grantedDeviceSchema, + type ProtocolRange, + workerViewSchema, +} from "../contract/index.js"; import { DispatchError } from "../daemon/dispatch.js"; import type { Clock, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; @@ -37,6 +41,18 @@ export type WorkerViewSnapshot = Pick< | "version" >; +/** A worker's device in the shape a grant carries it: what `GET /v1/leases/{id}` builds a lease + * payload from. Kept beside a view, never on it, because a view is what `status.get` and + * `worker.list` show every agent, and `driverDeviceId` is only the lease holder's to see. */ +export type WorkerGrantedDevice = z.infer; + +/** What one refresh over the uplink commits: the view's fields, and the same devices in the + * grant shape. Both come from one refresh and land in one call, so a lease the view reports is + * never visible before the device it names. */ +export type WorkerRefresh = Partial & { + readonly grantedDevices?: readonly WorkerGrantedDevice[]; +}; + export interface WorkerRegistryOptions { readonly clock: Clock; readonly eventBus: EventBus; @@ -70,6 +86,9 @@ export interface WorkerRegistryOptions { export class WorkerRegistry { readonly #workers = new Map(); + /** Each worker's devices in the grant shape (see `WorkerGrantedDevice`). Set by `refresh`, + * which writes nothing for a worker with no view, and deleted with the view by `#forget`. */ + readonly #grantedDevices = new Map(); /** * Drained worker ids, including ids with no view yet. Kept beside the views rather than only * on them because drain outlives a view: an operator drains a machine, the machine is turned @@ -102,6 +121,20 @@ export class WorkerRegistry { return this.#workers.get(workerId); } + /** + * Every worker's devices in the grant shape, each with the `workerId` it came from: what a + * gateway's `GET /v1/leases/{id}` builds the lease payload from. Ordered by worker id, as + * `views()` is. The caller matches a device by worker and id together, never by id alone. + */ + grantedDevices(): readonly (WorkerGrantedDevice & { readonly workerId: string })[] { + return this.views().flatMap((view) => + (this.#grantedDevices.get(view.id) ?? []).map((device) => ({ + ...device, + workerId: view.id, + })), + ); + } + /** * `./fleet-ports.ts`'s `FleetViews#onViewsChanged` -- #118's seam for running dispatch * whenever the fleet's queue or any worker view changes (ADR 0005 §11), without reaching into @@ -252,15 +285,17 @@ export class WorkerRegistry { * previous value standing rather than blank it. A refresh for a worker whose view is gone * (removed while a status call was in flight) is dropped rather than resurrecting it. */ - refresh(workerId: string, snapshot: Partial): void { + refresh(workerId: string, refresh: WorkerRefresh): void { const existing = this.#workers.get(workerId); if (existing === undefined) return; + const { grantedDevices, ...snapshot } = refresh; const next: WorkerView = { ...existing, ...snapshot, lastSeenAt: this.options.clock.now(), }; this.#workers.set(workerId, next); + if (grantedDevices !== undefined) this.#grantedDevices.set(workerId, grantedDevices); this.#warnOnLowerMaxTtl(existing, next); this.#notifyViewsChanged(); } @@ -455,6 +490,7 @@ export class WorkerRegistry { { clearDrain }: { clearDrain: boolean }, ): Promise { this.#workers.delete(view.id); + this.#grantedDevices.delete(view.id); if (clearDrain && this.#drained.delete(view.id)) { await this.options.drainStore?.save([...this.#drained]); } diff --git a/src/http/app.test.ts b/src/http/app.test.ts index db7a0587b..f18843c81 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -33,6 +33,8 @@ function buildHarness( overrides: { readonly config?: HttpGatewayDeps["config"]; readonly leaseRequests?: HttpGatewayDeps["leaseRequests"]; + /** A gateway's device reader, in place of the fake worker registry. */ + readonly registry?: HttpGatewayDeps["registry"]; } = {}, ) { const clock = new FakeClock(1_000); @@ -67,7 +69,7 @@ function buildHarness( leaseRequests: overrides.leaseRequests ?? dispatcher.requests, logger, ownerRoutedFacts, - registry, + registry: overrides.registry ?? registry, tokens, }); @@ -970,6 +972,40 @@ describe("lease routes", () => { platform: "ios", udid: "ABCD-1234", }); + expect(body.lease).not.toHaveProperty("worker"); + expect(body.lease).not.toHaveProperty("workerId"); + }); + + it("GET /v1/leases/:id on a gateway builds the lease from its own worker's device, not another worker's with the same device id", async () => { + const device = (workerId: string, udid: string) => ({ + ...makeDevice({ driverDeviceId: udid, id: "dev_1" }), + workerId, + }); + const { app, dispatcher } = buildHarness({ + registry: { + snapshot: { devices: [device("wrk_a", "UDID-A"), device("wrk_b", "UDID-B")] }, + }, + }); + dispatcher.handlers["lease.list"] = () => ({ + leases: [ + { + ...makeLease({ deviceId: "dev_1", id: "wrk_b.lse_1", ownerId: "tok_agent" }), + worker: { id: "wrk_b", label: "mac-b" }, + workerId: "wrk_b", + }, + ], + }); + + const response = await app.request("/v1/leases/wrk_b.lse_1", { headers: agentAuth }); + + expect(response.status).toBe(200); + expect(((await response.json()) as { lease: unknown }).lease).toMatchObject({ + deviceId: "dev_1", + id: "wrk_b.lse_1", + udid: "UDID-B", + worker: { id: "wrk_b", label: "mac-b" }, + workerId: "wrk_b", + }); }); it("404s an unknown lease id", async () => { @@ -1381,8 +1417,10 @@ describe("lease routes", () => { dispatcher.handlers["lease.release"] = (input) => { const leaseId = (input as { leaseId: string }).leaseId; registry.leases = registry.leases.filter((lease) => lease.id !== leaseId); + // Not `reclaiming`: that is also the route's default for a device it cannot find, so only + // another state proves the answer is read from the registry. registry.devices = registry.devices.map((device) => - device.id === "dev_1" ? { ...device, state: "reclaiming" } : device, + device.id === "dev_1" ? { ...device, state: "quarantined" } : device, ); return { leaseId }; }; @@ -1393,7 +1431,7 @@ describe("lease routes", () => { }); expect(response.status).toBe(202); expect(await response.json()).toEqual({ - device: { id: "dev_1", state: "reclaiming" }, + device: { id: "dev_1", state: "quarantined" }, released: true, }); }); diff --git a/src/http/app.ts b/src/http/app.ts index 7ec2b18b7..ff142485e 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -24,6 +24,7 @@ import { pipeSse } from "./sse.js"; import type { TokenIdentity } from "./token-store.js"; import { buildLeasePayload, + type HttpLeaseDevice, isTerminalStage, type LeaseRequestInput, type LeaseRequestReader, @@ -31,12 +32,25 @@ import { type TrackedRequestView, } from "./tracker.js"; +/** + * The device fields the lease routes read: what a lease payload is built from, plus two that + * only one kind of daemon has. A worker's own registry record carries `state`, which `DELETE + * /v1/leases/:id` reports; a gateway holds no device state of its own and leaves it out rather + * than inventing one. A gateway's device carries the `workerId` it lives on, because a device + * id is one worker's claim and is matched only together with the lease's own `workerId`. + */ +export interface HttpRegistryDevice extends HttpLeaseDevice { + readonly state?: DeviceRecord["state"]; + readonly workerId?: string; +} + /** Minimal structural read surface -- narrower than importing the `Registry` class itself. Kept * for the one thing dispatcher operations don't hand back: a device record for a specific - * lease's `GET /v1/leases/:id` decoration (there is no per-id device operation). */ + * lease's `GET /v1/leases/:id` decoration (there is no per-id device operation). A worker + * passes its registry; a gateway passes the devices its worker views hold in the grant shape. */ export interface HttpRegistryReader { readonly snapshot: { - readonly devices: readonly DeviceRecord[]; + readonly devices: readonly HttpRegistryDevice[]; }; } @@ -344,7 +358,7 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const identity = c.get("identity"); const session = buildHttpSession(identity); const lease = await findOwnedLease(deps, session, c.req.param("id")); - const device = findDevice(deps, lease.deviceId); + const device = findDevice(deps, lease); if (device === undefined) throw unknownLease(lease.id); // ADR 0004: `ttlMs` comes off the lease record itself, so a payload served after a daemon // restart reports the lease's real width rather than a mode default standing in for a @@ -555,13 +569,17 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa // the handler answers `UNKNOWN_LEASE`/404 for a nonexistent one, matching the socket // transport exactly -- unlike the `lease.list`-filtered `findOwnedLease`, which always // answered 404 for both cases. - const deviceId = await findLeaseDeviceId(deps, session, id); + const lease = await findLeaseForDecoration(deps, session, id); await deps.dispatch("lease.release", { leaseId: id }, session); - const device = deviceId === undefined ? undefined : findDevice(deps, deviceId); + // A gateway holds no device state, so its answer is always the `reclaiming` default. + const device = lease === undefined ? undefined : findDevice(deps, lease); return c.json( - { device: { id: deviceId ?? id, state: device?.state ?? "reclaiming" }, released: true }, + { + device: { id: lease?.deviceId ?? id, state: device?.state ?? "reclaiming" }, + released: true, + }, 202, ); }); @@ -704,17 +722,17 @@ async function findOwnedLease( return lease; } -/** Best-effort `deviceId` lookup for a lease id, scoped to what the session's `lease.list` - * would show it (own leases; admin sees all) -- used only to decorate a response after an +/** Best-effort lease lookup for a lease id, scoped to what the session's `lease.list` would + * show it (own leases; admin sees all) -- used only to decorate a response after an * authoritative dispatch has already decided whether the request is allowed. Never used to * gate access itself (see the `DELETE /v1/leases/:id` route). */ -async function findLeaseDeviceId( +async function findLeaseForDecoration( deps: HttpGatewayDeps, session: ReturnType, id: string, -): Promise { +) { const { leases } = await deps.dispatch("lease.list", {}, session); - return leases.find((candidate) => candidate.id === id)?.deviceId; + return leases.find((candidate) => candidate.id === id); } function serializeRequest( @@ -742,8 +760,16 @@ function serializeRequest( } } -function findDevice(deps: HttpGatewayDeps, id: string): DeviceRecord | undefined { - return deps.registry.snapshot.devices.find((device) => device.id === id); +/** The device a lease names. On a gateway both carry the `workerId` they came from, and a + * device matches only on the lease's own worker: a device id is that worker's claim, so another + * worker reporting the same id never answers for it. On a worker neither carries one. */ +function findDevice( + deps: HttpGatewayDeps, + lease: { readonly deviceId: string; readonly workerId?: string | undefined }, +): HttpRegistryDevice | undefined { + return deps.registry.snapshot.devices.find( + (device) => device.id === lease.deviceId && device.workerId === lease.workerId, + ); } async function parseRenewBody(c: { diff --git a/src/http/tracker.ts b/src/http/tracker.ts index 2a1ceaeb0..a19011c19 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -43,6 +43,11 @@ export interface LeasePayload { readonly mode: "slim" | "full"; /** The image tag the device was created from, on a device whose request named one. */ readonly imageTag?: string; + /** The worker a gateway-issued lease lives on, as its lease record names it. Absent from a + * worker's own lease. */ + readonly worker?: { readonly id: string; readonly label?: string | undefined }; + /** `worker.id`, flat, for the aggregate lists: present exactly when `worker` is. */ + readonly workerId?: string; } /** @@ -76,6 +81,10 @@ export function buildLeasePayload( dataPlane: null, mode: device.mode, ...(device.spec.imageTag === undefined ? {} : { imageTag: device.spec.imageTag }), + // A gateway's lease record names its worker and a worker's own never does. `workerId` is + // derived from `worker` rather than read off the record: a grant's record has no + // `workerId` field (only `lease.list`'s does), and the two must never disagree. + ...(lease.worker === undefined ? {} : { worker: lease.worker, workerId: lease.worker.id }), }; } @@ -366,7 +375,7 @@ type HttpLeaseProgress = * contract-shaped data, which need not match core's own types field for field, and this module * never imports core domain types at all -- everything it needs from a grant is these few fields. */ -interface HttpLeaseDevice { +export interface HttpLeaseDevice { readonly id: string; readonly driverDeviceId: string; readonly spec: { @@ -383,6 +392,8 @@ interface HttpLeaseRecord { readonly grantedAt: number; readonly ttlMs: number; readonly ttlDeadline: number; + /** ADR 0005 §18: set on a lease a gateway issued, naming the worker it lives on. */ + readonly worker?: { readonly id: string; readonly label?: string | undefined } | undefined; } type StoredRequest = z.infer;