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/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/daemon/lease-files.test.ts b/src/daemon/lease-files.test.ts new file mode 100644 index 000000000..a6b56574c --- /dev/null +++ b/src/daemon/lease-files.test.ts @@ -0,0 +1,259 @@ +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 { 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 } 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 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, + 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, drivers, 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); + // 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" } }); + }); + + 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"); + await writeFile(join(gone, "old.bin"), "old"); + expect(await r.folders()).toHaveLength(2); + + 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 } }, + dataDirectory: r.directory, + drivers: r.drivers, + filesystem: new NodeFilesystem(), + }); + + 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(), + }); +} + +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/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/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" }, 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/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 d4c7d46ae..e7d836322 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -1,4 +1,9 @@ -import { describe, expect, it } from "vitest"; +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"; + +import { afterEach, describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; import { UnknownLeaseError, SerializedDecision } from "../core/index.js"; @@ -11,7 +16,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 +1461,608 @@ 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; + readonly filesystem?: NodeFilesystem; + readonly diskPressureThreshold?: number; + } = {}, +) { + const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-lease-files-")); + filesRoots.push(dataDirectory); + const rig = buildHarness({ + leaseFiles: ({ clock, logger }) => + createLeaseFiles({ + clock, + dataDirectory, + 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"), + 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 }); + 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, list, put, remove }; +} + +// 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: 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 waiting: (() => void)[] = []; + let pulled!: () => void; + const firstPull = new Promise((resolve) => { + pulled = resolve; + }); + const stream = new ReadableStream( + { + start(c) { + controller = c; + }, + pull() { + pulled(); + for (const resume of waiting.splice(0)) resume(); + }, + }, + { highWaterMark: 0 }, + ); + 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, + waitMs = 2_000, +): Promise { + return Promise.race([ + Promise.resolve(response), + 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); + } +} + +// 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(); + 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)], + ]; + + 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 () => { + 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, + ); + }); + + 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", "1234567890")).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("1234567890"); + 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"]); + + 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"]); + } + 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(); + 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.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"); + first.finish(); + 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]); + } + chunks.finish(); + 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); + + 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([]); + }); + + 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(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({ + 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(329_999); + expect(await answered(muteRequest, 50)).toBeUndefined(); + rig.clock.advance(1); + 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); + } + }); + + 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" }, + }); + }); + + 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) => + 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"]); + + 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); + } + }); + + 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", + }, + }); + }); + + 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]); + }); + + it("on a gateway, before the gateway relays them, the file routes answer 501 UNSUPPORTED_IN_GATEWAY_MODE", async () => { + const { app, registry } = buildHarness(); + registry.leases = [makeLease({ id: "lse_1", ownerId: "tok_agent" })]; + const routes = [ + ["PUT", "/v1/leases/lse_1/files/fixture.tar"], + ["GET", "/v1/leases/lse_1/files/fixture.tar"], + ["DELETE", "/v1/leases/lse_1/files/fixture.tar"], + ["GET", "/v1/leases/lse_1/files"], + ] as const; + + for (const [method, path] of routes) { + const response = await app.request(path, { headers: agentAuth, method }); + expect(response.status).toBe(501); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe( + "UNSUPPORTED_IN_GATEWAY_MODE", + ); + } + }); +}); diff --git a/src/http/app.ts b/src/http/app.ts index 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/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(); + } + }); }); 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 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/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..05d4ecd21 --- /dev/null +++ b/src/lease-files/AGENTS.md @@ -0,0 +1,12 @@ +# 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. +- `end` marks the lease ended, aborts its running uploads, waits for them and removes the folder; an upload or folder creation that finishes after that removes its own work. `sweep` at startup removes every folder whose lease is not live, upload temporary files included. diff --git a/src/lease-files/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/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/guarded-body.ts b/src/lease-files/guarded-body.ts new file mode 100644 index 000000000..65da9f677 --- /dev/null +++ b/src/lease-files/guarded-body.ts @@ -0,0 +1,81 @@ +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; + readonly signal: AbortSignal; +} + +/** + * 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, + 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(); + guard.signal.addEventListener("abort", () => { + stall = guard.signal.reason as Error; + rejectStall(stall); + }); + 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 { + 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); + }, + }, + { highWaterMark: 0 }, + ); +} diff --git a/src/lease-files/handler.ts b/src/lease-files/handler.ts new file mode 100644 index 000000000..ae3789815 --- /dev/null +++ b/src/lease-files/handler.ts @@ -0,0 +1,93 @@ +import { ERROR_TABLE } from "../contract/index.js"; +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 { LeaseFileView, LeaseFilesLease } from "./types.js"; + +export async function handleRequest( + store: LeaseFolders, + request: Request, + lease: LeaseFilesLease, + name: string | undefined, +): Promise { + 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( + { error: { code: refusal.code, message: refusal.message, ...refusal.details } }, + { status: ERROR_TABLE[refusal.code].httpStatus }, + ); + } +} + +async function serve( + store: LeaseFolders, + request: Request, + lease: LeaseFilesLease, + name: string | undefined, +): Promise { + const grant = store.findGrant(lease.id); + 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() }); + return Response.json(await store.put(grant, name, body, contentLengthOf(request)), { + status: 201, + }); + } + if (request.method === "DELETE") { + await store.remove(grant, name); + return new Response(null, { status: 204 }); + } + 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(); + 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); + // why: a HEAD gets a GET's headers and no body, and a body nobody reads would keep the file open. + const head = request.method === "HEAD"; + if (head) await file.close(); + const body = head ? null : file.read(answer.kind === "range" ? { end, start } : undefined); + return new Response(body, { + 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, + }); +} + +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/index.ts b/src/lease-files/index.ts new file mode 100644 index 000000000..50103dfc5 --- /dev/null +++ b/src/lease-files/index.ts @@ -0,0 +1,2 @@ +export { createLeaseFiles } from "./lease-files.js"; +export type { LeaseFilesLimits } 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..a4e2324da --- /dev/null +++ b/src/lease-files/lease-files.ts @@ -0,0 +1,23 @@ +import type { Identity } from "../auth/index.js"; +import { handleRequest } from "./handler.js"; +import { LeaseFolders } from "./store.js"; +import type { LeaseFiles, LeaseFilesDeps, LeaseFilesLease } from "./types.js"; + +export function createLeaseFiles(deps: LeaseFilesDeps): LeaseFiles { + const folders = new LeaseFolders(deps); + return { + folderOf: (grant) => folders.folderOf(grant), + handle: ( + request: Request, + _identity: Identity, + lease: LeaseFilesLease, + name: string | undefined, + ) => handleRequest(folders, request, lease, name), + leaseEnd: { + leaseEnded: (ended) => + folders.end({ grantedAt: ended.grantedAt, id: ended.leaseId, platform: ended.platform }), + }, + openFile: (grant, name) => folders.openFile(grant, name), + sweep: (live) => folders.sweep(live), + }; +} 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, +}; 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`, + {}, + ); + } +} 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, + }; +} diff --git a/src/lease-files/store.ts b/src/lease-files/store.ts new file mode 100644 index 000000000..75776e1cb --- /dev/null +++ b/src/lease-files/store.ts @@ -0,0 +1,320 @@ +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"; + +function folderKey(id: string, grantedAt: number): string { + return `${Buffer.from(id, "utf8").toString("hex")}-${String(grantedAt)}`; +} + +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; +} + +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 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 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 }); +} + +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.#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); + 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 { + 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. + 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( + 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.#track(state, grant, () => + 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 = { abort: new AbortController(), 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()); + } + 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 }, + ), + signal: upload.abort.signal, + silenceMs: this.#limits.silenceMs, + }), + { mode: 0o600 }, + ); + 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) { + 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 = { ended: false, inFlight: new Set(), 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; + } +} 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/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", 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/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"; 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/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}`; } 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", 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 |