Skip to content

Commit 22cd258

Browse files
authored
feat(gateway): relayed bodies travel on byte channels (#570)
Closes #558 ### Status Implement: done (1198 green) Review: round 2, clean; 2 text fixes unreviewed Hardware: n/a Gate: waiting for the stack ## Done when - [x] Every Tests line passes (`src/daemon`, `src/gateway`, `src/link`, `src/contract` unit files green on the head; CI checked). ## Assumptions - Assumption: where the spec says the startup tests are "modelled on `server.test.ts:1241`", they live in `src/daemon/server.test.ts` as a new `describe`, using the existing `createHarness` (given a `relayTargets` option) with a link pair on the uplink, and the fake clock of the link pair for the 60 s wait — the smallest change that reuses the harness. - Assumption: the protocol bump is tested as 34 (33 plus one) in the existing protocol-range tests, with 33 added to the list of previous versions the daemon refuses. - Assumption: `relayChannelSchema` is a placeholder (`z.string()`) in `src/contract/relay.ts` so the red tests compile; green gives it the 1–32 `[A-Za-z0-9-]` bound. - Assumption: a request that reaches an uplink before `start()` has claimed its socket parks on a gate that follows convergence — the startup tests send a relay in that window, and the conservative option is to park every non-`status.get` call there, as it already does after the claim. - Assumption: `src/daemon/relay.test.ts` (not named in F17) only changes how it builds its arguments: `relay.request` takes the accepted channel and the push has no `chunk`. - Assumption: the daemon test helpers `settle` and `readAll` are renamed `settleWithin` and `readParts`, so they do not repeat the link's exports (Fallow `duplicate-export`). ## Review Spec review: 7 blocking, 7 fixed, 0 notes. Code review: 5 blocking, 5 fixed, 0 notes. Claims review: 3 blocking, 3 fixed, 0 notes. Rounds: 2. Tokens: 9.6M. Fixed unreviewed: server.test.ts:1516 channel-before-parking assertion; COMPONENTS.md:45 Relay targets row. *Written by an agent.*
1 parent 6d35d3e commit 22cd258

36 files changed

Lines changed: 1986 additions & 903 deletions

‎docs/internal/ARCHITECTURE.md‎

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -897,28 +897,26 @@ receives. The gateway's `GatewayRelay` hands one `Request` to the worker's
897897
`relayTargets` under the module's capability name, and answers the target's
898898
`Response` with its body streamed. The core names no target.
899899

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

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

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

923921
### Aggregated reads
924922

‎docs/internal/COMPONENTS.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ rule 14); a single-file component's surface is what the file exports.
4141
| `DaemonEndpointHost` | `src/daemon/connection-host.ts` | Claiming the socket, recovering a stale entry, the listener lifecycle. | Anything after a connection is accepted. |
4242
| `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. |
4343
| `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. |
44-
| 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). |
45-
| 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. |
44+
| 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). |
45+
| 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. |
4646
| `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. |
4747

4848
## Core: device management
@@ -156,7 +156,7 @@ typed against and catalog matching (ARCHITECTURE.md, "Boundaries").
156156
| 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. |
157157
| `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. |
158158
| 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. |
159-
| `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. |
159+
| `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. |
160160
| `GatewayOwnerRoutedFacts` | `src/gateway/owner-routed-facts.ts` | The gateway's owner-attributed lease facts, from relayed worker events. | Emit a fact of its own. |
161161

162162
## Ports

‎docs/internal/adr/0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# 0028. The uplink carries byte channels beside its messages, and small messages go first
22

3-
- **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
3+
- **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
44
- **Date:** 2026-10-14
55
- **Issue:** [#552](https://github.com/callstackincubator/simlock/issues/552)
66
- **Narrows:** [ADR 0026](0026-agent-device-through-a-gateway-relays-over-the-uplink.md)

‎src/admin/index.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ describe("simlock/admin", () => {
1010
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("relayRequest");
1111
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("relayBody");
1212
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("relayCancel");
13+
expectTypeOf<SimlockAdminClient>().not.toHaveProperty("openChannel");
1314

1415
const documented = readFileSync(new URL("../../docs/CLIENT.md", import.meta.url), "utf8");
1516
expect(Object.keys(admin).filter((name) => /relay/i.test(name))).toEqual([]);

‎src/agent-device/gateway-front.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1301,9 +1301,10 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () =>
13011301
const held = member.fake.leases.get(hex(1));
13021302
expect(held).toBeDefined();
13031303
member.fake.leases.set(hex(2), { ...(held as NonNullable<typeof held>), leaseId: hex(2) });
1304+
// 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.
13041305
await rig.gateway.dispatch(
13051306
"lease.request",
1306-
{ leaseId: hex(2), platform: "ios", requesterId: hex(2), requires: ["agent-device"] },
1307+
{ leaseId: hex(2), platform: "ios", requesterId: "someone-else", requires: ["agent-device"] },
13071308
sessionFor(principals.one),
13081309
);
13091310
interceptRelay(rig, async ({ request }) => {
@@ -1998,8 +1999,15 @@ describe(
19981999

19992000
async function restarted(rig: Rig, member: Member, leases: number): Promise<void> {
20002001
await rig.restart();
2001-
// 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.
2002-
await advance(rig, 8_000, 500);
2002+
// 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.
2003+
await vi.waitFor(
2004+
async () => {
2005+
const view = await viewOf(rig, member.label);
2006+
if (view?.connection !== "connected") await advance(rig, 1_000, 500);
2007+
expect(view?.connection).toBe("connected");
2008+
},
2009+
{ interval: 20, timeout: 30_000 },
2010+
);
20032011
await untilRead(rig, member);
20042012
await expect.poll(async () => (await fleetLeases(rig)).length).toBe(leases);
20052013
}

‎src/contract/operations.test.ts‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
requestedDevice,
99
} from "./operations.js";
1010
import { PUSH_SCHEMAS } from "./pushes.js";
11+
import { relayChannelSchema } from "./relay.js";
1112
import type { Role } from "./roles.js";
1213
import { platformCatalogSchema } from "./schemas.js";
1314

@@ -80,7 +81,6 @@ const ROLE_MATRIX: ReadonlyArray<{
8081
},
8182
role: "admin",
8283
},
83-
{ name: "relay.body", input: { end: true, relayId: "r-1" }, role: "admin" },
8484
{ name: "relay.cancel", input: { relayId: "r-1" }, role: "admin" },
8585
];
8686

@@ -162,7 +162,6 @@ const EFFECT_MATRIX: ReadonlyArray<{
162162
},
163163
effect: "write",
164164
},
165-
{ name: "relay.body", input: { end: true, relayId: "r-1" }, effect: "write" },
166165
{ name: "relay.cancel", input: { relayId: "r-1" }, effect: "write" },
167166
];
168167

@@ -1556,3 +1555,40 @@ describe("lease.request requires", () => {
15561555
);
15571556
});
15581557
});
1558+
1559+
describe("relay.request on a byte channel", () => {
1560+
const request = {
1561+
hasBody: false,
1562+
headers: [],
1563+
method: "GET",
1564+
relayId: "r-1",
1565+
target: "agent-device",
1566+
tenant: "gw.g.a",
1567+
url: "http://gateway.test/x",
1568+
};
1569+
const parse = (input: Record<string, unknown>) =>
1570+
OPERATIONS["relay.request"].input.safeParse(input).success;
1571+
1572+
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", () => {
1573+
expect(parse({ ...request, channel: "a" })).toBe(true);
1574+
expect(parse({ ...request, channel: "Ab-9".repeat(8) })).toBe(true);
1575+
expect(parse({ ...request, channel: "" })).toBe(false);
1576+
expect(parse({ ...request, channel: "a".repeat(33) })).toBe(false);
1577+
expect(parse({ ...request, channel: "a b" })).toBe(false);
1578+
expect(parse({ ...request, channel: "a_b" })).toBe(false);
1579+
expect(parse(request)).toBe(false);
1580+
});
1581+
1582+
it("relayChannelSchema holds the same bound the operation uses", () => {
1583+
expect(relayChannelSchema.safeParse("a".repeat(32)).success).toBe(true);
1584+
expect(relayChannelSchema.safeParse("a".repeat(33)).success).toBe(false);
1585+
expect(relayChannelSchema.safeParse("").success).toBe(false);
1586+
expect(relayChannelSchema.safeParse("a b").success).toBe(false);
1587+
});
1588+
1589+
it("OPERATIONS has no relay.body and PUSH_SCHEMAS has no relay-chunk", () => {
1590+
expect(Object.keys(OPERATIONS)).not.toContain("relay.body");
1591+
expect(Object.keys(PUSH_SCHEMAS)).not.toContain("relay-chunk");
1592+
expect(Object.keys(PUSH_SCHEMAS)).toContain("relay-head");
1593+
});
1594+
});

‎src/contract/operations.ts‎

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { z } from "zod";
1111

1212
import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js";
1313
import { parseOsConstraint } from "./os-range.js";
14-
import { relayChunkSchema, relayHeadersSchema, relayIdSchema } from "./relay.js";
14+
import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js";
1515
import { ownsLease, type AuthorizeContext, type Role } from "./roles.js";
1616
import {
1717
capabilityNameSchema,
@@ -977,8 +977,9 @@ const relayUrlSchema = z
977977

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

1007-
/** One part of a relayed request body, in `seq` order, or its end. */
1008-
// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface.
1009-
export const relayBody = defineOperation({
1010-
name: "relay.body",
1011-
role: "admin",
1012-
effect: "write",
1013-
input: z.union([
1014-
z
1015-
.object({ relayId: relayIdSchema, seq: z.number().int().min(0), chunk: relayChunkSchema })
1016-
.strict(),
1017-
z.object({ relayId: relayIdSchema, end: z.literal(true) }).strict(),
1018-
]),
1019-
output: z.object({}),
1020-
});
1021-
10221009
// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface.
10231010
export const relayCancel = defineOperation({
10241011
name: "relay.cancel",
@@ -1062,7 +1049,6 @@ export const OPERATIONS = {
10621049
"device.add": deviceAdd,
10631050
"device.remove": deviceRemove,
10641051
"relay.request": relayRequest,
1065-
"relay.body": relayBody,
10661052
"relay.cancel": relayCancel,
10671053
} as const;
10681054

‎src/contract/protocol.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export interface ProtocolRange {
1010
const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() });
1111

1212
/** 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. */
13-
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 33, max: 33 };
13+
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 34, max: 34 };
1414

1515
const LEGACY_DAEMON_PROTOCOL_VERSION = 2;
1616

‎src/contract/pushes.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22
* why: server pushes (ADR 0003 §8). Three families, each with its correlation key required by
33
* schema:
44
*
5-
* - Request-scoped (`progress`, `started`, `output`, `component-progress`, `relay-head`,
6-
* `relay-chunk`): carries the
5+
* - Request-scoped (`progress`, `started`, `output`, `component-progress`, `relay-head`): carries the
76
* originating request's frame id.
87
* - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id,
98
* and goes to every live connection whose principal owns that lease (ADR 0004 §5 keeps
@@ -15,7 +14,7 @@
1514
*/
1615
import { z } from "zod";
1716

18-
import { relayChunkSchema, relayHeadersSchema } from "./relay.js";
17+
import { relayHeadersSchema } from "./relay.js";
1918
import { eventEnvelopeSchema, leaseProgressSchema } from "./schemas.js";
2019

2120
/**
@@ -105,11 +104,6 @@ const relayHeadPushSchema = z.object({
105104
headers: relayHeadersSchema,
106105
});
107106

108-
const relayChunkPushSchema = z.object({
109-
requestId: requestIdSchema,
110-
chunk: relayChunkSchema,
111-
});
112-
113107
const leaseLostPushSchema = z.object({
114108
leaseId: z.string(),
115109
deviceId: z.string(),
@@ -139,7 +133,6 @@ export const PUSH_SCHEMAS = {
139133
started: startedPushSchema,
140134
"component-progress": componentProgressPushSchema,
141135
"relay-head": relayHeadPushSchema,
142-
"relay-chunk": relayChunkPushSchema,
143136
"lease-lost": leaseLostPushSchema,
144137
"device-unhealthy": deviceUnhealthyPushSchema,
145138
"device-recovered": deviceRecoveredPushSchema,

‎src/contract/relay.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,14 @@
55
import { z } from "zod";
66

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

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

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

13+
// why: the channel id is wire input the worker checks before it accepts a channel (ADR 0028).
14+
export const relayChannelSchema = z.string().regex(/^[A-Za-z0-9-]{1,32}$/);
15+
1816
export const relayHeadersSchema = z
1917
.array(
2018
z.tuple([
@@ -27,8 +25,6 @@ export const relayHeadersSchema = z
2725
)
2826
.max(RELAY_MAX_HEADERS);
2927

30-
export const relayChunkSchema = z.string().max(RELAY_MAX_CHUNK_CHARACTERS).regex(BASE64);
31-
3228
// why: the relay re-creates these on each side instead of carrying them.
3329
const FRAMING_HEADERS: ReadonlySet<string> = new Set([
3430
"connection",

0 commit comments

Comments
 (0)