From f453c8863f2bbaf0011213928266f0c082577809 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:19:43 +0100 Subject: [PATCH 01/20] test: through a gateway, a lease holder's PUT, GET, list and DELETE reach the lease's worker (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 0c93ed3a0..c39fc914c 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -13,6 +13,7 @@ import type { RelayTarget, TwoWayRelayTarget } from "./relay.js"; import type { DaemonServer } from "./server.js"; import { aborted, + adminSession, cleanUp, digestOf, gate, @@ -385,6 +386,51 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(missing).toMatchObject({ code: "RELAY_TARGET_MISSING", state: "rejected" }); }, 30_000); + async function fileRig() { + const fleet = await startFleet(); + const { secret, token } = await fleet.gateway.dispatch( + "token.create", + { label: "holder", role: "agent" }, + adminSession, + ); + const holder = agent({ principal: token.id }); + const grant = await fleet.gateway.dispatch( + "lease.request", + { model: "Pixel-A", noWait: true, platform: "android" }, + holder, + ); + const base = `http://127.0.0.1:${String(fleet.port)}/v1/leases/${grant.lease.id}/files`; + const call = (path: string, init: RequestInit = {}) => + fetch(`${base}${path}`, { + ...init, + headers: { authorization: `Bearer ${secret}`, ...init.headers }, + }); + return { ...fleet, call, leaseId: grant.lease.id }; + } + + it("through a gateway, a lease holder's PUT, GET, list and DELETE reach the lease's worker and answer as on a worker", async () => { + const { call } = await fileRig(); + const bytes = patternBytes(20 * MIB, 5); + + const put = await call("/fixture.tar", { + body: patternStream(20 * MIB, 5), + duplex: "half", + method: "PUT", + } as RequestInit); + const get = await call("/fixture.tar"); + const listed = await call(""); + const deleted = await call("/fixture.tar", { method: "DELETE" }); + const after = await call(""); + + expect(put.status).toBe(201); + expect(await put.json()).toEqual({ name: "fixture.tar", size: 20 * MIB }); + expect(get.status).toBe(200); + expect(digestOf([new Uint8Array(await get.arrayBuffer())])).toBe(digestOf([bytes])); + expect(await listed.json()).toMatchObject({ files: [{ name: "fixture.tar", size: 20 * MIB }] }); + expect(deleted.status).toBe(204); + expect(await after.json()).toEqual({ files: [] }); + }, 120_000); + it("a 20 MiB PUT body arrives at the target byte for byte, and a 20 MiB response body comes back byte for byte", async () => { let received = ""; behavior = async (request) => { From 92f41a7808b2ab0f93a32183a4402264c7230f05 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:21:46 +0100 Subject: [PATCH 02/20] feat(lease-files): a gateway relays the file routes to the lease's worker (#1358) --- src/daemon/gateway-lease-files.ts | 39 +++++++++++++++++++++++++++++++ src/daemon/main.ts | 5 ++++ src/daemon/worker-composition.ts | 2 ++ src/http/app-leases.test.ts | 19 --------------- src/http/app.ts | 15 +----------- src/http/core-routes.test.ts | 3 ++- src/http/lease-declarations.ts | 13 +++-------- src/http/server.test.ts | 3 ++- src/http/test-app.ts | 5 ++-- src/http/test-fakes.ts | 5 ++++ src/lease-files/handler.ts | 4 ++-- src/lease-files/lease-files.ts | 2 ++ src/lease-files/relay-target.ts | 24 +++++++++++++++++++ src/lease-files/types.ts | 2 ++ 14 files changed, 91 insertions(+), 50 deletions(-) create mode 100644 src/daemon/gateway-lease-files.ts create mode 100644 src/lease-files/relay-target.ts diff --git a/src/daemon/gateway-lease-files.ts b/src/daemon/gateway-lease-files.ts new file mode 100644 index 000000000..c837c2e03 --- /dev/null +++ b/src/daemon/gateway-lease-files.ts @@ -0,0 +1,39 @@ +import type { Identity } from "../auth/index.js"; +import type { HttpLeaseFiles } from "../http/app.js"; + +// why: only `main.ts` imports the gateway, so the relay is typed by the shape of the call it takes. +export interface GatewayLeaseFilesOptions { + readonly relay: ( + workerId: string, + call: { + readonly target: string; + readonly request: Request; + readonly tenant: string; + readonly leaseId?: string; + }, + ) => Promise; + readonly requesterPrefix: string; +} + +/** why: a gateway holds no file; it relays each file request to the worker that holds the lease, through the worker's `files` target (ADR 0067 §2). */ +export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): HttpLeaseFiles { + return { + handle: (request, identity: Identity, lease, name) => { + const workerLeaseId = lease.workerLeaseId ?? lease.id; + const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${ + name === undefined ? "" : `/${encodeURIComponent(name)}` + }`; + return options.relay(lease.workerId ?? "", { + leaseId: workerLeaseId, + request: new Request(`http://simlock-worker${path}`, { + headers: request.headers, + method: request.method, + signal: request.signal, + ...(request.body === null ? {} : { body: request.body, duplex: "half" }), + } as RequestInit), + target: "files", + tenant: `${options.requesterPrefix}${identity.principal}`, + }); + }, + }; +} diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 4762e29df..31ef923e2 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -29,6 +29,7 @@ import { androidSourceDataOwner } from "../drivers/android/index.js"; import { iosSourceDataOwner } from "../drivers/ios/index.js"; import { type Auth, createAuth, tokensOwner } from "../auth/index.js"; import { createHttpApp } from "../http/app.js"; +import { createGatewayLeaseFiles } from "./gateway-lease-files.js"; import type { HttpDispatch } from "../http/dispatcher-session.js"; import { HttpGateway } from "../http/server.js"; import { @@ -629,6 +630,10 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise gatewayRelay.relay(workerId, call), + requesterPrefix: gatewayRequesterPrefix, + }), leaseRequests: fleetCoordinator.requests, logger: httpLogger, leaseRoutes: [...moduleHost.leaseRoutes()], diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index ca6b5168b..2e5cbc05e 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -517,6 +517,8 @@ export async function composeWorker( relayTargets: { ...moduleHost.relayTargets, ...options.relayTargets, + // why: `files` is reserved as a module name (ADR 0067 §7), so the core target never shadows a module's. + files: (request) => leaseFiles.relayTarget(request), }, relayTwoWayTargets: { ...moduleHost.relayTwoWayTargets, diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index e7d836322..0ceb62193 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -2046,23 +2046,4 @@ describe("a lease's files on a worker", () => { for (const call of routes("lse_1", operatorAuth)) statuses.push((await call()).status); expect(statuses).toEqual([201, 200, 200, 204]); }); - - it("on a gateway, before the gateway relays them, the file routes answer 501 UNSUPPORTED_IN_GATEWAY_MODE", async () => { - const { app, registry } = buildHarness(); - registry.leases = [makeLease({ id: "lse_1", ownerId: "tok_agent" })]; - const routes = [ - ["PUT", "/v1/leases/lse_1/files/fixture.tar"], - ["GET", "/v1/leases/lse_1/files/fixture.tar"], - ["DELETE", "/v1/leases/lse_1/files/fixture.tar"], - ["GET", "/v1/leases/lse_1/files"], - ] as const; - - for (const [method, path] of routes) { - const response = await app.request(path, { headers: agentAuth, method }); - expect(response.status).toBe(501); - expect(((await response.json()) as { error: { code: string } }).error.code).toBe( - "UNSUPPORTED_IN_GATEWAY_MODE", - ); - } - }); }); diff --git a/src/http/app.ts b/src/http/app.ts index a7fcaaf84..251767de5 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -39,7 +39,6 @@ import { badRequest, errorResponse, forbidden, - HttpApiError, mapError, requestNotCancellable, unknownLease, @@ -123,8 +122,7 @@ export interface HttpGatewayDeps { readonly answerDownloadsEarly?: boolean | undefined; readonly mounts?: readonly HttpMount[]; readonly leaseRoutes?: readonly HttpLeaseRoute[]; - // why: absent on a gateway, whose file routes answer 501 until it relays them. - readonly leaseFiles?: HttpLeaseFiles | undefined; + readonly leaseFiles: HttpLeaseFiles; } export interface HttpLeaseFiles { @@ -842,17 +840,6 @@ export function createHttpApp(deps: HttpGatewayDeps): OpenAPIHono & HttpApp // why: the lease is resolved with `lease.get` (owner or operator) before the files handler runs, so it never checks an owner. const serveLeaseFiles = async (c: Context, id: string, name: string | undefined) => { - if (deps.leaseFiles === undefined) { - return errorResponse( - c, - new HttpApiError( - 501, - "UNSUPPORTED_IN_GATEWAY_MODE", - "Lease files are not served through a gateway", - { operation: "lease.files" }, - ), - ); - } const identity = c.get("identity"); const lease = await findOwnedLease(deps, buildHttpSession(identity), id); return deps.leaseFiles.handle( diff --git a/src/http/core-routes.test.ts b/src/http/core-routes.test.ts index ff2959d45..4c4b830e9 100644 --- a/src/http/core-routes.test.ts +++ b/src/http/core-routes.test.ts @@ -9,7 +9,7 @@ import { optionalModules } from "../module-registry/index.js"; import { createHttpApp, type HttpMount } from "./app.js"; import { buildOpenApiDocument } from "./openapi.js"; import { DECLARED_ROUTES } from "./route-declarations.js"; -import { FakeDispatcher, FakeRegistry, sequenceIdGenerator } from "./test-fakes.js"; +import { FakeDispatcher, FakeRegistry, noLeaseFiles, sequenceIdGenerator } from "./test-fakes.js"; function coverageProblems(registered: readonly string[], declared: readonly string[]): string[] { const known = new Set(declared); @@ -36,6 +36,7 @@ function buildApp(mounts: readonly HttpMount[] = []) { ownerRoutedFacts: new OwnerRoutedFactBus(eventBus, registry), registry, auth: fakeAuth(new Map()), + leaseFiles: noLeaseFiles, mounts, }); } diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index c5a9dbd9b..8a083ba55 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -386,7 +386,6 @@ export const leaseFilePutRoute = declareRoute({ 409: ["FILE_BUSY"], 413: ["FILE_TOO_LARGE", "LEASE_FILES_FULL"], 422: ["INSUFFICIENT_DISK_SPACE"], - 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], }, }); @@ -401,10 +400,7 @@ export const leaseFileGetRoute = declareRoute({ request: { params: leaseFileParamsSchema }, binaryReply: true, alsoStatus: 206, - errors: { - 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], - 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], - }, + errors: { 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"] }, }); export const leaseFileDeleteRoute = declareRoute({ @@ -415,10 +411,7 @@ export const leaseFileDeleteRoute = declareRoute({ role: "agent", request: { params: leaseFileParamsSchema }, status: 204, - errors: { - 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], - 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], - }, + errors: { 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"] }, }); export const leaseFileListRoute = declareRoute({ @@ -429,7 +422,7 @@ export const leaseFileListRoute = declareRoute({ role: "agent", request: { params: leaseParamsSchema }, reply: z.object({ files: z.array(leaseFileSchema) }), - errors: { 404: ["UNKNOWN_LEASE"], 501: ["UNSUPPORTED_IN_GATEWAY_MODE"] }, + errors: { 404: ["UNKNOWN_LEASE"] }, }); export const LEASE_ROUTES = [ diff --git a/src/http/server.test.ts b/src/http/server.test.ts index 7fb49638e..caf6bebbc 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -12,7 +12,7 @@ import type { Identity } from "../auth/index.js"; import { fakeAuth, tokenIdentity } from "../auth/testing.js"; import { createHttpApp } from "./app.js"; import { CONSOLE_CONTENT_SECURITY_POLICY, HttpGateway, withConsole } from "./server.js"; -import { FakeDispatcher, FakeRegistry, sequenceIdGenerator } from "./test-fakes.js"; +import { FakeDispatcher, FakeRegistry, noLeaseFiles, sequenceIdGenerator } from "./test-fakes.js"; const PAGE = 'Simlock
'; const SCRIPT = "console.log('console');"; @@ -61,6 +61,7 @@ function harness(root: string) { ownerRoutedFacts: new OwnerRoutedFactBus(eventBus, registry), registry, auth, + leaseFiles: noLeaseFiles, }); const site = withConsole(app, { logger, root }); const get = (path: string, init: RequestInit = {}) => diff --git a/src/http/test-app.ts b/src/http/test-app.ts index cd987afad..7efef48b0 100644 --- a/src/http/test-app.ts +++ b/src/http/test-app.ts @@ -10,6 +10,7 @@ import { FakeRegistry, sequenceIdGenerator, waitForDispatch, + noLeaseFiles, } from "./test-fakes.js"; export function buildHarness( @@ -75,9 +76,7 @@ export function buildHarness( registry: overrides.registry ?? registry, auth, ...(overrides.mounts === undefined ? {} : { mounts: overrides.mounts }), - ...(overrides.leaseFiles === undefined - ? {} - : { leaseFiles: overrides.leaseFiles({ clock, logger }) }), + leaseFiles: overrides.leaseFiles?.({ clock, logger }) ?? noLeaseFiles, ...(overrides.answerDownloadsEarly === undefined ? {} : { answerDownloadsEarly: overrides.answerDownloadsEarly }), diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 42763ec42..e6279ab46 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -16,6 +16,7 @@ import { requestedDevice, type OperationName, } from "../contract/index.js"; +import type { HttpLeaseFiles } from "./app.js"; import { DispatchError } from "../daemon/dispatch.js"; import type { DispatchSession } from "../daemon/dispatcher.js"; import { describeLeaseRequestFailure } from "../daemon/error-code.js"; @@ -238,3 +239,7 @@ export class FakeRegistry { }; } } + +export const noLeaseFiles: HttpLeaseFiles = { + handle: () => Promise.reject(new Error("this harness serves no lease files")), +}; diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index ae3789815..15bf195c0 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -9,7 +9,7 @@ import type { LeaseFileView, LeaseFilesLease } from "./types.js"; export async function handleRequest( store: LeaseFolders, request: Request, - lease: LeaseFilesLease, + lease: Pick, name: string | undefined, ): Promise { try { @@ -29,7 +29,7 @@ export async function handleRequest( async function serve( store: LeaseFolders, request: Request, - lease: LeaseFilesLease, + lease: Pick, name: string | undefined, ): Promise { const grant = store.findGrant(lease.id); diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts index a4e2324da..49528a503 100644 --- a/src/lease-files/lease-files.ts +++ b/src/lease-files/lease-files.ts @@ -1,5 +1,6 @@ import type { Identity } from "../auth/index.js"; import { handleRequest } from "./handler.js"; +import { relayTarget } from "./relay-target.js"; import { LeaseFolders } from "./store.js"; import type { LeaseFiles, LeaseFilesDeps, LeaseFilesLease } from "./types.js"; @@ -18,6 +19,7 @@ export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { folders.end({ grantedAt: ended.grantedAt, id: ended.leaseId, platform: ended.platform }), }, openFile: (grant, name) => folders.openFile(grant, name), + relayTarget: relayTarget(folders), sweep: (live) => folders.sweep(live), }; } diff --git a/src/lease-files/relay-target.ts b/src/lease-files/relay-target.ts new file mode 100644 index 000000000..a9c0b8135 --- /dev/null +++ b/src/lease-files/relay-target.ts @@ -0,0 +1,24 @@ +import { LEASE_ID_PATTERN, ERROR_TABLE } from "../contract/index.js"; +import { LeaseFilesError } from "./errors.js"; +import { handleRequest } from "./handler.js"; +import type { LeaseFolders } from "./store.js"; + +const PATH = /^\/files\/leases\/([^/]+)(?:\/([^/]+))?$/; + +/** why: the gateway names the worker's own lease id in the path, and the worker checks it as it checks any id from the wire. */ +export function relayTarget(store: LeaseFolders): (request: Request) => Promise { + return async (request) => { + const match = PATH.exec(new URL(request.url).pathname); + const [leaseId, name] = [match?.[1], match?.[2]].map((part) => + part === undefined ? undefined : decodeURIComponent(part), + ); + if (leaseId === undefined || !LEASE_ID_PATTERN.test(leaseId)) { + const refusal = new LeaseFilesError("BAD_REQUEST", "Not a lease files path", {}); + return Response.json( + { error: { code: refusal.code, message: refusal.message } }, + { status: ERROR_TABLE[refusal.code].httpStatus }, + ); + } + return handleRequest(store, request, { id: leaseId }, name); + }; +} diff --git a/src/lease-files/types.ts b/src/lease-files/types.ts index dfeec2095..56b356c84 100644 --- a/src/lease-files/types.ts +++ b/src/lease-files/types.ts @@ -50,6 +50,8 @@ export interface LeaseFiles { lease: LeaseFilesLease, name: string | undefined, ): Promise; + /** why: the worker end of a gateway's relayed file request; the path names the worker's own lease id. */ + relayTarget(request: Request): Promise; folderOf(grant: LeaseFilesGrant): Promise; openFile(grant: LeaseFilesGrant, name: string): Promise; readonly leaseEnd: LeaseEndParticipant; From edc905e718489f5e8ad6e2b4671f85a06d8d8582 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:22:19 +0100 Subject: [PATCH 03/20] test: a gateway gives a download its Content-Length and answers a Range GET 206 (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index c39fc914c..9e6c157b4 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -418,6 +418,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { method: "PUT", } as RequestInit); const get = await call("/fixture.tar"); + const ranged = await call("/fixture.tar", { headers: { range: "bytes=10-19" } }); const listed = await call(""); const deleted = await call("/fixture.tar", { method: "DELETE" }); const after = await call(""); @@ -426,6 +427,11 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(await put.json()).toEqual({ name: "fixture.tar", size: 20 * MIB }); expect(get.status).toBe(200); expect(digestOf([new Uint8Array(await get.arrayBuffer())])).toBe(digestOf([bytes])); + expect(get.headers.get("content-length")).toBe(String(20 * MIB)); + expect(ranged.status).toBe(206); + expect(ranged.headers.get("content-length")).toBe("10"); + expect(ranged.headers.get("content-range")).toBe(`bytes 10-19/${String(20 * MIB)}`); + expect(new Uint8Array(await ranged.arrayBuffer())).toEqual(bytes.subarray(10, 20)); expect(await listed.json()).toMatchObject({ files: [{ name: "fixture.tar", size: 20 * MIB }] }); expect(deleted.status).toBe(204); expect(await after.json()).toEqual({ files: [] }); From 1b2fc8cb03003aa72a243b15d1cd47f6f09c4b77 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:22:34 +0100 Subject: [PATCH 04/20] feat(lease-files): a gateway gives a download its Content-Length from the worker's simlock-content-length (#1358) --- src/daemon/gateway-lease-files.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/daemon/gateway-lease-files.ts b/src/daemon/gateway-lease-files.ts index c837c2e03..8189d0baf 100644 --- a/src/daemon/gateway-lease-files.ts +++ b/src/daemon/gateway-lease-files.ts @@ -18,12 +18,12 @@ export interface GatewayLeaseFilesOptions { /** why: a gateway holds no file; it relays each file request to the worker that holds the lease, through the worker's `files` target (ADR 0067 §2). */ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): HttpLeaseFiles { return { - handle: (request, identity: Identity, lease, name) => { + handle: async (request, identity: Identity, lease, name) => { const workerLeaseId = lease.workerLeaseId ?? lease.id; const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${ name === undefined ? "" : `/${encodeURIComponent(name)}` }`; - return options.relay(lease.workerId ?? "", { + const answer = await options.relay(lease.workerId ?? "", { leaseId: workerLeaseId, request: new Request(`http://simlock-worker${path}`, { headers: request.headers, @@ -34,6 +34,12 @@ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): Http target: "files", tenant: `${options.requesterPrefix}${identity.principal}`, }); + const length = answer.headers.get("simlock-content-length"); + if (length === null) return answer; + // why: the relay carries no `Content-Length`, so the worker sent the body's length under its own header and the gateway gives it back to the caller. + const headers = new Headers(answer.headers); + headers.set("content-length", length); + return new Response(answer.body, { headers, status: answer.status }); }, }; } From 1e42fa239f228e578ab8f7e1d3873985a9fad4b6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:25:14 +0100 Subject: [PATCH 05/20] test: a gateway refuses a Content-Length over 2 GiB with 413 FILE_TOO_LARGE and relays nothing (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 42 ++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 9e6c157b4..bdab0fac6 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -1,3 +1,5 @@ +import { request as httpRequest } from "node:http"; + import { afterEach, describe, expect, it } from "vitest"; import { @@ -405,11 +407,40 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { ...init, headers: { authorization: `Bearer ${secret}`, ...init.headers }, }); - return { ...fleet, call, leaseId: grant.lease.id }; + // why: `fetch` refuses a `Content-Length` that does not match its body, and the 2 GiB refusal is decided on the header alone. + const declare = (path: string, bytes: number) => + new Promise<{ status: number; body: string }>((resolve, reject) => { + const request = httpRequest( + `${base}${path}`, + { + headers: { authorization: `Bearer ${secret}`, "content-length": String(bytes) }, + method: "PUT", + }, + (response) => { + const parts: Buffer[] = []; + response.on("data", (part: Buffer) => parts.push(part)); + response.on("end", () => + resolve({ + body: Buffer.concat(parts).toString(), + status: response.statusCode ?? 0, + }), + ); + }, + ); + request.on("error", reject); + // why: a gateway that waits for the body instead of refusing the header must fail the assertion, not the test's timeout. + request.setTimeout(5_000, () => { + request.destroy(); + resolve({ body: "no answer within 5 s", status: 0 }); + }); + request.flushHeaders(); + }); + const channelsOpened = () => fleet.taps.flatMap((tap) => tap.binaries(TYPE.OPEN)).length; + return { ...fleet, call, channelsOpened, declare, leaseId: grant.lease.id }; } it("through a gateway, a lease holder's PUT, GET, list and DELETE reach the lease's worker and answer as on a worker", async () => { - const { call } = await fileRig(); + const { call, channelsOpened, declare } = await fileRig(); const bytes = patternBytes(20 * MIB, 5); const put = await call("/fixture.tar", { @@ -422,6 +453,8 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const listed = await call(""); const deleted = await call("/fixture.tar", { method: "DELETE" }); const after = await call(""); + const opened = channelsOpened(); + const tooLarge = await declare("/huge.bin", 2 * 1024 * MIB + 1); expect(put.status).toBe(201); expect(await put.json()).toEqual({ name: "fixture.tar", size: 20 * MIB }); @@ -435,6 +468,11 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(await listed.json()).toMatchObject({ files: [{ name: "fixture.tar", size: 20 * MIB }] }); expect(deleted.status).toBe(204); expect(await after.json()).toEqual({ files: [] }); + expect(tooLarge.status).toBe(413); + expect(JSON.parse(tooLarge.body)).toMatchObject({ + error: { code: "FILE_TOO_LARGE", name: "huge.bin" }, + }); + expect(channelsOpened()).toBe(opened); }, 120_000); it("a 20 MiB PUT body arrives at the target byte for byte, and a 20 MiB response body comes back byte for byte", async () => { From 307039653a5ebb1a91b9f83701183491a3942857 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:25:48 +0100 Subject: [PATCH 06/20] feat(lease-files): a gateway refuses a Content-Length over 2 GiB before it relays anything (#1358) --- src/daemon/gateway-lease-files.ts | 16 +++++++++++++++- src/lease-files/index.ts | 1 + src/lease-files/limits.ts | 5 ++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/daemon/gateway-lease-files.ts b/src/daemon/gateway-lease-files.ts index 8189d0baf..c8541b356 100644 --- a/src/daemon/gateway-lease-files.ts +++ b/src/daemon/gateway-lease-files.ts @@ -1,4 +1,5 @@ import type { Identity } from "../auth/index.js"; +import { MAX_FILE_BYTES } from "../lease-files/index.js"; import type { HttpLeaseFiles } from "../http/app.js"; // why: only `main.ts` imports the gateway, so the relay is typed by the shape of the call it takes. @@ -19,6 +20,19 @@ export interface GatewayLeaseFilesOptions { export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): HttpLeaseFiles { return { handle: async (request, identity: Identity, lease, name) => { + const declared = request.headers.get("content-length"); + if (name !== undefined && declared !== null && Number(declared) > MAX_FILE_BYTES) { + return Response.json( + { + error: { + code: "FILE_TOO_LARGE", + message: `File ${name} is over the 2 GiB limit for one file`, + name, + }, + }, + { status: 413 }, + ); + } const workerLeaseId = lease.workerLeaseId ?? lease.id; const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${ name === undefined ? "" : `/${encodeURIComponent(name)}` @@ -35,7 +49,7 @@ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): Http tenant: `${options.requesterPrefix}${identity.principal}`, }); const length = answer.headers.get("simlock-content-length"); - if (length === null) return answer; + if (length === null || !/^\d{1,16}$/.test(length)) return answer; // why: the relay carries no `Content-Length`, so the worker sent the body's length under its own header and the gateway gives it back to the caller. const headers = new Headers(answer.headers); headers.set("content-length", length); diff --git a/src/lease-files/index.ts b/src/lease-files/index.ts index 50103dfc5..ef9be4ca9 100644 --- a/src/lease-files/index.ts +++ b/src/lease-files/index.ts @@ -1,2 +1,3 @@ export { createLeaseFiles } from "./lease-files.js"; +export { MAX_FILE_BYTES } from "./limits.js"; export type { LeaseFilesLimits } from "./types.js"; diff --git a/src/lease-files/limits.ts b/src/lease-files/limits.ts index e05b6c6d9..3f0b81249 100644 --- a/src/lease-files/limits.ts +++ b/src/lease-files/limits.ts @@ -1,7 +1,10 @@ import type { LeaseFilesLimits } from "./types.js"; +/** why: a gateway refuses a larger `Content-Length` itself, because the relay does not carry that header to the worker. */ +export const MAX_FILE_BYTES = 2 * 1024 ** 3; + export const DEFAULT_LIMITS: LeaseFilesLimits = { - fileBytes: 2 * 1024 ** 3, + fileBytes: MAX_FILE_BYTES, leaseBytes: 4 * 1024 ** 3, silenceMs: 330_000, }; From 5778ebf646ae11880cc27b191125367c6dfa7e24 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:26:34 +0100 Subject: [PATCH 07/20] test: through a gateway, a worker's 413, 409 and 404 reach the caller as on a worker (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 45 +++++++++++++++++++++++++--- src/daemon/test-relay-support.ts | 3 ++ src/daemon/worker-composition.ts | 4 ++- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index bdab0fac6..589bafa96 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -8,10 +8,12 @@ import { type TwoWayRelay, type WorkerDirectory, } from "../gateway/index.js"; +import type { LeaseFilesLimits } from "../lease-files/index.js"; import { linkPair, TYPE } from "../link/testing.js"; import { connectSimlockClient } from "../simlock-client/client.js"; import type { DispatchSession } from "./dispatch.js"; import type { RelayTarget, TwoWayRelayTarget } from "./relay.js"; +import type { StartDaemonOptions } from "./main.js"; import type { DaemonServer } from "./server.js"; import { aborted, @@ -180,7 +182,10 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const startFleet = ( execCommand?: FleetExec, - extra: { readonly proxyAuth?: Record } = {}, + extra: { + readonly proxyAuth?: Record; + readonly worker?: Partial; + } = {}, ) => startFleet_( { daemons, directories, target, twoWayTarget }, @@ -388,8 +393,11 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(missing).toMatchObject({ code: "RELAY_TARGET_MISSING", state: "rejected" }); }, 30_000); - async function fileRig() { - const fleet = await startFleet(); + async function fileRig(limits?: LeaseFilesLimits) { + const fleet = await startFleet( + undefined, + limits === undefined ? {} : { worker: { leaseFilesLimits: limits } }, + ); const { secret, token } = await fleet.gateway.dispatch( "token.create", { label: "holder", role: "agent" }, @@ -440,7 +448,11 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { } it("through a gateway, a lease holder's PUT, GET, list and DELETE reach the lease's worker and answer as on a worker", async () => { - const { call, channelsOpened, declare } = await fileRig(); + const { call, channelsOpened, declare } = await fileRig({ + fileBytes: 32 * MIB, + leaseBytes: 512 * MIB, + silenceMs: 330_000, + }); const bytes = patternBytes(20 * MIB, 5); const put = await call("/fixture.tar", { @@ -453,6 +465,25 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const listed = await call(""); const deleted = await call("/fixture.tar", { method: "DELETE" }); const after = await call(""); + const busy = new TransformStream(); + const holding = call("/busy.bin", { + body: busy.readable, + duplex: "half", + method: "PUT", + } as RequestInit); + const feed = busy.writable.getWriter(); + await feed.write(new Uint8Array(1)); + await poll(async () => (await call("/busy.bin", { method: "PUT", body: "x" })).status).toBe( + 409, + ); + const missing = await call("/missing.bin"); + const oversized = await call("/large.bin", { + body: patternStream(33 * MIB, 6), + duplex: "half", + method: "PUT", + } as RequestInit); + await feed.close(); + await holding; const opened = channelsOpened(); const tooLarge = await declare("/huge.bin", 2 * 1024 * MIB + 1); @@ -468,6 +499,12 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(await listed.json()).toMatchObject({ files: [{ name: "fixture.tar", size: 20 * MIB }] }); expect(deleted.status).toBe(204); expect(await after.json()).toEqual({ files: [] }); + expect(missing.status).toBe(404); + expect(await missing.json()).toMatchObject({ error: { code: "UNKNOWN_FILE" } }); + expect(oversized.status).toBe(413); + expect(await oversized.json()).toMatchObject({ + error: { code: "FILE_TOO_LARGE", name: "large.bin" }, + }); expect(tooLarge.status).toBe(413); expect(JSON.parse(tooLarge.body)).toMatchObject({ error: { code: "FILE_TOO_LARGE", name: "huge.bin" }, diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index a7e1ba599..25a7d58d9 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -327,6 +327,8 @@ export interface FleetOptions { readonly gatewayUrl?: (gatewayPort: number) => string | Promise; // why: a test starts the gateway behind an identity-aware proxy, so http.proxyAuth is set. readonly proxyAuth?: Record; + // why: a test gives the worker options of its own, such as lower lease file limits. + readonly worker?: Partial; } export async function startFleet(context: FleetContext, options: FleetOptions = {}) { @@ -382,6 +384,7 @@ export async function startFleet(context: FleetContext, options: FleetOptions = { "agent-device": target, echo: target }, { ...(twoWayTarget === undefined ? {} : { relayTwoWayTargets: { echo: twoWayTarget } }), + ...options.worker, configOverrides: { gateway: { label: "worker-a", token: secret, url: workerDials }, }, diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index 2e5cbc05e..460bd486e 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -38,7 +38,7 @@ import { androidDriverConfig } from "../drivers/android/index.js"; import { iosDriverConfig } from "../drivers/ios/index.js"; import { type Auth } from "../auth/index.js"; import { createHttpApp } from "../http/app.js"; -import { createLeaseFiles } from "../lease-files/index.js"; +import { createLeaseFiles, type LeaseFilesLimits } from "../lease-files/index.js"; import type { HttpDispatch } from "../http/dispatcher-session.js"; import { HttpGateway } from "../http/server.js"; import { @@ -86,6 +86,8 @@ export interface WorkerOptions { readonly defaultRequesterId?: string; readonly drivers?: readonly Driver[]; readonly hostLoadProbe?: HostLoadProbe | null; + /** why: test-only, lower file and folder limits so a rig reaches a refusal without gigabytes. */ + readonly leaseFilesLimits?: LeaseFilesLimits; readonly prerequisiteChecks?: readonly PrerequisiteCheck[]; /** why: test-only, the protocol range the worker daemon announces. */ readonly protocolVersion?: number | ProtocolRange; From b357b8a81cc9e184c8cfc4684d8639db5572286b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:26:40 +0100 Subject: [PATCH 08/20] feat(daemon): a worker takes lease file limits for tests (#1358) --- src/daemon/worker-composition.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index 460bd486e..74ac63e6e 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -342,6 +342,7 @@ export async function composeWorker( : { grantedAt: lease.grantedAt, id: lease.id, platform: device.spec.platform }; }, idGenerator, + ...(options.leaseFilesLimits === undefined ? {} : { limits: options.leaseFilesLimits }), logger: logger.child("lease-files"), }); const leasing = createLeasing({ From 46c1dc1cb1d013742acf1aabd2264484ac4cedb5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:27:01 +0100 Subject: [PATCH 09/20] test: through a gateway, ten 20 MiB uploads at once are all stored (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 589bafa96..ebcc24bf4 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -465,6 +465,17 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const listed = await call(""); const deleted = await call("/fixture.tar", { method: "DELETE" }); const after = await call(""); + const names = Array.from({ length: 10 }, (_, index) => `many-${String(index)}.bin`); + const many = await Promise.all( + names.map((name, index) => + call(`/${name}`, { + body: patternStream(20 * MIB, 20 + index), + duplex: "half", + method: "PUT", + } as RequestInit), + ), + ); + const stored = await (await call("")).json(); const busy = new TransformStream(); const holding = call("/busy.bin", { body: busy.readable, @@ -499,6 +510,8 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(await listed.json()).toMatchObject({ files: [{ name: "fixture.tar", size: 20 * MIB }] }); expect(deleted.status).toBe(204); expect(await after.json()).toEqual({ files: [] }); + expect(many.map((response) => response.status)).toEqual(names.map(() => 201)); + expect(stored).toMatchObject({ files: names.map((name) => ({ name, size: 20 * MIB })) }); expect(missing.status).toBe(404); expect(await missing.json()).toMatchObject({ error: { code: "UNKNOWN_FILE" } }); expect(oversized.status).toBe(413); From dc0ed55e28abde9c6e360feed2975521eff64603 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:30:07 +0100 Subject: [PATCH 10/20] test: through a gateway, a caller that does not hold the lease gets 404 UNKNOWN_LEASE, and a lease whose worker is gone gets 503 WORKER_UNREACHABLE (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 92 ++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 6 deletions(-) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index ebcc24bf4..a01c3885c 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -409,12 +409,15 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { { model: "Pixel-A", noWait: true, platform: "android" }, holder, ); + const callOn = + (leaseId: string, bearer: string) => + (path: string, init: RequestInit = {}) => + fetch(`http://127.0.0.1:${String(fleet.port)}/v1/leases/${leaseId}/files${path}`, { + ...init, + headers: { authorization: `Bearer ${bearer}`, ...init.headers }, + }); + const call = callOn(grant.lease.id, secret); const base = `http://127.0.0.1:${String(fleet.port)}/v1/leases/${grant.lease.id}/files`; - const call = (path: string, init: RequestInit = {}) => - fetch(`${base}${path}`, { - ...init, - headers: { authorization: `Bearer ${secret}`, ...init.headers }, - }); // why: `fetch` refuses a `Content-Length` that does not match its body, and the 2 GiB refusal is decided on the header alone. const declare = (path: string, bytes: number) => new Promise<{ status: number; body: string }>((resolve, reject) => { @@ -444,7 +447,32 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { request.flushHeaders(); }); const channelsOpened = () => fleet.taps.flatMap((tap) => tap.binaries(TYPE.OPEN)).length; - return { ...fleet, call, channelsOpened, declare, leaseId: grant.lease.id }; + const newLease = async () => { + const next = await fleet.gateway.dispatch( + "lease.request", + { model: "Pixel-A", noWait: true, platform: "android" }, + holder, + ); + return { call: callOn(next.lease.id, secret), leaseId: next.lease.id }; + }; + const stranger = async () => { + const other = await fleet.gateway.dispatch( + "token.create", + { label: "stranger", role: "agent" }, + adminSession, + ); + return callOn(grant.lease.id, other.secret); + }; + return { + ...fleet, + call, + channelsOpened, + declare, + holder, + leaseId: grant.lease.id, + newLease, + stranger, + }; } it("through a gateway, a lease holder's PUT, GET, list and DELETE reach the lease's worker and answer as on a worker", async () => { @@ -525,6 +553,58 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(channelsOpened()).toBe(opened); }, 120_000); + it("through a gateway, a caller that does not hold the lease gets 404 UNKNOWN_LEASE, and a lease whose worker is gone gets 503 WORKER_UNREACHABLE", async () => { + const rig = await fileRig({ fileBytes: 32 * MIB, leaseBytes: MIB, silenceMs: 330_000 }); + const asStranger = await rig.stranger(); + const routes = (call: typeof rig.call) => [ + () => call("/fixture.tar", { body: "x", method: "PUT" }), + () => call("/fixture.tar"), + () => call("/fixture.tar", { method: "DELETE" }), + () => call(""), + ]; + + const refused = await Promise.all(routes(asStranger).map((send) => send())); + const full = await rig.call("/big.bin", { body: new Uint8Array(2 * MIB), method: "PUT" }); + const feed = new TransformStream(); + const writer = feed.writable.getWriter(); + const running = rig.call("/running.bin", { + body: feed.readable, + duplex: "half", + method: "PUT", + } as RequestInit); + await writer.write(new Uint8Array(1)); + await poll(async () => (await rig.call("")).status).toBe(200); + await rig.gateway.dispatch("lease.release", { leaseId: rig.leaseId }, rig.holder); + await writer.write(new Uint8Array(1)); + await writer.close(); + const ended = await running; + const next = await rig.newLease(); + await rig.worker.worker.stop("test"); + await poll(async () => (await next.call("")).status).toBe(503); + + expect(refused.map((response) => response.status)).toEqual([404, 404, 404, 404]); + for (const response of refused) { + expect(await response.json()).toMatchObject({ + error: { code: "UNKNOWN_LEASE", leaseId: rig.leaseId }, + }); + } + expect(full.status).toBe(413); + const fullBody = (await full.json()) as { + error: { code: string; message: string; leaseId: string }; + }; + expect(fullBody.error).toMatchObject({ code: "LEASE_FILES_FULL", leaseId: rig.leaseId }); + expect(fullBody.error.message).toContain(`Lease ${rig.leaseId} holds`); + expect(ended.status).toBe(404); + const endedBody = (await ended.json()) as { + error: { code: string; message: string; leaseId: string }; + }; + expect(endedBody.error).toMatchObject({ code: "UNKNOWN_LEASE", leaseId: rig.leaseId }); + expect(endedBody.error.message).toBe(`Unknown lease: ${rig.leaseId}`); + expect(await (await next.call("")).json()).toMatchObject({ + error: { code: "WORKER_UNREACHABLE" }, + }); + }, 60_000); + it("a 20 MiB PUT body arrives at the target byte for byte, and a 20 MiB response body comes back byte for byte", async () => { let received = ""; behavior = async (request) => { From 69ae3203a963d147055fbd25aa8618d45c5a3d59 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:32:13 +0100 Subject: [PATCH 11/20] feat(lease-files): a gateway gives the caller's lease id back in a worker's refusal, and a worker whose upload body was cut still answers (#1358) --- src/daemon/callers-lease-id.ts | 81 +++++++++++++++++++++++++++++++ src/daemon/gateway-lease-files.ts | 4 +- src/daemon/relay.ts | 9 +++- 3 files changed, 92 insertions(+), 2 deletions(-) create mode 100644 src/daemon/callers-lease-id.ts diff --git a/src/daemon/callers-lease-id.ts b/src/daemon/callers-lease-id.ts new file mode 100644 index 000000000..f38c2c7ef --- /dev/null +++ b/src/daemon/callers-lease-id.ts @@ -0,0 +1,81 @@ +// why: a worker's refusal is a claim, so the gateway reads at most this much of it, as the stream module does. +const MAX_REFUSAL_BYTES = 16 * 1024; + +const WORKER_LEASE_ID_CODES: ReadonlySet = new Set(["UNKNOWN_LEASE", "LEASE_FILES_FULL"]); + +/** why: the worker names a lease by its own id, which the caller never saw; the gateway puts back the id the caller used in the two refusals that name it, and relays every other body as the worker sent it. */ +export async function withCallersLeaseId( + answer: Response, + workerLeaseId: string, + callersLeaseId: string, +): Promise { + if ((answer.status !== 404 && answer.status !== 413) || answer.body === null) return answer; + const reader = answer.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + let ended = false; + while (size <= MAX_REFUSAL_BYTES) { + const step = await reader.read(); + if (step.done) { + ended = true; + break; + } + chunks.push(step.value); + size += step.value.length; + } + if (ended) { + const rewritten = rewrite(Buffer.concat(chunks).toString(), workerLeaseId, callersLeaseId); + if (rewritten !== undefined) { + const headers = new Headers(answer.headers); + headers.delete("content-length"); + headers.delete("simlock-content-length"); + return new Response(rewritten, { headers, status: answer.status }); + } + } + return new Response(stitched(chunks, reader), { headers: answer.headers, status: answer.status }); +} + +function rewrite(text: string, workerLeaseId: string, callersLeaseId: string): string | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return undefined; + } + const error = (parsed as { error?: unknown } | null)?.error; + if (typeof error !== "object" || error === null) return undefined; + const fields = error as { code?: unknown; message?: unknown }; + if (typeof fields.code !== "string" || !WORKER_LEASE_ID_CODES.has(fields.code)) return undefined; + return JSON.stringify({ + error: { + ...error, + leaseId: callersLeaseId, + ...(typeof fields.message === "string" + ? { message: fields.message.replaceAll(workerLeaseId, callersLeaseId) } + : {}), + }, + }); +} + +function stitched( + chunks: readonly Uint8Array[], + reader: ReadableStreamDefaultReader, +): ReadableStream { + const pending = [...chunks]; + return new ReadableStream( + { + cancel: (reason) => reader.cancel(reason), + async pull(controller) { + const next = pending.shift(); + if (next !== undefined) { + controller.enqueue(next); + return; + } + const step = await reader.read(); + if (step.done) controller.close(); + else controller.enqueue(step.value); + }, + }, + { highWaterMark: 0 }, + ); +} diff --git a/src/daemon/gateway-lease-files.ts b/src/daemon/gateway-lease-files.ts index c8541b356..dcde6f251 100644 --- a/src/daemon/gateway-lease-files.ts +++ b/src/daemon/gateway-lease-files.ts @@ -1,4 +1,5 @@ import type { Identity } from "../auth/index.js"; +import { withCallersLeaseId } from "./callers-lease-id.js"; import { MAX_FILE_BYTES } from "../lease-files/index.js"; import type { HttpLeaseFiles } from "../http/app.js"; @@ -37,7 +38,7 @@ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): Http const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${ name === undefined ? "" : `/${encodeURIComponent(name)}` }`; - const answer = await options.relay(lease.workerId ?? "", { + const relayed = await options.relay(lease.workerId ?? "", { leaseId: workerLeaseId, request: new Request(`http://simlock-worker${path}`, { headers: request.headers, @@ -48,6 +49,7 @@ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): Http target: "files", tenant: `${options.requesterPrefix}${identity.principal}`, }); + const answer = await withCallersLeaseId(relayed, workerLeaseId, lease.id); const length = answer.headers.get("simlock-content-length"); if (length === null || !/^\d{1,16}$/.test(length)) return answer; // why: the relay carries no `Content-Length`, so the worker sent the body's length under its own header and the gateway gives it back to the caller. diff --git a/src/daemon/relay.ts b/src/daemon/relay.ts index 83cb06ff3..23e494ed5 100644 --- a/src/daemon/relay.ts +++ b/src/daemon/relay.ts @@ -208,17 +208,24 @@ export class RelayConnection { #requestBody(active: ActiveRelay): ReadableStream { const reader = active.channel.readable.getReader(); active.reader = reader; + let cancelled = false; return new ReadableStream( { - cancel: () => reader.cancel().catch(() => undefined), + cancel: () => { + cancelled = true; + return reader.cancel().catch(() => undefined); + }, pull: async (controller) => { try { const step = await reader.read(); + // why: a target that stopped reading its body (a lease file upload cut by the lease's end) is no channel failure, and the read it left in flight ends with the cancel. + if (cancelled) return; if (active.abandoned) { controller.error(new Error("The relay answered before its request body ended")); } else if (step.done) controller.close(); else controller.enqueue(step.value); } catch (error: unknown) { + if (cancelled) return; this.#note(active, error); controller.error(error); } From 8218b04c37e1f902125a0918dd12ac7accc9146b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:33:13 +0100 Subject: [PATCH 12/20] test: through a gateway, a file upload is cut only by silence, not by the time it takes in total (#1358) --- src/daemon/main.ts | 2 + src/daemon/relay-gateway.e2e.test.ts | 55 +++++++++++++++++++++++++--- src/daemon/test-relay-support.ts | 3 ++ 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 31ef923e2..cc897a3c4 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -129,6 +129,8 @@ export interface StartDaemonOptions extends WorkerOptions { readonly configPath?: string; readonly dataDirectory?: string; readonly deviceDataTables?: ReadonlyMap; + /** why: test-only, a gateway's silence bound on a relayed file upload, so a rig reaches 408 without waiting 330 s. */ + readonly fileSilenceMs?: number; readonly gatewayRelay?: (relay: GatewayRelay) => void; /** why: test-only, hands over the gateway's uplink listener, to close one worker's socket. */ readonly gatewayUplinks?: (uplinks: WebSocketUplinkListenerFactory) => void; diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index a01c3885c..9645d6f63 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -185,6 +185,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { extra: { readonly proxyAuth?: Record; readonly worker?: Partial; + readonly gateway?: Partial; } = {}, ) => startFleet_( @@ -393,11 +394,11 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(missing).toMatchObject({ code: "RELAY_TARGET_MISSING", state: "rejected" }); }, 30_000); - async function fileRig(limits?: LeaseFilesLimits) { - const fleet = await startFleet( - undefined, - limits === undefined ? {} : { worker: { leaseFilesLimits: limits } }, - ); + async function fileRig(limits?: LeaseFilesLimits, fileSilenceMs?: number) { + const fleet = await startFleet(undefined, { + ...(limits === undefined ? {} : { worker: { leaseFilesLimits: limits } }), + ...(fileSilenceMs === undefined ? {} : { gateway: { fileSilenceMs } }), + }); const { secret, token } = await fleet.gateway.dispatch( "token.create", { label: "holder", role: "agent" }, @@ -605,6 +606,50 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { }); }, 60_000); + it("through a gateway, a file upload is cut only by 330 s of silence, not by 330 s in total", async () => { + const { call } = await fileRig(undefined, 1_000); + const pieces = 12; + let sent = 0; + const flowing = new ReadableStream({ + async pull(controller) { + await sleep(300); + controller.enqueue(new Uint8Array(KIB)); + sent += 1; + if (sent === pieces) controller.close(); + }, + }); + const silent = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(KIB)); + }, + }); + + const slow = await call("/slow.bin", { + body: flowing, + duplex: "half", + method: "PUT", + } as RequestInit); + const stalled = await settleWithin( + call("/stalled.bin", { body: silent, duplex: "half", method: "PUT" } as RequestInit), + 6_000, + ); + + expect(slow.status).toBe(201); + expect(await slow.json()).toEqual({ name: "slow.bin", size: pieces * KIB }); + expect(stalled).toMatchObject({ state: "fulfilled", value: { status: 408 } }); + const body = await (stalled as { value: Response }).value.json(); + expect(body).toEqual({ + error: { + code: "UPLOAD_STALLED", + message: "No bytes of stalled.bin arrived for 1 s", + name: "stalled.bin", + }, + }); + expect((await (await call("")).json()) as { files: { name: string }[] }).toEqual({ + files: [{ name: "slow.bin", size: pieces * KIB }], + }); + }, 30_000); + it("a 20 MiB PUT body arrives at the target byte for byte, and a 20 MiB response body comes back byte for byte", async () => { let received = ""; behavior = async (request) => { diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index 25a7d58d9..86d838939 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -329,6 +329,8 @@ export interface FleetOptions { readonly proxyAuth?: Record; // why: a test gives the worker options of its own, such as lower lease file limits. readonly worker?: Partial; + // why: a test gives the gateway options of its own, such as a lower file silence bound. + readonly gateway?: Partial; } export async function startFleet(context: FleetContext, options: FleetOptions = {}) { @@ -369,6 +371,7 @@ export async function startFleet(context: FleetContext, options: FleetOptions = }, logger: new NoopLogger(), version: "1.0.0-e2e", + ...options.gateway, }); daemons.push(gateway); const { secret } = await gateway.dispatch( From 671fee4e70790e1b6746ca5885f630401baaa272 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:35:41 +0100 Subject: [PATCH 13/20] feat(gateway): a relayed file upload is cut by 330 s of silence, and its head deadline counts from the body's end (#1358) --- src/daemon/gateway-lease-files.ts | 8 ++++++ src/daemon/main.ts | 4 +++ src/gateway/relay.ts | 48 +++++++++++++++++++++++++++++-- 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/daemon/gateway-lease-files.ts b/src/daemon/gateway-lease-files.ts index dcde6f251..b937f0a32 100644 --- a/src/daemon/gateway-lease-files.ts +++ b/src/daemon/gateway-lease-files.ts @@ -12,11 +12,16 @@ export interface GatewayLeaseFilesOptions { readonly request: Request; readonly tenant: string; readonly leaseId?: string; + readonly upload?: { readonly name: string; readonly silenceMs: number }; }, ) => Promise; readonly requesterPrefix: string; + readonly silenceMs?: number; } +// why: the worker cuts an upload silent for the same 330 s, so the gateway's bound is the one the caller meets first. +const UPLOAD_SILENCE_MS = 330_000; + /** why: a gateway holds no file; it relays each file request to the worker that holds the lease, through the worker's `files` target (ADR 0067 §2). */ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): HttpLeaseFiles { return { @@ -48,6 +53,9 @@ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): Http } as RequestInit), target: "files", tenant: `${options.requesterPrefix}${identity.principal}`, + ...(request.method === "PUT" && name !== undefined + ? { upload: { name, silenceMs: options.silenceMs ?? UPLOAD_SILENCE_MS } } + : {}), }); const answer = await withCallersLeaseId(relayed, workerLeaseId, lease.id); const length = answer.headers.get("simlock-content-length"); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index cc897a3c4..d7bc8a68e 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -324,6 +324,7 @@ async function composeDaemon( eventHistory, filesystem, ...(options.gatewayRelay === undefined ? {} : { gatewayRelay: options.gatewayRelay }), + ...(options.fileSilenceMs === undefined ? {} : { fileSilenceMs: options.fileSilenceMs }), ...(options.gatewayUplinks === undefined ? {} : { gatewayUplinks: options.gatewayUplinks }), hostSystem, ...(options.hostLoadProbe === undefined ? {} : { hostLoadProbe: options.hostLoadProbe }), @@ -380,6 +381,8 @@ interface GatewayDaemonOptions { readonly config: Config; readonly dataDirectory: string; readonly eventBus: EventBus; + /** why: test-only, see `StartDaemonOptions.fileSilenceMs`. */ + readonly fileSilenceMs?: number; readonly eventHistory: EventHistoryHandle; readonly filesystem: Filesystem; readonly gatewayRelay?: (relay: GatewayRelay) => void; @@ -635,6 +638,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise gatewayRelay.relay(workerId, call), requesterPrefix: gatewayRequesterPrefix, + ...(options.fileSilenceMs === undefined ? {} : { silenceMs: options.fileSilenceMs }), }), leaseRequests: fleetCoordinator.requests, logger: httpLogger, diff --git a/src/gateway/relay.ts b/src/gateway/relay.ts index ceede6de4..70885433b 100644 --- a/src/gateway/relay.ts +++ b/src/gateway/relay.ts @@ -27,6 +27,8 @@ export interface GatewayRelayCall { readonly request: Request; readonly tenant: string; readonly leaseId?: string; + /** why: a file upload may run as long as bytes keep coming; its request body is bounded by silence, and the head deadline counts from the body's end. */ + readonly upload?: { readonly name: string; readonly silenceMs: number }; } export interface TwoWayRelay { @@ -127,6 +129,7 @@ class Exchange { #ahead: Promise> | undefined; #timer: TimerHandle | undefined; #idleTimer: TimerHandle | undefined; + #silenceTimer: TimerHandle | undefined; #callerBody: ReadableStreamDefaultReader | undefined; #requestSent = false; #cancelSent = false; @@ -144,13 +147,19 @@ class Exchange { constructor(private readonly init: ExchangeInit) {} start(): void { - const { call, deadlineMs, workerId } = this.init; + const { call } = this.init; const signal = call.request.signal; if (signal.aborted) { this.init.reject(signal.reason); return; } signal.addEventListener("abort", this.#abortListener, { once: true }); + this.#armDeadline(); + void this.#run(); + } + + #armDeadline(): void { + const { deadlineMs, workerId } = this.init; this.#timer = this.init.clock.setTimer(deadlineMs, () => { this.#fail( new DispatchError( @@ -160,7 +169,24 @@ class Exchange { ), ); }); - void this.#run(); + } + + #armSilence(upload: { readonly name: string; readonly silenceMs: number }): void { + this.#disarmSilence(); + this.#silenceTimer = this.init.clock.setTimer(upload.silenceMs, () => { + this.#fail( + new DispatchError( + "UPLOAD_STALLED", + `No bytes of ${upload.name} arrived for ${String(upload.silenceMs / 1000)} s`, + { name: upload.name }, + ), + ); + }); + } + + #disarmSilence(): void { + if (this.#silenceTimer !== undefined) this.init.clock.cancel(this.#silenceTimer); + this.#silenceTimer = undefined; } async #run(): Promise { @@ -182,6 +208,11 @@ class Exchange { return; } this.#channel = channel; + // why: an upload's time is bounded by silence from here on, so the start deadline ends once the channel is open. + if (this.init.call.upload !== undefined && this.#timer !== undefined) { + this.init.clock.cancel(this.#timer); + this.#timer = undefined; + } this.#reader = channel.readable.getReader(); this.#look(); const { request } = this.init.call; @@ -220,20 +251,25 @@ class Exchange { async #upload(channel: LinkChannel, body: ReadableStream | null): Promise { const writer = channel.writable.getWriter(); + const { upload } = this.init.call; if (body === null) { await writer.close().catch(() => undefined); + this.#armHeadDeadline(); return; } const reader = body.getReader(); this.#callerBody = reader; try { for (;;) { + if (upload !== undefined) this.#armSilence(upload); const step = await reader.read(); + this.#disarmSilence(); if (this.#done) return; if (step.done) break; await writer.write(step.value); } await writer.close(); + this.#armHeadDeadline(); } catch (error: unknown) { if (this.#done) return; if (error instanceof LinkChannelError) { @@ -246,6 +282,12 @@ class Exchange { } } + // why: an upload's head can arrive only after its body, so its deadline counts from the body's end. + #armHeadDeadline(): void { + if (this.init.call.upload === undefined || this.#done || this.#headed) return; + this.#armDeadline(); + } + // why: a single read is kept ahead so a channel that fails before the head is seen without anyone reading the body. #look(): Promise> { if (this.#ahead === undefined) { @@ -275,6 +317,7 @@ class Exchange { this.#headed = true; // why: once the head is in, the body is bounded by silence, not by the deadline, so a live stream is not cut. if (this.#timer !== undefined) this.init.clock.cancel(this.#timer); + this.#disarmSilence(); if (this.init.twoWay && this.#openOrRefuse(status, responseHeaders)) return; this.#armIdle(); const method = this.init.call.request.method; @@ -573,6 +616,7 @@ class Exchange { this.#done = true; if (this.#timer !== undefined) this.init.clock.cancel(this.#timer); if (this.#idleTimer !== undefined) this.init.clock.cancel(this.#idleTimer); + this.#disarmSilence(); this.init.call.request.signal.removeEventListener("abort", this.#abortListener); this.#callerBody?.cancel().catch(() => undefined); } From 30c2076013fe592963ae05194ef57291f3a4a590 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:37:24 +0100 Subject: [PATCH 14/20] test: a gateway cuts a file upload only after 330 s of silence and keeps the 330 s deadline for any other relay (#1358) --- src/gateway/relay.test.ts | 104 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/src/gateway/relay.test.ts b/src/gateway/relay.test.ts index d3234d5d1..27f553233 100644 --- a/src/gateway/relay.test.ts +++ b/src/gateway/relay.test.ts @@ -499,6 +499,110 @@ describe("GatewayRelay on a byte channel", () => { expect(connection.sent.filter((frame) => frame.type === "relay.request")).toEqual([]); }); + it("cuts a file upload only after 330 s with no byte from the caller, counts its head deadline from the body's end, and keeps the 330 s deadline for any other relay", async () => { + const BOUND = 330_000; + const upload = { name: "fixture.tar", silenceMs: BOUND }; + async function start(options: { upload?: typeof upload; holdOpen?: boolean } = {}) { + const clock = new FakeClock(); + const { connection, relay } = await setup({ + clock, + deadlineMs: BOUND, + ...(options.holdOpen === true ? { holdOpen: true } : {}), + }); + let feed!: ReadableStreamDefaultController; + const body = new ReadableStream({ + start(controller) { + feed = controller; + }, + }); + let result: Awaited>> | undefined; + void outcome( + relay.relay(WORKER_ID, { + ...call(body), + ...(options.upload === undefined ? {} : { upload: options.upload }), + }), + ).then((settled) => { + result = settled; + }); + const pass = async (ms: number) => { + clock.advance(ms); + await sleep(20); + return result; + }; + return { + clock, + connection, + feed, + pass, + request: () => connection.lastSentOf("relay.request"), + }; + } + const stalled = { + code: "UPLOAD_STALLED", + message: "No bytes of fixture.tar arrived for 330 s", + state: "rejected", + }; + const unreachable = { + code: "WORKER_UNREACHABLE", + message: `worker ${WORKER_ID} did not finish the relayed request within ${String(BOUND)} ms`, + state: "rejected", + }; + + const flowing = await start({ upload }); + await sentFrame(flowing.connection, "relay.request"); + flowing.feed.enqueue(new Uint8Array(KIB)); + const flowingAt300 = await flowing.pass(300_000); + flowing.feed.enqueue(new Uint8Array(KIB)); + const flowingAt600 = await flowing.pass(300_000); + flowing.feed.close(); + await sleep(20); + const beforeHeadDeadline = await flowing.pass(BOUND - 1); + const atHeadDeadline = await flowing.pass(1); + + const silent = await start({ upload }); + await sentFrame(silent.connection, "relay.request"); + silent.feed.enqueue(new Uint8Array(KIB)); + await sleep(20); + const beforeSilenceBound = await silent.pass(BOUND - 1); + const atSilenceBound = await silent.pass(1); + + const opening = await start({ holdOpen: true, upload }); + const beforeOpenDeadline = await opening.pass(BOUND - 1); + const atOpenDeadline = await opening.pass(1); + + const other = await start(); + await sentFrame(other.connection, "relay.request"); + other.feed.enqueue(new Uint8Array(KIB)); + await other.pass(300_000); + other.feed.enqueue(new Uint8Array(KIB)); + const otherBeforeDeadline = await other.pass(BOUND - 300_000 - 1); + const otherAtDeadline = await other.pass(1); + + const refused = await start({ upload }); + const refusal = await sentFrame(refused.connection, "relay.request"); + await refused.pass(100_000); + refused.connection.push("relay-head", { headers: [], requestId: refusal.id, status: 413 }); + await sleep(20); + // why: the silence bound would fire at 330 s; the response body's own idle bound runs to 430 s. + const afterRefusal = await refused.pass(BOUND - 100_000 + 1); + + expect([flowingAt300, flowingAt600, beforeHeadDeadline]).toEqual([ + undefined, + undefined, + undefined, + ]); + expect(atHeadDeadline).toEqual(unreachable); + expect(beforeSilenceBound).toBeUndefined(); + expect(atSilenceBound).toEqual(stalled); + expect(silent.connection.lastSentOf("relay.cancel")).toBeDefined(); + expect(beforeOpenDeadline).toBeUndefined(); + expect(atOpenDeadline).toEqual(unreachable); + expect(otherBeforeDeadline).toBeUndefined(); + expect(otherAtDeadline).toEqual(unreachable); + expect(afterRefusal).toMatchObject({ state: "fulfilled" }); + expect(refused.connection.lastSentOf("relay.cancel")).toBeUndefined(); + }); + it("fails at once with the abort reason, and sends no relay.request, when the caller aborts while it waits for a channel", async () => { const { connection, relay } = await setup({ holdOpen: true }); const controller = new AbortController(); From 1d03cdf929d683bf104db3af91a79b068c6a040b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:38:24 +0100 Subject: [PATCH 15/20] docs(lease-files): the file routes work through a gateway (#1358) --- src/daemon/AGENTS.md | 1 + src/daemon/relay.ts | 4 ++-- src/gateway/AGENTS.md | 1 + src/gateway/relay.ts | 4 ++-- src/http/lease-declarations.ts | 7 ++++--- src/lease-files/AGENTS.md | 1 + .../docs/docs/using-devices/remote-agents.mdx | 14 +++++++------- 7 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index e61cf4532..7c7f7af7e 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -46,6 +46,7 @@ Relays (worker side): - `relay.request` runs only on the uplink connection. - A `twoWay` relay runs no body cut-off. Its target answers a refusal before touching the pipe, or a 2xx with no body and then uses the pipe; the call answers once both directions have ended. The silence bound is the gateway's. +- `files` is the one relay target the core names: the lease files of a worker, served for a gateway (ADR 0067 §7). A module cannot take the name. - `GatewayUplink` retries forever. ## Security model diff --git a/src/daemon/relay.ts b/src/daemon/relay.ts index 23e494ed5..0905ed6d4 100644 --- a/src/daemon/relay.ts +++ b/src/daemon/relay.ts @@ -1,6 +1,6 @@ /** - * why: the core names no relay target (ADR 0026); a module's function is registered under its capability name through - * `relayTargets`, and each uplink connection carries its own relays. + * why: the core names one relay target, `files` (ADR 0067 §7, narrowing ADR 0026); a module's function is registered under + * its capability name through `relayTargets`, and each uplink connection carries its own relays. */ import type { z } from "zod"; diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 64febfd78..ecaf14097 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -44,6 +44,7 @@ Relay: - `relay.*` runs only on a worker's uplink session. A gateway refuses them from everyone. - A worker never holds a gateway credential: `relayHeaderPairs` (`../contract/relay.ts`) drops the credential headers and the configured `http.proxyAuth.header`. - Every wait is bounded on the `Clock`: one deadline for the channel and the head, then a silence bound on the body, so a live body is never cut. At either limit: `WORKER_UNREACHABLE`, and `relay.cancel` to the worker. +- A relayed file upload (`upload` on the call) is bounded by silence from the caller's body instead: no start deadline once the channel is open, `UPLOAD_STALLED` after `silenceMs` with no byte read from the caller, and the head deadline counts from the body's end. Every other relay keeps the one deadline. - A two-way relay keeps both directions open after a 2xx head; ending one ends only that one. - Its silence bound (`TWO_WAY_SILENCE_MS` in `relay.ts`) counts only bytes read from the worker. Bytes the gateway writes never reset it, and it stops while the relay's read-ahead is full. A worker module keeps it alive with the heartbeat in `../modules/relay-channel.ts`. - On an uplink close the worker aborts that connection's relays. Leases, requests and exec keep running. diff --git a/src/gateway/relay.ts b/src/gateway/relay.ts index 70885433b..372f56c6a 100644 --- a/src/gateway/relay.ts +++ b/src/gateway/relay.ts @@ -1,6 +1,6 @@ // why: every wait of a relayed exchange is bounded (architecture rule on cross-process waits): one deadline covers the -// channel wait and the wait for the head, and an idle bound covers the response body, which may be a live stream that -// runs as long as someone reads it; the link bounds the channels open to a worker (ADR 0028). +// channel wait and the wait for the head (a file upload's counts from its body's end, and its body is bounded by silence), +// and an idle bound covers the response body, which may be a live stream that runs as long as someone reads it; the link bounds the channels open to a worker (ADR 0028). import { isRelayFramingHeader, diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 8a083ba55..4803c26f7 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -386,6 +386,7 @@ export const leaseFilePutRoute = declareRoute({ 409: ["FILE_BUSY"], 413: ["FILE_TOO_LARGE", "LEASE_FILES_FULL"], 422: ["INSUFFICIENT_DISK_SPACE"], + 503: ["WORKER_UNREACHABLE"], }, }); @@ -400,7 +401,7 @@ export const leaseFileGetRoute = declareRoute({ request: { params: leaseFileParamsSchema }, binaryReply: true, alsoStatus: 206, - errors: { 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"] }, + errors: { 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], 503: ["WORKER_UNREACHABLE"] }, }); export const leaseFileDeleteRoute = declareRoute({ @@ -411,7 +412,7 @@ export const leaseFileDeleteRoute = declareRoute({ role: "agent", request: { params: leaseFileParamsSchema }, status: 204, - errors: { 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"] }, + errors: { 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], 503: ["WORKER_UNREACHABLE"] }, }); export const leaseFileListRoute = declareRoute({ @@ -422,7 +423,7 @@ export const leaseFileListRoute = declareRoute({ role: "agent", request: { params: leaseParamsSchema }, reply: z.object({ files: z.array(leaseFileSchema) }), - errors: { 404: ["UNKNOWN_LEASE"] }, + errors: { 404: ["UNKNOWN_LEASE"], 503: ["WORKER_UNREACHABLE"] }, }); export const LEASE_ROUTES = [ diff --git a/src/lease-files/AGENTS.md b/src/lease-files/AGENTS.md index 05d4ecd21..1fafd72c9 100644 --- a/src/lease-files/AGENTS.md +++ b/src/lease-files/AGENTS.md @@ -9,4 +9,5 @@ Does: stores the files a lease's holder (or an operator) uploads over `PUT /v1/l - An upload goes to `.upload-` in the folder and is renamed into place only after the whole body arrived. A cut or stalled body leaves nothing visible. - Names are compared ignoring case: a PUT removes the other spellings, a lookup prefers the exact spelling, a DELETE removes every spelling. One writer per lowercase name (`FILE_BUSY`). - A lease's bytes count what is stored plus the other running uploads' received bytes; the file a PUT replaces is not counted. The disk check runs once per upload, before the first byte is stored. +- A gateway holds no file: `gateway-lease-files.ts` (daemon) relays each request to the worker's `files` relay target, path `/files/leases/[/]`, which checks the id and the name and then serves it as a local request does. The worker names its own lease id in a refusal; the gateway puts the caller's back. - `end` marks the lease ended, aborts its running uploads, waits for them and removes the folder; an upload or folder creation that finishes after that removes its own work. `sweep` at startup removes every folder whose lease is not live, upload temporary files included. diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index e22716446..2cbefcb5d 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -158,28 +158,28 @@ The command runs on the worker, as the user who runs the worker's daemon. Treat ## Lease files -A lease holder (or an operator) can put files into its lease's folder on the worker and read them back, with raw bytes in the request body and no base64. Nothing is held in memory: the body streams to disk, and the file appears under its name once the whole body has arrived. +A lease holder (or an operator) can put files into its lease's folder on the worker and read them back, with raw bytes in the request body and no base64. Nothing is held in memory: the body streams to disk, and the file appears under its name once the whole body has arrived. The same calls work against a worker and against a gateway, which relays each one to the lease's worker; `$SIMLOCK_URL` is either. ```bash -curl -X PUT "$W/v1/leases/$LEASE/files/fixture.tar" -H "Authorization: Bearer $T" --data-binary @fixture.tar +curl -X PUT "$SIMLOCK_URL/v1/leases/$LEASE/files/fixture.tar" -H "Authorization: Bearer $T" --data-binary @fixture.tar # {"name":"fixture.tar","size":70000000} (201) -curl "$W/v1/leases/$LEASE/files/fixture.tar" -H "Range: bytes=0-99" -H "Authorization: Bearer $T" -o head.bin +curl "$SIMLOCK_URL/v1/leases/$LEASE/files/fixture.tar" -H "Range: bytes=0-99" -H "Authorization: Bearer $T" -o head.bin # 206, Content-Range: bytes 0-99/70000000, 100 bytes -curl "$W/v1/leases/$LEASE/files" -H "Authorization: Bearer $T" +curl "$SIMLOCK_URL/v1/leases/$LEASE/files" -H "Authorization: Bearer $T" # {"files":[{"name":"fixture.tar","size":70000000}]} -curl -X DELETE "$W/v1/leases/$LEASE/files/fixture.tar" -H "Authorization: Bearer $T" +curl -X DELETE "$SIMLOCK_URL/v1/leases/$LEASE/files/fixture.tar" -H "Authorization: Bearer $T" # 204 ``` - **Names.** 1 to 128 letters, digits, `.`, `_` or `-`, starting with a letter or digit, so `.hidden`, `-rf` and `my file.tar` are refused with `400 BAD_REQUEST`. Names match ignoring case: `A.tar` and `a.tar` are one file, and a `PUT` replaces it. - **Limits.** 2 GiB a file and 4 GiB a lease folder (files a command wrote there count). A larger file is refused with `413 FILE_TOO_LARGE`, a full folder with `413 LEASE_FILES_FULL`, and nothing is stored when the worker's free disk is under its `diskPressure.freeBytesThreshold` (`422 INSUFFICIENT_DISK_SPACE`). - **One upload per name.** A second `PUT` to a name being uploaded gets `409 FILE_BUSY`. A `PUT` that is cut leaves the previous file untouched. -- **No total time limit.** An upload is cut only when no byte of its body arrives for 330 seconds (`408 UPLOAD_STALLED`). +- **No total time limit.** An upload is cut only when no byte of its body arrives for 330 seconds (`408 UPLOAD_STALLED`), also through a gateway. Through a gateway, a `Content-Length` over 2 GiB is refused at the gateway, and a worker that is not connected answers `503 WORKER_UNREACHABLE`. - **Downloads.** `GET` answers the whole file or one `Range` (`bytes=a-b`, `a-` or `-n`) as `206`; a start past the end is `416`. An unknown name is `404 UNKNOWN_FILE`. -- **The folder goes with the lease.** The files are deleted when the lease ends. Through a gateway these routes answer `501 UNSUPPORTED_IN_GATEWAY_MODE` for now. +- **The folder goes with the lease.** The files are deleted when the lease ends. ## More calls From 7fb9e595f487b42ae368510a11a5d9fb77597799 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:41:50 +0100 Subject: [PATCH 16/20] refactor(gateway): split the file relay and the upload exchange into smaller functions (#1358) --- src/daemon/gateway-lease-files.ts | 63 ++++++++++++++++------------ src/daemon/relay-gateway.e2e.test.ts | 2 +- src/gateway/relay.ts | 47 +++++++++++++-------- 3 files changed, 67 insertions(+), 45 deletions(-) diff --git a/src/daemon/gateway-lease-files.ts b/src/daemon/gateway-lease-files.ts index b937f0a32..f10fe6e8f 100644 --- a/src/daemon/gateway-lease-files.ts +++ b/src/daemon/gateway-lease-files.ts @@ -28,42 +28,53 @@ export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): Http handle: async (request, identity: Identity, lease, name) => { const declared = request.headers.get("content-length"); if (name !== undefined && declared !== null && Number(declared) > MAX_FILE_BYTES) { - return Response.json( - { - error: { - code: "FILE_TOO_LARGE", - message: `File ${name} is over the 2 GiB limit for one file`, - name, - }, - }, - { status: 413 }, - ); + return tooLarge(name); } const workerLeaseId = lease.workerLeaseId ?? lease.id; - const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${ - name === undefined ? "" : `/${encodeURIComponent(name)}` - }`; const relayed = await options.relay(lease.workerId ?? "", { leaseId: workerLeaseId, - request: new Request(`http://simlock-worker${path}`, { - headers: request.headers, - method: request.method, - signal: request.signal, - ...(request.body === null ? {} : { body: request.body, duplex: "half" }), - } as RequestInit), + request: workerRequest(request, workerLeaseId, name), target: "files", tenant: `${options.requesterPrefix}${identity.principal}`, ...(request.method === "PUT" && name !== undefined ? { upload: { name, silenceMs: options.silenceMs ?? UPLOAD_SILENCE_MS } } : {}), }); - const answer = await withCallersLeaseId(relayed, workerLeaseId, lease.id); - const length = answer.headers.get("simlock-content-length"); - if (length === null || !/^\d{1,16}$/.test(length)) return answer; - // why: the relay carries no `Content-Length`, so the worker sent the body's length under its own header and the gateway gives it back to the caller. - const headers = new Headers(answer.headers); - headers.set("content-length", length); - return new Response(answer.body, { headers, status: answer.status }); + return withContentLength(await withCallersLeaseId(relayed, workerLeaseId, lease.id)); }, }; } + +function tooLarge(name: string): Response { + return Response.json( + { + error: { + code: "FILE_TOO_LARGE", + message: `File ${name} is over the 2 GiB limit for one file`, + name, + }, + }, + { status: 413 }, + ); +} + +function workerRequest(request: Request, workerLeaseId: string, name: string | undefined): Request { + const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${ + name === undefined ? "" : `/${encodeURIComponent(name)}` + }`; + return new Request(`http://simlock-worker${path}`, { + headers: request.headers, + method: request.method, + signal: request.signal, + ...(request.body === null ? {} : { body: request.body, duplex: "half" }), + } as RequestInit); +} + +// why: the relay carries no `Content-Length`, so the worker sent the body's length under its own header and the gateway gives it back to the caller. +function withContentLength(answer: Response): Response { + const length = answer.headers.get("simlock-content-length"); + if (length === null || !/^\d{1,16}$/.test(length)) return answer; + const headers = new Headers(answer.headers); + headers.set("content-length", length); + return new Response(answer.body, { headers, status: answer.status }); +} diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 9645d6f63..b9e33b6dd 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -565,7 +565,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { ]; const refused = await Promise.all(routes(asStranger).map((send) => send())); - const full = await rig.call("/big.bin", { body: new Uint8Array(2 * MIB), method: "PUT" }); + const full = await rig.call("/big.bin", { body: new Uint8Array(MIB + 1), method: "PUT" }); const feed = new TransformStream(); const writer = feed.writable.getWriter(); const running = rig.call("/running.bin", { diff --git a/src/gateway/relay.ts b/src/gateway/relay.ts index 372f56c6a..39a286f96 100644 --- a/src/gateway/relay.ts +++ b/src/gateway/relay.ts @@ -171,8 +171,9 @@ class Exchange { }); } - #armSilence(upload: { readonly name: string; readonly silenceMs: number }): void { - this.#disarmSilence(); + #armSilence(): void { + const { upload } = this.init.call; + if (upload === undefined) return; this.#silenceTimer = this.init.clock.setTimer(upload.silenceMs, () => { this.#fail( new DispatchError( @@ -208,13 +209,21 @@ class Exchange { return; } this.#channel = channel; - // why: an upload's time is bounded by silence from here on, so the start deadline ends once the channel is open. - if (this.init.call.upload !== undefined && this.#timer !== undefined) { - this.init.clock.cancel(this.#timer); - this.#timer = undefined; - } + this.#endStartDeadlineOfUpload(); this.#reader = channel.readable.getReader(); this.#look(); + this.#sendRequest(client, channel); + if (!this.init.twoWay) await this.#upload(channel, this.init.call.request.body); + } + + // why: an upload's time is bounded by silence from here on, so the start deadline ends once the channel is open. + #endStartDeadlineOfUpload(): void { + if (this.init.call.upload === undefined || this.#timer === undefined) return; + this.init.clock.cancel(this.#timer); + this.#timer = undefined; + } + + #sendRequest(client: GatewayWorkerClient, channel: LinkChannel): void { const { request } = this.init.call; const body = request.body; this.#requestSent = true; @@ -246,12 +255,10 @@ class Exchange { (answer) => this.#onAnswer(answer), (error: unknown) => this.#onCallError(error), ); - if (!this.init.twoWay) await this.#upload(channel, body); } async #upload(channel: LinkChannel, body: ReadableStream | null): Promise { const writer = channel.writable.getWriter(); - const { upload } = this.init.call; if (body === null) { await writer.close().catch(() => undefined); this.#armHeadDeadline(); @@ -261,7 +268,7 @@ class Exchange { this.#callerBody = reader; try { for (;;) { - if (upload !== undefined) this.#armSilence(upload); + this.#armSilence(); const step = await reader.read(); this.#disarmSilence(); if (this.#done) return; @@ -271,15 +278,19 @@ class Exchange { await writer.close(); this.#armHeadDeadline(); } catch (error: unknown) { - if (this.#done) return; - if (error instanceof LinkChannelError) { - // why: the worker stopped reading this direction, so the caller's body is no longer read. - if (error.reason === "stopped") reader.cancel().catch(() => undefined); - else this.#onChannelError(error); - return; - } - this.#fail(error); + this.#uploadFailed(error, reader); + } + } + + #uploadFailed(error: unknown, reader: ReadableStreamDefaultReader): void { + if (this.#done) return; + if (error instanceof LinkChannelError) { + // why: the worker stopped reading this direction, so the caller's body is no longer read. + if (error.reason === "stopped") reader.cancel().catch(() => undefined); + else this.#onChannelError(error); + return; } + this.#fail(error); } // why: an upload's head can arrive only after its body, so its deadline counts from the body's end. From dbbdeb510b85a69d088e9223d6eb33eece78e5d8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:48:27 +0100 Subject: [PATCH 17/20] test(gateway): the upload relay test fails on its named assertion when the relay cuts the body early (#1358) --- src/gateway/relay.test.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/gateway/relay.test.ts b/src/gateway/relay.test.ts index 27f553233..91ee065d2 100644 --- a/src/gateway/relay.test.ts +++ b/src/gateway/relay.test.ts @@ -509,12 +509,29 @@ describe("GatewayRelay on a byte channel", () => { deadlineMs: BOUND, ...(options.holdOpen === true ? { holdOpen: true } : {}), }); - let feed!: ReadableStreamDefaultController; + let controller!: ReadableStreamDefaultController; const body = new ReadableStream({ - start(controller) { - feed = controller; + start(started) { + controller = started; }, }); + // why: a relay that cut the upload too early cancelled this body, and the assertions below must name that, not a closed controller. + const feed = { + close: () => { + try { + controller.close(); + } catch { + // why: the relay already cancelled the body. + } + }, + enqueue: (chunk: Uint8Array) => { + try { + controller.enqueue(chunk); + } catch { + // why: the relay already cancelled the body. + } + }, + }; let result: Awaited>> | undefined; void outcome( relay.relay(WORKER_ID, { From 296696297953a3d027abe66dfd63a31a6b462d79 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 16:04:27 +0100 Subject: [PATCH 18/20] fix(gateway): an upload the worker stopped reading still ends at the head deadline (#1358) --- src/gateway/AGENTS.md | 8 ++++---- src/gateway/relay.test.ts | 15 ++++++++++++++- src/gateway/relay.ts | 7 +++++-- src/lease-files/AGENTS.md | 2 +- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index ecaf14097..9e51682c3 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -43,8 +43,8 @@ Relay: - `relay.*` runs only on a worker's uplink session. A gateway refuses them from everyone. - A worker never holds a gateway credential: `relayHeaderPairs` (`../contract/relay.ts`) drops the credential headers and the configured `http.proxyAuth.header`. -- Every wait is bounded on the `Clock`: one deadline for the channel and the head, then a silence bound on the body, so a live body is never cut. At either limit: `WORKER_UNREACHABLE`, and `relay.cancel` to the worker. -- A relayed file upload (`upload` on the call) is bounded by silence from the caller's body instead: no start deadline once the channel is open, `UPLOAD_STALLED` after `silenceMs` with no byte read from the caller, and the head deadline counts from the body's end. Every other relay keeps the one deadline. +- Every wait is bounded on the `Clock`: one deadline for the channel and the head, then a silence bound on the body. At either limit: `WORKER_UNREACHABLE`, and `relay.cancel` to the worker. +- A file upload (`upload` on the call) is bounded by `UPLOAD_STALLED` silence of the caller instead; its head deadline starts at the body's end. - A two-way relay keeps both directions open after a 2xx head; ending one ends only that one. - Its silence bound (`TWO_WAY_SILENCE_MS` in `relay.ts`) counts only bytes read from the worker. Bytes the gateway writes never reset it, and it stops while the relay's read-ahead is full. A worker module keeps it alive with the heartbeat in `../modules/relay-channel.ts`. - On an uplink close the worker aborts that connection's relays. Leases, requests and exec keep running. @@ -70,9 +70,9 @@ Relay: - **A dispatched request whose uplink drops may have granted a lease anyway.** Client sees `WORKER_UNREACHABLE`; the lease stands until TTL. A re-request may name it or get a second lease. - **A lease survives a gateway restart, but nothing renews it until the gateway is back.** Renew, release and exec fail meanwhile; past the TTL it expires. Knob: `lease.defaultTtlMs`/`--ttl`. -- **Local agents and the gateway share a worker's capacity.** A busy machine answers `NO_CAPACITY`; the request waits elsewhere. `worker drain` leaves it to the owner. +- **Local agents and the gateway share a worker's capacity.** A busy machine answers `NO_CAPACITY`. `worker drain` leaves it to the owner. - **`device.exec` backpressure through a gateway does not slow the worker's own process.** Output is relayed with `void session.onOutput(...)`; a slow fleet client is buffered in the gateway. -- **A worker's future-stamped event keeps its own timestamp.** ADR 0014 §2 has the gateway republish the worker's `timestamp`, so the usage projection's shared fleet clock can move forward; amending the ADR is the maintainer's call. +- **A worker's future-stamped event keeps its own timestamp.** ADR 0014 §2 has the gateway republish the worker's `timestamp`; amending the ADR is the maintainer's call. - **Gateway warm hits miss some devices.** A slim-pool device that failed its slim pass reports `full` and counts for `full`; a default-slim worker's full device on an unslimmable runtime is no hit for a mode-less request; a `--mode slim` request there is no hit on a ready full device. diff --git a/src/gateway/relay.test.ts b/src/gateway/relay.test.ts index 91ee065d2..7214ba415 100644 --- a/src/gateway/relay.test.ts +++ b/src/gateway/relay.test.ts @@ -499,7 +499,7 @@ describe("GatewayRelay on a byte channel", () => { expect(connection.sent.filter((frame) => frame.type === "relay.request")).toEqual([]); }); - it("cuts a file upload only after 330 s with no byte from the caller, counts its head deadline from the body's end, and keeps the 330 s deadline for any other relay", async () => { + it("cuts a file upload only after 330 s with no byte from the caller, counts its head deadline from the body's end, and keeps the 330 s deadline for any other relay or for an upload the worker stopped reading", async () => { const BOUND = 330_000; const upload = { name: "fixture.tar", silenceMs: BOUND }; async function start(options: { upload?: typeof upload; holdOpen?: boolean } = {}) { @@ -595,6 +595,17 @@ describe("GatewayRelay on a byte channel", () => { const otherBeforeDeadline = await other.pass(BOUND - 300_000 - 1); const otherAtDeadline = await other.pass(1); + const stopped = await start({ upload }); + await sentFrame(stopped.connection, "relay.request"); + const stoppedChannel = await openedChannel(stopped.connection); + stopped.feed.enqueue(new Uint8Array(KIB)); + await vi.waitFor(() => expect(stoppedChannel.written.length).toBeGreaterThan(0)); + stoppedChannel.failWritable("stopped"); + stopped.feed.enqueue(new Uint8Array(KIB)); + await sleep(20); + const stoppedBeforeDeadline = await stopped.pass(BOUND - 1); + const stoppedAtDeadline = await stopped.pass(1); + const refused = await start({ upload }); const refusal = await sentFrame(refused.connection, "relay.request"); await refused.pass(100_000); @@ -616,6 +627,8 @@ describe("GatewayRelay on a byte channel", () => { expect(atOpenDeadline).toEqual(unreachable); expect(otherBeforeDeadline).toBeUndefined(); expect(otherAtDeadline).toEqual(unreachable); + expect(stoppedBeforeDeadline).toBeUndefined(); + expect(stoppedAtDeadline).toEqual(unreachable); expect(afterRefusal).toMatchObject({ state: "fulfilled" }); expect(refused.connection.lastSentOf("relay.cancel")).toBeUndefined(); }); diff --git a/src/gateway/relay.ts b/src/gateway/relay.ts index 39a286f96..7a981bbf2 100644 --- a/src/gateway/relay.ts +++ b/src/gateway/relay.ts @@ -286,8 +286,11 @@ class Exchange { if (this.#done) return; if (error instanceof LinkChannelError) { // why: the worker stopped reading this direction, so the caller's body is no longer read. - if (error.reason === "stopped") reader.cancel().catch(() => undefined); - else this.#onChannelError(error); + if (error.reason === "stopped") { + reader.cancel().catch(() => undefined); + // why: no timer is left running once the body is no longer read, and the worker may never send a head. + this.#armHeadDeadline(); + } else this.#onChannelError(error); return; } this.#fail(error); diff --git a/src/lease-files/AGENTS.md b/src/lease-files/AGENTS.md index 1fafd72c9..155c8964b 100644 --- a/src/lease-files/AGENTS.md +++ b/src/lease-files/AGENTS.md @@ -9,5 +9,5 @@ Does: stores the files a lease's holder (or an operator) uploads over `PUT /v1/l - An upload goes to `.upload-` in the folder and is renamed into place only after the whole body arrived. A cut or stalled body leaves nothing visible. - Names are compared ignoring case: a PUT removes the other spellings, a lookup prefers the exact spelling, a DELETE removes every spelling. One writer per lowercase name (`FILE_BUSY`). - A lease's bytes count what is stored plus the other running uploads' received bytes; the file a PUT replaces is not counted. The disk check runs once per upload, before the first byte is stored. -- A gateway holds no file: `gateway-lease-files.ts` (daemon) relays each request to the worker's `files` relay target, path `/files/leases/[/]`, which checks the id and the name and then serves it as a local request does. The worker names its own lease id in a refusal; the gateway puts the caller's back. +- A gateway holds no file. The worker names its own lease id in a refusal; the gateway puts the caller's back. - `end` marks the lease ended, aborts its running uploads, waits for them and removes the folder; an upload or folder creation that finishes after that removes its own work. `sweep` at startup removes every folder whose lease is not live, upload temporary files included. From 08eab7419d538488b8685fe2a7939841e57707ae Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 16:07:16 +0100 Subject: [PATCH 19/20] test(daemon): the relay test's second lease waits until the fleet can grant it (#1358) --- src/daemon/relay-gateway.e2e.test.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index b9e33b6dd..4b3252774 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -448,13 +448,24 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { request.flushHeaders(); }); const channelsOpened = () => fleet.taps.flatMap((tap) => tap.binaries(TYPE.OPEN)).length; + // why: CI saw NO_CAPACITY for a request right after the release, so the helper retries until the fleet can grant. const newLease = async () => { - const next = await fleet.gateway.dispatch( - "lease.request", - { model: "Pixel-A", noWait: true, platform: "android" }, - holder, - ); - return { call: callOn(next.lease.id, secret), leaseId: next.lease.id }; + let granted: string | undefined; + await poll(async () => { + granted = await fleet.gateway + .dispatch( + "lease.request", + { model: "Pixel-A", noWait: true, platform: "android" }, + holder, + ) + .then( + (next) => next.lease.id, + () => undefined, + ); + return granted !== undefined; + }, 15_000).toBe(true); + const leaseId = granted as string; + return { call: callOn(leaseId, secret), leaseId }; }; const stranger = async () => { const other = await fleet.gateway.dispatch( From 038394f3fc5afed0425ba13702d694474e0084a9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 16:16:22 +0100 Subject: [PATCH 20/20] docs(adr): ADR 0067 is Accepted (#1358) --- ...file-folder-on-its-worker-that-http-callers-fill-and-read.md | 2 +- docs/internal/adr/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/internal/adr/0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md b/docs/internal/adr/0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md index 91ed94794..5baf6f897 100644 --- a/docs/internal/adr/0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md +++ b/docs/internal/adr/0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md @@ -1,6 +1,6 @@ # 0067. A lease has a file folder on its worker that HTTP callers fill and read -- **Status:** Accepted — not yet implemented +- **Status:** Accepted - **Date:** 2026-11-06 - **Issue:** [#1351](https://github.com/callstackincubator/simlock/issues/1351) (request [#1323](https://github.com/callstackincubator/simlock/issues/1323)) - **Narrows:** [ADR 0005](0005-gateway-and-worker-modes.md) Non-goals diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index a50a8011b..33f9ab893 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -102,4 +102,4 @@ the status is stale. | [0064](0064-a-tunnel-reaches-an-ios-simulators-ports-and-an-emulators-adb-port.md) | A tunnel reaches an iOS simulator's ports and an emulator's adb port | Accepted; narrows 0054 §2, §5, §6, 0001 §4 and 0005 Non-goals | | [0065](0065-a-driver-owns-its-config-keys-and-a-module-takes-the-sections-it-reads.md) | A driver owns its config keys, and a module takes the config sections it reads | Accepted | | [0066](0066-a-slim-lease-may-keep-named-categories-running.md) | A slim lease may keep named categories running | Accepted; narrows 0007 §8, §9, 0008 §4, §9, 0009 §2, §4 and 0060 §1, §2, §6 | -| [0067](0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md) | A lease has a file folder on its worker that HTTP callers fill and read | Accepted — not yet implemented; narrows 0005 Non-goals (file transfer) and §19b′, 0026 §1 (a core relay target) and 0028 §4 (a file PUT's deadline) | +| [0067](0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md) | A lease has a file folder on its worker that HTTP callers fill and read | Accepted; narrows 0005 Non-goals (file transfer) and §19b′, 0026 §1 (a core relay target) and 0028 §4 (a file PUT's deadline) |