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) | 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/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 new file mode 100644 index 000000000..f10fe6e8f --- /dev/null +++ b/src/daemon/gateway-lease-files.ts @@ -0,0 +1,80 @@ +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"; + +// 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; + 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 { + 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 tooLarge(name); + } + const workerLeaseId = lease.workerLeaseId ?? lease.id; + const relayed = await options.relay(lease.workerId ?? "", { + leaseId: workerLeaseId, + 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 } } + : {}), + }); + 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/main.ts b/src/daemon/main.ts index 4762e29df..d7bc8a68e 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 { @@ -128,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; @@ -321,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 }), @@ -377,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; @@ -629,6 +635,11 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise gatewayRelay.relay(workerId, call), + requesterPrefix: gatewayRequesterPrefix, + ...(options.fileSilenceMs === undefined ? {} : { silenceMs: options.fileSilenceMs }), + }), leaseRequests: fleetCoordinator.requests, logger: httpLogger, leaseRoutes: [...moduleHost.leaseRoutes()], diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 0c93ed3a0..4b3252774 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 { @@ -6,13 +8,16 @@ 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, + adminSession, cleanUp, digestOf, gate, @@ -177,7 +182,11 @@ 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; + readonly gateway?: Partial; + } = {}, ) => startFleet_( { daemons, directories, target, twoWayTarget }, @@ -385,6 +394,273 @@ 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, 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" }, + adminSession, + ); + const holder = agent({ principal: token.id }); + const grant = await fleet.gateway.dispatch( + "lease.request", + { 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`; + // 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; + // why: CI saw NO_CAPACITY for a request right after the release, so the helper retries until the fleet can grant. + const newLease = async () => { + 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( + "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 () => { + 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", { + body: patternStream(20 * MIB, 5), + duplex: "half", + 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(""); + 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, + 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); + + 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(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: [] }); + 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); + 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" }, + }); + 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(MIB + 1), 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("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/relay.ts b/src/daemon/relay.ts index 83cb06ff3..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"; @@ -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); } diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index ac8abf8cf..3db4a5592 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -334,6 +334,10 @@ 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; + // 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 = {}) { @@ -374,6 +378,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( @@ -389,6 +394,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 9e5a006aa..7703aa7c9 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; @@ -340,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({ @@ -518,6 +521,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/gateway/AGENTS.md b/src/gateway/AGENTS.md index 64febfd78..9e51682c3 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -43,7 +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. +- 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. @@ -69,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 d3234d5d1..7214ba415 100644 --- a/src/gateway/relay.test.ts +++ b/src/gateway/relay.test.ts @@ -499,6 +499,140 @@ 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 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 } = {}) { + const clock = new FakeClock(); + const { connection, relay } = await setup({ + clock, + deadlineMs: BOUND, + ...(options.holdOpen === true ? { holdOpen: true } : {}), + }); + let controller!: ReadableStreamDefaultController; + const body = new ReadableStream({ + 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, { + ...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 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); + 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(stoppedBeforeDeadline).toBeUndefined(); + expect(stoppedAtDeadline).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(); diff --git a/src/gateway/relay.ts b/src/gateway/relay.ts index ceede6de4..7a981bbf2 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, @@ -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,25 @@ class Exchange { ), ); }); - void this.#run(); + } + + #armSilence(): void { + const { upload } = this.init.call; + if (upload === undefined) return; + 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,8 +209,21 @@ class Exchange { return; } this.#channel = channel; + 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; @@ -215,37 +255,53 @@ 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(); if (body === null) { await writer.close().catch(() => undefined); + this.#armHeadDeadline(); return; } const reader = body.getReader(); this.#callerBody = reader; try { for (;;) { + this.#armSilence(); 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) { - // 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); + // 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); + } + + // 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 +331,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 +630,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); } 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 3c9b9f697..3bff2db37 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -396,7 +396,7 @@ export const leaseFilePutRoute = declareRoute({ 409: ["FILE_BUSY"], 413: ["FILE_TOO_LARGE", "LEASE_FILES_FULL"], 422: ["INSUFFICIENT_DISK_SPACE"], - 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], + 503: ["WORKER_UNREACHABLE"], }, }); @@ -411,10 +411,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"], 503: ["WORKER_UNREACHABLE"] }, }); export const leaseFileDeleteRoute = declareRoute({ @@ -425,10 +422,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"], 503: ["WORKER_UNREACHABLE"] }, }); export const leaseFileListRoute = declareRoute({ @@ -439,7 +433,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"], 503: ["WORKER_UNREACHABLE"] }, }); 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/AGENTS.md b/src/lease-files/AGENTS.md index 05d4ecd21..155c8964b 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. 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/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/index.ts b/src/lease-files/index.ts index 14d20e74c..5f9ad5e20 100644 --- a/src/lease-files/index.ts +++ b/src/lease-files/index.ts @@ -1,3 +1,4 @@ export { LeaseFilesError } from "./errors.js"; export { createLeaseFiles } from "./lease-files.js"; +export { MAX_FILE_BYTES } from "./limits.js"; export type { LeaseFilesGrant, LeaseFileView, LeaseFiles, LeaseFilesLimits } from "./types.js"; 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/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, }; 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; 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 28b8c2de8..28fb0a584 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