Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f453c88
test: through a gateway, a lease holder's PUT, GET, list and DELETE r…
V3RON Nov 6, 2026
92f41a7
feat(lease-files): a gateway relays the file routes to the lease's wo…
V3RON Nov 6, 2026
edc905e
test: a gateway gives a download its Content-Length and answers a Ran…
V3RON Nov 6, 2026
1b2fc8c
feat(lease-files): a gateway gives a download its Content-Length from…
V3RON Nov 6, 2026
1e42fa2
test: a gateway refuses a Content-Length over 2 GiB with 413 FILE_TOO…
V3RON Nov 6, 2026
3070396
feat(lease-files): a gateway refuses a Content-Length over 2 GiB befo…
V3RON Nov 6, 2026
5778ebf
test: through a gateway, a worker's 413, 409 and 404 reach the caller…
V3RON Nov 6, 2026
b357b8a
feat(daemon): a worker takes lease file limits for tests (#1358)
V3RON Nov 6, 2026
46c1dc1
test: through a gateway, ten 20 MiB uploads at once are all stored (#…
V3RON Nov 6, 2026
dc0ed55
test: through a gateway, a caller that does not hold the lease gets 4…
V3RON Nov 6, 2026
69ae320
feat(lease-files): a gateway gives the caller's lease id back in a wo…
V3RON Nov 6, 2026
8218b04
test: through a gateway, a file upload is cut only by silence, not by…
V3RON Nov 6, 2026
671fee4
feat(gateway): a relayed file upload is cut by 330 s of silence, and …
V3RON Nov 6, 2026
30c2076
test: a gateway cuts a file upload only after 330 s of silence and ke…
V3RON Nov 6, 2026
1d03cdf
docs(lease-files): the file routes work through a gateway (#1358)
V3RON Nov 6, 2026
7fb9e59
refactor(gateway): split the file relay and the upload exchange into …
V3RON Nov 6, 2026
dbbdeb5
test(gateway): the upload relay test fails on its named assertion whe…
V3RON Nov 6, 2026
5fb547d
chore(stack): merge task/1357 into the lease files client (#1358)
V3RON Nov 6, 2026
e8dd5d5
Merge remote-tracking branch 'origin/task/1357' into HEAD
V3RON Nov 6, 2026
2966962
fix(gateway): an upload the worker stopped reading still ends at the …
V3RON Nov 6, 2026
08eab74
test(daemon): the relay test's second lease waits until the fleet can…
V3RON Nov 6, 2026
df9230e
Merge remote-tracking branch 'origin/task/1357' into HEAD
V3RON Nov 6, 2026
038394f
docs(adr): ADR 0067 is Accepted (#1358)
V3RON Nov 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 0067. A lease has a file folder on its worker that HTTP callers fill and read

- **Status:** Accepted — not yet implemented
- **Status:** Accepted
- **Date:** 2026-11-06
- **Issue:** [#1351](https://github.com/callstackincubator/simlock/issues/1351) (request [#1323](https://github.com/callstackincubator/simlock/issues/1323))
- **Narrows:** [ADR 0005](0005-gateway-and-worker-modes.md) Non-goals
Expand Down
2 changes: 1 addition & 1 deletion docs/internal/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,4 @@ the status is stale.
| [0064](0064-a-tunnel-reaches-an-ios-simulators-ports-and-an-emulators-adb-port.md) | A tunnel reaches an iOS simulator's ports and an emulator's adb port | Accepted; narrows 0054 §2, §5, §6, 0001 §4 and 0005 Non-goals |
| [0065](0065-a-driver-owns-its-config-keys-and-a-module-takes-the-sections-it-reads.md) | A driver owns its config keys, and a module takes the config sections it reads | Accepted |
| [0066](0066-a-slim-lease-may-keep-named-categories-running.md) | A slim lease may keep named categories running | Accepted; narrows 0007 §8, §9, 0008 §4, §9, 0009 §2, §4 and 0060 §1, §2, §6 |
| [0067](0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md) | A lease has a file folder on its worker that HTTP callers fill and read | Accepted — not yet implemented; narrows 0005 Non-goals (file transfer) and §19b′, 0026 §1 (a core relay target) and 0028 §4 (a file PUT's deadline) |
| [0067](0067-a-lease-has-a-file-folder-on-its-worker-that-http-callers-fill-and-read.md) | A lease has a file folder on its worker that HTTP callers fill and read | Accepted; narrows 0005 Non-goals (file transfer) and §19b′, 0026 §1 (a core relay target) and 0028 §4 (a file PUT's deadline) |
1 change: 1 addition & 0 deletions src/daemon/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Relays (worker side):

- `relay.request` runs only on the uplink connection.
- A `twoWay` relay runs no body cut-off. Its target answers a refusal before touching the pipe, or a 2xx with no body and then uses the pipe; the call answers once both directions have ended. The silence bound is the gateway's.
- `files` is the one relay target the core names: the lease files of a worker, served for a gateway (ADR 0067 §7). A module cannot take the name.
- `GatewayUplink` retries forever.

## Security model
Expand Down
81 changes: 81 additions & 0 deletions src/daemon/callers-lease-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// why: a worker's refusal is a claim, so the gateway reads at most this much of it, as the stream module does.
const MAX_REFUSAL_BYTES = 16 * 1024;

const WORKER_LEASE_ID_CODES: ReadonlySet<string> = new Set(["UNKNOWN_LEASE", "LEASE_FILES_FULL"]);

/** why: the worker names a lease by its own id, which the caller never saw; the gateway puts back the id the caller used in the two refusals that name it, and relays every other body as the worker sent it. */
export async function withCallersLeaseId(
answer: Response,
workerLeaseId: string,
callersLeaseId: string,
): Promise<Response> {
if ((answer.status !== 404 && answer.status !== 413) || answer.body === null) return answer;
const reader = answer.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
let ended = false;
while (size <= MAX_REFUSAL_BYTES) {
const step = await reader.read();
if (step.done) {
ended = true;
break;
}
chunks.push(step.value);
size += step.value.length;
}
if (ended) {
const rewritten = rewrite(Buffer.concat(chunks).toString(), workerLeaseId, callersLeaseId);
if (rewritten !== undefined) {
const headers = new Headers(answer.headers);
headers.delete("content-length");
headers.delete("simlock-content-length");
return new Response(rewritten, { headers, status: answer.status });
}
}
return new Response(stitched(chunks, reader), { headers: answer.headers, status: answer.status });
}

function rewrite(text: string, workerLeaseId: string, callersLeaseId: string): string | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return undefined;
}
const error = (parsed as { error?: unknown } | null)?.error;
if (typeof error !== "object" || error === null) return undefined;
const fields = error as { code?: unknown; message?: unknown };
if (typeof fields.code !== "string" || !WORKER_LEASE_ID_CODES.has(fields.code)) return undefined;
return JSON.stringify({
error: {
...error,
leaseId: callersLeaseId,
...(typeof fields.message === "string"
? { message: fields.message.replaceAll(workerLeaseId, callersLeaseId) }
: {}),
},
});
}

function stitched(
chunks: readonly Uint8Array[],
reader: ReadableStreamDefaultReader<Uint8Array>,
): ReadableStream<Uint8Array> {
const pending = [...chunks];
return new ReadableStream<Uint8Array>(
{
cancel: (reason) => reader.cancel(reason),
async pull(controller) {
const next = pending.shift();
if (next !== undefined) {
controller.enqueue(next);
return;
}
const step = await reader.read();
if (step.done) controller.close();
else controller.enqueue(step.value);
},
},
{ highWaterMark: 0 },
);
}
80 changes: 80 additions & 0 deletions src/daemon/gateway-lease-files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { Identity } from "../auth/index.js";
import { withCallersLeaseId } from "./callers-lease-id.js";
import { MAX_FILE_BYTES } from "../lease-files/index.js";
import type { HttpLeaseFiles } from "../http/app.js";

// why: only `main.ts` imports the gateway, so the relay is typed by the shape of the call it takes.
export interface GatewayLeaseFilesOptions {
readonly relay: (
workerId: string,
call: {
readonly target: string;
readonly request: Request;
readonly tenant: string;
readonly leaseId?: string;
readonly upload?: { readonly name: string; readonly silenceMs: number };
},
) => Promise<Response>;
readonly requesterPrefix: string;
readonly silenceMs?: number;
}

// why: the worker cuts an upload silent for the same 330 s, so the gateway's bound is the one the caller meets first.
const UPLOAD_SILENCE_MS = 330_000;

/** why: a gateway holds no file; it relays each file request to the worker that holds the lease, through the worker's `files` target (ADR 0067 §2). */
export function createGatewayLeaseFiles(options: GatewayLeaseFilesOptions): HttpLeaseFiles {
return {
handle: async (request, identity: Identity, lease, name) => {
const declared = request.headers.get("content-length");
if (name !== undefined && declared !== null && Number(declared) > MAX_FILE_BYTES) {
return tooLarge(name);
}
const workerLeaseId = lease.workerLeaseId ?? lease.id;
const relayed = await options.relay(lease.workerId ?? "", {
leaseId: workerLeaseId,
request: workerRequest(request, workerLeaseId, name),
target: "files",
tenant: `${options.requesterPrefix}${identity.principal}`,
...(request.method === "PUT" && name !== undefined
? { upload: { name, silenceMs: options.silenceMs ?? UPLOAD_SILENCE_MS } }
: {}),
});
return withContentLength(await withCallersLeaseId(relayed, workerLeaseId, lease.id));
},
};
}

function tooLarge(name: string): Response {
return Response.json(
{
error: {
code: "FILE_TOO_LARGE",
message: `File ${name} is over the 2 GiB limit for one file`,
name,
},
},
{ status: 413 },
);
}

function workerRequest(request: Request, workerLeaseId: string, name: string | undefined): Request {
const path = `/files/leases/${encodeURIComponent(workerLeaseId)}${
name === undefined ? "" : `/${encodeURIComponent(name)}`
}`;
return new Request(`http://simlock-worker${path}`, {
headers: request.headers,
method: request.method,
signal: request.signal,
...(request.body === null ? {} : { body: request.body, duplex: "half" }),
} as RequestInit);
}

// why: the relay carries no `Content-Length`, so the worker sent the body's length under its own header and the gateway gives it back to the caller.
function withContentLength(answer: Response): Response {
const length = answer.headers.get("simlock-content-length");
if (length === null || !/^\d{1,16}$/.test(length)) return answer;
const headers = new Headers(answer.headers);
headers.set("content-length", length);
return new Response(answer.body, { headers, status: answer.status });
}
11 changes: 11 additions & 0 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { androidSourceDataOwner } from "../drivers/android/index.js";
import { iosSourceDataOwner } from "../drivers/ios/index.js";
import { type Auth, createAuth, tokensOwner } from "../auth/index.js";
import { createHttpApp } from "../http/app.js";
import { createGatewayLeaseFiles } from "./gateway-lease-files.js";
import type { HttpDispatch } from "../http/dispatcher-session.js";
import { HttpGateway } from "../http/server.js";
import {
Expand Down Expand Up @@ -128,6 +129,8 @@ export interface StartDaemonOptions extends WorkerOptions {
readonly configPath?: string;
readonly dataDirectory?: string;
readonly deviceDataTables?: ReadonlyMap<Platform, DeviceDataTable>;
/** why: test-only, a gateway's silence bound on a relayed file upload, so a rig reaches 408 without waiting 330 s. */
readonly fileSilenceMs?: number;
readonly gatewayRelay?: (relay: GatewayRelay) => void;
/** why: test-only, hands over the gateway's uplink listener, to close one worker's socket. */
readonly gatewayUplinks?: (uplinks: WebSocketUplinkListenerFactory) => void;
Expand Down Expand Up @@ -321,6 +324,7 @@ async function composeDaemon(
eventHistory,
filesystem,
...(options.gatewayRelay === undefined ? {} : { gatewayRelay: options.gatewayRelay }),
...(options.fileSilenceMs === undefined ? {} : { fileSilenceMs: options.fileSilenceMs }),
...(options.gatewayUplinks === undefined ? {} : { gatewayUplinks: options.gatewayUplinks }),
hostSystem,
...(options.hostLoadProbe === undefined ? {} : { hostLoadProbe: options.hostLoadProbe }),
Expand Down Expand Up @@ -377,6 +381,8 @@ interface GatewayDaemonOptions {
readonly config: Config;
readonly dataDirectory: string;
readonly eventBus: EventBus;
/** why: test-only, see `StartDaemonOptions.fileSilenceMs`. */
readonly fileSilenceMs?: number;
readonly eventHistory: EventHistoryHandle;
readonly filesystem: Filesystem;
readonly gatewayRelay?: (relay: GatewayRelay) => void;
Expand Down Expand Up @@ -629,6 +635,11 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise<Daemon
dispatch,
eventBus,
idGenerator,
leaseFiles: createGatewayLeaseFiles({
relay: (workerId, call) => gatewayRelay.relay(workerId, call),
requesterPrefix: gatewayRequesterPrefix,
...(options.fileSilenceMs === undefined ? {} : { silenceMs: options.fileSilenceMs }),
}),
leaseRequests: fleetCoordinator.requests,
logger: httpLogger,
leaseRoutes: [...moduleHost.leaseRoutes()],
Expand Down
Loading
Loading