From 2e72bb7d7d1b510e3ef3944d27e569519c80f465 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:21:14 +0100 Subject: [PATCH 01/30] test: a lease holder PUTs a file and gets 201 with its name and size; a GET returns the same bytes (#1356) --- src/auth/admin-secret.test.ts | 12 ++++ src/contract/errors.ts | 20 ++++++ src/contract/protocol.ts | 2 +- src/http/app-leases.test.ts | 56 ++++++++++++++++- src/http/app.ts | 55 ++++++++++++++++ src/http/errors.ts | 2 + src/http/lease-declarations.ts | 71 +++++++++++++++++++++ src/http/routes.ts | 39 +++++++++++- src/http/test-app.ts | 7 +++ src/lease-files/index.ts | 9 +++ src/lease-files/lease-files.ts | 11 ++++ src/lease-files/types.ts | 57 +++++++++++++++++ src/ports/filesystem.ts | 111 ++++++++++++++++++++++++++++++++- 13 files changed, 443 insertions(+), 9 deletions(-) create mode 100644 src/lease-files/index.ts create mode 100644 src/lease-files/lease-files.ts create mode 100644 src/lease-files/types.ts diff --git a/src/auth/admin-secret.test.ts b/src/auth/admin-secret.test.ts index 35021ed32..85dd1effc 100644 --- a/src/auth/admin-secret.test.ts +++ b/src/auth/admin-secret.test.ts @@ -69,6 +69,12 @@ describe("AdminSecretManager", () => { copyFile: () => { throw new Error("verify() must not touch the filesystem"); }, + writeFileStream: () => { + throw new Error("verify() must not touch the filesystem"); + }, + openFile: () => { + throw new Error("verify() must not touch the filesystem"); + }, copyTree: () => { throw new Error("verify() must not touch the filesystem"); }, @@ -150,6 +156,12 @@ describe("AdminSecretManager", () => { copyFile: () => { throw new Error("verify() must not touch the filesystem"); }, + writeFileStream: () => { + throw new Error("verify() must not touch the filesystem"); + }, + openFile: () => { + throw new Error("verify() must not touch the filesystem"); + }, copyTree: () => { throw new Error("verify() must not touch the filesystem"); }, diff --git a/src/contract/errors.ts b/src/contract/errors.ts index e9c699fb4..99c590c4d 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -129,6 +129,15 @@ export interface ErrorDetailsMap { }; /** why: `device.rotate` could not reach the lease's input helper; `reason` is the driver's text, cut to 200 characters. */ INPUT_UNAVAILABLE: { readonly leaseId: string; readonly reason: string }; + /** why: ADR 0067 §4: a lease's file upload passed 2 GiB. */ + FILE_TOO_LARGE: { readonly name: string }; + /** why: ADR 0067 §4: an upload would take a lease's folder past 4 GiB. */ + LEASE_FILES_FULL: { readonly leaseId: string; readonly usedBytes: number }; + UNKNOWN_FILE: { readonly name: string }; + /** why: ADR 0067 §6: no byte of an upload's body arrived for 330 s. */ + UPLOAD_STALLED: { readonly name: string }; + /** why: ADR 0067 §2: another request is uploading the same file name. */ + FILE_BUSY: { readonly name: string }; DOCTOR_UNAVAILABLE: Record; HISTORY_NOT_KEPT: { readonly oldestTs: number }; HISTORY_UNAVAILABLE: Record; @@ -217,6 +226,11 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record UNKNOWN_MODEL: true, HISTORY_NOT_KEPT: true, INSUFFICIENT_DISK_SPACE: true, + FILE_TOO_LARGE: true, + LEASE_FILES_FULL: true, + UNKNOWN_FILE: true, + UPLOAD_STALLED: true, + FILE_BUSY: true, LICENSE_NOT_ACCEPTED: true, DOWNLOAD_TIMEOUT: true, DOWNLOADS_DISABLED: true, @@ -350,6 +364,12 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry httpStatus: 422, }, UNKNOWN_LEASE: { code: "UNKNOWN_LEASE", kind: "domain", cliExitCode: 1, httpStatus: 404 }, + // why: a lease's file routes (ADR 0067): a refused upload or a missing file is a fact about the request, not a state of the host. + FILE_TOO_LARGE: { code: "FILE_TOO_LARGE", kind: "domain", cliExitCode: 1, httpStatus: 413 }, + LEASE_FILES_FULL: { code: "LEASE_FILES_FULL", kind: "domain", cliExitCode: 1, httpStatus: 413 }, + UNKNOWN_FILE: { code: "UNKNOWN_FILE", kind: "domain", cliExitCode: 1, httpStatus: 404 }, + UPLOAD_STALLED: { code: "UPLOAD_STALLED", kind: "domain", cliExitCode: 1, httpStatus: 408 }, + FILE_BUSY: { code: "FILE_BUSY", kind: "domain", cliExitCode: 1, httpStatus: 409 }, // why: a lease's tunnel socket refuses with these (ADR 0054 section 7), so every surface reports them alike. TUNNEL_UNSUPPORTED: { code: "TUNNEL_UNSUPPORTED", diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index a06179f0e..0293a60ee 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 80, max: 80 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 81, max: 81 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index d4c7d46ae..6b51aa4f8 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1,4 +1,8 @@ -import { describe, expect, it } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; import { UnknownLeaseError, SerializedDecision } from "../core/index.js"; @@ -11,7 +15,8 @@ import { } from "../leasing/index.js"; import { DispatchError } from "../daemon/dispatcher.js"; import { describeLeaseRequestFailure } from "../daemon/error-code.js"; -import { FakeClock } from "../ports/index.js"; +import { createLeaseFiles, type LeaseFilesLimits } from "../lease-files/index.js"; +import { FakeClock, NodeFilesystem } from "../ports/index.js"; import { agentAuth, type App, @@ -1455,3 +1460,50 @@ describe("lease routes", () => { expect(((await response.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); }); }); + +const filesRoots: string[] = []; + +afterEach(async () => { + await Promise.all(filesRoots.splice(0).map((root) => rm(root, { force: true, recursive: true }))); +}); + +// why: a worker's HTTP app over a real lease-files store in a temporary folder, with lease `lse_1` held by `tok_agent`. */ +async function filesRig(options: { readonly limits?: LeaseFilesLimits } = {}) { + const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-lease-files-")); + filesRoots.push(dataDirectory); + const rig = buildHarness({ + leaseFiles: ({ clock, logger }) => + createLeaseFiles({ + clock, + dataDirectory, + diskPressureThreshold: 0, + filesystem: new NodeFilesystem(), + findGrant: (leaseId) => + leaseId === "lse_1" ? { grantedAt: 1_000, id: leaseId, platform: "ios" } : undefined, + idGenerator: sequenceIdGenerator("up"), + logger, + ...(options.limits === undefined ? {} : { limits: options.limits }), + }), + }); + rig.registry.leases = [makeLease({ id: "lse_1", ownerId: "tok_agent" })]; + const put = (name: string, body: BodyInit, headers: Record = agentAuth) => + rig.app.request(`/v1/leases/lse_1/files/${name}`, { body, headers, method: "PUT" }); + const get = (name: string, headers: Record = agentAuth) => + rig.app.request(`/v1/leases/lse_1/files/${name}`, { headers }); + return { ...rig, dataDirectory, get, put }; +} + +describe("a lease's files on a worker", () => { + it("a lease holder PUTs a file and gets 201 with its name and size; a GET returns the same bytes", async () => { + const { get, put } = await filesRig(); + const bytes = Uint8Array.from({ length: 3 * 1024 * 1024 }, (_, index) => index % 251); + + const response = await put("fixture.tar", bytes); + + expect(response.status).toBe(201); + expect(await response.json()).toEqual({ name: "fixture.tar", size: bytes.length }); + const download = await get("fixture.tar"); + expect(download.status).toBe(200); + expect(new Uint8Array(await download.arrayBuffer())).toEqual(bytes); + }); +}); diff --git a/src/http/app.ts b/src/http/app.ts index a05843bc9..a7fcaaf84 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -39,6 +39,7 @@ import { badRequest, errorResponse, forbidden, + HttpApiError, mapError, requestNotCancellable, unknownLease, @@ -48,6 +49,10 @@ import { type leaseRequestBodySchema, leaseEventsRoute, leaseExecRoute, + leaseFileDeleteRoute, + leaseFileGetRoute, + leaseFileListRoute, + leaseFilePutRoute, leaseGetRoute, leaseListRoute, leaseReleaseRoute, @@ -118,6 +123,17 @@ 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; +} + +export interface HttpLeaseFiles { + handle( + request: Request, + identity: Identity, + lease: HttpLeaseSocketLease, + name: string | undefined, + ): Promise; } // why: the lease is resolved here, with `lease.get`'s own owner-or-operator answer, so a module's @@ -824,6 +840,45 @@ 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( + c.req.raw, + identity, + { + deviceId: lease.deviceId, + id: lease.id, + ...(lease.workerId === undefined ? {} : { workerId: lease.workerId }), + ...(lease.workerLeaseId === undefined ? {} : { workerLeaseId: lease.workerLeaseId }), + }, + name, + ); + }; + for (const route of [leaseFilePutRoute, leaseFileGetRoute, leaseFileDeleteRoute]) { + app.openapi({ ...route, middleware: [agentAuth] }, (c) => { + const { id, name } = c.req.valid("param"); + return serveLeaseFiles(c as unknown as Context, id, name) as never; + }); + } + app.openapi( + { ...leaseFileListRoute, middleware: [agentAuth] }, + (c) => + serveLeaseFiles(c as unknown as Context, c.req.valid("param").id, undefined) as never, + ); + for (const mount of deps.mounts ?? []) { const handler = (c: Context) => mount.handle(c.req.raw, c.get("identity")); app.all(`/v1/${mount.prefix}`, agentAuth, handler); diff --git a/src/http/errors.ts b/src/http/errors.ts index c7da9ee8f..831f958d5 100644 --- a/src/http/errors.ts +++ b/src/http/errors.ts @@ -27,7 +27,9 @@ export type HttpStatus = | 403 | 404 | 405 + | 408 | 409 + | 413 | 415 | 422 | 500 diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 19014dab2..c5a9dbd9b 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -365,6 +365,73 @@ export const leaseReleaseRoute = declareRoute({ errors: { 404: ["UNKNOWN_LEASE"] }, }); +const leaseFileParamsSchema = z.object({ id: z.string(), name: z.string() }); + +const leaseFileSchema = z.object({ name: z.string(), size: z.number().int() }); + +export const leaseFilePutRoute = declareRoute({ + method: "put", + path: "/v1/leases/{id}/files/{name}", + tag: "Leases", + summary: "Upload a file to the lease's folder", + role: "agent", + notes: + "The body is the file's raw bytes: up to 2 GiB a file and 4 GiB a lease, streamed to disk. The same name again replaces the file; names match ignoring case. An upload is cut only after 330 s with no byte.", + request: { params: leaseFileParamsSchema, octetBody: true }, + reply: leaseFileSchema, + status: 201, + errors: { + 404: ["UNKNOWN_LEASE"], + 408: ["UPLOAD_STALLED"], + 409: ["FILE_BUSY"], + 413: ["FILE_TOO_LARGE", "LEASE_FILES_FULL"], + 422: ["INSUFFICIENT_DISK_SPACE"], + 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], + }, +}); + +export const leaseFileGetRoute = declareRoute({ + method: "get", + path: "/v1/leases/{id}/files/{name}", + tag: "Leases", + summary: "Download a file from the lease's folder", + role: "agent", + notes: + "Answers the whole file, or one byte range of it (`Range: bytes=a-b`, `a-` or `-n`) as 206. A start past the end answers 416 with `Content-Range: bytes */`.", + request: { params: leaseFileParamsSchema }, + binaryReply: true, + alsoStatus: 206, + errors: { + 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], + 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], + }, +}); + +export const leaseFileDeleteRoute = declareRoute({ + method: "delete", + path: "/v1/leases/{id}/files/{name}", + tag: "Leases", + summary: "Delete a file from the lease's folder", + role: "agent", + request: { params: leaseFileParamsSchema }, + status: 204, + errors: { + 404: ["UNKNOWN_LEASE", "UNKNOWN_FILE"], + 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], + }, +}); + +export const leaseFileListRoute = declareRoute({ + method: "get", + path: "/v1/leases/{id}/files", + tag: "Leases", + summary: "List the files in the lease's folder", + role: "agent", + request: { params: leaseParamsSchema }, + reply: z.object({ files: z.array(leaseFileSchema) }), + errors: { 404: ["UNKNOWN_LEASE"], 501: ["UNSUPPORTED_IN_GATEWAY_MODE"] }, +}); + export const LEASE_ROUTES = [ leaseRequestCreateRoute, leaseRequestListRoute, @@ -376,6 +443,10 @@ export const LEASE_ROUTES = [ leaseRenewRoute, leaseExecRoute, leaseRotateRoute, + leaseFilePutRoute, + leaseFileGetRoute, + leaseFileDeleteRoute, + leaseFileListRoute, leaseEventsRoute, leaseReleaseRoute, ] as const; diff --git a/src/http/routes.ts b/src/http/routes.ts index a8b4b8243..04c76437f 100644 --- a/src/http/routes.ts +++ b/src/http/routes.ts @@ -15,8 +15,23 @@ type RouteTag = | "Baselines" | "Tokens" | "Events"; -type SuccessStatus = 200 | 201 | 202 | 204; -type ErrorStatus = 400 | 401 | 403 | 404 | 409 | 415 | 422 | 500 | 501 | 502 | 503 | 504; +type SuccessStatus = 200 | 201 | 202 | 204 | 206; +type ErrorStatus = + | 400 + | 401 + | 403 + | 404 + | 408 + | 409 + | 413 + | 415 + | 416 + | 422 + | 500 + | 501 + | 502 + | 503 + | 504; type JsonContent = { "application/json": { schema: Schema } }; type ErrorBody = { error: { code: string; message: string } }; type ErrorResponse = { @@ -31,6 +46,8 @@ type ErrorExtras = Partial< export const BEARER_SCHEME = "bearer"; +const BINARY_SCHEMA = z.string().openapi({ format: "binary" }); + const BASE_CODES = { 400: ["BAD_REQUEST"], 401: ["UNAUTHENTICATED"], @@ -46,6 +63,8 @@ type RequestSchemas = { readonly headers?: z.ZodType; readonly json?: z.ZodType; readonly optionalJson?: z.ZodType; + // why: the body is raw bytes, which the app's validators never read; the document only names it. + readonly octetBody?: true; }; type DeclaredRequest = (Request["query"] extends z.ZodType @@ -96,7 +115,7 @@ interface Declaration< Also extends SuccessStatus, Own extends Partial>, > { - readonly method: "get" | "post" | "delete"; + readonly method: "get" | "post" | "put" | "delete"; readonly path: Path; readonly tag: RouteTag; readonly summary: string; @@ -105,6 +124,8 @@ interface Declaration< readonly request?: Request; readonly reply?: Reply; readonly stream?: Stream; + // why: the success body is raw bytes, not JSON. + readonly binaryReply?: true; readonly replyHeaders?: z.ZodType; readonly status?: Success; // why: a route that answers 202 when it began the work and 200 when it only followed or found nothing to do declares both. @@ -160,7 +181,11 @@ function declaredErrors( function successContent(declaration: { readonly reply?: z.ZodType | undefined; readonly stream?: z.ZodType | undefined; + readonly binaryReply?: true | undefined; }) { + if (declaration.binaryReply === true) { + return { content: { "application/octet-stream": { schema: BINARY_SCHEMA } } }; + } if (declaration.stream !== undefined) { return { content: { "text/event-stream": { schema: declaration.stream } } }; } @@ -232,6 +257,14 @@ export function declareRoute< content: { "application/json": { schema: body } }, }, }), + ...(request.octetBody === undefined + ? {} + : { + body: { + required: false, + content: { "application/octet-stream": { schema: BINARY_SCHEMA } }, + }, + }), } as DeclaredRequest, responses, }); diff --git a/src/http/test-app.ts b/src/http/test-app.ts index a71237ee0..cd987afad 100644 --- a/src/http/test-app.ts +++ b/src/http/test-app.ts @@ -20,6 +20,10 @@ export function buildHarness( readonly identities?: Readonly>; readonly auth?: Auth; readonly mounts?: HttpGatewayDeps["mounts"]; + readonly leaseFiles?: (parts: { + readonly clock: FakeClock; + readonly logger: JsonLinesLogger; + }) => HttpGatewayDeps["leaseFiles"]; } = {}, ) { const clock = new FakeClock(1_000); @@ -71,6 +75,9 @@ export function buildHarness( registry: overrides.registry ?? registry, auth, ...(overrides.mounts === undefined ? {} : { mounts: overrides.mounts }), + ...(overrides.leaseFiles === undefined + ? {} + : { leaseFiles: overrides.leaseFiles({ clock, logger }) }), ...(overrides.answerDownloadsEarly === undefined ? {} : { answerDownloadsEarly: overrides.answerDownloadsEarly }), diff --git a/src/lease-files/index.ts b/src/lease-files/index.ts new file mode 100644 index 000000000..a28b1ddd8 --- /dev/null +++ b/src/lease-files/index.ts @@ -0,0 +1,9 @@ +export { createLeaseFiles } from "./lease-files.js"; +export type { + LeaseFilesDeps, + LeaseFilesGrant, + LeaseFilesLease, + LeaseFilesLimits, + LeaseFiles, + LeaseFileView, +} from "./types.js"; diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts new file mode 100644 index 000000000..21f1cbbc2 --- /dev/null +++ b/src/lease-files/lease-files.ts @@ -0,0 +1,11 @@ +import type { LeaseFiles, LeaseFilesDeps } from "./types.js"; + +export function createLeaseFiles(_deps: LeaseFilesDeps): LeaseFiles { + return { + folderOf: () => Promise.resolve(""), + handle: () => Promise.resolve(new Response(null, { status: 501 })), + leaseEnd: { leaseEnded: () => Promise.resolve() }, + openFile: () => Promise.reject(new Error("not built")), + sweep: () => Promise.resolve(), + }; +} diff --git a/src/lease-files/types.ts b/src/lease-files/types.ts new file mode 100644 index 000000000..dfeec2095 --- /dev/null +++ b/src/lease-files/types.ts @@ -0,0 +1,57 @@ +import type { Identity } from "../auth/index.js"; +import type { Platform } from "../contract/index.js"; +import type { LeaseEndParticipant } from "../leasing/index.js"; +import type { Clock, Filesystem, IdGenerator, Logger } from "../ports/index.js"; + +/** why: the live grant a lease folder belongs to; `grantedAt` keeps two grants of one lease id apart. */ +export interface LeaseFilesGrant { + readonly id: string; + readonly grantedAt: number; + readonly platform: Platform; +} + +/** why: the lease as the HTTP app resolved it, which a gateway's own handler reads further than a worker's. */ +export interface LeaseFilesLease { + readonly id: string; + readonly deviceId: string; + readonly workerId?: string; + readonly workerLeaseId?: string; +} + +export interface LeaseFilesLimits { + readonly fileBytes: number; + readonly leaseBytes: number; + readonly silenceMs: number; +} + +export interface LeaseFilesDeps { + readonly filesystem: Filesystem; + readonly dataDirectory: string; + readonly diskPressureThreshold: number; + readonly clock: Clock; + readonly logger: Logger; + readonly idGenerator: IdGenerator; + readonly findGrant: (leaseId: string) => LeaseFilesGrant | undefined; + /** why: for tests only; nothing in config sets it. */ + readonly limits?: LeaseFilesLimits; +} + +export interface LeaseFileView { + readonly name: string; + readonly size: number; + read(range?: { readonly start: number; readonly end: number }): ReadableStream; + close(): Promise; +} + +export interface LeaseFiles { + handle( + request: Request, + identity: Identity, + lease: LeaseFilesLease, + name: string | undefined, + ): Promise; + folderOf(grant: LeaseFilesGrant): Promise; + openFile(grant: LeaseFilesGrant, name: string): Promise; + readonly leaseEnd: LeaseEndParticipant; + sweep(liveGrants: readonly { readonly id: string; readonly grantedAt: number }[]): Promise; +} diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index b44167389..835a32b7d 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -1,3 +1,4 @@ +import { createWriteStream } from "node:fs"; import { chmod, copyFile, @@ -16,6 +17,8 @@ import { writeFile, } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; import { NodeProcessRunner, type ProcessRunner } from "./process-runner.js"; @@ -52,7 +55,28 @@ export interface PathDetails { readonly mode: number; } +/** + * why: a file opened for reading, so what a caller reads is the file it opened even when the path is + * replaced afterwards. `read` takes inclusive byte offsets; one of `read` or `close` ends the handle. + */ +export interface OpenedFile { + readonly size: number; + read(range?: { readonly start: number; readonly end: number }): ReadableStream; + close(): Promise; +} + export interface Filesystem { + /** + * why: a body too big for memory goes to a new file piece by piece; the file must not exist. + * A body that errors rejects the write and leaves the partial file for the caller to remove. + * Answers the bytes written. + */ + writeFileStream( + path: string, + body: ReadableStream, + options?: { readonly mode?: number }, + ): Promise; + openFile(path: string): Promise; readFile(path: string): Promise; readFileFrom(path: string, offset: number): Promise; writeFileAtomic(path: string, contents: string, options?: WriteFileAtomicOptions): Promise; @@ -146,6 +170,39 @@ export class NodeFilesystem implements Filesystem { await copyFile(from, to); } + async writeFileStream( + path: string, + body: ReadableStream, + options: { readonly mode?: number } = {}, + ): Promise { + const out = createWriteStream(path, { + flags: "wx", + ...(options.mode === undefined ? {} : { mode: options.mode }), + }); + await pipeline(Readable.fromWeb(body as never), out); + return out.bytesWritten; + } + + async openFile(path: string): Promise { + const handle = await open(path, "r"); + try { + const { size } = await handle.stat(); + return { + size, + read: (range) => + Readable.toWeb( + handle.createReadStream( + range === undefined ? {} : { start: range.start, end: range.end }, + ), + ) as ReadableStream, + close: () => handle.close().catch(() => undefined), + }; + } catch (error: unknown) { + await handle.close(); + throw error; + } + } + async copyTree(from: string, to: string, options: { readonly timeoutMs: number }): Promise { if (this.#platform === "darwin") return this.#copyWithCp(["-c", "-p", "-R", from, to], options); if (this.#platform === "linux") { @@ -368,7 +425,7 @@ interface MemoryAttributes { } type MemoryEntryKind = - | { readonly kind: "file"; contents: string } + | { readonly kind: "file"; contents: string; bytes?: Uint8Array } | { readonly kind: "directory" } | { readonly kind: "symlink"; readonly target: string }; @@ -414,6 +471,50 @@ export class MemoryFilesystem implements Filesystem { await this.writeFileAtomic(to, await this.readFile(from)); } + async writeFileStream( + path: string, + body: ReadableStream, + options: { readonly mode?: number } = {}, + ): Promise { + this.#failIfDefined(path); + path = this.#underResolvedParent(path); + this.#requireDirectory(parentPath(path)); + if (this.#entries.has(path)) throw errnoError("EEXIST", `File already exists: ${path}`); + const chunks: Uint8Array[] = []; + const reader = body.getReader(); + for (;;) { + const piece = await reader.read(); + if (piece.done) break; + chunks.push(piece.value); + } + const bytes = Buffer.concat(chunks); + this.#entries.set(path, { + ...this.#newEntry({ kind: "file", contents: bytes.toString("utf8"), bytes }), + mode: options.mode ?? DEFAULT_FILE_MODE, + }); + return bytes.byteLength; + } + + async openFile(path: string): Promise { + this.#failIfDefined(path); + const entry = this.#entryAt(path); + if (entry.kind !== "file") throw errnoError("EISDIR", `Is a directory: ${path}`); + const bytes = fileBytes(entry); + return { + size: bytes.byteLength, + read: (range) => { + const piece = range === undefined ? bytes : bytes.subarray(range.start, range.end + 1); + return new ReadableStream({ + start(controller) { + controller.enqueue(piece); + controller.close(); + }, + }); + }, + close: async () => undefined, + }; + } + async copyTree( from: string, to: string, @@ -557,7 +658,7 @@ export class MemoryFilesystem implements Filesystem { return { kind: entry.kind === "file" ? "file" : "directory", - size: entry.kind === "file" ? Buffer.byteLength(entry.contents) : 0, + size: entry.kind === "file" ? fileBytes(entry).byteLength : 0, modifiedAtMs: entry.modifiedAtMs, mode: entry.mode, identity: String(entry.identity), @@ -660,7 +761,7 @@ export class MemoryFilesystem implements Filesystem { this.#failIfDefined(child); const entry = this.#rawEntryAt(child); if (entry.kind === "directory") total += await this.directorySize(child); - else if (entry.kind === "file") total += Buffer.byteLength(entry.contents); + else if (entry.kind === "file") total += fileBytes(entry).byteLength; } return total; } @@ -772,6 +873,10 @@ export class MemoryFilesystem implements Filesystem { } } +function fileBytes(entry: { readonly contents: string; readonly bytes?: Uint8Array }): Uint8Array { + return entry.bytes ?? Buffer.from(entry.contents, "utf8"); +} + function joinMemoryPath(parent: string, child: string): string { return parent === "/" || parent === "" ? `/${child}` : `${parent}/${child}`; } From f88b6c902ca3f03d4970f82f536238ac572289cc Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:25:28 +0100 Subject: [PATCH 02/30] feat(lease-files): a PUT stores a file in the lease's folder and a GET returns its bytes (#1356) --- src/http/app-leases.test.ts | 10 ++++- src/lease-files/errors.ts | 13 +++++++ src/lease-files/handler.ts | 31 +++++++++++++++ src/lease-files/lease-files.ts | 70 +++++++++++++++++++++++++++++++--- src/lease-files/limits.ts | 7 ++++ 5 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 src/lease-files/errors.ts create mode 100644 src/lease-files/handler.ts create mode 100644 src/lease-files/limits.ts diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 6b51aa4f8..97124bb5a 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -1467,7 +1468,7 @@ afterEach(async () => { await Promise.all(filesRoots.splice(0).map((root) => rm(root, { force: true, recursive: true }))); }); -// why: a worker's HTTP app over a real lease-files store in a temporary folder, with lease `lse_1` held by `tok_agent`. */ +// why: a worker's HTTP app over a real lease-files store in a temporary folder, with lease `lse_1` held by `tok_agent`. async function filesRig(options: { readonly limits?: LeaseFilesLimits } = {}) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-lease-files-")); filesRoots.push(dataDirectory); @@ -1493,6 +1494,11 @@ async function filesRig(options: { readonly limits?: LeaseFilesLimits } = {}) { return { ...rig, dataDirectory, get, put }; } +// why: comparing megabytes with `toEqual` walks them one by one and takes seconds; their digests say the same. +function sha256(bytes: Uint8Array): string { + return createHash("sha256").update(bytes).digest("hex"); +} + describe("a lease's files on a worker", () => { it("a lease holder PUTs a file and gets 201 with its name and size; a GET returns the same bytes", async () => { const { get, put } = await filesRig(); @@ -1504,6 +1510,6 @@ describe("a lease's files on a worker", () => { expect(await response.json()).toEqual({ name: "fixture.tar", size: bytes.length }); const download = await get("fixture.tar"); expect(download.status).toBe(200); - expect(new Uint8Array(await download.arrayBuffer())).toEqual(bytes); + expect(sha256(new Uint8Array(await download.arrayBuffer()))).toBe(sha256(bytes)); }); }); diff --git a/src/lease-files/errors.ts b/src/lease-files/errors.ts new file mode 100644 index 000000000..77bca3ff1 --- /dev/null +++ b/src/lease-files/errors.ts @@ -0,0 +1,13 @@ +import type { ErrorDetailsMap, SimlockErrorCode } from "../contract/index.js"; + +/** why: a refusal the lease-files routes answer with its code, the message and the code's declared details on the wire. */ +export class LeaseFilesError extends Error { + constructor( + readonly code: Code, + message: string, + readonly details: ErrorDetailsMap[Code], + ) { + super(message); + this.name = "LeaseFilesError"; + } +} diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts new file mode 100644 index 000000000..6282cef13 --- /dev/null +++ b/src/lease-files/handler.ts @@ -0,0 +1,31 @@ +import type { LeaseFileStore } from "./lease-files.js"; +import type { LeaseFilesLease } from "./types.js"; + +export async function handleRequest( + store: LeaseFileStore, + request: Request, + lease: LeaseFilesLease, + name: string | undefined, +): Promise { + const grant = store.findGrant(lease.id); + if (grant === undefined || name === undefined) return new Response(null, { status: 404 }); + if (request.method === "PUT") { + const stored = await store.put( + grant, + name, + request.body ?? new ReadableStream({ start: (c) => c.close() }), + ); + return Response.json(stored, { status: 201 }); + } + const file = await store.openFile(grant, name); + const length = String(file.size); + return new Response(file.read(), { + headers: { + "accept-ranges": "bytes", + "cache-control": "no-store", + "content-length": length, + "content-type": "application/octet-stream", + "simlock-content-length": length, + }, + }); +} diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts index 21f1cbbc2..5d209ce44 100644 --- a/src/lease-files/lease-files.ts +++ b/src/lease-files/lease-files.ts @@ -1,11 +1,71 @@ -import type { LeaseFiles, LeaseFilesDeps } from "./types.js"; +import { join } from "node:path"; + +import type { Identity } from "../auth/index.js"; +import { DEFAULT_LIMITS } from "./limits.js"; +import { handleRequest } from "./handler.js"; +import type { + LeaseFileView, + LeaseFiles, + LeaseFilesDeps, + LeaseFilesGrant, + LeaseFilesLease, +} from "./types.js"; + +export function folderKey(id: string, grantedAt: number): string { + return `${Buffer.from(id, "utf8").toString("hex")}-${String(grantedAt)}`; +} + +/** why: the store's part the HTTP handler calls; `LeaseFiles` is the surface other modules get. */ +export interface LeaseFileStore { + put( + grant: LeaseFilesGrant, + name: string, + body: ReadableStream, + ): Promise<{ readonly name: string; readonly size: number }>; + openFile(grant: LeaseFilesGrant, name: string): Promise; + findGrant(leaseId: string): LeaseFilesGrant | undefined; +} + +export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { + const { filesystem } = deps; + const limits = deps.limits ?? DEFAULT_LIMITS; + void limits; + const rootOf = () => join(deps.dataDirectory, "lease-files"); + const pathOf = (grant: LeaseFilesGrant) => join(rootOf(), folderKey(grant.id, grant.grantedAt)); + + const folderOf = async (grant: LeaseFilesGrant): Promise => { + const folder = pathOf(grant); + await filesystem.mkdirp(folder, { mode: 0o700 }); + return folder; + }; + + const openFile = async (grant: LeaseFilesGrant, name: string): Promise => { + const file = await filesystem.openFile(join(pathOf(grant), name)); + return { name, ...file }; + }; + + const store: LeaseFileStore = { + findGrant: deps.findGrant, + openFile, + put: async (grant, name, body) => { + const folder = await folderOf(grant); + const temporary = join(folder, `.upload-${deps.idGenerator.generate()}`); + const size = await filesystem.writeFileStream(temporary, body, { mode: 0o600 }); + await filesystem.rename(temporary, join(folder, name)); + return { name, size }; + }, + }; -export function createLeaseFiles(_deps: LeaseFilesDeps): LeaseFiles { return { - folderOf: () => Promise.resolve(""), - handle: () => Promise.resolve(new Response(null, { status: 501 })), + folderOf, + handle: ( + request: Request, + _identity: Identity, + lease: LeaseFilesLease, + name: string | undefined, + ) => handleRequest(store, request, lease, name), leaseEnd: { leaseEnded: () => Promise.resolve() }, - openFile: () => Promise.reject(new Error("not built")), + openFile, sweep: () => Promise.resolve(), }; } diff --git a/src/lease-files/limits.ts b/src/lease-files/limits.ts new file mode 100644 index 000000000..e05b6c6d9 --- /dev/null +++ b/src/lease-files/limits.ts @@ -0,0 +1,7 @@ +import type { LeaseFilesLimits } from "./types.js"; + +export const DEFAULT_LIMITS: LeaseFilesLimits = { + fileBytes: 2 * 1024 ** 3, + leaseBytes: 4 * 1024 ** 3, + silenceMs: 330_000, +}; From 22ed6425eb88c2ffb0772d6b1985a7acfe2a1351 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:26:12 +0100 Subject: [PATCH 03/30] docs(lease-files): the lease files section and the five new error codes (#1356) --- .../content/docs/docs/reference/errors.mdx | 14 +++++++++- .../docs/docs/using-devices/remote-agents.mdx | 27 ++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 36bf326fe..74de4bf06 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -22,7 +22,7 @@ In a script, check `code`, not the message: the wording of a message can change, | Exit | Error codes | Meaning | | --- | --- | --- | | 0 | — | Success. For a `simlock lease` that stayed running: the lease ended because you asked. | -| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `BASELINE_SAVE_FAILED`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `INPUT_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED`, `TUNNEL_UNSUPPORTED`, `TUNNEL_PORT_IN_USE`, `TUNNEL_BAD_PORT`, `TUNNEL_LIMIT`, `TUNNEL_FAILED`, `TUNNEL_UNAVAILABLE`, `TUNNEL_DISCONNECTED`, `TUNNEL_CALLER_PORT_IN_USE` | The command failed. Read the code and the message. | +| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `UNKNOWN_FILE`, `FILE_TOO_LARGE`, `LEASE_FILES_FULL`, `FILE_BUSY`, `UPLOAD_STALLED`, `BASELINE_SAVE_FAILED`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `INPUT_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED`, `TUNNEL_UNSUPPORTED`, `TUNNEL_PORT_IN_USE`, `TUNNEL_BAD_PORT`, `TUNNEL_LIMIT`, `TUNNEL_FAILED`, `TUNNEL_UNAVAILABLE`, `TUNNEL_DISCONNECTED`, `TUNNEL_CALLER_PORT_IN_USE` | The command failed. Read the code and the message. | | 2 | `USAGE`, `BAD_REQUEST`, `BASELINE_MISMATCH`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | @@ -103,6 +103,18 @@ A lease's tunnel socket (`GET /v1/leases/{id}/tunnel`, on a worker with `capabil | `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | | `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator cannot take input right now: for a rotate, the part of Simlock that sends input to it did not start within 10 seconds or failed, and the message ends with the reason. Through a gateway, the same code answers an input socket when the lease's worker has input off. | Run it again. If it repeats, check `simlock daemon logs`. | +## Lease files + +| Code | Exit | HTTP | Meaning | What to do | +| --- | --- | --- | --- | --- | +| `FILE_TOO_LARGE` | 1 | 413 | An upload to a lease is over 2 GiB: its `Content-Length`, or the bytes received when it has none. Nothing is stored. | Send a smaller file. | +| `LEASE_FILES_FULL` | 1 | 413 | The upload would take the lease's folder past 4 GiB, counting every file in it and the uploads running at the same time. The message gives the bytes held. | Delete files with `DELETE /v1/leases/{id}/files/{name}`, or finish the other uploads first. | +| `UNKNOWN_FILE` | 1 | 404 | The lease has no file with this name (names match ignoring case). | List the files with `GET /v1/leases/{id}/files`. | +| `FILE_BUSY` | 1 | 409 | Another request is uploading a file with this name. | Wait for it to finish, then upload again. | +| `UPLOAD_STALLED` | 1 | 408 | No byte of the upload's body arrived for 330 seconds. The previous file is kept. | Send the upload again from the start. | + +A bad file name is `BAD_REQUEST`, and a worker whose free disk is under `diskPressure.freeBytesThreshold` answers an upload with `INSUFFICIENT_DISK_SPACE`. + ## Daemon and connection | Code | Exit | HTTP | Meaning | What to do | 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 5b3662827..e22716446 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -149,13 +149,38 @@ The command runs on the worker, as the user who runs the worker's daemon. Treat - **Leave the device out.** Simlock adds the lease's device to the command: the UDID for `simctl` (where the subcommand takes one), `-s ` for `adb`, and `--device ` for `devicectl`. Write `["install","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/builds/MyApp.app"]`, not a UDID or serial. - **Naming another device is refused.** A command that names a different device, such as `booted`, another UDID, `adb -s emulator-5556`, `-e`, `-d` or `-t`, is refused with `422 PASSTHROUGH_REFUSED` before anything runs. Naming the lease's own device is accepted, except on a physical Android phone, which refuses any option before the subcommand, even its own `-s `. -- **Paths are on the worker.** `{"tool":"simctl","args":["install","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/builds/MyApp.app"]}` needs `/builds/MyApp.app` to exist on the worker. The API can't upload files. Get the file there another way, or use [agent-device](/simlock/docs/using-devices/agent-device), which uploads apps for you. +- **Paths are on the worker.** `{"tool":"simctl","args":["install","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/builds/MyApp.app"]}` needs `/builds/MyApp.app` to exist on the worker. Upload a file to the lease's folder with [lease files](#lease-files), or use [agent-device](/simlock/docs/using-devices/agent-device), which uploads apps for you. - **No terminal.** `stdin` in the body is sent to the command once, and may hold at most 8,388,608 characters; a longer one is refused with `BAD_REQUEST`. Interactive commands, such as a bare `adb shell`, are refused. - **Output is text.** Output is decoded as UTF-8, so binary output, such as a screenshot written to stdout, gets corrupted. Write it to a file on the worker instead. - **Time limit.** A command that runs longer than 10 minutes is stopped, and the stream ends with an `error` event carrying `EXEC_TIMEOUT`. Disconnecting doesn't stop the command. - **The same commands are refused as locally.** Everything `simlock simctl` and `simlock adb` refuse (see [Commands Simlock refuses](/simlock/docs/using-devices/working-with-a-device#commands-simlock-refuses)) is refused here with `422 PASSTHROUGH_REFUSED`, before anything runs. So is `simctl` on an Android lease, and `adb` on an iOS one. - **The command gets a short list of environment variables**: `PATH`, `HOME`, `TMPDIR`, `USER`, `LOGNAME`, `SHELL`, `LANG`, every `LC_*` variable, `TERM`, `DEVELOPER_DIR`, `ANDROID_HOME`, `ANDROID_SDK_ROOT`, `ANDROID_USER_HOME`, `ANDROID_AVD_HOME`, `ANDROID_PREFS_ROOT`, `ANDROID_SDK_HOME` and `JAVA_HOME`, plus what it needs to reach the device. Other variables, such as a token the daemon was started with, aren't passed. That doesn't make them secret: the command runs as the same user and can read the daemon's environment. +## 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. + +```bash +curl -X PUT "$W/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 +# 206, Content-Range: bytes 0-99/70000000, 100 bytes + +curl "$W/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" +# 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`). +- **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. + ## More calls | Call | What it does | From a618e4d7e9786748119727b5ead36d49e2f90aa6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:26:50 +0100 Subject: [PATCH 04/30] test: a lease holder PUTs a bad file name and gets 400 BAD_REQUEST with the name rule (#1356) --- src/http/app-leases.test.ts | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 97124bb5a..7e0101b9e 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1512,4 +1512,39 @@ describe("a lease's files on a worker", () => { expect(download.status).toBe(200); expect(sha256(new Uint8Array(await download.arrayBuffer()))).toBe(sha256(bytes)); }); + + it("a lease holder PUTs a bad file name and gets 400 BAD_REQUEST with the name rule", async () => { + const { get, put, app } = await filesRig(); + const accepted = [ + "fixture.tar", + "app-release.apk", + "Documents.tar.deflate", + "A", + "a".repeat(128), + ]; + const refused = [ + ["a".repeat(129), "a".repeat(129)], + [".hidden", ".hidden"], + ["-rf", "-rf"], + ["my%20file.tar", "my file.tar"], + ["a%2Fb.tar", "a/b.tar"], + ["za%C5%BC%C3%B3%C5%82%C4%87.txt", "zażółć.txt"], + ] as const; + + for (const name of accepted) expect((await put(name, "x")).status).toBe(201); + for (const [encoded, decoded] of refused) { + for (const response of [await put(encoded, "x"), await get(encoded)]) { + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: { + code: "BAD_REQUEST", + message: `File ${decoded} must be 1 to 128 letters, digits, '.', '_' or '-', starting with a letter or digit`, + }, + }); + } + } + expect((await app.request("/v1/leases/lse_1/files/..", { headers: agentAuth })).status).toBe( + 404, + ); + }); }); From bda04294430adabe0854fe31691e7166fd8aaac1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:27:23 +0100 Subject: [PATCH 05/30] feat(lease-files): a file name outside the name rule is refused 400 BAD_REQUEST (#1356) --- src/lease-files/handler.ts | 30 ++++++++++++++++++++++++------ src/lease-files/names.ts | 17 +++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 src/lease-files/names.ts diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index 6282cef13..fad19abef 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -1,4 +1,7 @@ +import { ERROR_TABLE } from "../contract/index.js"; +import { LeaseFilesError } from "./errors.js"; import type { LeaseFileStore } from "./lease-files.js"; +import { requireFileName } from "./names.js"; import type { LeaseFilesLease } from "./types.js"; export async function handleRequest( @@ -6,16 +9,31 @@ export async function handleRequest( request: Request, lease: LeaseFilesLease, name: string | undefined, +): Promise { + try { + return await serve(store, request, lease, name); + } catch (error: unknown) { + if (!(error instanceof LeaseFilesError)) throw error; + const refusal: LeaseFilesError = error; + return Response.json( + { error: { code: refusal.code, message: refusal.message, ...refusal.details } }, + { status: ERROR_TABLE[refusal.code].httpStatus }, + ); + } +} + +async function serve( + store: LeaseFileStore, + request: Request, + lease: LeaseFilesLease, + name: string | undefined, ): Promise { const grant = store.findGrant(lease.id); if (grant === undefined || name === undefined) return new Response(null, { status: 404 }); + requireFileName(name); if (request.method === "PUT") { - const stored = await store.put( - grant, - name, - request.body ?? new ReadableStream({ start: (c) => c.close() }), - ); - return Response.json(stored, { status: 201 }); + const body = request.body ?? new ReadableStream({ start: (c) => c.close() }); + return Response.json(await store.put(grant, name, body), { status: 201 }); } const file = await store.openFile(grant, name); const length = String(file.size); diff --git a/src/lease-files/names.ts b/src/lease-files/names.ts new file mode 100644 index 000000000..0c4a7185a --- /dev/null +++ b/src/lease-files/names.ts @@ -0,0 +1,17 @@ +import { LeaseFilesError } from "./errors.js"; + +const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +export function isFileName(name: string): boolean { + return NAME_PATTERN.test(name); +} + +export function requireFileName(name: string): void { + if (!isFileName(name)) { + throw new LeaseFilesError( + "BAD_REQUEST", + `File ${name} must be 1 to 128 letters, digits, '.', '_' or '-', starting with a letter or digit`, + {}, + ); + } +} From ed511969a6ceec8e4a9d37e45f023bb4cd4b9de0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:28:29 +0100 Subject: [PATCH 06/30] test: a lease holder PUTs past a limit and gets the limit's code, with nothing stored and the previous file kept (#1356) --- src/http/app-leases.test.ts | 68 ++++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 5 deletions(-) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 7e0101b9e..d48d7dc79 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -1469,7 +1469,13 @@ afterEach(async () => { }); // why: a worker's HTTP app over a real lease-files store in a temporary folder, with lease `lse_1` held by `tok_agent`. -async function filesRig(options: { readonly limits?: LeaseFilesLimits } = {}) { +async function filesRig( + options: { + readonly limits?: LeaseFilesLimits; + readonly filesystem?: NodeFilesystem; + readonly diskPressureThreshold?: number; + } = {}, +) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-lease-files-")); filesRoots.push(dataDirectory); const rig = buildHarness({ @@ -1477,8 +1483,8 @@ async function filesRig(options: { readonly limits?: LeaseFilesLimits } = {}) { createLeaseFiles({ clock, dataDirectory, - diskPressureThreshold: 0, - filesystem: new NodeFilesystem(), + diskPressureThreshold: options.diskPressureThreshold ?? 0, + filesystem: options.filesystem ?? new NodeFilesystem(), findGrant: (leaseId) => leaseId === "lse_1" ? { grantedAt: 1_000, id: leaseId, platform: "ios" } : undefined, idGenerator: sequenceIdGenerator("up"), @@ -1491,7 +1497,17 @@ async function filesRig(options: { readonly limits?: LeaseFilesLimits } = {}) { rig.app.request(`/v1/leases/lse_1/files/${name}`, { body, headers, method: "PUT" }); const get = (name: string, headers: Record = agentAuth) => rig.app.request(`/v1/leases/lse_1/files/${name}`, { headers }); - return { ...rig, dataDirectory, get, put }; + const leaseFolder = join( + dataDirectory, + "lease-files", + `${Buffer.from("lse_1").toString("hex")}-1000`, + ); + return { ...rig, dataDirectory, get, leaseFolder, put }; +} + +// why: what a lease folder holds, temporary upload files included, so "nothing stored" means nothing on disk. +async function folderEntries(folder: string): Promise { + return readdir(folder).catch(() => []); } // why: comparing megabytes with `toEqual` walks them one by one and takes seconds; their digests say the same. @@ -1547,4 +1563,46 @@ describe("a lease's files on a worker", () => { 404, ); }); + + it("a lease holder PUTs past a limit and gets the limit's code, with nothing stored and the previous file kept", async () => { + const limits = { fileBytes: 10, leaseBytes: 100, silenceMs: 330_000 }; + const big = new Uint8Array(11); + const rig = await filesRig({ limits }); + const refusal = async (response: Response) => + (await response.json()) as { error: { code: string; message: string } }; + const text = async (response: Response) => + new TextDecoder().decode(await response.arrayBuffer()); + + expect((await rig.put("kept.bin", "12345")).status).toBe(201); + const tooBig = await rig.put("kept.bin", big); + expect(tooBig.status).toBe(413); + expect((await refusal(tooBig)).error).toEqual({ + code: "FILE_TOO_LARGE", + message: "File kept.bin is over the 2 GiB limit for one file", + name: "kept.bin", + }); + expect(await text(await rig.get("kept.bin"))).toBe("12345"); + expect(await folderEntries(rig.leaseFolder)).toEqual(["kept.bin"]); + + let pulled = false; + const unread = new ReadableStream( + { + pull(c) { + pulled = true; + c.close(); + }, + }, + { highWaterMark: 0 }, + ); + const declared = await rig.app.request("/v1/leases/lse_1/files/declared.bin", { + body: unread, + duplex: "half", + headers: { ...agentAuth, "content-length": "11" }, + method: "PUT", + } as RequestInit); + expect(declared.status).toBe(413); + expect((await refusal(declared)).error.code).toBe("FILE_TOO_LARGE"); + expect(pulled).toBe(false); + expect(await folderEntries(rig.leaseFolder)).toEqual(["kept.bin"]); + }); }); From 6306cfabce8dde12d863d9d602a58418f9a7667f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:28:32 +0100 Subject: [PATCH 07/30] feat(lease-files): an upload past 2 GiB is refused 413 FILE_TOO_LARGE and stores nothing (#1356) --- src/lease-files/guarded-body.ts | 30 ++++++++++++++++++++++++++++++ src/lease-files/handler.ts | 13 ++++++++++++- src/lease-files/lease-files.ts | 30 +++++++++++++++++++++++++----- 3 files changed, 67 insertions(+), 6 deletions(-) create mode 100644 src/lease-files/guarded-body.ts diff --git a/src/lease-files/guarded-body.ts b/src/lease-files/guarded-body.ts new file mode 100644 index 000000000..1d5171e5f --- /dev/null +++ b/src/lease-files/guarded-body.ts @@ -0,0 +1,30 @@ +/** + * why: an upload's body is read through this, so every limit is checked as the bytes arrive: a body + * that breaks one errors the stream, and the write that reads it fails with that error. + */ +export function guardedBody( + source: ReadableStream, + onChunk: (chunk: Uint8Array) => void, +): ReadableStream { + const reader = source.getReader(); + return new ReadableStream( + { + async pull(controller) { + try { + const piece = await reader.read(); + if (piece.done) { + controller.close(); + return; + } + onChunk(piece.value); + controller.enqueue(piece.value); + } catch (error: unknown) { + void reader.cancel().catch(() => undefined); + controller.error(error); + } + }, + cancel: (reason) => reader.cancel(reason), + }, + { highWaterMark: 0 }, + ); +} diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index fad19abef..73d3e0ef1 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -33,7 +33,9 @@ async function serve( requireFileName(name); if (request.method === "PUT") { const body = request.body ?? new ReadableStream({ start: (c) => c.close() }); - return Response.json(await store.put(grant, name, body), { status: 201 }); + return Response.json(await store.put(grant, name, body, contentLengthOf(request)), { + status: 201, + }); } const file = await store.openFile(grant, name); const length = String(file.size); @@ -47,3 +49,12 @@ async function serve( }, }); } + +function contentLengthOf(request: Request): number | undefined { + const header = request.headers.get("content-length"); + if (header === null) return undefined; + if (!/^\d+$/.test(header)) { + throw new LeaseFilesError("BAD_REQUEST", "Content-Length must be a non-negative integer", {}); + } + return Number(header); +} diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts index 5d209ce44..6378f0f01 100644 --- a/src/lease-files/lease-files.ts +++ b/src/lease-files/lease-files.ts @@ -1,6 +1,8 @@ import { join } from "node:path"; import type { Identity } from "../auth/index.js"; +import { LeaseFilesError } from "./errors.js"; +import { guardedBody } from "./guarded-body.js"; import { DEFAULT_LIMITS } from "./limits.js"; import { handleRequest } from "./handler.js"; import type { @@ -21,6 +23,7 @@ export interface LeaseFileStore { grant: LeaseFilesGrant, name: string, body: ReadableStream, + contentLength: number | undefined, ): Promise<{ readonly name: string; readonly size: number }>; openFile(grant: LeaseFilesGrant, name: string): Promise; findGrant(leaseId: string): LeaseFilesGrant | undefined; @@ -29,7 +32,6 @@ export interface LeaseFileStore { export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { const { filesystem } = deps; const limits = deps.limits ?? DEFAULT_LIMITS; - void limits; const rootOf = () => join(deps.dataDirectory, "lease-files"); const pathOf = (grant: LeaseFilesGrant) => join(rootOf(), folderKey(grant.id, grant.grantedAt)); @@ -47,12 +49,30 @@ export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { const store: LeaseFileStore = { findGrant: deps.findGrant, openFile, - put: async (grant, name, body) => { + put: async (grant, name, body, contentLength) => { + const tooLarge = () => + new LeaseFilesError("FILE_TOO_LARGE", `File ${name} is over the 2 GiB limit for one file`, { + name, + }); + if (contentLength !== undefined && contentLength > limits.fileBytes) throw tooLarge(); const folder = await folderOf(grant); const temporary = join(folder, `.upload-${deps.idGenerator.generate()}`); - const size = await filesystem.writeFileStream(temporary, body, { mode: 0o600 }); - await filesystem.rename(temporary, join(folder, name)); - return { name, size }; + let received = 0; + try { + const size = await filesystem.writeFileStream( + temporary, + guardedBody(body, (chunk) => { + received += chunk.byteLength; + if (received > limits.fileBytes) throw tooLarge(); + }), + { mode: 0o600 }, + ); + await filesystem.rename(temporary, join(folder, name)); + return { name, size }; + } catch (error: unknown) { + await filesystem.rm(temporary); + throw error; + } }, }; From 2923cb7703e6207e287542ad441f8eccabd93068 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:29:11 +0100 Subject: [PATCH 08/30] test: a lease holder PUTs past a limit and gets the limit's code, with nothing stored and the previous file kept (#1356) --- src/http/app-leases.test.ts | 86 ++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index d48d7dc79..53a0abaa1 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { mkdtemp, readdir, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -1510,6 +1510,36 @@ async function folderEntries(folder: string): Promise { return readdir(folder).catch(() => []); } +// why: a request body the test feeds by hand, so a test can hold an upload open after its first bytes arrived. +function heldBody(first: Uint8Array) { + let release!: () => void; + const firstConsumed = new Promise((resolve) => { + release = resolve; + }); + let controller!: ReadableStreamDefaultController; + let pulls = 0; + const stream = new ReadableStream( + { + start(c) { + controller = c; + }, + pull(c) { + pulls += 1; + if (pulls === 1) c.enqueue(first); + else release(); + }, + }, + { highWaterMark: 0 }, + ); + return { firstConsumed, finish: () => controller.close(), stream }; +} + +class LowDiskFilesystem extends NodeFilesystem { + override diskFree(): Promise { + return Promise.resolve(5 * 1024 ** 3); + } +} + // why: comparing megabytes with `toEqual` walks them one by one and takes seconds; their digests say the same. function sha256(bytes: Uint8Array): string { return createHash("sha256").update(bytes).digest("hex"); @@ -1604,5 +1634,59 @@ describe("a lease's files on a worker", () => { expect((await refusal(declared)).error.code).toBe("FILE_TOO_LARGE"); expect(pulled).toBe(false); expect(await folderEntries(rig.leaseFolder)).toEqual(["kept.bin"]); + + const roomy = { fileBytes: 1000, leaseBytes: 100, silenceMs: 330_000 }; + const full = await filesRig({ limits: roomy }); + await mkdir(full.leaseFolder, { recursive: true }); + await writeFile(join(full.leaseFolder, "my file.png"), new Uint8Array(60)); + expect((await full.put("fits.bin", new Uint8Array(40))).status).toBe(201); + await rm(join(full.leaseFolder, "fits.bin")); + for (const headers of [agentAuth, { ...agentAuth, "content-length": "50" }]) { + const over = await full.put("over.bin", new Uint8Array(50), headers); + expect(over.status).toBe(413); + expect((await refusal(over)).error).toEqual({ + code: "LEASE_FILES_FULL", + leaseId: "lse_1", + message: "Lease lse_1 holds 60 bytes of files; this upload would pass the 4 GiB limit", + usedBytes: 60, + }); + expect(await folderEntries(full.leaseFolder)).toEqual(["my file.png"]); + } + + const together = await filesRig({ limits: roomy }); + const first = heldBody(new Uint8Array(60)); + const running = together.app.request("/v1/leases/lse_1/files/a.bin", { + body: first.stream, + duplex: "half", + headers: agentAuth, + method: "PUT", + } as RequestInit); + await first.firstConsumed; + const second = await together.put("b.bin", new Uint8Array(60)); + expect(second.status).toBe(413); + expect((await refusal(second)).error.code).toBe("LEASE_FILES_FULL"); + first.finish(); + expect((await running).status).toBe(201); + expect(await folderEntries(together.leaseFolder)).toEqual(["a.bin"]); + + const replacing = await filesRig({ limits: roomy }); + expect((await replacing.put("x.bin", new Uint8Array(80))).status).toBe(201); + expect((await replacing.put("x.bin", new Uint8Array(80))).status).toBe(201); + + const lowDisk = await filesRig({ + diskPressureThreshold: 10 * 1024 ** 3, + filesystem: new LowDiskFilesystem(), + }); + const noDisk = await lowDisk.put("fixture.tar", "x"); + expect(noDisk.status).toBe(422); + expect((await refusal(noDisk)).error).toEqual({ + availableBytes: 5 * 1024 ** 3, + code: "INSUFFICIENT_DISK_SPACE", + message: + "Not enough free disk space to store fixture.tar: the worker keeps 10.0 GiB free, only 5.0 GiB available", + platform: "ios", + requiredBytes: 10 * 1024 ** 3, + }); + expect(await folderEntries(lowDisk.leaseFolder)).toEqual([]); }); }); From d86cf0aaee4d1530e6265cfbd1729f3452aaf6e4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:29:24 +0100 Subject: [PATCH 09/30] feat(lease-files): a lease's folder holds at most 4 GiB and a worker under its disk threshold stores nothing (#1356) --- src/lease-files/lease-files.ts | 83 ++++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 3 deletions(-) diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts index 6378f0f01..9050505e9 100644 --- a/src/lease-files/lease-files.ts +++ b/src/lease-files/lease-files.ts @@ -29,6 +29,18 @@ export interface LeaseFileStore { findGrant(leaseId: string): LeaseFilesGrant | undefined; } +interface RunningUpload { + received: number; +} + +interface GrantState { + readonly uploads: Set; +} + +function gibibytes(bytes: number): string { + return `${(bytes / 1024 ** 3).toFixed(1)} GiB`; +} + export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { const { filesystem } = deps; const limits = deps.limits ?? DEFAULT_LIMITS; @@ -46,6 +58,41 @@ export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { return { name, ...file }; }; + const states = new Map(); + const stateOf = (grant: LeaseFilesGrant): GrantState => { + const key = folderKey(grant.id, grant.grantedAt); + let state = states.get(key); + if (state === undefined) { + state = { uploads: new Set() }; + states.set(key, state); + } + return state; + }; + + // why: a file listed a moment ago may be gone (a command removed it), and it then counts for nothing. + const sizeOf = async (path: string): Promise => { + try { + return (await filesystem.stat(path)).size; + } catch (error: unknown) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return 0; + throw error; + } + }; + + // why: every entry counts, whoever wrote it (subfolders walked, symlinks not followed); upload temp files are the running uploads' received bytes instead. + const folderBytes = async (folder: string, replacing: string | undefined): Promise => { + let total = 0; + for (const entry of await filesystem.readdir(folder)) { + if (entry.startsWith(".upload-")) continue; + if (replacing !== undefined && entry.toLowerCase() === replacing) continue; + const child = join(folder, entry); + const details = await filesystem.lstat(child).catch(() => undefined); + if (details?.kind === "directory") total += await folderBytes(child, undefined); + else if (details?.kind === "file") total += await sizeOf(child); + } + return total; + }; + const store: LeaseFileStore = { findGrant: deps.findGrant, openFile, @@ -54,16 +101,44 @@ export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { new LeaseFilesError("FILE_TOO_LARGE", `File ${name} is over the 2 GiB limit for one file`, { name, }); + const full = (usedBytes: number) => + new LeaseFilesError( + "LEASE_FILES_FULL", + `Lease ${grant.id} holds ${String(usedBytes)} bytes of files; this upload would pass the 4 GiB limit`, + { leaseId: grant.id, usedBytes }, + ); if (contentLength !== undefined && contentLength > limits.fileBytes) throw tooLarge(); const folder = await folderOf(grant); + const free = await filesystem.diskFree(folder); + if (free < deps.diskPressureThreshold) { + throw new LeaseFilesError( + "INSUFFICIENT_DISK_SPACE", + `Not enough free disk space to store ${name}: the worker keeps ${gibibytes(deps.diskPressureThreshold)} free, only ${gibibytes(free)} available`, + { + availableBytes: free, + platform: grant.platform, + requiredBytes: deps.diskPressureThreshold, + }, + ); + } + const state = stateOf(grant); + const stored = await folderBytes(folder, name.toLowerCase()); + const upload: RunningUpload = { received: 0 }; + const others = () => [...state.uploads].reduce((sum, running) => sum + running.received, 0); + if (stored + others() + (contentLength ?? 0) > limits.leaseBytes) + throw full(stored + others()); + state.uploads.add(upload); const temporary = join(folder, `.upload-${deps.idGenerator.generate()}`); - let received = 0; try { const size = await filesystem.writeFileStream( temporary, guardedBody(body, (chunk) => { - received += chunk.byteLength; - if (received > limits.fileBytes) throw tooLarge(); + const beforeThis = others(); + upload.received += chunk.byteLength; + if (upload.received > limits.fileBytes) throw tooLarge(); + if (stored + beforeThis + upload.received > limits.leaseBytes) { + throw full(stored + beforeThis); + } }), { mode: 0o600 }, ); @@ -72,6 +147,8 @@ export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { } catch (error: unknown) { await filesystem.rm(temporary); throw error; + } finally { + state.uploads.delete(upload); } }, }; From 35aa36e5e4c845b275c711a9ba566c5d6aeba26a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:31:54 +0100 Subject: [PATCH 10/30] feat(lease-files): a cut upload keeps the previous file, silence ends it 408, a second upload to a name gets 409 (#1356) --- src/http/app-leases.test.ts | 127 ++++++++++++++++++--- src/lease-files/guarded-body.ts | 68 ++++++++++-- src/lease-files/handler.ts | 9 +- src/lease-files/lease-files.ts | 160 +-------------------------- src/lease-files/store.ts | 190 ++++++++++++++++++++++++++++++++ 5 files changed, 372 insertions(+), 182 deletions(-) create mode 100644 src/lease-files/store.ts diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 53a0abaa1..69fc60fa8 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1510,28 +1510,45 @@ async function folderEntries(folder: string): Promise { return readdir(folder).catch(() => []); } -// why: a request body the test feeds by hand, so a test can hold an upload open after its first bytes arrived. -function heldBody(first: Uint8Array) { - let release!: () => void; - const firstConsumed = new Promise((resolve) => { - release = resolve; - }); +// why: a request body the test feeds by hand: `push` resolves once the upload has taken the bytes and asks for more, so a test acts only after the store has seen them. +function liveBody() { let controller!: ReadableStreamDefaultController; - let pulls = 0; + let waiting: (() => void)[] = []; + let pulled!: () => void; + const firstPull = new Promise((resolve) => { + pulled = resolve; + }); const stream = new ReadableStream( { start(c) { controller = c; }, - pull(c) { - pulls += 1; - if (pulls === 1) c.enqueue(first); - else release(); + pull() { + pulled(); + for (const resume of waiting.splice(0)) resume(); }, }, { highWaterMark: 0 }, ); - return { firstConsumed, finish: () => controller.close(), stream }; + return { + fail: (error: Error) => controller.error(error), + finish: () => controller.close(), + firstPull, + push: (bytes: Uint8Array) => + new Promise((resolve) => { + controller.enqueue(bytes); + waiting = [...waiting, resolve]; + }), + stream, + }; +} + +// why: a request the code under test must answer; when it never does, the assertion on `undefined` fails by name where an await would time the whole test out. +function answered(response: Promise | Response): Promise { + return Promise.race([ + Promise.resolve(response), + new Promise((resolve) => setTimeout(() => resolve(undefined), 2_000)), + ]); } class LowDiskFilesystem extends NodeFilesystem { @@ -1654,14 +1671,14 @@ describe("a lease's files on a worker", () => { } const together = await filesRig({ limits: roomy }); - const first = heldBody(new Uint8Array(60)); + const first = liveBody(); const running = together.app.request("/v1/leases/lse_1/files/a.bin", { body: first.stream, duplex: "half", headers: agentAuth, method: "PUT", } as RequestInit); - await first.firstConsumed; + await first.push(new Uint8Array(60)); const second = await together.put("b.bin", new Uint8Array(60)); expect(second.status).toBe(413); expect((await refusal(second)).error.code).toBe("LEASE_FILES_FULL"); @@ -1689,4 +1706,86 @@ describe("a lease's files on a worker", () => { }); expect(await folderEntries(lowDisk.leaseFolder)).toEqual([]); }); + + it("a lease holder whose PUT is cut or goes silent keeps the previous file or none; a second PUT to a name being uploaded gets 409 FILE_BUSY", async () => { + const rig = await filesRig(); + const uploading = (name: string, body: ReadableStream) => + rig.app.request(`/v1/leases/lse_1/files/${name}`, { + body, + duplex: "half", + headers: agentAuth, + method: "PUT", + } as RequestInit); + const text = async (response: Response) => + new TextDecoder().decode(await response.arrayBuffer()); + const bytes = new TextEncoder().encode("new"); + + const cutFresh = liveBody(); + const cutting = uploading("fresh.bin", cutFresh.stream); + await cutFresh.push(bytes); + cutFresh.fail(new Error("socket hang up")); + expect(await answered(cutting)).toBeDefined(); + expect(await folderEntries(rig.leaseFolder)).toEqual([]); + + expect((await rig.put("kept.bin", "old")).status).toBe(201); + const cutKept = liveBody(); + const cuttingKept = uploading("kept.bin", cutKept.stream); + await cutKept.push(bytes); + cutKept.fail(new Error("socket hang up")); + expect(await answered(cuttingKept)).toBeDefined(); + expect(await folderEntries(rig.leaseFolder)).toEqual(["kept.bin"]); + expect(await text(await rig.get("kept.bin"))).toBe("old"); + + const silent = liveBody(); + const silentRequest = uploading("kept.bin", silent.stream); + await silent.push(bytes); + rig.clock.advance(330_000); + const stalled = await answered(silentRequest); + expect(stalled?.status).toBe(408); + expect(await stalled?.json()).toEqual({ + error: { + code: "UPLOAD_STALLED", + message: "No bytes of kept.bin arrived for 330 s", + name: "kept.bin", + }, + }); + expect(await folderEntries(rig.leaseFolder)).toEqual(["kept.bin"]); + expect(await text(await rig.get("kept.bin"))).toBe("old"); + + const mute = liveBody(); + const muteRequest = uploading("mute.bin", mute.stream); + await mute.firstPull; + rig.clock.advance(330_000); + expect((await answered(muteRequest))?.status).toBe(408); + + const moving = liveBody(); + const movingRequest = uploading("moving.bin", moving.stream); + for (const chunk of ["a", "b", "c"]) { + await moving.push(new TextEncoder().encode(chunk)); + rig.clock.advance(200_000); + } + moving.finish(); + expect((await movingRequest).status).toBe(201); + expect(await text(await rig.get("moving.bin"))).toBe("abc"); + + for (const [firstName, secondName] of [ + ["x.bin", "x.bin"], + ["A.tar", "a.tar"], + ] as const) { + const running = liveBody(); + const runningRequest = uploading(firstName, running.stream); + await running.push(bytes); + const refused = await rig.put(secondName, "other"); + expect(refused.status).toBe(409); + expect(await refused.json()).toEqual({ + error: { + code: "FILE_BUSY", + message: `File ${secondName} is being uploaded by another request`, + name: secondName, + }, + }); + running.finish(); + expect((await runningRequest).status).toBe(201); + } + }); }); diff --git a/src/lease-files/guarded-body.ts b/src/lease-files/guarded-body.ts index 1d5171e5f..25fc8cf60 100644 --- a/src/lease-files/guarded-body.ts +++ b/src/lease-files/guarded-body.ts @@ -1,29 +1,75 @@ +import type { Clock } from "../ports/index.js"; + +/** why: the request body failed on its own (the caller went away), apart from a limit or a write the store raised. */ +export class BodyCutError extends Error { + constructor(cause: unknown) { + super("The request body ended before it was complete", { cause }); + this.name = "BodyCutError"; + } +} + +export interface BodyGuard { + readonly clock: Clock; + readonly silenceMs: number; + readonly onStalled: () => Error; + readonly onChunk: (chunk: Uint8Array) => void; +} + /** - * why: an upload's body is read through this, so every limit is checked as the bytes arrive: a body - * that breaks one errors the stream, and the write that reads it fails with that error. + * why: an upload's body is read through this, so every limit is checked as the bytes arrive and the + * silence bound counts from the start or the last byte: a body that breaks one errors the stream, and + * the write that reads it fails with that error. */ export function guardedBody( source: ReadableStream, - onChunk: (chunk: Uint8Array) => void, + guard: BodyGuard, ): ReadableStream { const reader = source.getReader(); + let rejectStall!: (error: Error) => void; + const stalled = new Promise((_, reject) => { + rejectStall = reject; + }); + stalled.catch(() => undefined); + let stall: Error | undefined; + const arm = () => + guard.clock.setTimer(guard.silenceMs, () => { + stall = guard.onStalled(); + rejectStall(stall); + }); + let timer = arm(); + const disarm = () => guard.clock.cancel(timer); + return new ReadableStream( { async pull(controller) { + let piece: ReadableStreamReadResult; + try { + piece = await Promise.race([reader.read(), stalled]); + } catch (error: unknown) { + disarm(); + void reader.cancel().catch(() => undefined); + controller.error(error === stall ? error : new BodyCutError(error)); + return; + } + disarm(); + if (piece.done) { + controller.close(); + return; + } try { - const piece = await reader.read(); - if (piece.done) { - controller.close(); - return; - } - onChunk(piece.value); - controller.enqueue(piece.value); + guard.onChunk(piece.value); } catch (error: unknown) { void reader.cancel().catch(() => undefined); controller.error(error); + return; } + timer = arm(); + controller.enqueue(piece.value); + }, + cancel: (reason) => { + disarm(); + return reader.cancel(reason); }, - cancel: (reason) => reader.cancel(reason), }, { highWaterMark: 0 }, ); diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index 73d3e0ef1..f6b5c4fef 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -1,11 +1,12 @@ import { ERROR_TABLE } from "../contract/index.js"; import { LeaseFilesError } from "./errors.js"; -import type { LeaseFileStore } from "./lease-files.js"; +import { BodyCutError } from "./guarded-body.js"; +import type { LeaseFolders } from "./store.js"; import { requireFileName } from "./names.js"; import type { LeaseFilesLease } from "./types.js"; export async function handleRequest( - store: LeaseFileStore, + store: LeaseFolders, request: Request, lease: LeaseFilesLease, name: string | undefined, @@ -13,6 +14,8 @@ export async function handleRequest( try { return await serve(store, request, lease, name); } catch (error: unknown) { + // why: a caller that went away mid-upload cannot be answered, and is no fault of the daemon's. + if (error instanceof BodyCutError) return new Response(null, { status: 499 }); if (!(error instanceof LeaseFilesError)) throw error; const refusal: LeaseFilesError = error; return Response.json( @@ -23,7 +26,7 @@ export async function handleRequest( } async function serve( - store: LeaseFileStore, + store: LeaseFolders, request: Request, lease: LeaseFilesLease, name: string | undefined, diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts index 9050505e9..e3c0163db 100644 --- a/src/lease-files/lease-files.ts +++ b/src/lease-files/lease-files.ts @@ -1,168 +1,20 @@ -import { join } from "node:path"; - import type { Identity } from "../auth/index.js"; -import { LeaseFilesError } from "./errors.js"; -import { guardedBody } from "./guarded-body.js"; -import { DEFAULT_LIMITS } from "./limits.js"; import { handleRequest } from "./handler.js"; -import type { - LeaseFileView, - LeaseFiles, - LeaseFilesDeps, - LeaseFilesGrant, - LeaseFilesLease, -} from "./types.js"; - -export function folderKey(id: string, grantedAt: number): string { - return `${Buffer.from(id, "utf8").toString("hex")}-${String(grantedAt)}`; -} - -/** why: the store's part the HTTP handler calls; `LeaseFiles` is the surface other modules get. */ -export interface LeaseFileStore { - put( - grant: LeaseFilesGrant, - name: string, - body: ReadableStream, - contentLength: number | undefined, - ): Promise<{ readonly name: string; readonly size: number }>; - openFile(grant: LeaseFilesGrant, name: string): Promise; - findGrant(leaseId: string): LeaseFilesGrant | undefined; -} - -interface RunningUpload { - received: number; -} - -interface GrantState { - readonly uploads: Set; -} - -function gibibytes(bytes: number): string { - return `${(bytes / 1024 ** 3).toFixed(1)} GiB`; -} +import { LeaseFolders } from "./store.js"; +import type { LeaseFiles, LeaseFilesDeps, LeaseFilesLease } from "./types.js"; export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { - const { filesystem } = deps; - const limits = deps.limits ?? DEFAULT_LIMITS; - const rootOf = () => join(deps.dataDirectory, "lease-files"); - const pathOf = (grant: LeaseFilesGrant) => join(rootOf(), folderKey(grant.id, grant.grantedAt)); - - const folderOf = async (grant: LeaseFilesGrant): Promise => { - const folder = pathOf(grant); - await filesystem.mkdirp(folder, { mode: 0o700 }); - return folder; - }; - - const openFile = async (grant: LeaseFilesGrant, name: string): Promise => { - const file = await filesystem.openFile(join(pathOf(grant), name)); - return { name, ...file }; - }; - - const states = new Map(); - const stateOf = (grant: LeaseFilesGrant): GrantState => { - const key = folderKey(grant.id, grant.grantedAt); - let state = states.get(key); - if (state === undefined) { - state = { uploads: new Set() }; - states.set(key, state); - } - return state; - }; - - // why: a file listed a moment ago may be gone (a command removed it), and it then counts for nothing. - const sizeOf = async (path: string): Promise => { - try { - return (await filesystem.stat(path)).size; - } catch (error: unknown) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return 0; - throw error; - } - }; - - // why: every entry counts, whoever wrote it (subfolders walked, symlinks not followed); upload temp files are the running uploads' received bytes instead. - const folderBytes = async (folder: string, replacing: string | undefined): Promise => { - let total = 0; - for (const entry of await filesystem.readdir(folder)) { - if (entry.startsWith(".upload-")) continue; - if (replacing !== undefined && entry.toLowerCase() === replacing) continue; - const child = join(folder, entry); - const details = await filesystem.lstat(child).catch(() => undefined); - if (details?.kind === "directory") total += await folderBytes(child, undefined); - else if (details?.kind === "file") total += await sizeOf(child); - } - return total; - }; - - const store: LeaseFileStore = { - findGrant: deps.findGrant, - openFile, - put: async (grant, name, body, contentLength) => { - const tooLarge = () => - new LeaseFilesError("FILE_TOO_LARGE", `File ${name} is over the 2 GiB limit for one file`, { - name, - }); - const full = (usedBytes: number) => - new LeaseFilesError( - "LEASE_FILES_FULL", - `Lease ${grant.id} holds ${String(usedBytes)} bytes of files; this upload would pass the 4 GiB limit`, - { leaseId: grant.id, usedBytes }, - ); - if (contentLength !== undefined && contentLength > limits.fileBytes) throw tooLarge(); - const folder = await folderOf(grant); - const free = await filesystem.diskFree(folder); - if (free < deps.diskPressureThreshold) { - throw new LeaseFilesError( - "INSUFFICIENT_DISK_SPACE", - `Not enough free disk space to store ${name}: the worker keeps ${gibibytes(deps.diskPressureThreshold)} free, only ${gibibytes(free)} available`, - { - availableBytes: free, - platform: grant.platform, - requiredBytes: deps.diskPressureThreshold, - }, - ); - } - const state = stateOf(grant); - const stored = await folderBytes(folder, name.toLowerCase()); - const upload: RunningUpload = { received: 0 }; - const others = () => [...state.uploads].reduce((sum, running) => sum + running.received, 0); - if (stored + others() + (contentLength ?? 0) > limits.leaseBytes) - throw full(stored + others()); - state.uploads.add(upload); - const temporary = join(folder, `.upload-${deps.idGenerator.generate()}`); - try { - const size = await filesystem.writeFileStream( - temporary, - guardedBody(body, (chunk) => { - const beforeThis = others(); - upload.received += chunk.byteLength; - if (upload.received > limits.fileBytes) throw tooLarge(); - if (stored + beforeThis + upload.received > limits.leaseBytes) { - throw full(stored + beforeThis); - } - }), - { mode: 0o600 }, - ); - await filesystem.rename(temporary, join(folder, name)); - return { name, size }; - } catch (error: unknown) { - await filesystem.rm(temporary); - throw error; - } finally { - state.uploads.delete(upload); - } - }, - }; - + const folders = new LeaseFolders(deps); return { - folderOf, + folderOf: (grant) => folders.folderOf(grant), handle: ( request: Request, _identity: Identity, lease: LeaseFilesLease, name: string | undefined, - ) => handleRequest(store, request, lease, name), + ) => handleRequest(folders, request, lease, name), leaseEnd: { leaseEnded: () => Promise.resolve() }, - openFile, + openFile: (grant, name) => folders.openFile(grant, name), sweep: () => Promise.resolve(), }; } diff --git a/src/lease-files/store.ts b/src/lease-files/store.ts new file mode 100644 index 000000000..c5b3aa90d --- /dev/null +++ b/src/lease-files/store.ts @@ -0,0 +1,190 @@ +import { join } from "node:path"; + +import { LeaseFilesError } from "./errors.js"; +import { guardedBody } from "./guarded-body.js"; +import { DEFAULT_LIMITS } from "./limits.js"; +import type { LeaseFileView, LeaseFilesDeps, LeaseFilesGrant } from "./types.js"; + +export function folderKey(id: string, grantedAt: number): string { + return `${Buffer.from(id, "utf8").toString("hex")}-${String(grantedAt)}`; +} + +interface RunningUpload { + received: number; +} + +interface GrantState { + readonly uploads: Set; + // why: file names compare ignoring case, so a name's writer slot is its lowercase spelling. + readonly writers: Set; +} + +function gibibytes(bytes: number): string { + return `${(bytes / 1024 ** 3).toFixed(1)} GiB`; +} + +function tooLarge(name: string): LeaseFilesError { + return new LeaseFilesError( + "FILE_TOO_LARGE", + `File ${name} is over the 2 GiB limit for one file`, + { + name, + }, + ); +} + +function leaseFull(grant: LeaseFilesGrant, usedBytes: number): LeaseFilesError { + return new LeaseFilesError( + "LEASE_FILES_FULL", + `Lease ${grant.id} holds ${String(usedBytes)} bytes of files; this upload would pass the 4 GiB limit`, + { leaseId: grant.id, usedBytes }, + ); +} + +/** why: every lease folder of a worker, behind the one set of rules the HTTP handler and exec share. */ +export class LeaseFolders { + readonly #deps: LeaseFilesDeps; + readonly #limits; + readonly #states = new Map(); + + constructor(deps: LeaseFilesDeps) { + this.#deps = deps; + this.#limits = deps.limits ?? DEFAULT_LIMITS; + } + + findGrant(leaseId: string): LeaseFilesGrant | undefined { + return this.#deps.findGrant(leaseId); + } + + async folderOf(grant: LeaseFilesGrant): Promise { + const folder = this.#pathOf(grant); + await this.#deps.filesystem.mkdirp(folder, { mode: 0o700 }); + return folder; + } + + async openFile(grant: LeaseFilesGrant, name: string): Promise { + const file = await this.#deps.filesystem.openFile(join(this.#pathOf(grant), name)); + return { name, ...file }; + } + + async put( + grant: LeaseFilesGrant, + name: string, + body: ReadableStream, + contentLength: number | undefined, + ): Promise<{ readonly name: string; readonly size: number }> { + if (contentLength !== undefined && contentLength > this.#limits.fileBytes) { + throw tooLarge(name); + } + const state = this.#stateOf(grant); + const slot = name.toLowerCase(); + if (state.writers.has(slot)) { + throw new LeaseFilesError("FILE_BUSY", `File ${name} is being uploaded by another request`, { + name, + }); + } + state.writers.add(slot); + try { + return await this.#receive(grant, name, state, body, contentLength); + } finally { + state.writers.delete(slot); + } + } + + async #receive( + grant: LeaseFilesGrant, + name: string, + state: GrantState, + body: ReadableStream, + contentLength: number | undefined, + ): Promise<{ readonly name: string; readonly size: number }> { + const { filesystem, diskPressureThreshold } = this.#deps; + const folder = await this.folderOf(grant); + const free = await filesystem.diskFree(folder); + if (free < diskPressureThreshold) { + throw new LeaseFilesError( + "INSUFFICIENT_DISK_SPACE", + `Not enough free disk space to store ${name}: the worker keeps ${gibibytes(diskPressureThreshold)} free, only ${gibibytes(free)} available`, + { availableBytes: free, platform: grant.platform, requiredBytes: diskPressureThreshold }, + ); + } + const stored = await this.#folderBytes(folder, name.toLowerCase()); + const upload: RunningUpload = { received: 0 }; + const others = () => [...state.uploads].reduce((sum, running) => sum + running.received, 0); + if (stored + others() + (contentLength ?? 0) > this.#limits.leaseBytes) { + throw leaseFull(grant, stored + others()); + } + state.uploads.add(upload); + const temporary = join(folder, `.upload-${this.#deps.idGenerator.generate()}`); + try { + const size = await filesystem.writeFileStream( + temporary, + guardedBody(body, { + clock: this.#deps.clock, + onChunk: (chunk) => { + const beforeThis = others(); + upload.received += chunk.byteLength; + if (upload.received > this.#limits.fileBytes) throw tooLarge(name); + if (stored + beforeThis + upload.received > this.#limits.leaseBytes) { + throw leaseFull(grant, stored + beforeThis); + } + }, + onStalled: () => + new LeaseFilesError( + "UPLOAD_STALLED", + `No bytes of ${name} arrived for ${String(this.#limits.silenceMs / 1000)} s`, + { name }, + ), + silenceMs: this.#limits.silenceMs, + }), + { mode: 0o600 }, + ); + await filesystem.rename(temporary, join(folder, name)); + return { name, size }; + } catch (error: unknown) { + await filesystem.rm(temporary); + throw error; + } finally { + state.uploads.delete(upload); + } + } + + #pathOf(grant: LeaseFilesGrant): string { + return join(this.#deps.dataDirectory, "lease-files", folderKey(grant.id, grant.grantedAt)); + } + + #stateOf(grant: LeaseFilesGrant): GrantState { + const key = folderKey(grant.id, grant.grantedAt); + let state = this.#states.get(key); + if (state === undefined) { + state = { uploads: new Set(), writers: new Set() }; + this.#states.set(key, state); + } + return state; + } + + // why: a file listed a moment ago may be gone (a command removed it), and it then counts for nothing. + async #sizeOf(path: string): Promise { + try { + return (await this.#deps.filesystem.stat(path)).size; + } catch (error: unknown) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return 0; + throw error; + } + } + + // why: every entry counts, whoever wrote it (subfolders walked, symlinks not followed); upload temp files are the running uploads' received bytes instead. + async #folderBytes(folder: string, replacing: string | undefined): Promise { + const { filesystem } = this.#deps; + let total = 0; + for (const entry of await filesystem.readdir(folder)) { + if (entry.startsWith(".upload-")) continue; + if (replacing !== undefined && entry.toLowerCase() === replacing) continue; + const child = join(folder, entry); + const details = await filesystem.lstat(child).catch(() => undefined); + if (details?.kind === "directory") total += await this.#folderBytes(child, undefined); + else if (details?.kind === "file") total += await this.#sizeOf(child); + } + return total; + } +} From 26a171f8b44fcdd03014da2053762ea1913052db Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:32:26 +0100 Subject: [PATCH 11/30] test: a lease holder lists the lease's files and deletes one (#1356) --- src/http/app-leases.test.ts | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 69fc60fa8..8a76d9cdc 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1497,12 +1497,16 @@ async function filesRig( rig.app.request(`/v1/leases/lse_1/files/${name}`, { body, headers, method: "PUT" }); const get = (name: string, headers: Record = agentAuth) => rig.app.request(`/v1/leases/lse_1/files/${name}`, { headers }); + const remove = (name: string, headers: Record = agentAuth) => + rig.app.request(`/v1/leases/lse_1/files/${name}`, { headers, method: "DELETE" }); + const list = (headers: Record = agentAuth) => + rig.app.request("/v1/leases/lse_1/files", { headers }); const leaseFolder = join( dataDirectory, "lease-files", `${Buffer.from("lse_1").toString("hex")}-1000`, ); - return { ...rig, dataDirectory, get, leaseFolder, put }; + return { ...rig, dataDirectory, get, leaseFolder, list, put, remove }; } // why: what a lease folder holds, temporary upload files included, so "nothing stored" means nothing on disk. @@ -1788,4 +1792,32 @@ describe("a lease's files on a worker", () => { expect((await runningRequest).status).toBe(201); } }); + + it("a lease holder lists the lease's files and deletes one", async () => { + const { leaseFolder, list, put, remove } = await filesRig(); + const files = async () => ((await (await list()).json()) as { files: unknown[] }).files; + + expect((await list()).status).toBe(200); + expect(await files()).toEqual([]); + + expect((await put("b.txt", "bb")).status).toBe(201); + expect((await put("a.txt", "a")).status).toBe(201); + await mkdir(join(leaseFolder, "sub")); + await writeFile(join(leaseFolder, "sub", "inner.txt"), "x"); + await writeFile(join(leaseFolder, "my file.png"), "x"); + expect(await files()).toEqual([ + { name: "a.txt", size: 1 }, + { name: "b.txt", size: 2 }, + ]); + + const removed = await remove("a.txt"); + expect(removed.status).toBe(204); + expect(await files()).toEqual([{ name: "b.txt", size: 2 }]); + + const unknown = await remove("a.txt"); + expect(unknown.status).toBe(404); + expect(await unknown.json()).toEqual({ + error: { code: "UNKNOWN_FILE", message: "No file a.txt in this lease", name: "a.txt" }, + }); + }); }); From cd248d13995843123cc2d088b0036179aff9a7f5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:32:47 +0100 Subject: [PATCH 12/30] feat(lease-files): list the files of a lease, delete one, and answer UNKNOWN_FILE for a missing name (#1356) --- src/lease-files/handler.ts | 11 +++++++++- src/lease-files/store.ts | 44 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index f6b5c4fef..4bd489566 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -32,7 +32,12 @@ async function serve( name: string | undefined, ): Promise { const grant = store.findGrant(lease.id); - if (grant === undefined || name === undefined) return new Response(null, { status: 404 }); + if (grant === undefined) { + throw new LeaseFilesError("UNKNOWN_LEASE", `Unknown lease: ${lease.id}`, { + leaseId: lease.id, + }); + } + if (name === undefined) return Response.json({ files: await store.list(grant) }); requireFileName(name); if (request.method === "PUT") { const body = request.body ?? new ReadableStream({ start: (c) => c.close() }); @@ -40,6 +45,10 @@ async function serve( status: 201, }); } + if (request.method === "DELETE") { + await store.remove(grant, name); + return new Response(null, { status: 204 }); + } const file = await store.openFile(grant, name); const length = String(file.size); return new Response(file.read(), { diff --git a/src/lease-files/store.ts b/src/lease-files/store.ts index c5b3aa90d..7f4515b2e 100644 --- a/src/lease-files/store.ts +++ b/src/lease-files/store.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { LeaseFilesError } from "./errors.js"; import { guardedBody } from "./guarded-body.js"; import { DEFAULT_LIMITS } from "./limits.js"; +import { isFileName } from "./names.js"; import type { LeaseFileView, LeaseFilesDeps, LeaseFilesGrant } from "./types.js"; export function folderKey(id: string, grantedAt: number): string { @@ -33,6 +34,10 @@ function tooLarge(name: string): LeaseFilesError { ); } +function unknownFile(name: string): LeaseFilesError { + return new LeaseFilesError("UNKNOWN_FILE", `No file ${name} in this lease`, { name }); +} + function leaseFull(grant: LeaseFilesGrant, usedBytes: number): LeaseFilesError { return new LeaseFilesError( "LEASE_FILES_FULL", @@ -63,8 +68,43 @@ export class LeaseFolders { } async openFile(grant: LeaseFilesGrant, name: string): Promise { - const file = await this.#deps.filesystem.openFile(join(this.#pathOf(grant), name)); - return { name, ...file }; + const stored = (await this.#names(grant)).find((candidate) => candidate === name); + if (stored === undefined) throw unknownFile(name); + const file = await this.#deps.filesystem.openFile(join(this.#pathOf(grant), stored)); + return { name: stored, ...file }; + } + + async list( + grant: LeaseFilesGrant, + ): Promise { + const folder = this.#pathOf(grant); + const files = []; + for (const name of await this.#names(grant)) { + files.push({ name, size: await this.#sizeOf(join(folder, name)) }); + } + return files; + } + + async remove(grant: LeaseFilesGrant, name: string): Promise { + if (!(await this.#names(grant)).includes(name)) throw unknownFile(name); + await this.#deps.filesystem.rm(join(this.#pathOf(grant), name)); + } + + // why: only regular files whose names pass the name rule are the lease's files; a command may have left a subfolder or `my file.png` beside them. + async #names(grant: LeaseFilesGrant): Promise { + const { filesystem } = this.#deps; + const folder = this.#pathOf(grant); + const entries = await filesystem.readdir(folder).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + }); + const names: string[] = []; + for (const entry of entries) { + if (!isFileName(entry)) continue; + const details = await filesystem.lstat(join(folder, entry)).catch(() => undefined); + if (details?.kind === "file") names.push(entry); + } + return names.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); } async put( From 800f8ae76033a8048c1323f11c1596d291ed3df1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:33:01 +0100 Subject: [PATCH 13/30] test: a lease holder's file names match ignoring case (#1356) --- src/http/app-leases.test.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 8a76d9cdc..95e7abf60 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1820,4 +1820,33 @@ describe("a lease's files on a worker", () => { error: { code: "UNKNOWN_FILE", message: "No file a.txt in this lease", name: "a.txt" }, }); }); + + it("a lease holder's file names match ignoring case", async () => { + const { get, leaseFolder, list, put, remove } = await filesRig(); + const text = async (response: Response) => + new TextDecoder().decode(await response.arrayBuffer()); + const names = async () => + ((await (await list()).json()) as { files: { name: string }[] }).files.map( + (file) => file.name, + ); + + expect((await put("A.tar", "upper")).status).toBe(201); + expect(await text(await get("a.tar"))).toBe("upper"); + + expect((await put("a.tar", "lower")).status).toBe(201); + expect(await folderEntries(leaseFolder)).toEqual(["a.tar"]); + expect(await names()).toEqual(["a.tar"]); + expect(await text(await get("A.TAR"))).toBe("lower"); + + expect((await remove("A.TAR")).status).toBe(204); + expect(await names()).toEqual([]); + + await writeFile(join(leaseFolder, "A.tar"), "first"); + await writeFile(join(leaseFolder, "a.tar"), "second"); + if ((await folderEntries(leaseFolder)).length === 2) { + expect(await text(await get("a.tar"))).toBe("second"); + expect(await text(await get("A.TAR"))).toBe("first"); + expect(await names()).toEqual(["A.tar", "a.tar"]); + } + }); }); From 823c278e8a3aff244541bb9b4f1300b24c96da8d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:33:04 +0100 Subject: [PATCH 14/30] feat(lease-files): file names match ignoring case on every disk (#1356) --- src/lease-files/store.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/lease-files/store.ts b/src/lease-files/store.ts index 7f4515b2e..aeaaf5163 100644 --- a/src/lease-files/store.ts +++ b/src/lease-files/store.ts @@ -34,6 +34,15 @@ function tooLarge(name: string): LeaseFilesError { ); } +function sameName(names: readonly string[], name: string): string[] { + return names.filter((candidate) => candidate.toLowerCase() === name.toLowerCase()); +} + +// why: the exact spelling wins; else the first spelling in byte order, which `names` is sorted by. +function lookup(names: readonly string[], name: string): string | undefined { + return names.includes(name) ? name : sameName(names, name)[0]; +} + function unknownFile(name: string): LeaseFilesError { return new LeaseFilesError("UNKNOWN_FILE", `No file ${name} in this lease`, { name }); } @@ -68,7 +77,7 @@ export class LeaseFolders { } async openFile(grant: LeaseFilesGrant, name: string): Promise { - const stored = (await this.#names(grant)).find((candidate) => candidate === name); + const stored = lookup(await this.#names(grant), name); if (stored === undefined) throw unknownFile(name); const file = await this.#deps.filesystem.openFile(join(this.#pathOf(grant), stored)); return { name: stored, ...file }; @@ -86,8 +95,11 @@ export class LeaseFolders { } async remove(grant: LeaseFilesGrant, name: string): Promise { - if (!(await this.#names(grant)).includes(name)) throw unknownFile(name); - await this.#deps.filesystem.rm(join(this.#pathOf(grant), name)); + const spellings = sameName(await this.#names(grant), name); + if (spellings.length === 0) throw unknownFile(name); + for (const spelling of spellings) { + await this.#deps.filesystem.rm(join(this.#pathOf(grant), spelling)); + } } // why: only regular files whose names pass the name rule are the lease's files; a command may have left a subfolder or `my file.png` beside them. @@ -179,6 +191,9 @@ export class LeaseFolders { }), { mode: 0o600 }, ); + for (const other of sameName(await this.#names(grant), name)) { + if (other !== name) await filesystem.rm(join(folder, other)); + } await filesystem.rename(temporary, join(folder, name)); return { name, size }; } catch (error: unknown) { From 3b47da1166012db6fe414228651519a4cdf2d696 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:33:29 +0100 Subject: [PATCH 15/30] test: a lease holder GETs a file and gets it whole or the range it asked for (#1356) --- src/http/app-leases.test.ts | 64 +++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 95e7abf60..acfe6ba8c 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1849,4 +1849,68 @@ describe("a lease's files on a worker", () => { expect(await names()).toEqual(["A.tar", "a.tar"]); } }); + + it("a lease holder GETs a file and gets it whole or the range it asked for", async () => { + const { get, put } = await filesRig(); + const thousand = Uint8Array.from({ length: 1000 }, (_, index) => index % 251); + expect((await put("thousand.bin", thousand)).status).toBe(201); + expect((await put("empty.bin", "")).status).toBe(201); + const ranged = (name: string, range: string) => get(name, { ...agentAuth, range }); + const bytesOf = async (response: Response) => new Uint8Array(await response.arrayBuffer()); + + const whole = await get("thousand.bin"); + expect(whole.status).toBe(200); + expect(Object.fromEntries(whole.headers)).toMatchObject({ + "accept-ranges": "bytes", + "cache-control": "no-store", + "content-length": "1000", + "content-type": "application/octet-stream", + "simlock-content-length": "1000", + }); + expect(await bytesOf(whole)).toEqual(thousand); + + const partial = [ + ["bytes=0-99", 0, 99], + ["bytes=900-", 900, 999], + ["bytes=-100", 900, 999], + ["bytes=990-5000", 990, 999], + ["bytes=-5000", 0, 999], + ] as const; + for (const [range, start, end] of partial) { + const response = await ranged("thousand.bin", range); + expect(response.status).toBe(206); + expect(response.headers.get("content-range")).toBe(`bytes ${start}-${end}/1000`); + expect(response.headers.get("content-length")).toBe(String(end - start + 1)); + expect(response.headers.get("simlock-content-length")).toBe(String(end - start + 1)); + expect(await bytesOf(response)).toEqual(thousand.subarray(start, end + 1)); + } + + for (const [name, range] of [ + ["thousand.bin", "bytes=1000-"], + ["thousand.bin", "bytes=-0"], + ["empty.bin", "bytes=-5"], + ] as const) { + const response = await ranged(name, range); + expect(response.status).toBe(416); + expect(response.headers.get("content-range")).toBe( + `bytes */${name === "empty.bin" ? 0 : 1000}`, + ); + } + + for (const range of ["bytes=0-1,5-9", "bytes=9-5", "items=0-9", "bytes=abc", "bytes=-"]) { + const response = await ranged("thousand.bin", range); + expect(response.status).toBe(200); + expect(await bytesOf(response)).toEqual(thousand); + } + + const unknown = await get("missing.bin"); + expect(unknown.status).toBe(404); + expect(await unknown.json()).toEqual({ + error: { + code: "UNKNOWN_FILE", + message: "No file missing.bin in this lease", + name: "missing.bin", + }, + }); + }); }); From a67de15f55fe253b8c2e0337a64c968bc6930595 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:33:42 +0100 Subject: [PATCH 16/30] feat(lease-files): a GET answers the whole file or one byte range, 416 past the end (#1356) --- src/lease-files/handler.ts | 18 ++++++++++++++++-- src/lease-files/range.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 src/lease-files/range.ts diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index 4bd489566..16a5b1e51 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -3,6 +3,7 @@ import { LeaseFilesError } from "./errors.js"; import { BodyCutError } from "./guarded-body.js"; import type { LeaseFolders } from "./store.js"; import { requireFileName } from "./names.js"; +import { parseRange } from "./range.js"; import type { LeaseFilesLease } from "./types.js"; export async function handleRequest( @@ -50,15 +51,28 @@ async function serve( return new Response(null, { status: 204 }); } const file = await store.openFile(grant, name); - const length = String(file.size); - return new Response(file.read(), { + const answer = parseRange(request.headers.get("range"), file.size); + if (answer.kind === "unsatisfiable") { + await file.close(); + return new Response(null, { + headers: { "content-range": `bytes */${String(file.size)}` }, + status: 416, + }); + } + const [start, end] = answer.kind === "range" ? [answer.start, answer.end] : [0, file.size - 1]; + const length = String(answer.kind === "range" ? end - start + 1 : file.size); + return new Response(file.read(answer.kind === "range" ? { end, start } : undefined), { headers: { "accept-ranges": "bytes", "cache-control": "no-store", "content-length": length, + ...(answer.kind === "range" + ? { "content-range": `bytes ${String(start)}-${String(end)}/${String(file.size)}` } + : {}), "content-type": "application/octet-stream", "simlock-content-length": length, }, + status: answer.kind === "range" ? 206 : 200, }); } diff --git a/src/lease-files/range.ts b/src/lease-files/range.ts new file mode 100644 index 000000000..1b6e16a91 --- /dev/null +++ b/src/lease-files/range.ts @@ -0,0 +1,31 @@ +export type RangeAnswer = + | { readonly kind: "whole" } + | { readonly kind: "range"; readonly start: number; readonly end: number } + | { readonly kind: "unsatisfiable" }; + +const WHOLE: RangeAnswer = { kind: "whole" }; +const SINGLE_BYTE_RANGE = /^bytes=(\d*)-(\d*)$/; + +/** + * why: one `bytes=a-b`, `a-` or `-n` range is served; several ranges, another unit, a malformed + * value and `b < a` are ignored, which answers the whole file. + */ +export function parseRange(header: string | null, size: number): RangeAnswer { + const match = header === null ? null : SINGLE_BYTE_RANGE.exec(header.trim()); + if (match === null) return WHOLE; + const [, first = "", last = ""] = match; + if (first === "" && last === "") return WHOLE; + if (first === "") { + const count = Number(last); + if (count === 0 || size === 0) return { kind: "unsatisfiable" }; + return { end: size - 1, kind: "range", start: Math.max(0, size - count) }; + } + const start = Number(first); + if (last !== "" && Number(last) < start) return WHOLE; + if (start >= size) return { kind: "unsatisfiable" }; + return { + end: last === "" ? size - 1 : Math.min(Number(last), size - 1), + kind: "range", + start, + }; +} From 48a51cb221b926b0a1fc31e1c91a65ed340c97ed Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:33:59 +0100 Subject: [PATCH 17/30] test: a lease holder PUTs a file and gets 201 with its name and size; a GET returns the same bytes (#1356) --- src/http/app-leases.test.ts | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index acfe6ba8c..10b6dabe8 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1,4 +1,4 @@ -import { createHash } from "node:crypto"; +import { createHash, randomFillSync } from "node:crypto"; import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -1569,15 +1569,27 @@ function sha256(bytes: Uint8Array): string { describe("a lease's files on a worker", () => { it("a lease holder PUTs a file and gets 201 with its name and size; a GET returns the same bytes", async () => { const { get, put } = await filesRig(); - const bytes = Uint8Array.from({ length: 3 * 1024 * 1024 }, (_, index) => index % 251); - - const response = await put("fixture.tar", bytes); + const patterned = (length: number): Uint8Array => { + const bytes = new Uint8Array(length); + randomFillSync(bytes.subarray(0, Math.min(length, 1 << 20))); + for (let at = 1 << 20; at < length; at += 1 << 20) bytes.copyWithin(at, 0, 1 << 20); + return bytes; + }; + const cases: [string, Uint8Array][] = [ + ["fixture.tar", patterned(3 * 1024 * 1024)], + ["fixture.tar", patterned(1000)], + ["empty.bin", new Uint8Array(0)], + ["big.bin", patterned(70_000_000)], + ]; - expect(response.status).toBe(201); - expect(await response.json()).toEqual({ name: "fixture.tar", size: bytes.length }); - const download = await get("fixture.tar"); - expect(download.status).toBe(200); - expect(sha256(new Uint8Array(await download.arrayBuffer()))).toBe(sha256(bytes)); + for (const [name, bytes] of cases) { + const response = await put(name, bytes); + expect(response.status).toBe(201); + expect(await response.json()).toEqual({ name, size: bytes.length }); + const download = await get(name); + expect(download.status).toBe(200); + expect(sha256(new Uint8Array(await download.arrayBuffer()))).toBe(sha256(bytes)); + } }); it("a lease holder PUTs a bad file name and gets 400 BAD_REQUEST with the name rule", async () => { From ca55b675d6e6fadebf58aeaa1b1416773196fcdc Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:34:22 +0100 Subject: [PATCH 18/30] test: a caller that does not hold the lease gets 404 UNKNOWN_LEASE on every file route, and an operator is served (#1356) --- src/http/app-leases.test.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 10b6dabe8..d61d3fa9e 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1925,4 +1925,34 @@ describe("a lease's files on a worker", () => { }, }); }); + + it("a caller that does not hold the lease gets 404 UNKNOWN_LEASE on every file route, and an operator is served", async () => { + const { app, put, list, get } = await filesRig(); + expect((await put("mine.bin", "mine")).status).toBe(201); + const routes = (leaseId: string, headers: Record) => [ + () => + app.request(`/v1/leases/${leaseId}/files/mine.bin`, { body: "x", headers, method: "PUT" }), + () => app.request(`/v1/leases/${leaseId}/files/mine.bin`, { headers }), + () => app.request(`/v1/leases/${leaseId}/files`, { headers }), + () => app.request(`/v1/leases/${leaseId}/files/mine.bin`, { headers, method: "DELETE" }), + ]; + + for (const [leaseId, headers] of [ + ["lse_1", otherAgentAuth], + ["lse_unknown", agentAuth], + ] as const) { + for (const response of await Promise.all(routes(leaseId, headers).map((call) => call()))) { + expect(response.status).toBe(404); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe( + "UNKNOWN_LEASE", + ); + } + } + expect(await (await list()).json()).toEqual({ files: [{ name: "mine.bin", size: 4 }] }); + expect(new TextDecoder().decode(await (await get("mine.bin")).arrayBuffer())).toBe("mine"); + + const statuses: number[] = []; + for (const call of routes("lse_1", operatorAuth)) statuses.push((await call()).status); + expect(statuses).toEqual([201, 200, 200, 204]); + }); }); From 18570b39d51c02ad27d0a2c5ceb47c965115b888 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:34:31 +0100 Subject: [PATCH 19/30] test: on a gateway, before the gateway relays them, the file routes answer 501 UNSUPPORTED_IN_GATEWAY_MODE (#1356) --- src/http/app-leases.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index d61d3fa9e..ff94a66ea 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1955,4 +1955,23 @@ 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", + ); + } + }); }); From 7570f3b8606fe1ab3b00802236b383b98479c27e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:34:56 +0100 Subject: [PATCH 20/30] test: a module named files is refused when the module host loads (#1356) --- src/daemon/optional-modules.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/daemon/optional-modules.test.ts b/src/daemon/optional-modules.test.ts index bcd91c387..fb35c7024 100644 --- a/src/daemon/optional-modules.test.ts +++ b/src/daemon/optional-modules.test.ts @@ -280,8 +280,8 @@ describe("optional modules: HTTP routes", () => { ); }); - it("a module named like a core lease sub-route (renew, exec, rotate) fails the start, and POST /v1/leases/{id}/renew still renews", async () => { - for (const name of ["renew", "exec", "rotate"]) { + it("a module named like a core lease sub-route (renew, exec, rotate, files) fails the start, and POST /v1/leases/{id}/renew still renews", async () => { + for (const name of ["renew", "exec", "rotate", "files"]) { await expect(start({ modules: definitions(fakeModule({ name })) })).rejects.toThrow(name); } @@ -290,6 +290,9 @@ describe("optional modules: HTTP routes", () => { modules: definitions(fakeModule({ name: "alpha" })), on: ["alpha"], }); + expect( + (await start({ modules: definitions(fakeModule({ name: "stream" })) })).daemon, + ).toBeDefined(); const { secret } = await daemon.dispatch( "token.create", { label: "o", role: "operator" }, From 9ae674c864d0a69025d45d43c352df545bd45b00 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:35:00 +0100 Subject: [PATCH 21/30] feat(modules): files is a core lease sub-route no module may take (#1356) --- src/modules/host.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/modules/host.ts b/src/modules/host.ts index 792c02f88..1eed77eea 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -111,7 +111,7 @@ function targetsByName( } // why: a module's lease route is `/v1/leases/:id/`; these are the sub-routes the HTTP app registers itself, and a module may not take one. -const CORE_LEASE_SUBROUTES: readonly string[] = ["exec", "renew", "rotate"]; +const CORE_LEASE_SUBROUTES: readonly string[] = ["exec", "files", "renew", "rotate"]; type StopHook = "beforeDrain" | "beforeDriversDispose"; From a57a19ae3b1eeb1f77a38f48bd7ff63c64f37aef Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:35:21 +0100 Subject: [PATCH 22/30] test: the HTTP listener of a worker and of a gateway has no total request time limit (#1356) --- src/http/server.test.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/http/server.test.ts b/src/http/server.test.ts index 1ca569e04..7fb49638e 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -1,5 +1,6 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; +import type { Server } from "node:http"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -200,12 +201,18 @@ describe("withConsole", () => { }); describe("HttpGateway", () => { - async function started(root: string) { + async function started(root: string, onServerCreated?: (server: Server) => void) { const logSink = new MemoryLogSink(); const logger = new JsonLinesLogger({ clock: new FakeClock(0), sink: logSink }); const gateway = new HttpGateway( { fetch: () => new Response("api") }, - { consoleRoot: root, host: "127.0.0.1", logger, port: 0 }, + { + consoleRoot: root, + host: "127.0.0.1", + logger, + port: 0, + ...(onServerCreated === undefined ? {} : { onServerCreated }), + }, ); const { port } = await gateway.start(); const warnings = () => @@ -227,4 +234,16 @@ describe("HttpGateway", () => { await gateway.stop(); } }); + + it("the HTTP listener has no total request time limit, so a slow upload that keeps moving is not cut", async () => { + let created: Server | undefined; + const { gateway } = await started(await emptyRoot(), (server) => { + created = server; + }); + try { + expect(created?.requestTimeout).toBe(0); + } finally { + await gateway.stop(); + } + }); }); From 5f05862a351f3b512df76536ce0eaf11b69c97ad Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:35:24 +0100 Subject: [PATCH 23/30] feat(http): the listener has no total request time limit (#1356) --- src/http/server.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/http/server.ts b/src/http/server.ts index e16015044..63aea9f5e 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -195,6 +195,8 @@ export class HttpGateway { this.#sockets.add(socket); socket.once("close", () => this.#sockets.delete(socket)); }); + // why: Node cuts any request that lasts over 300 s by default, which would cut a big upload that keeps moving; a stalled one is cut by the upload's own silence bound, and headers stay bounded by `headersTimeout`. + server.requestTimeout = 0; this.#server = server; // Before `listening` fires deliberately: an upgrade cannot arrive until the server is // listening, and wiring it here means there is no window where a connection is accepted From 08d4a4ad3d8523c9845debbe4dee9c2ee9635e6b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:40:38 +0100 Subject: [PATCH 24/30] test: a lease's files are gone once it ends, and startup removes the folders of leases that are gone (#1356) --- .dependency-cruiser.mjs | 12 ++ docs/internal/ARCHITECTURE.md | 1 + src/agent-device/host/lease-end.test.ts | 1 + src/daemon/lease-files.test.ts | 144 +++++++++++++++++++++++ src/daemon/lease-inputs.test.ts | 1 + src/daemon/worker-composition.ts | 26 +++- src/input/worker.test.ts | 9 +- src/lease-files/AGENTS.md | 14 +++ src/lease-files/CLAUDE.md | 1 + src/lease-files/guarded-body.ts | 5 + src/lease-files/lease-files.ts | 7 +- src/lease-files/store.ts | 79 ++++++++++++- src/leasing/lease-ports.ts | 2 + src/leasing/lease-release-coordinator.ts | 1 + src/modules/conformance.test.ts | 1 + src/modules/types.ts | 1 + src/tunnel/worker.test.ts | 4 + 17 files changed, 301 insertions(+), 8 deletions(-) create mode 100644 src/daemon/lease-files.test.ts create mode 100644 src/lease-files/AGENTS.md create mode 100644 src/lease-files/CLAUDE.md diff --git a/.dependency-cruiser.mjs b/.dependency-cruiser.mjs index 6cf0e83fa..ed9d25b61 100644 --- a/.dependency-cruiser.mjs +++ b/.dependency-cruiser.mjs @@ -150,6 +150,18 @@ export default { "^src/input/", { path: "^src/(http|gateway|drivers|daemon|cli|mcp|leasing)/" }, ), + direction( + "not-lease-files", + "core, leasing, the drivers, the gateway and the contract import nothing from lease-files: the daemon builds it and the HTTP frontend serves it", + "^src/(core|leasing|drivers|gateway|contract)/", + { path: "^src/lease-files/" }, + ), + direction( + "lease-files-imports-little", + "lease-files reads and writes through the Filesystem port and knows leases only by the types it takes from leasing; it imports no frontend, gateway, driver or core", + "^src/lease-files/", + { path: "^src/(http|gateway|drivers|daemon|cli|mcp|core)/" }, + ), direction( "host-load-imports-ports-only", "host-load reads the machine through the HostLoadProbe port and imports no other component", diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index a5a5ac147..4c4787647 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -52,6 +52,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) | | input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) | | tunnel | Optional edge: a lease holder's reverse tunnels (device to caller) and forward tunnels (caller to device) on its Android device or iOS simulator over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) | +| lease-files | Core worker feature: a lease's files uploaded over HTTP to a folder under the data directory, served back with ranges, and removed when the lease ends | [lease-files](../../src/lease-files/AGENTS.md) | | auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) | | http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) | | cli | Operator command surface | [cli](../../src/cli/AGENTS.md) | diff --git a/src/agent-device/host/lease-end.test.ts b/src/agent-device/host/lease-end.test.ts index b778f3258..61243825f 100644 --- a/src/agent-device/host/lease-end.test.ts +++ b/src/agent-device/host/lease-end.test.ts @@ -11,6 +11,7 @@ const tenant = "tok_one"; function ended(n: number): EndedLease { return { deviceId: "dev_1", + grantedAt: 1_000, leaseId: hex(n), ownerId: tenant, platform: "ios", diff --git a/src/daemon/lease-files.test.ts b/src/daemon/lease-files.test.ts new file mode 100644 index 000000000..d9e5066b4 --- /dev/null +++ b/src/daemon/lease-files.test.ts @@ -0,0 +1,144 @@ +import { mkdir, readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { FakeDriver } from "../core/testing.js"; +import { FakeClock, NodeFilesystem } from "../ports/index.js"; +import { freeLoopbackPort } from "./test-relay-support.js"; +import { start, runningDaemons, temporaryDirectories } from "./test-main.js"; + +afterEach(async () => { + await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test").catch(() => {}))); +}); + +const admin = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "test-operator", + role: "admin", +} as const; +const ios = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; + +// why: a real daemon with HTTP on, a real data folder, and a lease its token holds, so lease end reaches the lease-files participant through the same path production uses. +async function rig() { + const clock = new FakeClock(1_000); + const port = await freeLoopbackPort(); + const started = await start({ + clock, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + filesystem: new NodeFilesystem(), + }); + const { secret, token } = await started.daemon.dispatch( + "token.create", + { label: "holder", role: "agent" }, + admin, + ); + const origin = `http://127.0.0.1:${String(port)}`; + const headers = { authorization: `Bearer ${secret}` }; + const holder = { + manageEventSubscription: () => undefined, + via: "socket", + principal: token.id, + role: "agent", + } as const; + const lease = async (): Promise => { + const grant = (await started.daemon.dispatch( + "lease.request", + { ...ios, requesterId: "agent-1" }, + holder, + )) as { lease: { id: string } }; + return grant.lease.id; + }; + const put = (id: string, name: string, body: BodyInit) => + fetch(`${origin}/v1/leases/${id}/files/${name}`, { body, headers, method: "PUT" }); + const list = (id: string) => fetch(`${origin}/v1/leases/${id}/files`, { headers }); + const release = (id: string) => started.daemon.dispatch("lease.release", { leaseId: id }, holder); + const root = join(started.directory, "lease-files"); + const folders = () => readdir(root).catch(() => []); + return { ...started, clock, folders, headers, lease, list, origin, put, release, root }; +} + +describe("a lease's files at lease end", () => { + it("are gone once the lease is released, expires or is killed, and a new lease starts empty", async () => { + const r = await rig(); + const ends: Record Promise> = { + expired: () => { + r.clock.advance(24 * 3_600_000); + return new Promise((done) => setTimeout(done, 50)); + }, + killed: () => r.daemon.dispatch("nuke.run", { deleteDevices: true }, admin), + released: (id) => r.release(id), + }; + for (const [reason, end] of Object.entries(ends)) { + const id = await r.lease(); + expect((await r.put(id, `${reason}.bin`, "bytes")).status, reason).toBe(201); + expect(await r.folders(), reason).toHaveLength(1); + + await end(id); + await new Promise((done) => setTimeout(done, 200)); + + expect(await r.folders(), reason).toEqual([]); + expect((await r.list(id)).status, reason).toBe(404); + } + const fresh = await r.lease(); + expect(await (await r.list(fresh)).json()).toEqual({ files: [] }); + }); + + it("an upload still running when its lease ends answers 404 UNKNOWN_LEASE and leaves nothing behind", async () => { + const r = await rig(); + const id = await r.lease(); + let feed!: ReadableStreamDefaultController; + const body = new ReadableStream({ + start(controller) { + feed = controller; + controller.enqueue(new TextEncoder().encode("first half")); + }, + }); + const running = fetch(`${r.origin}/v1/leases/${id}/files/big.bin`, { + body, + duplex: "half", + headers: r.headers, + method: "PUT", + } as RequestInit); + await vi.waitFor(async () => + expect(await readdir(join(r.root, (await r.folders())[0] ?? ""))).toHaveLength(1), + ); + + await r.release(id); + feed.enqueue(new TextEncoder().encode("second half")); + feed.close(); + const answer = await running; + + expect(answer.status).toBe(404); + expect(await answer.json()).toMatchObject({ error: { code: "UNKNOWN_LEASE" } }); + await vi.waitFor(async () => expect(await r.folders()).toEqual([])); + }); + + it("startup removes the folders of leases that are no longer live, an upload's temporary file included", async () => { + const r = await rig(); + const live = await r.lease(); + await r.put(live, "kept.bin", "bytes"); + const gone = join(r.root, `${Buffer.from("lse_gone").toString("hex")}-500`); + await mkdir(gone, { recursive: true }); + await writeFile(join(gone, ".upload-x"), "half"); + await writeFile(join(gone, "old.bin"), "old"); + expect(await r.folders()).toHaveLength(2); + + await r.daemon.stop("test"); + runningDaemons.length = 0; + const again = await start({ + clock: r.clock, + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + }, + dataDirectory: r.directory, + filesystem: new NodeFilesystem(), + }).catch(() => undefined); + + expect(again).toBeDefined(); + expect(temporaryDirectories.length).toBeGreaterThan(0); + expect(await r.folders()).toEqual([]); + }); +}); diff --git a/src/daemon/lease-inputs.test.ts b/src/daemon/lease-inputs.test.ts index ea9032cd3..b585729aa 100644 --- a/src/daemon/lease-inputs.test.ts +++ b/src/daemon/lease-inputs.test.ts @@ -6,6 +6,7 @@ import { createLeaseInputs } from "./lease-inputs.js"; const device = { id: "device-1", platform: "ios" } as never; const ended = { deviceId: "device-1", + grantedAt: 1_000, leaseId: "lease-1", ownerId: "owner-1", platform: "ios", diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index aebbcdc3d..ca6b5168b 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -38,6 +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 type { HttpDispatch } from "../http/dispatcher-session.js"; import { HttpGateway } from "../http/server.js"; import { @@ -324,6 +325,23 @@ export async function composeWorker( tokens: auth.tokens, role: "worker", }); + const leaseFiles = createLeaseFiles({ + clock, + dataDirectory, + diskPressureThreshold: config.diskPressure.freeBytesThreshold, + filesystem, + findGrant: (leaseId) => { + const lease = registry.snapshot.leases.find((candidate) => candidate.id === leaseId); + const device = registry.snapshot.devices.find( + (candidate) => candidate.id === lease?.deviceId, + ); + return lease === undefined || device === undefined + ? undefined + : { grantedAt: lease.grantedAt, id: lease.id, platform: device.spec.platform }; + }, + idGenerator, + logger: logger.child("lease-files"), + }); const leasing = createLeasing({ clock, components, @@ -333,7 +351,11 @@ export async function composeWorker( describeFailure: describeLeaseRequestFailure, eventBus, idGenerator, - leaseEndParticipants: [leaseInputs.leaseEnd, ...moduleHost.leaseEndParticipants], + leaseEndParticipants: [ + leaseInputs.leaseEnd, + leaseFiles.leaseEnd, + ...moduleHost.leaseEndParticipants, + ], logger, modelPreferences, }); @@ -437,6 +459,7 @@ export async function composeWorker( const steps = [ () => core.doctor.reconcile({ read }), () => leasing.reconcile(read), + () => leaseFiles.sweep(registry.snapshot.leases), () => core.converge(read), ]; for (const step of steps) { @@ -628,6 +651,7 @@ export async function composeWorker( dispatch, eventBus, idGenerator, + leaseFiles, leaseRequests: leasing.requests, logger: httpLogger, leaseRoutes: [...moduleHost.leaseRoutes()], diff --git a/src/input/worker.test.ts b/src/input/worker.test.ts index b2259e8e8..1a4c60aec 100644 --- a/src/input/worker.test.ts +++ b/src/input/worker.test.ts @@ -61,7 +61,14 @@ async function admitted(worker: WorkerModule): Promise { } function ended(reason: ModuleEndedLease["reason"]): ModuleEndedLease { - return { deviceId: "dev_1", leaseId: "L-1", ownerId: "tok_holder", platform: "android", reason }; + return { + deviceId: "dev_1", + grantedAt: 1_000, + leaseId: "L-1", + ownerId: "tok_holder", + platform: "android", + reason, + }; } function endLease( diff --git a/src/lease-files/AGENTS.md b/src/lease-files/AGENTS.md new file mode 100644 index 000000000..c4cdc9643 --- /dev/null +++ b/src/lease-files/AGENTS.md @@ -0,0 +1,14 @@ +# Lease files + +Does: stores the files a lease's holder (or an operator) uploads over `PUT /v1/leases/{id}/files/{name}` in a folder of the worker, serves them back (with byte ranges), lists and deletes them, and removes the folder when the lease ends. + +## Rules + +- The module imports no `node:fs`: every read and write goes through the `Filesystem` port. It never checks an owner; the HTTP layer resolves the lease for the caller and passes the lease's grant. +- A lease's folder is `/lease-files/-/`, so a new lease with a reused id starts empty and two ids that differ only in case never share a folder. +- 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 body that sends nothing for `silenceMs` (`DEFAULT_LIMITS`, `limits.ts`) is `UPLOAD_STALLED`; a body the client cut gets no answer, because nobody listens (the handler returns status 499 for the server's own log). +- `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. +- Errors are `LeaseFilesError`s; the handler turns them into responses with the contract's `ERROR_TABLE`. diff --git a/src/lease-files/CLAUDE.md b/src/lease-files/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/src/lease-files/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/lease-files/guarded-body.ts b/src/lease-files/guarded-body.ts index 25fc8cf60..65da9f677 100644 --- a/src/lease-files/guarded-body.ts +++ b/src/lease-files/guarded-body.ts @@ -13,6 +13,7 @@ export interface BodyGuard { readonly silenceMs: number; readonly onStalled: () => Error; readonly onChunk: (chunk: Uint8Array) => void; + readonly signal: AbortSignal; } /** @@ -37,6 +38,10 @@ export function guardedBody( rejectStall(stall); }); let timer = arm(); + guard.signal.addEventListener("abort", () => { + stall = guard.signal.reason as Error; + rejectStall(stall); + }); const disarm = () => guard.clock.cancel(timer); return new ReadableStream( diff --git a/src/lease-files/lease-files.ts b/src/lease-files/lease-files.ts index e3c0163db..a4e2324da 100644 --- a/src/lease-files/lease-files.ts +++ b/src/lease-files/lease-files.ts @@ -13,8 +13,11 @@ export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { lease: LeaseFilesLease, name: string | undefined, ) => handleRequest(folders, request, lease, name), - leaseEnd: { leaseEnded: () => Promise.resolve() }, + leaseEnd: { + leaseEnded: (ended) => + folders.end({ grantedAt: ended.grantedAt, id: ended.leaseId, platform: ended.platform }), + }, openFile: (grant, name) => folders.openFile(grant, name), - sweep: () => Promise.resolve(), + sweep: (live) => folders.sweep(live), }; } diff --git a/src/lease-files/store.ts b/src/lease-files/store.ts index aeaaf5163..8b8cff58b 100644 --- a/src/lease-files/store.ts +++ b/src/lease-files/store.ts @@ -12,10 +12,14 @@ export function folderKey(id: string, grantedAt: number): string { interface RunningUpload { received: number; + readonly abort: AbortController; } interface GrantState { + ended: boolean; readonly uploads: Set; + // why: every folder, upload and rename of a grant, so the lease end waits for what already started before it removes the folder. + readonly inFlight: Set>; // why: file names compare ignoring case, so a name's writer slot is its lowercase spelling. readonly writers: Set; } @@ -43,6 +47,10 @@ function lookup(names: readonly string[], name: string): string | undefined { return names.includes(name) ? name : sameName(names, name)[0]; } +function unknownLease(grant: LeaseFilesGrant): LeaseFilesError { + return new LeaseFilesError("UNKNOWN_LEASE", `Unknown lease: ${grant.id}`, { leaseId: grant.id }); +} + function unknownFile(name: string): LeaseFilesError { return new LeaseFilesError("UNKNOWN_FILE", `No file ${name} in this lease`, { name }); } @@ -72,10 +80,69 @@ export class LeaseFolders { async folderOf(grant: LeaseFilesGrant): Promise { const folder = this.#pathOf(grant); - await this.#deps.filesystem.mkdirp(folder, { mode: 0o700 }); + await this.#track(this.#stateOf(grant), grant, () => + this.#deps.filesystem.mkdirp(folder, { mode: 0o700 }), + ); return folder; } + /** why: the lease ended: nothing more is written, a running upload answers `UNKNOWN_LEASE`, and what was already running settles before the folder goes. */ + async end(grant: LeaseFilesGrant): Promise { + const state = this.#stateOf(grant); + state.ended = true; + for (const upload of state.uploads) upload.abort.abort(unknownLease(grant)); + while (state.inFlight.size > 0) await Promise.allSettled(state.inFlight); + try { + await this.#deps.filesystem.rm(this.#pathOf(grant)); + } catch (error: unknown) { + this.#deps.logger.warn("A lease's file folder could not be removed; startup removes it", { + error: error instanceof Error ? error.message : String(error), + leaseId: grant.id, + }); + } + } + + /** why: startup removes the folder of every lease no longer live and the upload files a restart left in the rest. */ + async sweep(live: readonly { readonly id: string; readonly grantedAt: number }[]): Promise { + const { filesystem, logger } = this.#deps; + const root = join(this.#deps.dataDirectory, "lease-files"); + const kept = new Set(live.map((grant) => folderKey(grant.id, grant.grantedAt))); + const entries = await filesystem.readdir(root).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + }); + for (const entry of entries) { + try { + const folder = join(root, entry); + if (!kept.has(entry)) { + await filesystem.rm(folder); + continue; + } + for (const inner of await filesystem.readdir(folder)) { + if (inner.startsWith(".upload-")) await filesystem.rm(join(folder, inner)); + } + } catch (error: unknown) { + logger.warn("A lease file folder could not be swept", { + entry, + error: error instanceof Error ? error.message : String(error), + }); + } + } + } + + async #track(state: GrantState, grant: LeaseFilesGrant, work: () => Promise): Promise { + const running = (async () => { + if (state.ended) throw unknownLease(grant); + return work(); + })(); + state.inFlight.add(running); + try { + return await running; + } finally { + state.inFlight.delete(running); + } + } + async openFile(grant: LeaseFilesGrant, name: string): Promise { const stored = lookup(await this.#names(grant), name); if (stored === undefined) throw unknownFile(name); @@ -137,7 +204,9 @@ export class LeaseFolders { } state.writers.add(slot); try { - return await this.#receive(grant, name, state, body, contentLength); + return await this.#track(state, grant, () => + this.#receive(grant, name, state, body, contentLength), + ); } finally { state.writers.delete(slot); } @@ -161,7 +230,7 @@ export class LeaseFolders { ); } const stored = await this.#folderBytes(folder, name.toLowerCase()); - const upload: RunningUpload = { received: 0 }; + const upload: RunningUpload = { abort: new AbortController(), received: 0 }; const others = () => [...state.uploads].reduce((sum, running) => sum + running.received, 0); if (stored + others() + (contentLength ?? 0) > this.#limits.leaseBytes) { throw leaseFull(grant, stored + others()); @@ -187,6 +256,7 @@ export class LeaseFolders { `No bytes of ${name} arrived for ${String(this.#limits.silenceMs / 1000)} s`, { name }, ), + signal: upload.abort.signal, silenceMs: this.#limits.silenceMs, }), { mode: 0o600 }, @@ -194,6 +264,7 @@ export class LeaseFolders { for (const other of sameName(await this.#names(grant), name)) { if (other !== name) await filesystem.rm(join(folder, other)); } + if (state.ended) throw unknownLease(grant); await filesystem.rename(temporary, join(folder, name)); return { name, size }; } catch (error: unknown) { @@ -212,7 +283,7 @@ export class LeaseFolders { const key = folderKey(grant.id, grant.grantedAt); let state = this.#states.get(key); if (state === undefined) { - state = { uploads: new Set(), writers: new Set() }; + state = { ended: false, inFlight: new Set(), uploads: new Set(), writers: new Set() }; this.#states.set(key, state); } return state; diff --git a/src/leasing/lease-ports.ts b/src/leasing/lease-ports.ts index d98856cff..f318c7df8 100644 --- a/src/leasing/lease-ports.ts +++ b/src/leasing/lease-ports.ts @@ -34,6 +34,8 @@ export interface EndedLease { readonly ownerId: string; readonly deviceId: string; readonly platform: Platform; + // why: with the lease id it names the grant, so a file folder of an earlier lease with the same id is never touched. + readonly grantedAt: number; readonly reason: "explicit" | "killed" | "expired" | "device-lost"; } diff --git a/src/leasing/lease-release-coordinator.ts b/src/leasing/lease-release-coordinator.ts index 8e4987684..977019782 100644 --- a/src/leasing/lease-release-coordinator.ts +++ b/src/leasing/lease-release-coordinator.ts @@ -398,6 +398,7 @@ export class LeaseReleaseCoordinator const { clock, endWaitMs, participants } = leaseEnd; const ended: EndedLease = { deviceId: released.device.id, + grantedAt: released.lease.grantedAt, leaseId: released.lease.id, ownerId: released.lease.ownerId, platform: released.device.spec.platform, diff --git a/src/modules/conformance.test.ts b/src/modules/conformance.test.ts index 85be96841..585bcef3b 100644 --- a/src/modules/conformance.test.ts +++ b/src/modules/conformance.test.ts @@ -15,6 +15,7 @@ const HOOK_DEADLINE_MS = 30_000; const ended: ModuleEndedLease = { deviceId: "dev-1", + grantedAt: 1_000, leaseId: "lease-1", ownerId: "agent-1", platform: "ios", diff --git a/src/modules/types.ts b/src/modules/types.ts index c146e5e45..af24b12a3 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -50,6 +50,7 @@ export interface ModuleEndedLease { readonly ownerId: string; readonly deviceId: string; readonly platform: Platform; + readonly grantedAt: number; readonly reason: "explicit" | "killed" | "expired" | "device-lost"; } diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 0513bd7ea..e46bfdc1d 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -53,6 +53,7 @@ function oversizeData(conn: number): Uint8Array { function ending(reason: "device-lost" | "expired" | "explicit" | "killed") { return { deviceId: "dev_1", + grantedAt: 1_000, leaseId: "L-1", ownerId: "tok_holder", platform: "android", @@ -640,6 +641,7 @@ describe("a worker's tunnel socket", () => { await pair.worker.hooks?.beforeDeviceReclaim?.( { deviceId: "dev_1", + grantedAt: 1_000, leaseId: "L-1", ownerId: "tok_holder", platform: "android", @@ -662,6 +664,7 @@ describe("a worker's tunnel socket", () => { await failing.worker.hooks?.beforeDeviceReclaim?.( { deviceId: "dev_1", + grantedAt: 1_000, leaseId: "L-1", ownerId: "tok_holder", platform: "android", @@ -712,6 +715,7 @@ describe("a worker's tunnel socket", () => { await reclaimed.worker.hooks?.beforeDeviceReclaim?.( { deviceId: "dev_1", + grantedAt: 1_000, leaseId: "L-1", ownerId: "tok_holder", platform: "android", From c8dfe5e8d8897f230402c02434cd2e65d5bcc000 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:41:30 +0100 Subject: [PATCH 25/30] fix(leasing): the lease-end participant test expects the lease's grant time (#1356) --- src/leasing/lease-end-participants.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/leasing/lease-end-participants.test.ts b/src/leasing/lease-end-participants.test.ts index 357f5160c..aa0862828 100644 --- a/src/leasing/lease-end-participants.test.ts +++ b/src/leasing/lease-end-participants.test.ts @@ -320,6 +320,7 @@ describe("lease-end participants (#469)", () => { expect(participant.calls.map((call) => call.ended)).toEqual([ { deviceId: grant.device.id, + grantedAt: 1_000, leaseId: grant.lease.id, ownerId: "agent-owner", platform: "ios", From c126093818e38648a820985ad038db8fffe62177 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:42:21 +0100 Subject: [PATCH 26/30] refactor(lease-files): GET serving is its own function and the index exports only what is imported (#1356) --- src/lease-files/handler.ts | 7 +++++-- src/lease-files/index.ts | 9 +-------- src/lease-files/store.ts | 2 +- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index 16a5b1e51..6ea19038e 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -4,7 +4,7 @@ import { BodyCutError } from "./guarded-body.js"; import type { LeaseFolders } from "./store.js"; import { requireFileName } from "./names.js"; import { parseRange } from "./range.js"; -import type { LeaseFilesLease } from "./types.js"; +import type { LeaseFileView, LeaseFilesLease } from "./types.js"; export async function handleRequest( store: LeaseFolders, @@ -50,7 +50,10 @@ async function serve( await store.remove(grant, name); return new Response(null, { status: 204 }); } - const file = await store.openFile(grant, name); + return serveFile(request, await store.openFile(grant, name)); +} + +async function serveFile(request: Request, file: LeaseFileView): Promise { const answer = parseRange(request.headers.get("range"), file.size); if (answer.kind === "unsatisfiable") { await file.close(); diff --git a/src/lease-files/index.ts b/src/lease-files/index.ts index a28b1ddd8..50103dfc5 100644 --- a/src/lease-files/index.ts +++ b/src/lease-files/index.ts @@ -1,9 +1,2 @@ export { createLeaseFiles } from "./lease-files.js"; -export type { - LeaseFilesDeps, - LeaseFilesGrant, - LeaseFilesLease, - LeaseFilesLimits, - LeaseFiles, - LeaseFileView, -} from "./types.js"; +export type { LeaseFilesLimits } from "./types.js"; diff --git a/src/lease-files/store.ts b/src/lease-files/store.ts index 8b8cff58b..7a290eb3f 100644 --- a/src/lease-files/store.ts +++ b/src/lease-files/store.ts @@ -6,7 +6,7 @@ import { DEFAULT_LIMITS } from "./limits.js"; import { isFileName } from "./names.js"; import type { LeaseFileView, LeaseFilesDeps, LeaseFilesGrant } from "./types.js"; -export function folderKey(id: string, grantedAt: number): string { +function folderKey(id: string, grantedAt: number): string { return `${Buffer.from(id, "utf8").toString("hex")}-${String(grantedAt)}`; } From 84e964a1cbfc3559c6997a6694b882fa3a07511e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:52:33 +0100 Subject: [PATCH 27/30] test(lease-files): the lease-end, sweep and limit tests go red when their code is removed (#1356) --- src/daemon/lease-files.test.ts | 139 ++++++++++++++++++++++++++++++--- src/http/AGENTS.md | 2 +- src/http/app-leases.test.ts | 33 +++++--- 3 files changed, 150 insertions(+), 24 deletions(-) diff --git a/src/daemon/lease-files.test.ts b/src/daemon/lease-files.test.ts index d9e5066b4..a6b56574c 100644 --- a/src/daemon/lease-files.test.ts +++ b/src/daemon/lease-files.test.ts @@ -4,9 +4,16 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { FakeDriver } from "../core/testing.js"; -import { FakeClock, NodeFilesystem } from "../ports/index.js"; +import { createLeaseFiles } from "../lease-files/index.js"; +import { + CryptoIdGenerator, + FakeClock, + MemoryFilesystem, + NodeFilesystem, + NoopLogger, +} from "../ports/index.js"; import { freeLoopbackPort } from "./test-relay-support.js"; -import { start, runningDaemons, temporaryDirectories } from "./test-main.js"; +import { start, runningDaemons } from "./test-main.js"; afterEach(async () => { await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test").catch(() => {}))); @@ -24,10 +31,11 @@ const ios = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; async function rig() { const clock = new FakeClock(1_000); const port = await freeLoopbackPort(); + const drivers = [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })]; const started = await start({ clock, configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + drivers, filesystem: new NodeFilesystem(), }); const { secret, token } = await started.daemon.dispatch( @@ -57,7 +65,7 @@ async function rig() { const release = (id: string) => started.daemon.dispatch("lease.release", { leaseId: id }, holder); const root = join(started.directory, "lease-files"); const folders = () => readdir(root).catch(() => []); - return { ...started, clock, folders, headers, lease, list, origin, put, release, root }; + return { ...started, clock, drivers, folders, headers, lease, list, origin, put, release, root }; } describe("a lease's files at lease end", () => { @@ -107,19 +115,22 @@ describe("a lease's files at lease end", () => { ); await r.release(id); + // why: the lease end stops the upload itself; it does not wait for the caller to finish sending. + await vi.waitFor(async () => expect(await r.folders()).toEqual([])); feed.enqueue(new TextEncoder().encode("second half")); feed.close(); const answer = await running; expect(answer.status).toBe(404); expect(await answer.json()).toMatchObject({ error: { code: "UNKNOWN_LEASE" } }); - await vi.waitFor(async () => expect(await r.folders()).toEqual([])); }); it("startup removes the folders of leases that are no longer live, an upload's temporary file included", async () => { const r = await rig(); const live = await r.lease(); await r.put(live, "kept.bin", "bytes"); + const [liveFolder = ""] = await r.folders(); + await writeFile(join(r.root, liveFolder, ".upload-left"), "half"); const gone = join(r.root, `${Buffer.from("lse_gone").toString("hex")}-500`); await mkdir(gone, { recursive: true }); await writeFile(join(gone, ".upload-x"), "half"); @@ -128,17 +139,121 @@ describe("a lease's files at lease end", () => { await r.daemon.stop("test"); runningDaemons.length = 0; + const port = await freeLoopbackPort(); const again = await start({ clock: r.clock, - configOverrides: { - http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, - }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, dataDirectory: r.directory, + drivers: r.drivers, filesystem: new NodeFilesystem(), - }).catch(() => undefined); + }); + + expect(again.daemon).toBeDefined(); + expect(await r.folders()).toEqual([liveFolder]); + expect(await readdir(join(r.root, liveFolder))).toEqual(["kept.bin"]); + }); +}); + +// why: the folder-level rules of `createLeaseFiles` that the worker's HTTP routes cannot reach yet (`folderOf` is for exec) or only by luck of timing: a held mkdir or listing, and grants whose lease ids differ only in case or in grant time. +class GatedFilesystem extends MemoryFilesystem { + release: (() => void) | undefined; + #gate: "mkdirp" | "readdir" | undefined; + + hold(call: "mkdirp" | "readdir"): void { + this.#gate = call; + } + + async #gated(call: "mkdirp" | "readdir"): Promise { + if (this.#gate !== call) return; + this.#gate = undefined; + await new Promise((resolve) => (this.release = resolve)); + } + + override async mkdirp(path: string, options?: Parameters[1]) { + await this.#gated("mkdirp"); + return super.mkdirp(path, options); + } + + // why: the first listing that shows a finished upload's temporary file is the one before the upload is renamed into place. + override async readdir(path: string) { + const names = await super.readdir(path); + if (names.some((name) => name.startsWith(".upload-"))) await this.#gated("readdir"); + return names; + } +} + +function leaseFilesOver(filesystem: GatedFilesystem) { + return createLeaseFiles({ + clock: new FakeClock(1_000), + dataDirectory: "/data", + diskPressureThreshold: 0, + filesystem, + findGrant: (id) => ({ grantedAt: 1, id, platform: "ios" }), + idGenerator: new CryptoIdGenerator(), + logger: new NoopLogger(), + }); +} - expect(again).toBeDefined(); - expect(temporaryDirectories.length).toBeGreaterThan(0); - expect(await r.folders()).toEqual([]); +const grant = (id: string, grantedAt: number) => ({ grantedAt, id, platform: "ios" }) as const; +const ended = (id: string, grantedAt: number) => + ({ + deviceId: "dev-1", + grantedAt, + leaseId: id, + ownerId: "agent-1", + platform: "ios", + reason: "explicit", + }) as const; + +describe("a lease's folder", () => { + it("is removed with its own grant only: not a later grant of the same id, not an id that differs in case", async () => { + const filesystem = new GatedFilesystem(); + const files = leaseFilesOver(filesystem); + + expect(await files.folderOf(grant("CI", 1))).toBe("/data/lease-files/4349-1"); + expect(await files.folderOf(grant("ci", 1))).toBe("/data/lease-files/6369-1"); + expect(await files.folderOf(grant("ci", 2))).toBe("/data/lease-files/6369-2"); + + await files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal); + + expect(await filesystem.readdir("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/data/lease-files")).toEqual(["4349-1", "6369-2"]); + }); + + it("a folderOf whose mkdir is still running when the lease ends leaves no folder, and a later folderOf is refused", async () => { + const filesystem = new GatedFilesystem(); + const files = leaseFilesOver(filesystem); + filesystem.hold("mkdirp"); + + const making = files.folderOf(grant("ci", 1)); + await vi.waitFor(() => expect(filesystem.release).toBeDefined()); + const ending = files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal); + filesystem.release?.(); + await ending; + + await making; + expect(await filesystem.readdir("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/data/lease-files")).toEqual([]); + await expect(files.folderOf(grant("ci", 1))).rejects.toMatchObject({ code: "UNKNOWN_LEASE" }); + }); + + it("an upload whose body is in but whose name is not yet taken when the lease ends answers 404 UNKNOWN_LEASE and leaves no folder", async () => { + const filesystem = new GatedFilesystem(); + const files = leaseFilesOver(filesystem); + filesystem.hold("readdir"); + + const uploading = files.handle( + new Request("http://worker/v1/leases/ci/files/a.bin", { body: "bytes", method: "PUT" }), + { ambient: false, name: "agent", principal: "agent-1", role: "agent", via: "token" }, + { deviceId: "dev-1", id: "ci" }, + "a.bin", + ); + await vi.waitFor(() => expect(filesystem.release).toBeDefined()); + const ending = files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal); + filesystem.release?.(); + await ending; + + const answer = await uploading; + expect(answer.status).toBe(404); + expect(await answer.json()).toMatchObject({ error: { code: "UNKNOWN_LEASE" } }); + expect(await filesystem.readdir("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/data/lease-files")).toEqual([]); }); }); diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 1df38e9c1..cab668e2f 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -8,7 +8,7 @@ Surface: [remote-agents.mdx](../../website/src/content/docs/docs/using-devices/r Dispatch: - Never a second dispatcher and never the unix socket: `deps.dispatch` is the daemon's own dispatcher, called in process. Role check, `authorize` and readiness parking run there. -- No role or `authorize` check here. The exceptions: the cross-site check on a proxy-signed identity (`requireAuth`), the lease lookup of a module's lease route, and request ownership (`requireOwnRequest`): a stored request is read or cancelled by its owner or an operator, else 403. +- No role or `authorize` check here. The exceptions: the cross-site check on a proxy-signed identity (`requireAuth`), the lease lookup of a module's lease route and of the lease file routes, and request ownership (`requireOwnRequest`): a stored request is read or cancelled by its owner or an operator, else 403. - `app.ts` is a pure request → response function; the console lives in `server.ts`. - Never imports drivers or gateway. No lint rule holds this. - The listener starts right after the socket claim, before startup convergence. Early requests park in the dispatcher. diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index ff94a66ea..334dafc5f 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1636,7 +1636,7 @@ describe("a lease's files on a worker", () => { const text = async (response: Response) => new TextDecoder().decode(await response.arrayBuffer()); - expect((await rig.put("kept.bin", "12345")).status).toBe(201); + expect((await rig.put("kept.bin", "1234567890")).status).toBe(201); const tooBig = await rig.put("kept.bin", big); expect(tooBig.status).toBe(413); expect((await refusal(tooBig)).error).toEqual({ @@ -1644,21 +1644,22 @@ describe("a lease's files on a worker", () => { message: "File kept.bin is over the 2 GiB limit for one file", name: "kept.bin", }); - expect(await text(await rig.get("kept.bin"))).toBe("12345"); + expect(await text(await rig.get("kept.bin"))).toBe("1234567890"); expect(await folderEntries(rig.leaseFolder)).toEqual(["kept.bin"]); let pulled = false; - const unread = new ReadableStream( - { - pull(c) { - pulled = true; - c.close(); + const unread = () => + new ReadableStream( + { + pull(c) { + pulled = true; + c.close(); + }, }, - }, - { highWaterMark: 0 }, - ); + { highWaterMark: 0 }, + ); const declared = await rig.app.request("/v1/leases/lse_1/files/declared.bin", { - body: unread, + body: unread(), duplex: "half", headers: { ...agentAuth, "content-length": "11" }, method: "PUT", @@ -1685,6 +1686,16 @@ describe("a lease's files on a worker", () => { }); expect(await folderEntries(full.leaseFolder)).toEqual(["my file.png"]); } + pulled = false; + const declaredFull = await full.app.request("/v1/leases/lse_1/files/over.bin", { + body: unread(), + duplex: "half", + headers: { ...agentAuth, "content-length": "50" }, + method: "PUT", + } as RequestInit); + expect(declaredFull.status).toBe(413); + expect((await refusal(declaredFull)).error.code).toBe("LEASE_FILES_FULL"); + expect(pulled).toBe(false); const together = await filesRig({ limits: roomy }); const first = liveBody(); From 07b1d713855949205b0d79c41dc01fada709a6c3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 14:54:33 +0100 Subject: [PATCH 28/30] test(lease-files): a DELETE removes every spelling a command left (#1356) --- src/http/app-leases.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 334dafc5f..4843e70aa 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1870,6 +1870,12 @@ describe("a lease's files on a worker", () => { expect(await text(await get("a.tar"))).toBe("second"); expect(await text(await get("A.TAR"))).toBe("first"); expect(await names()).toEqual(["A.tar", "a.tar"]); + + expect((await remove("a.tar")).status).toBe(204); + expect(await names()).toEqual([]); + expect(await folderEntries(leaseFolder)).toEqual([]); + expect((await get("a.tar")).status).toBe(404); + expect((await get("A.tar")).status).toBe(404); } }); From 72ff0b98e158102894e371dc320a0fdff43e3622 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:06:08 +0100 Subject: [PATCH 29/30] fix(lease-files): an upload is not counted twice, a HEAD closes its file, silence is tested just under its bound (#1356) --- src/http/app-leases.test.ts | 86 +++++++++++++++++++++++++++++++++++-- src/lease-files/AGENTS.md | 2 - src/lease-files/handler.ts | 6 ++- src/lease-files/store.ts | 6 ++- 4 files changed, 92 insertions(+), 8 deletions(-) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 4843e70aa..f2ecf5c6e 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1548,13 +1548,54 @@ function liveBody() { } // why: a request the code under test must answer; when it never does, the assertion on `undefined` fails by name where an await would time the whole test out. -function answered(response: Promise | Response): Promise { +function answered( + response: Promise | Response, + waitMs = 2_000, +): Promise { return Promise.race([ Promise.resolve(response), - new Promise((resolve) => setTimeout(() => resolve(undefined), 2_000)), + new Promise((resolve) => setTimeout(() => resolve(undefined), waitMs)), ]); } +// why: counts the files opened and not yet closed, so a test sees a response that left one open. +class CountingFilesystem extends NodeFilesystem { + open = 0; + override async openFile(path: string) { + const file = await super.openFile(path); + this.open += 1; + let closed = false; + const release = () => { + if (!closed) this.open -= 1; + closed = true; + }; + return { + size: file.size, + read: (range?: { readonly start: number; readonly end: number }) => { + const stream = file.read(range); + const reader = stream.getReader(); + return new ReadableStream({ + async pull(controller) { + const piece = await reader.read(); + if (piece.done) { + release(); + controller.close(); + } else controller.enqueue(piece.value); + }, + async cancel(reason) { + release(); + await reader.cancel(reason); + }, + }); + }, + close: async () => { + release(); + await file.close(); + }, + }; + } +} + class LowDiskFilesystem extends NodeFilesystem { override diskFree(): Promise { return Promise.resolve(5 * 1024 ** 3); @@ -1713,6 +1754,26 @@ describe("a lease's files on a worker", () => { expect((await running).status).toBe(201); expect(await folderEntries(together.leaseFolder)).toEqual(["a.bin"]); + const chunked = await filesRig({ limits: roomy }); + const chunks = liveBody(); + const chunkedRequest = chunked.app.request("/v1/leases/lse_1/files/chunks.bin", { + body: chunks.stream, + duplex: "half", + headers: agentAuth, + method: "PUT", + } as RequestInit); + for (let piece = 0; piece < 3; piece += 1) { + await Promise.race([chunks.push(new Uint8Array(30)), chunkedRequest]); + } + // why: a refused upload has already closed its body, and the status below must name that, not a thrown close. + try { + chunks.finish(); + } catch { + // why: nothing to close; the refusal below is what the test reads. + } + expect((await chunkedRequest).status).toBe(201); + expect(await folderEntries(chunked.leaseFolder)).toEqual(["chunks.bin"]); + const replacing = await filesRig({ limits: roomy }); expect((await replacing.put("x.bin", new Uint8Array(80))).status).toBe(201); expect((await replacing.put("x.bin", new Uint8Array(80))).status).toBe(201); @@ -1766,7 +1827,9 @@ describe("a lease's files on a worker", () => { const silent = liveBody(); const silentRequest = uploading("kept.bin", silent.stream); await silent.push(bytes); - rig.clock.advance(330_000); + rig.clock.advance(329_999); + expect(await answered(silentRequest, 50)).toBeUndefined(); + rig.clock.advance(1); const stalled = await answered(silentRequest); expect(stalled?.status).toBe(408); expect(await stalled?.json()).toEqual({ @@ -1782,7 +1845,8 @@ describe("a lease's files on a worker", () => { const mute = liveBody(); const muteRequest = uploading("mute.bin", mute.stream); await mute.firstPull; - rig.clock.advance(330_000); + rig.clock.advance(329_999); + rig.clock.advance(1); expect((await answered(muteRequest))?.status).toBe(408); const moving = liveBody(); @@ -1844,6 +1908,20 @@ describe("a lease's files on a worker", () => { }); }); + it("a lease holder's HEAD answers a GET's headers with no body and leaves no file open", async () => { + const filesystem = new CountingFilesystem(); + const { app, put } = await filesRig({ filesystem }); + expect((await put("head.bin", "twelve bytes")).status).toBe(201); + const head = await app.request("/v1/leases/lse_1/files/head.bin", { + headers: agentAuth, + method: "HEAD", + }); + expect(head.status).toBe(200); + expect(head.headers.get("content-length")).toBe("12"); + expect(await head.text()).toBe(""); + expect(filesystem.open).toBe(0); + }); + it("a lease holder's file names match ignoring case", async () => { const { get, leaseFolder, list, put, remove } = await filesRig(); const text = async (response: Response) => diff --git a/src/lease-files/AGENTS.md b/src/lease-files/AGENTS.md index c4cdc9643..05d4ecd21 100644 --- a/src/lease-files/AGENTS.md +++ b/src/lease-files/AGENTS.md @@ -9,6 +9,4 @@ 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 body that sends nothing for `silenceMs` (`DEFAULT_LIMITS`, `limits.ts`) is `UPLOAD_STALLED`; a body the client cut gets no answer, because nobody listens (the handler returns status 499 for the server's own log). - `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. -- Errors are `LeaseFilesError`s; the handler turns them into responses with the contract's `ERROR_TABLE`. diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts index 6ea19038e..ae3789815 100644 --- a/src/lease-files/handler.ts +++ b/src/lease-files/handler.ts @@ -64,7 +64,11 @@ async function serveFile(request: Request, file: LeaseFileView): Promise [...state.uploads].reduce((sum, running) => sum + running.received, 0); + const others = () => + [...state.uploads].reduce( + (sum, running) => (running === upload ? sum : sum + running.received), + 0, + ); if (stored + others() + (contentLength ?? 0) > this.#limits.leaseBytes) { throw leaseFull(grant, stored + others()); } From c0e8b00a5c8f3ed5cf767f378deb0f390eae6103 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 15:12:18 +0100 Subject: [PATCH 30/30] test(lease-files): the mute upload test shows no answer one ms before its bound; drop false refusal comments (#1356) --- src/http/app-leases.test.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index f2ecf5c6e..e7d836322 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1765,12 +1765,7 @@ describe("a lease's files on a worker", () => { for (let piece = 0; piece < 3; piece += 1) { await Promise.race([chunks.push(new Uint8Array(30)), chunkedRequest]); } - // why: a refused upload has already closed its body, and the status below must name that, not a thrown close. - try { - chunks.finish(); - } catch { - // why: nothing to close; the refusal below is what the test reads. - } + chunks.finish(); expect((await chunkedRequest).status).toBe(201); expect(await folderEntries(chunked.leaseFolder)).toEqual(["chunks.bin"]); @@ -1846,6 +1841,7 @@ describe("a lease's files on a worker", () => { const muteRequest = uploading("mute.bin", mute.stream); await mute.firstPull; rig.clock.advance(329_999); + expect(await answered(muteRequest, 50)).toBeUndefined(); rig.clock.advance(1); expect((await answered(muteRequest))?.status).toBe(408);