Repository navigation
Description
Part of #552.
Scope
After this PR, simlock has a link module (ADR 0028 §1–3): it wraps an
uplink transport connection, passes text messages through unchanged and
ahead of bulk bytes, and offers byte channels with credit. The uplink
transport port carries binary messages. Nothing in the daemons uses the
link yet: #558 wraps the uplink with it and moves relay bodies onto
channels, where the wiring is first tested. Tests drive the link directly.
The task stays whole: the transport half (port, WebSocket adapter,
in-memory pair) has three test lines of its own, and the link's tests need
it.
Every value this task builds is in #552's Shared values table.
In short
New term:
- byte channel: a pair of byte streams, one each way, between the
gateway and one worker, over that worker's uplink. Example: feat(gateway): relayed bodies travel on byte channels #558 opens
one per relayed HTTP exchange; the upload goes one way, the response the
other.
flowchart LR
U["tests now; #558 later"] -->|text messages, openChannel / acceptChannel| L["link module (new)"]
L -->|text + binary messages| P["uplink transport port *"]
P --> WS["WebSocket adapter *"]
P --> MP["in-memory pair *"]
(* = changed.) If this goes wrong, nothing changes for users yet; #558
would find a link that loses, reorders or stalls bytes or messages.
Technical spec
Facts
| # | Fact | Source |
|---|---|---|
| F1 | IpcConnection carries strings only: onData(chunk: string), write(contents: string) |
src/ports/ipc.ts:20-27 |
| F2 | The WebSocket adapter drops every binary message it receives, and buffers text that arrives before the first onData because the gateway's hello can arrive before the worker subscribes |
src/ports/uplink-websocket.ts:69, :49-61 |
| F3 | The WebSocket adapter's write sends one text message and resolves on ws's send callback; a write to a closed socket resolves without sending |
src/ports/uplink-websocket.ts:115-125 |
| F4 | The uplink connector returns an IpcConnection; an accepted uplink carries an IpcConnection |
src/ports/uplink.ts:157, :64 |
| F5 | The port's implementers: the WebSocket listener and connector, MemoryUplinkTransport, and the test's ScriptedConnector; createConnectionPair hands out PairedConnections |
src/ports/uplink-websocket.ts:146, :251; src/ports/uplink.ts:187, :233, :241; src/daemon/gateway-uplink.test.ts:16, :263-267 (an inline connector) |
| F6 | DaemonServer and SimlockWire subscribe to onData, onClose and onError |
src/daemon/server.ts:680-682; src/simlock-client/wire.ts:127, :128, :133 |
| F7 | ws negotiates no compression here: the server's perMessageDeflate defaults to false |
node_modules/ws/lib/websocket-server.js:67 (ws 8.18.3, package.json) |
| F8 | ws reports no event when its buffered amount drops; a send's callback fires once that message is written |
node_modules/ws/lib/websocket.js:119 (bufferedAmount), :448 (send(data, options, cb)); its only drain (:229) is the receiver's |
| F9 | Clock and FakeClock are ports for timers in tests |
src/ports/clock.ts:5, :31 |
| F10 | Every wait that crosses a process boundary must be bounded | docs/internal/agent-rules/architecture.md:80 |
| F11 | Every directory under src/ with an index.ts is a component that lint makes others enter through its index |
docs/internal/agent-rules/architecture.md:104-111 |
Modules touched
flowchart LR
LK["link/ (new): index, channel, scheduler, envelope"] --> UP["ports/uplink.ts *"]
UP --> WSA["ports/uplink-websocket.ts *"]
LK --> CK["ports: Clock, Logger"]
GT["daemon/gateway-uplink.test.ts * (ScriptedConnector)"] --> UP
(* = changed.)
Transport port (src/ports/uplink.ts). New interface
UplinkTransportConnection extends IpcConnection:
writeBinary(bytes: Uint8Array): Promise<void>,
onBinary(listener: (bytes: Uint8Array) => void): () => void,
readonly unsentBytes: number, and onSent(listener: () => void): () => void,
called whenever written bytes leave and unsentBytes drops. The
connector, the accepted uplink and createConnectionPair hand it out
(F4, F5); ScriptedConnector and the inline connector at
src/daemon/gateway-uplink.test.ts:263-267 return one. DaemonServer#acceptUplink,
GatewayUplinkOptions.accept and WorkerLink are unchanged: a transport
connection is an IpcConnection.
- In-memory pair. Carries binary messages; a binary message that
arrives with noonBinarylistener is dropped, as the WebSocket adapter
drops them today.hold()andrelease(): while held, written messages
stay unsent, count inunsentBytes(text by its UTF-8 bytes), and their
writeandwriteBinarypromises stay pending;releasedelivers them
in order, resolves the promises and firesonSent; closing a held pair
resolves them unsent.fail(error)raises a transport error on that end
and closes it, for tests. OtherwiseunsentBytesis 0. - WebSocket adapter. Sends a
Uint8Arrayas one binary message,
resolving on the send callback likewrite(F3). Delivers received
binary messages toonBinaryinstead of dropping them (F2); one that
arrives with noonBinarylistener is still dropped, so nothing piles up
before a link subscribes.unsentBytesis the socket's
bufferedAmount; each send callback firesonSent(F8).
Link module (new src/link/, a component through its index.ts,
F11). Exports createLink(transport, { end: "worker" | "gateway", clock, logger }), returning a LinkConnection, and the types LinkConnection,
LinkChannel and LinkChannelError.
LinkConnectionis anIpcConnection(F1, F6). Text that arrives
before the firstonDatais buffered and delivered to it.onClose
attached after the close fires at once. Transport errors reach
onError.writeresolves when the transport'swriteresolves; a
text message queued when the connection closes resolves without being
sent, as a write to a closed socket does today (F3). Closing the link
closes the transport; the transport closing closes the link.openChannel({ signal }): the signal is required. Resolves with a
LinkChannelonce itsOPENis queued ahead of any later message. With
64 channels already open from this side it waits until one ends; it
rejects with the signal's reason when the signal aborts, and with
closedwhen the connection closes. Waiters get a free slot first in,
first out. Numbers are 32-bit; if this side's run out,openChannel
rejects and the link logs it.acceptChannel(id)throws for an id the peer never opened, one already
accepted, and one already ended.LinkChannel:id(1–32 characters of[A-Za-z0-9-]),readable,
writable(standard Web streams of bytes),abort(reason?),credit
andwhenCredit().creditis the peer's remaining window less what
the link already holds unsent for this channel. The link takes as much
of a written chunk ascreditallows at once and the rest as credit
arrives, so a chunk of any size goes through; the write resolves once
all of it is taken, and thewritablequeues at most 64 KiB more
behind it before its writer waits.whenCredit()resolves when credit
arrives, and rejects when the channel fails or its sending direction
ends. The 60 s stall runs only while a write or awhenCredit()waits
and the peer already holds every byte this channel sent: the reader has
everything and grants nothing. Waiting behind the bulk lane or a held
transport never counts.- Ending: closing the
writablesendsEND; cancelling thereadable
sendsSTOP. OnSTOPthe peer'swritableerrors withstopped, the
peer sendsENDfor that direction to acknowledge it, and the other
direction goes on.DATAthat arrives after this side sentSTOPand
before thatENDis dropped quietly. ASTOPfor a direction whose
ENDthis side already sent is ignored, since thatENDalready
answers it, and cancelling areadablewhoseENDhas already
arrived sends nothing; so aSTOPand anENDcrossing on the wire is
never a rule break. On each side, a direction is done
once this side'sENDorRESETfor it has been written to the
transport and the peer'sENDorRESETfor it has arrived (after a
STOP, the peer's acknowledgingEND). A channel ends, and stops
counting toward the 64, once both directions are done on that side;
numbers are never reused on a connection. LinkChannelError.reason:aborted(either side aborted; the side that
calledabort(reason)gets its reason string as the error's message,
the peer gets none),invalid(the
peer broke a rule),not-accepted(the peer did not accept within
30 s),stalled(a write waited 60 s with no credit arriving),closed
(the connection closed); a writer stopped by its peer errors with
stopped.RESETcarries the first four as a code so both sides report
the same reason; a user's own abort reason string stays on its side.- Inside, private, as ADR 0028 §2: envelopes
OPEN,DATA(at most
64 KiB),END,STOP,CREDIT(at least 1),RESET; numbers (worker
odd, gateway even); the first 4 MiB each way need no credit, and the
receiver holds at most 4 MiB unread per channel; credit granted as the
user reads, oneCREDITper 64 KiB read or when the reader has read
everything it holds; one scheduler per connection with a priority lane (text,
OPEN,STOP,CREDIT,RESET) and a bulk lane (DATA,END) that
hands a message to the transport only whileunsentBytesis under
256 KiB and wakes ononSent; channels take turns; the bulk lane sends
at least one message per 64 KiB (UTF-8 bytes) of priority messages while it has one it
may send. A text message never waits for a bulk turn the 256 KiB mark
blocks. - Rule breaks (ADR 0028 §2's list) are dropped, never buffered; the named
channel, when held, is reset withinvalid; the link logs which rule.
Numbers are never reused, so a message naming a number of the right
parity at or below the highest the peer has opened, but no longer held
here, is late traffic for an ended channel: it is dropped quietly and
never answered. Only a number the peer never opened is a rule break.
Contract and event changes
None. No message changes, no protocol bump, no events.
Other code on the same state
The state is the uplink transport connection.
GatewayUplink,GatewayService,WorkerLink,DaemonServer: still
receive the transport connection as anIpcConnection; nothing wraps it
with the link until feat(gateway): relayed bodies travel on byte channels #558. Their behaviour does not change.- Tests that hand
createConnectionPairends toDaemonServer
(src/daemon/server.test.ts:2861,:2891,:2915;
src/daemon/test-relay-support.ts:187;
src/daemon/relay-gateway.e2e.test.ts:158) andScriptedConnector
(src/daemon/gateway-uplink.test.ts:16,:29,:272): typecheck
against the new return type; behaviour unchanged.
Rules in play
architecture.md: rule 11 (every wait bounded: open, accept, credit,
whenCredit), rule 14 (the module's surface is its index), rule 9 (the
transport is a port with an in-memory fake).safety.md: rule 10, every binary message from the peer is a claim:
length, type, number, size and credit checked before use.testing.md: lane order and credit tests fail on a named assertion,
not a timeout.
Tests
Seam: createLink from src/link/index.ts over createConnectionPair
ends (with hold/release and FakeClock), and over the real WebSocket
adapter on 127.0.0.1. Model: src/ports/uplink.test.ts and
src/ports/uplink-websocket.test.ts. Rule-break tests write raw binary
messages into one transport end.
- text messages written on one link arrive on the other unchanged and in order, over the in-memory pair and over the real WebSocket
- text that arrives before the first
onDatais delivered to it; anonCloseattached after the close fires; a pair'sfail(error)reachesonError; closing the transport fails every open channel withclosed; closing the link closes the transport writeresolves when the transport's write resolves; a text message queued at close resolves unsent, also when the pair was held- 20 MiB written to a channel arrives byte for byte at the accepted channel, each way at once, over the real WebSocket
- over the real WebSocket, a 20 MiB channel transfer puts at most 20.2 MiB on the socket, in binary messages
- a text message written right after
openChannelresolves never reaches the peer before the channel'sOPEN, even with the transport held - bytes written right after
openChannel, before the peer accepts, arrive once it accepts - with credit left but the bulk lane held, the
writabletakes the chunks that fit increditand then at most 64 KiB more before its writer waits - a writer whose peer never accepts stops after 4 MiB; 30 s after the open its streams error with
not-accepted, and the peer'sacceptChannelfor that id then throws - a reader that stops reading holds its writer after 4 MiB unread, and reading again lets it go on
- a write that waits 60 s with no credit arriving errors both sides' streams with
stalled; a reader that reads 64 KiB every 50 s keeps a 10 MiB transfer going without a reset creditcounts down as the writer writes and up as the peer reads;whenCredit()resolves when credit arrives, rejects when the channel fails, when the peer stops that direction and when this side closes its ownwritable, and awhenCredit()pending 60 s, with the peer holding every byte and granting nothing, errors the channelstalled- a single 20 MiB write goes through in parts as credit arrives, and resolves once all of it is taken
- with the transport held for 90 s and a write waiting behind it, the channel is not reset
- a writer that writes no more than
credit, against a reader that reads nothing for 10 minutes, is never reset - a channel whose peer sends nothing for 10 minutes, with no write waiting, stays open
- one channel's stalled reader does not slow another channel on the same link
- with the transport held and 1 MiB of channel bytes queued, a text message written next is sent before all but at most 256 KiB plus one 64 KiB message of them
- with text messages written without pause and channel bytes queued, at least one channel message goes out per 64 KiB of text
- two channels with bytes queued take turns, one message each
- closing a
writableends the peer'sreadable; cancelling areadableerrors the peer'swritablewithstopped,DATAstill in flight is dropped without a reset, and the peer's acknowledgingENDarrives; either way the other direction still carries bytes to its end - a
STOPand anENDfor the same direction crossing on the wire (the reader cancels while the writer closes, with the transport held) end that direction on both sides with no reset and no secondEND; cancelling areadableafter itsENDarrived sends nothing abort("why")on one side errors both streams on both sides withaborted; the aborting side's error message iswhy, and the peer's carries no reason stringacceptChannelthrows for an id never opened, an id already accepted and an id already ended- channel ids match
[A-Za-z0-9-]{1,32}, checked over 200 channels from each end - with 64 channels open from one side, the 65th
openChannelwaits, resolves once one ends, rejects with the signal's reason when its signal aborts first, and rejects withclosedwhen the connection closes; three waiters get slots in the order they asked - with this side's numbers exhausted (a test hook sets the next number to the last one), the next
openChannelrejects and the link logs it - with 64 channels open, ending one and opening another at once never makes the peer see 65, even with the transport held
- 50 channels opened at once from each end never collide, and 200 opened and ended one after another each get a new number
- each of these is dropped, resets the channel it names (when held) with
invalid, is logged, and leaves text flowing:DATApast the allowed bytes,DATAover 64 KiB,DATAorENDafter that direction ended, aCREDITof 0, credit beyond 4 MiB outstanding - each of these is dropped and logged and leaves text flowing: a channel number the peer never opened, an
OPENreusing a live number, anOPENwith the wrong parity, a 65thOPENfrom the peer, an unknown envelope type, a message too short to read - a
RESETfor a channel this side does not hold is dropped and not answered - a
STOPthat arrives after its channel ended on this side (this side'sENDwritten and the peer'sENDarrived, then the peer cancels its reader) is dropped quietly: no log, no reset, no answer - the WebSocket adapter sends
writeBinarybytes as one binary message and resolves on its send callback (and at once on a closed socket); it delivers a received binary message toonBinary, drops one that arrives with no listener, andunsentBytesfollows the socket's buffered amount withonSentfiring when a send completes - the in-memory pair carries binary messages and drops one with no
onBinarylistener; while held,unsentBytescounts what is written (text in UTF-8 bytes), nothing arrives and the write promises stay pending, untilreleasedelivers them in order and firesonSent
Done when
- Every Tests line passes.
Out of scope
- Wrapping the uplink with the link in either daemon, and any user of
channels (feat(gateway): relayed bodies travel on byte channels #558). - Any contract change or protocol bump (feat(gateway): relayed bodies travel on byte channels #558).
- The download size cap (feat(agent-device): a download over 2 GB fails, never cut short #557).
Depends on
Written by an agent.
Activity
feat(link): the uplink carries byte channels beside its messages, and…
test(link): credit batching, cancel after END, a failed pair closes, …
fix(link): a failed channel still counts the peer's END, tests fail o…
test: the uplink carries byte channels beside its messages, and small…
feat(link): the uplink carries byte channels beside its messages, and…
test(link): credit batching, cancel after END, a failed pair closes, …
fix(link): a failed channel still counts the peer's END, tests fail o…
fix(link): test support reaches the WebSocket adapters through the po…
feat(link): the uplink carries byte channels beside its messages, and…