Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
30 changes: 14 additions & 16 deletions docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -897,28 +897,26 @@ receives. The gateway's `GatewayRelay` hands one `Request` to the worker's
`relayTargets` under the module's capability name, and answers the target's
`Response` with its body streamed. The core names no target.

Three admin operations carry it over the uplink, and a worker answers them
only on the gateway's own uplink session (`FORBIDDEN` elsewhere; a gateway
refuses them from everyone):
Two admin operations and one byte channel carry it over the uplink, and a
worker answers the operations only on the gateway's own uplink session
(`FORBIDDEN` elsewhere; a gateway refuses them from everyone):

- `relay.request` opens a relay (`relayId`, `target`, method, URL, headers,
tenant, lease id, `hasBody`) and answers `{}` once the response body has
ended, or `{ cancelled: true }` once a cancel took effect. The response
leaves as request-scoped `relay-head` and `relay-chunk` pushes keyed by its
frame id, each written before the next part of the target's body is read.
- `relay.body` sends the request body in `seq` order, then `end`. A call is
answered once the target's stream has taken the chunk, so the gateway
keeps at most 4 unanswered.
tenant, lease id, `hasBody`, `channel`) and answers `{}` once the response
body has ended, or `{ cancelled: true }` once a cancel took effect. The head
leaves as a request-scoped `relay-head` push keyed by its frame id. The
request body arrives, and the response body leaves, on the byte channel
`channel` names (ADR 0028). The worker accepts the channel when it reads the
line, before the call parks for startup.
- `relay.cancel` aborts the target's `Request` signal; so does the close of
the connection the relay came on.

The gateway bounds every wait: a deadline for the whole exchange
(`WORKER_UNREACHABLE` when it passes), 8 relays at once per worker, and 64
MiB of response a caller has not read. A lost uplink fails the call as
The gateway bounds every wait: one deadline for the whole exchange, channel
wait included (`WORKER_UNREACHABLE` when it passes). The link bounds the
channels open to a worker at 64. A lost uplink fails the call as
`WORKER_UNREACHABLE` through `isUplinkLost`, the one function the relay, the
lease coordinator and the component relay all ask. The uplink is shared, so a
large relay delays the other calls on it (no flow control; #511 accepts
this).
lease coordinator and the component relay all ask. A slow reader slows only
its own channel, and small calls go first on the uplink.

### Aggregated reads

Expand Down
6 changes: 3 additions & 3 deletions docs/internal/COMPONENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ rule 14); a single-file component's surface is what the file exports.
| `DaemonEndpointHost` | `src/daemon/connection-host.ts` | Claiming the socket, recovering a stale entry, the listener lifecycle. | Anything after a connection is accepted. |
| `AdminSecretManager`, session resolver | `src/daemon/admin-secret.ts`, `src/daemon/session.ts` | The per-start admin secret, its hash and persistence; turning a credential into `{ principal, role }`. | Decide what a role may do. |
| `GatewayUplink` | `src/daemon/gateway-uplink.ts` | When a worker dials its gateway: one outbound connection, redialled with backoff, handed to `DaemonServer`. | What travels over the link. |
| Link module | `src/link/` (surface: `index.ts`) | Wrapping one uplink transport connection (ADR 0028 §1-3): text messages passed through unchanged and ahead of bulk bytes, byte channels with credit, the envelope, the two-lane scheduler and the channel rules, the 64 channel limit and the waits it bounds (30 s accept, 60 s credit). Nothing uses it yet; #558 wraps the uplink with it. | Know what a channel carries, or touch a socket (the transport port does). |
| Relay targets | `src/daemon/relay.ts` | A worker's `relayTargets` (capability name to a function that takes a `Request`, a tenant and a lease id and answers a `Response`), and per uplink connection the relays it carries: the request body fed by `relay.body`, the response sent as `relay-head` and `relay-chunk` pushes, cancel and abort on close. Nothing registers a target yet. | Name a target: the core knows none; modules register through the option. |
| Link module | `src/link/` (surface: `index.ts`) | Wrapping one uplink transport connection (ADR 0028 §1-3): text messages passed through unchanged and ahead of bulk bytes, byte channels with credit, the envelope, the two-lane scheduler and the channel rules, the 64 channel limit and the waits it bounds (30 s accept, 60 s credit). Both uplink ends (the worker's and the gateway's) wrap their connection with it. | Know what a channel carries, or touch a socket (the transport port does). |
| Relay targets | `src/daemon/relay.ts` | A worker's `relayTargets` (capability name to a function that takes a `Request`, a tenant and a lease id and answers a `Response`), and per uplink connection the relays it carries: the request body read from the relay's byte channel, the head sent as a `relay-head` push and the response body written to the channel, cancel and abort on close. `src/daemon/main.ts` registers the `agent-device` target through the option. | Name a target: the core knows none; modules register through the option. |
| `OwnerRoutedFactBus` | `src/daemon/owner-routed-facts.ts` | Re-emitting lease-scoped facts with the lease's owner attached, for pushes and HTTP notices. | Emit a business fact of its own. |

## Core: device management
Expand Down Expand Up @@ -156,7 +156,7 @@ typed against and catalog matching (ARCHITECTURE.md, "Boundaries").
| Routing | `src/gateway/routing.ts`, `src/gateway/routing/` (surface: `index.ts`) | The pure routing policy: an ordered list of stages (`takes-requests`, `can-serve`, `healthy`, `idle-queue`, `warm-hit`, `free-slot`, `ram-budget`, `free-capacity`) over worker views, selected by `gateway.routing`; a physical request skips the stages whose `appliesToPhysical` is `false` (`idle-queue`, `free-slot`, `ram-budget`, `free-capacity`) and matches the enrolled physical devices in each worker's view (`physicalMatch`). | Read anything but views; order stages from config. |
| `GatewayDispatcher` | `src/gateway/dispatcher.ts` | The second implementation of the contract's handlers (ADR 0005 §32): answered from the fleet, forwarded to one worker, or fanned out to all. | Define a second contract or role check. |
| Aggregate, component relay | `src/gateway/aggregate.ts`, `src/gateway/component-relay.ts` | The fleet expressed in one machine's shapes, as pure functions over views; asking every worker to install a component and collecting one outcome each. | Decide anything a worker decides. |
| `GatewayRelay` | `src/gateway/relay.ts` | Handing one HTTP exchange to a relay target on a worker over its uplink (ADR 0026): `relay.request`, the request body as `relay.body` calls (4 unanswered at most), the response from `relay-head` and `relay-chunk` pushes; the deadline, 8 relays per worker, 64 MiB of unread response, cancel and `WORKER_UNREACHABLE` on a lost uplink. | Route to a worker or know which module a target is. |
| `GatewayRelay` | `src/gateway/relay.ts` | Handing one HTTP exchange to a relay target on a worker over its uplink (ADR 0026): `relay.request`, the request body and the response body on a byte channel opened on the uplink's link, the head from a `relay-head` push; the deadline over the channel wait and the exchange, cancel and `WORKER_UNREACHABLE` on a lost uplink. | Route to a worker or know which module a target is. |
| `GatewayOwnerRoutedFacts` | `src/gateway/owner-routed-facts.ts` | The gateway's owner-attributed lease facts, from relayed worker events. | Emit a fact of its own. |

## Ports
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 0028. The uplink carries byte channels beside its messages, and small messages go first

- **Status:** Accepted — partly implemented: §1–3 (the link module and the transport port, #556); §4–6 (relays on channels, the download cap, the protocol bump) follow
- **Status:** Accepted — partly implemented: §1–3 (the link module and the transport port, #556); §4 and §6 (relays on channels, the protocol bump, #558); §5 (the download cap, #557) follows
- **Date:** 2026-10-14
- **Issue:** [#552](https://github.com/callstackincubator/simlock/issues/552)
- **Narrows:** [ADR 0026](0026-agent-device-through-a-gateway-relays-over-the-uplink.md)
Expand Down
1 change: 1 addition & 0 deletions src/admin/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe("simlock/admin", () => {
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("relayRequest");
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("relayBody");
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("relayCancel");
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("openChannel");

const documented = readFileSync(new URL("../../docs/CLIENT.md", import.meta.url), "utf8");
expect(Object.keys(admin).filter((name) => /relay/i.test(name))).toEqual([]);
Expand Down
14 changes: 11 additions & 3 deletions src/agent-device/gateway-front.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1301,9 +1301,10 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () =>
const held = member.fake.leases.get(hex(1));
expect(held).toBeDefined();
member.fake.leases.set(hex(2), { ...(held as NonNullable<typeof held>), leaseId: hex(2) });
// why: a lease whose requester is not its own id is never adopted, so the front's memory lacks it however soon the worker's catalog arrives.
await rig.gateway.dispatch(
"lease.request",
{ leaseId: hex(2), platform: "ios", requesterId: hex(2), requires: ["agent-device"] },
{ leaseId: hex(2), platform: "ios", requesterId: "someone-else", requires: ["agent-device"] },
sessionFor(principals.one),
);
interceptRelay(rig, async ({ request }) => {
Expand Down Expand Up @@ -1998,8 +1999,15 @@ describe(

async function restarted(rig: Rig, member: Member, leases: number): Promise<void> {
await rig.restart();
// why: the worker's redial delay doubles with each restart in a row (1 s, 2 s, 4 s ... up to its jitter), so one test that restarts four times waits up to 8 s.
await advance(rig, 8_000, 500);
// why: the worker's redial delay doubles with each restart in a row and carries jitter, so the clock moves on until the worker is back instead of by a sum that a fourth restart can outrun.
await vi.waitFor(
async () => {
const view = await viewOf(rig, member.label);
if (view?.connection !== "connected") await advance(rig, 1_000, 500);
expect(view?.connection).toBe("connected");
},
{ interval: 20, timeout: 30_000 },
);
await untilRead(rig, member);
await expect.poll(async () => (await fleetLeases(rig)).length).toBe(leases);
}
Expand Down
40 changes: 38 additions & 2 deletions src/contract/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
requestedDevice,
} from "./operations.js";
import { PUSH_SCHEMAS } from "./pushes.js";
import { relayChannelSchema } from "./relay.js";
import type { Role } from "./roles.js";
import { platformCatalogSchema } from "./schemas.js";

Expand Down Expand Up @@ -80,7 +81,6 @@ const ROLE_MATRIX: ReadonlyArray<{
},
role: "admin",
},
{ name: "relay.body", input: { end: true, relayId: "r-1" }, role: "admin" },
{ name: "relay.cancel", input: { relayId: "r-1" }, role: "admin" },
];

Expand Down Expand Up @@ -162,7 +162,6 @@ const EFFECT_MATRIX: ReadonlyArray<{
},
effect: "write",
},
{ name: "relay.body", input: { end: true, relayId: "r-1" }, effect: "write" },
{ name: "relay.cancel", input: { relayId: "r-1" }, effect: "write" },
];

Expand Down Expand Up @@ -1556,3 +1555,40 @@ describe("lease.request requires", () => {
);
});
});

describe("relay.request on a byte channel", () => {
const request = {
hasBody: false,
headers: [],
method: "GET",
relayId: "r-1",
target: "agent-device",
tenant: "gw.g.a",
url: "http://gateway.test/x",
};
const parse = (input: Record<string, unknown>) =>
OPERATIONS["relay.request"].input.safeParse(input).success;

it("accepts a channel of 1 to 32 characters of [A-Za-z0-9-] and refuses an empty, a 33-character and a bad-character one, and a request without one", () => {
expect(parse({ ...request, channel: "a" })).toBe(true);
expect(parse({ ...request, channel: "Ab-9".repeat(8) })).toBe(true);
expect(parse({ ...request, channel: "" })).toBe(false);
expect(parse({ ...request, channel: "a".repeat(33) })).toBe(false);
expect(parse({ ...request, channel: "a b" })).toBe(false);
expect(parse({ ...request, channel: "a_b" })).toBe(false);
expect(parse(request)).toBe(false);
});

it("relayChannelSchema holds the same bound the operation uses", () => {
expect(relayChannelSchema.safeParse("a".repeat(32)).success).toBe(true);
expect(relayChannelSchema.safeParse("a".repeat(33)).success).toBe(false);
expect(relayChannelSchema.safeParse("").success).toBe(false);
expect(relayChannelSchema.safeParse("a b").success).toBe(false);
});

it("OPERATIONS has no relay.body and PUSH_SCHEMAS has no relay-chunk", () => {
expect(Object.keys(OPERATIONS)).not.toContain("relay.body");
expect(Object.keys(PUSH_SCHEMAS)).not.toContain("relay-chunk");
expect(Object.keys(PUSH_SCHEMAS)).toContain("relay-head");
});
});
24 changes: 5 additions & 19 deletions src/contract/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { z } from "zod";

import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js";
import { parseOsConstraint } from "./os-range.js";
import { relayChunkSchema, relayHeadersSchema, relayIdSchema } from "./relay.js";
import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js";
import { ownsLease, type AuthorizeContext, type Role } from "./roles.js";
import {
capabilityNameSchema,
Expand Down Expand Up @@ -977,8 +977,9 @@ const relayUrlSchema = z

/**
* One HTTP exchange a gateway hands to a module on a worker, over the gateway's uplink. The
* response leaves as `relay-head` and `relay-chunk` pushes keyed by this call's frame id; the
* answer comes once its body has ended, or `{ cancelled: true }` once a `relay.cancel` took
* request body arrives, and the response body leaves, on the byte channel `channel` names (ADR 0028);
* the head leaves as a `relay-head` push keyed by this call's frame id. The
* answer comes once the response body has ended, or `{ cancelled: true }` once a `relay.cancel` took
* effect. Admin only, and on a worker only the gateway's own uplink session may call it.
*/
// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface.
Expand All @@ -996,6 +997,7 @@ export const relayRequest = defineOperation({
tenant: z.string().min(1).max(300),
leaseId: leaseIdSchema.optional(),
hasBody: z.boolean(),
channel: relayChannelSchema,
})
.strict()
.refine((input) => !input.hasBody || (input.method !== "GET" && input.method !== "HEAD"), {
Expand All @@ -1004,21 +1006,6 @@ export const relayRequest = defineOperation({
output: z.object({ cancelled: z.literal(true).optional() }),
});

/** One part of a relayed request body, in `seq` order, or its end. */
// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface.
export const relayBody = defineOperation({
name: "relay.body",
role: "admin",
effect: "write",
input: z.union([
z
.object({ relayId: relayIdSchema, seq: z.number().int().min(0), chunk: relayChunkSchema })
.strict(),
z.object({ relayId: relayIdSchema, end: z.literal(true) }).strict(),
]),
output: z.object({}),
});

// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface.
export const relayCancel = defineOperation({
name: "relay.cancel",
Expand Down Expand Up @@ -1062,7 +1049,6 @@ export const OPERATIONS = {
"device.add": deviceAdd,
"device.remove": deviceRemove,
"relay.request": relayRequest,
"relay.body": relayBody,
"relay.cancel": relayCancel,
} as const;

Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: 33, max: 33 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 34, max: 34 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down
11 changes: 2 additions & 9 deletions src/contract/pushes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
* why: server pushes (ADR 0003 §8). Three families, each with its correlation key required by
* schema:
*
* - Request-scoped (`progress`, `started`, `output`, `component-progress`, `relay-head`,
* `relay-chunk`): carries the
* - Request-scoped (`progress`, `started`, `output`, `component-progress`, `relay-head`): carries the
* originating request's frame id.
* - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id,
* and goes to every live connection whose principal owns that lease (ADR 0004 §5 keeps
Expand All @@ -15,7 +14,7 @@
*/
import { z } from "zod";

import { relayChunkSchema, relayHeadersSchema } from "./relay.js";
import { relayHeadersSchema } from "./relay.js";
import { eventEnvelopeSchema, leaseProgressSchema } from "./schemas.js";

/**
Expand Down Expand Up @@ -105,11 +104,6 @@ const relayHeadPushSchema = z.object({
headers: relayHeadersSchema,
});

const relayChunkPushSchema = z.object({
requestId: requestIdSchema,
chunk: relayChunkSchema,
});

const leaseLostPushSchema = z.object({
leaseId: z.string(),
deviceId: z.string(),
Expand Down Expand Up @@ -139,7 +133,6 @@ export const PUSH_SCHEMAS = {
started: startedPushSchema,
"component-progress": componentProgressPushSchema,
"relay-head": relayHeadPushSchema,
"relay-chunk": relayChunkPushSchema,
"lease-lost": leaseLostPushSchema,
"device-unhealthy": deviceUnhealthyPushSchema,
"device-recovered": deviceRecoveredPushSchema,
Expand Down
10 changes: 3 additions & 7 deletions src/contract/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@
import { z } from "zod";

export const RELAY_MAX_HEADERS = 100;
export const RELAY_MAX_CHUNK_BYTES = 262_144;
/** why: the base64 length of the largest chunk, rounded up to a whole quantum of four. */
const RELAY_MAX_CHUNK_CHARACTERS = 349_528;
export const RELAY_MAX_PUSH_BYTES = 256 * 1024;

const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;

export const relayIdSchema = z.string().regex(/^[A-Za-z0-9-]{1,64}$/);

// why: the channel id is wire input the worker checks before it accepts a channel (ADR 0028).
export const relayChannelSchema = z.string().regex(/^[A-Za-z0-9-]{1,32}$/);

export const relayHeadersSchema = z
.array(
z.tuple([
Expand All @@ -27,8 +25,6 @@ export const relayHeadersSchema = z
)
.max(RELAY_MAX_HEADERS);

export const relayChunkSchema = z.string().max(RELAY_MAX_CHUNK_CHARACTERS).regex(BASE64);

// why: the relay re-creates these on each side instead of carrying them.
const FRAMING_HEADERS: ReadonlySet<string> = new Set([
"connection",
Expand Down
2 changes: 1 addition & 1 deletion src/daemon-protocol/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {

describe("daemon protocol", () => {
it("keeps the current protocol version and newline framing", () => {
expect(DAEMON_PROTOCOL_VERSION).toBe(33);
expect(DAEMON_PROTOCOL_VERSION).toBe(34);
expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n');
});

Expand Down
5 changes: 3 additions & 2 deletions src/daemon/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { z } from "zod";

import type { Clock } from "../ports/clock.js";
import type { Logger } from "../ports/logger.js";
import type { LinkChannel } from "../link/index.js";
import type { RelayConnection } from "./relay.js";
import {
describeSchemaIssues,
Expand Down Expand Up @@ -122,8 +123,8 @@ export interface DispatchSession {
status: number,
headers: readonly (readonly [string, string])[],
) => Promise<void>;
// why: resolved once the part is written, so a target is read only as fast as the socket takes its parts.
readonly onRelayChunk?: (chunk: string) => Promise<void>;
// why: accepted by the server when it read the `relay.request` line, before the call parked for startup (ADR 0028).
readonly relayChannel?: LinkChannel;
/** `events.subscribe`/`events.unsubscribe` stay push-shaped (ADR §2: "pushes" stay with the
* transport), so the dispatcher's handler for them does nothing but call this: `true` to
* (re)subscribe, returning the new subscription id; `false` to tear an existing one down. */
Expand Down
Loading
Loading