@statewalker/webrun-streams-conformance 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ import type { MessagePipe } from "@statewalker/webrun-streams";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ /**
5
+ * One adapter's pipe over a fake (or real) transport, with handles to drive
6
+ * the transport from the outside.
7
+ */
8
+ export interface MessagePipeHarness {
9
+ /** What the adapter returned: `{ target, signal, maxMessageSize }`. */
10
+ pipe: MessagePipe;
11
+ /** The transport delivers one inbound message, as the adapter's transport would. */
12
+ inject(data: unknown): void | Promise<void>;
13
+ /** What the adapter has put on the transport so far, one entry per message. */
14
+ sent(): Uint8Array[] | Promise<Uint8Array[]>;
15
+ /** The transport ends on its own (the peer went away). */
16
+ endRemotely(): void | Promise<void>;
17
+ /** Makes the transport report `bytes` buffered. Absent: the drain cases are skipped. */
18
+ setBuffered?(bytes: number): void;
19
+ /** Lets the adapter see buffered bytes go down, where it needs an event for it. */
20
+ settle?(): void | Promise<void>;
21
+ /** Releases anything the harness holds. */
22
+ dispose?(): void | Promise<void>;
23
+ }
24
+
25
+ export interface DescribeMessagePipeOptions {
26
+ /** Build a pipe with this frame ceiling. Absent: the ceiling cases are skipped. */
27
+ withMaxFrameBytes?: (maxFrameBytes: number) => MessagePipeHarness | Promise<MessagePipeHarness>;
28
+ /** The adapter's drain low-water mark. Default 256 KiB. */
29
+ drainLowWater?: number;
30
+ }
31
+
32
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
33
+
34
+ /**
35
+ * The contract every pipe of byte messages keeps (statewalker/webrun-wire#151),
36
+ * run against an adapter through its harness. The pipe module
37
+ * (`newMessagePipe` in `@statewalker/webrun-streams`) implements it once; each
38
+ * `webrun-streams-*` adapter runs this suite to show it still does.
39
+ */
40
+ export function describeMessagePipe(
41
+ name: string,
42
+ make: () => MessagePipeHarness | Promise<MessagePipeHarness>,
43
+ options: DescribeMessagePipeOptions = {},
44
+ ): void {
45
+ const lowWater = options.drainLowWater ?? 256 * 1024;
46
+
47
+ async function withHarness(
48
+ build: () => MessagePipeHarness | Promise<MessagePipeHarness>,
49
+ body: (h: MessagePipeHarness) => Promise<void>,
50
+ ): Promise<void> {
51
+ const h = await build();
52
+ try {
53
+ await body(h);
54
+ } finally {
55
+ await h.dispose?.();
56
+ }
57
+ }
58
+
59
+ describe(`${name}: the message pipe contract`, () => {
60
+ it("carries its own life and ceiling: target.closeSignal is the signal, target.maxMessageSize the ceiling", () =>
61
+ withHarness(make, async ({ pipe }) => {
62
+ expect(pipe.target.closeSignal).toBe(pipe.signal);
63
+ expect(pipe.target.maxMessageSize).toBe(pipe.maxMessageSize);
64
+ }));
65
+
66
+ it("delivers inbound bytes to every listener as Uint8Array, in order, past a faulty listener", () =>
67
+ withHarness(make, async (h) => {
68
+ const got: number[][] = [];
69
+ const other: number[][] = [];
70
+ h.pipe.target.addEventListener("message", () => {
71
+ throw new Error("a faulty listener");
72
+ });
73
+ h.pipe.target.addEventListener("message", async () => {
74
+ throw new Error("a rejecting listener");
75
+ });
76
+ h.pipe.target.addEventListener("message", (e) => {
77
+ expect(e.data).toBeInstanceOf(Uint8Array);
78
+ got.push([...(e.data as Uint8Array)]);
79
+ });
80
+ const removed = (e: MessageEvent) => {
81
+ other.push([...(e.data as Uint8Array)]);
82
+ };
83
+ h.pipe.target.addEventListener("message", removed);
84
+ h.pipe.target.removeEventListener("message", removed);
85
+ await h.inject(new Uint8Array([1, 2]));
86
+ await h.inject(new Uint8Array([3]).buffer);
87
+ await h.inject(new Uint8Array([9, 4, 9]).subarray(1, 2));
88
+ await flush();
89
+ expect(got).toEqual([[1, 2], [3], [4]]);
90
+ expect(other).toEqual([]);
91
+ expect(h.pipe.signal.aborted).toBe(false);
92
+ }));
93
+
94
+ it("sends bytes one message each, and refuses anything else with TypeError", () =>
95
+ withHarness(make, async (h) => {
96
+ h.pipe.target.postMessage(new Uint8Array([1, 2, 3]));
97
+ h.pipe.target.postMessage(new Uint8Array([4, 5]).buffer);
98
+ expect(() => h.pipe.target.postMessage("text")).toThrow(TypeError);
99
+ expect(() => h.pipe.target.postMessage({ a: 1 })).toThrow(TypeError);
100
+ await flush();
101
+ expect((await h.sent()).map((b) => [...b])).toEqual([
102
+ [1, 2, 3],
103
+ [4, 5],
104
+ ]);
105
+ }));
106
+
107
+ it("ends when the transport ends: the signal aborts with an Error, and a post is a no-op", () =>
108
+ withHarness(make, async (h) => {
109
+ await h.endRemotely();
110
+ await flush();
111
+ expect(h.pipe.signal.aborted).toBe(true);
112
+ expect(h.pipe.signal.reason).toBeInstanceOf(Error);
113
+ const before = (await h.sent()).length;
114
+ h.pipe.target.postMessage(new Uint8Array([1]));
115
+ await flush();
116
+ expect((await h.sent()).length).toBe(before);
117
+ }));
118
+
119
+ it("close() ends the pipe: the signal aborts, and nothing more is delivered", () =>
120
+ withHarness(make, async (h) => {
121
+ const got: unknown[] = [];
122
+ h.pipe.target.addEventListener("message", (e) => {
123
+ got.push(e.data);
124
+ });
125
+ await h.pipe.target.close();
126
+ expect(h.pipe.signal.aborted).toBe(true);
127
+ await h.inject(new Uint8Array([1]));
128
+ await flush();
129
+ expect(got).toEqual([]);
130
+ // A second close is harmless.
131
+ await h.pipe.target.close();
132
+ }));
133
+
134
+ if (options.withMaxFrameBytes) {
135
+ const build = () => options.withMaxFrameBytes?.(100) as Promise<MessagePipeHarness>;
136
+ it("a message of exactly maxFrameBytes is sent; one byte past it ends the pipe with RangeError", () =>
137
+ withHarness(build, async (h) => {
138
+ h.pipe.target.postMessage(new Uint8Array(100));
139
+ expect(h.pipe.signal.aborted).toBe(false);
140
+ expect(() => h.pipe.target.postMessage(new Uint8Array(101))).toThrow(RangeError);
141
+ expect(h.pipe.signal.aborted).toBe(true);
142
+ expect(h.pipe.signal.reason).toBeInstanceOf(RangeError);
143
+ await flush();
144
+ expect((await h.sent()).map((b) => b.byteLength)).toEqual([100]);
145
+ }));
146
+ }
147
+
148
+ it("whenDrained resolves at once on an idle pipe, and once the pipe ended", () =>
149
+ withHarness(make, async (h) => {
150
+ await h.pipe.target.whenDrained();
151
+ await h.endRemotely();
152
+ await h.pipe.target.whenDrained();
153
+ }));
154
+
155
+ it("a pending whenDrained resolves when the buffer drains to the low-water mark", () =>
156
+ withHarness(make, async (h) => {
157
+ if (!h.setBuffered) return;
158
+ h.setBuffered(lowWater + 1);
159
+ expect(h.pipe.target.bufferedAmount).toBe(lowWater + 1);
160
+ let drained = false;
161
+ const wait = h.pipe.target.whenDrained().then(() => {
162
+ drained = true;
163
+ });
164
+ await new Promise((resolve) => setTimeout(resolve, 20));
165
+ expect(drained).toBe(false);
166
+ h.setBuffered(lowWater);
167
+ await h.settle?.();
168
+ await wait;
169
+ expect(drained).toBe(true);
170
+ }));
171
+
172
+ it("a pending whenDrained resolves when the pipe ends", () =>
173
+ withHarness(make, async (h) => {
174
+ if (!h.setBuffered) return;
175
+ h.setBuffered(lowWater + 1);
176
+ const wait = h.pipe.target.whenDrained();
177
+ await h.endRemotely();
178
+ await wait;
179
+ }));
180
+ });
181
+ }
@@ -0,0 +1,199 @@
1
+ import type { NativePort, NativePortMux, ValueCodec } from "@statewalker/webrun-streams";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ /** Two ends of one connection, from an adapter that opens a channel per port. */
5
+ export interface PortMuxHarness {
6
+ /** A mux that opens ports and accepts none. */
7
+ opener: NativePortMux;
8
+ /** A mux on the other end, handing each port the opener opens to `onPort`. */
9
+ serve(onPort: (port: NativePort) => boolean | undefined): Promise<NativePortMux>;
10
+ /** Releases the connection. */
11
+ dispose(): void | Promise<void>;
12
+ }
13
+
14
+ /** Builds two connected ends whose muxes use `codec`. */
15
+ export type MakePortMuxHarness = (codec: ValueCodec) => Promise<PortMuxHarness>;
16
+
17
+ /** A value whose encoding the contract's codec refuses to decode. */
18
+ const POISON = "\u0000poison";
19
+
20
+ /** JSON, except that {@link POISON} encodes to a frame `decode` rejects. */
21
+ const contractCodec: ValueCodec = {
22
+ encode: (value) =>
23
+ value === POISON ? new Uint8Array([0xff]) : new TextEncoder().encode(JSON.stringify(value)),
24
+ decode: (bytes) => {
25
+ if (bytes.byteLength === 1 && bytes[0] === 0xff) throw new Error("undecodable");
26
+ return JSON.parse(new TextDecoder().decode(bytes));
27
+ },
28
+ };
29
+
30
+ const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
31
+
32
+ async function until(predicate: () => boolean, label: string, ms = 5000): Promise<void> {
33
+ const deadline = Date.now() + ms;
34
+ while (!predicate()) {
35
+ if (Date.now() > deadline) throw new Error(`timed out waiting for: ${label}`);
36
+ await tick(5);
37
+ }
38
+ }
39
+
40
+ function received(port: NativePort): unknown[] {
41
+ const got: unknown[] = [];
42
+ port.addEventListener("message", (e) => {
43
+ got.push(e.data);
44
+ });
45
+ return got;
46
+ }
47
+
48
+ /**
49
+ * The lifecycle every native port mux keeps (statewalker/webrun-wire#152): the
50
+ * module (`newNativePortMux` in `@statewalker/webrun-streams`) implements it
51
+ * once, and each transport (an in-memory one, WebRTC, libp2p) runs this suite.
52
+ */
53
+ export function describePortMux(name: string, make: MakePortMuxHarness): void {
54
+ async function withPair(
55
+ body: (h: PortMuxHarness, inbound: NativePort[], server: NativePortMux) => Promise<void>,
56
+ accept: (port: NativePort) => boolean | undefined = () => true,
57
+ ): Promise<void> {
58
+ const h = await make(contractCodec);
59
+ const inbound: NativePort[] = [];
60
+ try {
61
+ const server = await h.serve((port) => {
62
+ inbound.push(port);
63
+ return accept(port);
64
+ });
65
+ await body(h, inbound, server);
66
+ } finally {
67
+ await h.opener.close().catch(() => undefined);
68
+ await h.dispose();
69
+ }
70
+ }
71
+
72
+ describe(`${name}: the native port mux contract`, () => {
73
+ it("a port opened on one end arrives on the other; values cross both ways, encoded", () =>
74
+ withPair(async (h, inbound) => {
75
+ const port = await h.opener.openPort();
76
+ const fromServer = received(port);
77
+ port.postMessage({ n: 1, s: "a" });
78
+ await until(() => inbound.length === 1, "the inbound port");
79
+ const server = inbound[0] as NativePort;
80
+ const fromClient = received(server);
81
+ await until(() => fromClient.length === 1, "the first message");
82
+ server.postMessage([2, "b"]);
83
+ await until(() => fromServer.length === 1, "the answer");
84
+ expect(fromClient).toEqual([{ n: 1, s: "a" }]);
85
+ expect(fromServer).toEqual([[2, "b"]]);
86
+ }));
87
+
88
+ it("messages that arrive before a port's first listener are held, for every listener added in that tick", () =>
89
+ withPair(async (h, inbound) => {
90
+ const port = await h.opener.openPort();
91
+ port.postMessage(1);
92
+ port.postMessage(2);
93
+ port.postMessage(3);
94
+ await until(() => inbound.length === 1, "the inbound port");
95
+ await tick(50);
96
+ const server = inbound[0] as NativePort;
97
+ const first = received(server);
98
+ const second = received(server);
99
+ await until(() => first.length === 3 && second.length === 3, "the held messages");
100
+ expect(first).toEqual([1, 2, 3]);
101
+ expect(second).toEqual([1, 2, 3]);
102
+ }));
103
+
104
+ it("removeEventListener stops delivery to that listener", () =>
105
+ withPair(async (h, inbound) => {
106
+ const port = await h.opener.openPort();
107
+ port.postMessage("one");
108
+ await until(() => inbound.length === 1, "the inbound port");
109
+ const server = inbound[0] as NativePort;
110
+ const kept: unknown[] = [];
111
+ const dropped: unknown[] = [];
112
+ const drop = (e: MessageEvent) => {
113
+ dropped.push(e.data);
114
+ };
115
+ server.addEventListener("message", (e) => {
116
+ kept.push(e.data);
117
+ });
118
+ server.addEventListener("message", drop);
119
+ await until(() => kept.length === 1, "the first message");
120
+ server.removeEventListener("message", drop);
121
+ port.postMessage("two");
122
+ await until(() => kept.length === 2, "the second message");
123
+ expect(dropped).toEqual(["one"]);
124
+ }));
125
+
126
+ it("a port the serving end refuses fails: the opener's close signal aborts", () =>
127
+ withPair(
128
+ async (h) => {
129
+ const port = await h.opener.openPort();
130
+ port.postMessage("hello");
131
+ await until(() => port.closeSignal.aborted, "the refusal");
132
+ },
133
+ () => false,
134
+ ));
135
+
136
+ it("an onPort that throws refuses the port", () =>
137
+ withPair(
138
+ async (h) => {
139
+ const port = await h.opener.openPort();
140
+ port.postMessage("hello");
141
+ await until(() => port.closeSignal.aborted, "the refusal");
142
+ },
143
+ () => {
144
+ throw new Error("onPort failed");
145
+ },
146
+ ));
147
+
148
+ it("a frame the codec cannot decode fails the receiving port", () =>
149
+ withPair(async (h, inbound) => {
150
+ const port = await h.opener.openPort();
151
+ port.postMessage("fine");
152
+ await until(() => inbound.length === 1, "the inbound port");
153
+ const server = inbound[0] as NativePort;
154
+ received(server);
155
+ port.postMessage(POISON);
156
+ await until(() => server.closeSignal.aborted, "the receiving port failed");
157
+ expect(String((server.closeSignal.reason as Error)?.message)).toMatch(/decode/);
158
+ }));
159
+
160
+ it("closing a port ends it on both ends", () =>
161
+ withPair(async (h, inbound) => {
162
+ const port = await h.opener.openPort();
163
+ port.postMessage("hello");
164
+ await until(() => inbound.length === 1, "the inbound port");
165
+ await port.close();
166
+ expect(port.closeSignal.aborted).toBe(true);
167
+ await until(() => (inbound[0] as NativePort).closeSignal.aborted, "the peer's port closed");
168
+ }));
169
+
170
+ it("close() closes the ports the mux opened, and openPort rejects afterwards", () =>
171
+ withPair(async (h) => {
172
+ const a = await h.opener.openPort();
173
+ const b = await h.opener.openPort();
174
+ await h.opener.close();
175
+ expect(a.closeSignal.aborted).toBe(true);
176
+ expect(b.closeSignal.aborted).toBe(true);
177
+ await expect(h.opener.openPort()).rejects.toThrow(/closed/);
178
+ }));
179
+
180
+ it("openPort honours its signal: aborted already, or aborted later, which closes the port", () =>
181
+ withPair(async (h) => {
182
+ const aborted = new AbortController();
183
+ aborted.abort(new Error("not wanted"));
184
+ await expect(h.opener.openPort(undefined, { signal: aborted.signal })).rejects.toThrow(
185
+ /not wanted/,
186
+ );
187
+ const later = new AbortController();
188
+ const port = await h.opener.openPort(undefined, { signal: later.signal });
189
+ expect(port.closeSignal.aborted).toBe(false);
190
+ later.abort(new Error("done with it"));
191
+ await until(() => port.closeSignal.aborted, "the port closed");
192
+ }));
193
+
194
+ it("reports its maxMessageSize as a positive number", () =>
195
+ withPair(async (h) => {
196
+ expect(h.opener.maxMessageSize).toBeGreaterThan(0);
197
+ }));
198
+ });
199
+ }
@@ -0,0 +1,295 @@
1
+ import {
2
+ MIN_PORT_WINDOW,
3
+ type NativePort,
4
+ type NativePortMux,
5
+ portFlow,
6
+ type ValueCodec,
7
+ } from "@statewalker/webrun-streams";
8
+ import { describe, expect, it } from "vitest";
9
+
10
+ /** The windows each end of a {@link PortWindowHarness} grants; unset is none (an older peer). */
11
+ export interface PortWindows {
12
+ opener?: number;
13
+ server?: number;
14
+ }
15
+
16
+ /** Two ends of one connection whose muxes may have a window (`window` on the transport's mux). */
17
+ export interface PortWindowHarness {
18
+ /** A mux that opens ports and accepts none, with `windows.opener`. */
19
+ opener: NativePortMux;
20
+ /** A mux on the other end, with `windows.server`, handing each port to `onPort`. */
21
+ serve(onPort: (port: NativePort) => boolean | undefined): Promise<NativePortMux>;
22
+ /** Releases the connection. */
23
+ dispose(): void | Promise<void>;
24
+ }
25
+
26
+ export interface DescribePortWindowOptions {
27
+ /**
28
+ * The largest encoded message the transport carries (WebRTC: 16 KiB). The
29
+ * case of a message larger than the window is skipped below 64 KiB.
30
+ */
31
+ maxFrameBytes?: number;
32
+ }
33
+
34
+ /** Builds two connected ends whose muxes use `codec` and the given windows. */
35
+ export type MakePortWindowHarness = (
36
+ codec: ValueCodec,
37
+ windows: PortWindows,
38
+ ) => Promise<PortWindowHarness>;
39
+
40
+ const encoder = new TextEncoder();
41
+ const decoder = new TextDecoder();
42
+
43
+ /** JSON: a string of n characters encodes to n + 2 bytes. */
44
+ const jsonCodec: ValueCodec = {
45
+ encode: (value) => encoder.encode(JSON.stringify(value)),
46
+ decode: (bytes) => JSON.parse(decoder.decode(bytes)),
47
+ };
48
+
49
+ /**
50
+ * JSON behind one leading byte: 0xC1, the byte a windowed channel's control
51
+ * frames start with, for a value marked `{ c1: true }`, else 0x00. A codec
52
+ * whose frames start with that byte must still have them arrive as values.
53
+ */
54
+ const leadingByteCodec: ValueCodec = {
55
+ encode: (value) => {
56
+ const json = encoder.encode(JSON.stringify(value));
57
+ const out = new Uint8Array(json.byteLength + 1);
58
+ out[0] = (value as { c1?: boolean } | null)?.c1 ? 0xc1 : 0x00;
59
+ out.set(json, 1);
60
+ return out;
61
+ },
62
+ decode: (bytes) => JSON.parse(decoder.decode(bytes.subarray(1))),
63
+ };
64
+
65
+ const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
66
+
67
+ async function until(predicate: () => boolean, label: string, ms = 5000): Promise<void> {
68
+ const deadline = Date.now() + ms;
69
+ while (!predicate()) {
70
+ if (Date.now() > deadline) throw new Error(`timed out waiting for: ${label}`);
71
+ await tick(5);
72
+ }
73
+ }
74
+
75
+ function received(port: NativePort): unknown[] {
76
+ const got: unknown[] = [];
77
+ port.addEventListener("message", (e) => {
78
+ got.push(e.data);
79
+ });
80
+ return got;
81
+ }
82
+
83
+ /** A listener that holds every message unconsumed until `release()`. */
84
+ function stalled(port: NativePort): { got: unknown[]; release(): void } {
85
+ const got: unknown[] = [];
86
+ let release!: () => void;
87
+ const gate = new Promise<void>((r) => {
88
+ release = r;
89
+ });
90
+ port.addEventListener("message", (e) => {
91
+ got.push(e.data);
92
+ return gate;
93
+ });
94
+ return { got, release };
95
+ }
96
+
97
+ const agreed = (port: NativePort) => !!portFlow(port)?.agreement()?.enforced;
98
+
99
+ /**
100
+ * Per-port flow control on native ports (statewalker/webrun-wire#153): a mux
101
+ * given `window` grants its peer at most that many bytes of a port's messages
102
+ * delivered and not yet consumed, where both ends speak it, and runs as before
103
+ * against one that does not. The module (`newNativePortMux` in
104
+ * `@statewalker/webrun-streams`) implements it once; each transport runs this
105
+ * suite with its own negotiation.
106
+ */
107
+ export function describePortWindow(
108
+ name: string,
109
+ make: MakePortWindowHarness,
110
+ options: DescribePortWindowOptions = {},
111
+ ): void {
112
+ const { maxFrameBytes = Number.POSITIVE_INFINITY } = options;
113
+ async function withPair(
114
+ windows: PortWindows,
115
+ body: (h: PortWindowHarness, inbound: NativePort[]) => Promise<void>,
116
+ codec: ValueCodec = jsonCodec,
117
+ ): Promise<void> {
118
+ const h = await make(codec, windows);
119
+ const inbound: NativePort[] = [];
120
+ try {
121
+ await h.serve((port) => {
122
+ inbound.push(port);
123
+ return true;
124
+ });
125
+ await body(h, inbound);
126
+ } finally {
127
+ await h.opener.close().catch(() => undefined);
128
+ await h.dispose();
129
+ }
130
+ }
131
+
132
+ /** A port both ends have agreed a window on, and its inbound end. */
133
+ async function agreedPort(
134
+ h: PortWindowHarness,
135
+ inbound: NativePort[],
136
+ ): Promise<{ port: NativePort; server: NativePort }> {
137
+ const port = await h.opener.openPort();
138
+ port.postMessage("hello");
139
+ await until(() => inbound.length === 1, "the inbound port");
140
+ const server = inbound[0] as NativePort;
141
+ await until(() => agreed(port) && agreed(server), "the window agreed on both ends");
142
+ return { port, server };
143
+ }
144
+
145
+ describe(`${name}: per-port windows`, () => {
146
+ it("both ends with a window agree it: each end reports pipeline and its own window", () =>
147
+ withPair({ opener: 128 * 1024, server: 64 * 1024 }, async (h, inbound) => {
148
+ const { port, server } = await agreedPort(h, inbound);
149
+ const mine = portFlow(port)?.agreement();
150
+ const theirs = portFlow(server)?.agreement();
151
+ expect(mine?.caps.has("pipeline")).toBe(true);
152
+ expect(theirs?.caps.has("pipeline")).toBe(true);
153
+ // The window an end polices is the one it grants.
154
+ expect(mine?.window).toBe(128 * 1024);
155
+ expect(theirs?.window).toBe(64 * 1024);
156
+ }));
157
+
158
+ it("control frames never reach listeners; values cross both ways intact", () =>
159
+ withPair({ opener: 64 * 1024, server: 64 * 1024 }, async (h, inbound) => {
160
+ const { port, server } = await agreedPort(h, inbound);
161
+ const fromServer = received(port);
162
+ const fromClient = received(server);
163
+ for (let i = 0; i < 20; i++) port.postMessage({ i });
164
+ for (let i = 0; i < 20; i++) server.postMessage([i]);
165
+ await until(
166
+ () => fromClient.length === 21 && fromServer.length === 20,
167
+ "every message, both ways",
168
+ );
169
+ expect(fromClient).toEqual(["hello", ...Array.from({ length: 20 }, (_, i) => ({ i }))]);
170
+ expect(fromServer).toEqual(Array.from({ length: 20 }, (_, i) => [i]));
171
+ }));
172
+
173
+ it("a frame whose encoding starts with the control byte still arrives as a value", () =>
174
+ withPair(
175
+ { opener: 64 * 1024, server: 64 * 1024 },
176
+ async (h, inbound) => {
177
+ const { port, server } = await agreedPort(h, inbound);
178
+ const fromServer = received(port);
179
+ const fromClient = received(server);
180
+ port.postMessage({ c1: true, n: 1 });
181
+ server.postMessage({ c1: true, n: 2 });
182
+ await until(() => fromClient.length === 2 && fromServer.length === 1, "both values");
183
+ expect(fromClient[1]).toEqual({ c1: true, n: 1 });
184
+ expect(fromServer[0]).toEqual({ c1: true, n: 2 });
185
+ },
186
+ leadingByteCodec,
187
+ ));
188
+
189
+ it("a stalled consumer holds the sender to the window; consuming returns the credit", () =>
190
+ withPair({ opener: 64 * 1024, server: 64 * 1024 }, async (h, inbound) => {
191
+ const { port, server } = await agreedPort(h, inbound);
192
+ const consumer = stalled(server);
193
+ // "hello" was consumed before the listener existed: nothing is outstanding.
194
+ await until(() => consumer.got.length === 1, "the held hello");
195
+ consumer.got.length = 0;
196
+ const body = "x".repeat(8000); // 8002 bytes in JSON
197
+ for (let i = 0; i < 30; i++) port.postMessage(body);
198
+ await tick(200);
199
+ const flow = portFlow(port);
200
+ // 8 messages fit 64 KiB; the rest wait in the sender's queue.
201
+ expect(consumer.got.length * 8002).toBeLessThanOrEqual(64 * 1024);
202
+ expect(consumer.got.length).toBeGreaterThan(0);
203
+ expect(flow?.bufferedAmount()).toBeGreaterThan(0);
204
+ let drained = false;
205
+ void flow?.ready().then(() => {
206
+ drained = true;
207
+ });
208
+ consumer.release();
209
+ await until(() => consumer.got.length === 30, "every message once consumed");
210
+ await until(() => drained, "the sender's queue drained");
211
+ expect(flow?.bufferedAmount()).toBe(0);
212
+ }));
213
+
214
+ it("a port opened once the mux has heard a peer's hello is agreed at once, holding back by the floor", () =>
215
+ withPair({ opener: 1024 * 1024, server: 1024 * 1024 }, async (h, inbound) => {
216
+ await agreedPort(h, inbound);
217
+ const second = await h.opener.openPort();
218
+ // No round trip: the peer's mux speaks the window, and grants at least the floor.
219
+ expect(agreed(second)).toBe(true);
220
+ expect(portFlow(second)?.stats().peerWindow).toBeGreaterThanOrEqual(MIN_PORT_WINDOW);
221
+ const body = "p".repeat(15000);
222
+ for (let i = 0; i < 6; i++) second.postMessage(body);
223
+ // Before the peer's hello, only the floor goes out: four of six.
224
+ expect(portFlow(second)?.bufferedAmount()).toBeGreaterThan(0);
225
+ await until(() => inbound.length === 2, "the second inbound port");
226
+ const got = received(inbound[1] as NativePort);
227
+ await until(() => got.length === 6, "every message, once the hello raised the window");
228
+ expect(portFlow(second)?.stats().peerWindow).toBe(1024 * 1024);
229
+ }));
230
+
231
+ it.skipIf(maxFrameBytes < 128 * 1024)(
232
+ "a message larger than the window goes once nothing is outstanding",
233
+ () =>
234
+ withPair({ opener: 64 * 1024, server: 64 * 1024 }, async (h, inbound) => {
235
+ const { port, server } = await agreedPort(h, inbound);
236
+ const got = received(server);
237
+ await until(() => got.length === 1, "the hello");
238
+ const big = "y".repeat(200 * 1024);
239
+ port.postMessage(big);
240
+ port.postMessage(big);
241
+ await until(() => got.length === 3, "both large messages");
242
+ expect(got.slice(1)).toEqual([big, big]);
243
+ }),
244
+ );
245
+
246
+ it("closing a port sends what the window held back before the close", () =>
247
+ withPair({ opener: 64 * 1024, server: 64 * 1024 }, async (h, inbound) => {
248
+ const { port, server } = await agreedPort(h, inbound);
249
+ const consumer = stalled(server);
250
+ const body = "z".repeat(8000);
251
+ for (let i = 0; i < 20; i++) port.postMessage(body);
252
+ await tick(50);
253
+ expect(portFlow(port)?.bufferedAmount()).toBeGreaterThan(0);
254
+ await port.close();
255
+ consumer.release();
256
+ await until(() => consumer.got.length === 21, "every message, the held ones included");
257
+ }));
258
+
259
+ it("an opener with a window and a serving end without: no agreement, messages flow as before", () =>
260
+ withPair({ opener: 64 * 1024 }, async (h, inbound) => {
261
+ const port = await h.opener.openPort();
262
+ port.postMessage("hello");
263
+ await until(() => inbound.length === 1, "the inbound port");
264
+ const server = inbound[0] as NativePort;
265
+ const consumer = stalled(server);
266
+ const fromServer = received(port);
267
+ const body = "w".repeat(1000);
268
+ for (let i = 0; i < 10; i++) port.postMessage(body);
269
+ server.postMessage("answer");
270
+ await until(() => consumer.got.length === 11, "every message, unwindowed");
271
+ await until(() => fromServer.length === 1, "the answer");
272
+ expect(fromServer).toEqual(["answer"]);
273
+ expect(agreed(port)).toBe(false);
274
+ expect(agreed(server)).toBe(false);
275
+ expect(portFlow(port)?.bufferedAmount() ?? 0).toBe(0);
276
+ }));
277
+
278
+ it("a serving end with a window and an opener without: no agreement, messages flow as before", () =>
279
+ withPair({ server: 64 * 1024 }, async (h, inbound) => {
280
+ const port = await h.opener.openPort();
281
+ const fromServer = received(port);
282
+ port.postMessage("hello");
283
+ await until(() => inbound.length === 1, "the inbound port");
284
+ const server = inbound[0] as NativePort;
285
+ const fromClient = received(server);
286
+ const body = "v".repeat(1000);
287
+ for (let i = 0; i < 10; i++) server.postMessage(body);
288
+ await until(() => fromServer.length === 10, "every message, unwindowed");
289
+ await until(() => fromClient.length === 1, "the hello");
290
+ expect(fromServer.every((m) => m === body)).toBe(true);
291
+ expect(agreed(port)).toBe(false);
292
+ expect(agreed(server)).toBe(false);
293
+ }));
294
+ });
295
+ }