@statewalker/webrun-streams-webrtc 0.1.6 → 0.3.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.
- package/README.md +80 -11
- package/dist/connect-serve.d.ts.map +1 -1
- package/dist/duplex-over-data-channel.d.ts +22 -1
- package/dist/duplex-over-data-channel.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +371 -36
- package/dist/port-mux.d.ts +74 -0
- package/dist/port-mux.d.ts.map +1 -0
- package/package.json +7 -5
- package/src/connect-serve.ts +40 -11
- package/src/duplex-over-data-channel.ts +141 -9
- package/src/index.ts +11 -0
- package/src/port-mux.ts +288 -0
package/dist/index.js
CHANGED
|
@@ -3,9 +3,59 @@ import { TransportClosedError, deserializeError, serializeError, toChunks } from
|
|
|
3
3
|
const TYPE_DATA = 0;
|
|
4
4
|
const TYPE_END = 1;
|
|
5
5
|
const TYPE_ERROR = 2;
|
|
6
|
+
const TYPE_CREDIT = 3;
|
|
7
|
+
const LOW_WATER_MARK = 262144;
|
|
8
|
+
/**
|
|
9
|
+
* Receive-side backpressure: a sender may have at most this many payload bytes outstanding that
|
|
10
|
+
* the receiving consumer has not yet pulled. The receiver returns credit (`CREDIT` frames) as its
|
|
11
|
+
* consumer pulls, half a window at a time. A DataChannel delivers every message as it arrives,
|
|
12
|
+
* whether or not anyone reads, so without credit a slow reader's queue grows without bound. The
|
|
13
|
+
* window is larger than the send buffer's high-water mark so a long round trip does not throttle a
|
|
14
|
+
* fast link: the buffer limit is what bounds the sender's memory.
|
|
15
|
+
*/
|
|
16
|
+
const RECEIVE_WINDOW = 4194304;
|
|
6
17
|
const textEncoder = new TextEncoder();
|
|
7
18
|
const textDecoder = new TextDecoder();
|
|
8
19
|
/**
|
|
20
|
+
* Messages (and a close) that arrive on a channel before its stream starts listening. A generator
|
|
21
|
+
* runs only on its first `next()`, so without this a peer that answers at once (a handler that
|
|
22
|
+
* throws, a reply with no input to wait for) can be faster than our listener: its frames are
|
|
23
|
+
* dropped and the call hangs or reports a bare close.
|
|
24
|
+
*/
|
|
25
|
+
const held = /* @__PURE__ */ new WeakMap();
|
|
26
|
+
/**
|
|
27
|
+
* Channels this side answers (from `datachannel`). A finished call is closed by its caller only,
|
|
28
|
+
* once it has the responder's `END` or `ERROR`: a responder that closed right after sending them
|
|
29
|
+
* could lose them in flight (Chrome delivers the close first), turning an error into a bare close.
|
|
30
|
+
*/
|
|
31
|
+
const answering = /* @__PURE__ */ new WeakSet();
|
|
32
|
+
function markAnswering(dc) {
|
|
33
|
+
answering.add(dc);
|
|
34
|
+
}
|
|
35
|
+
/** starts holding a channel's events until {@link duplexOverDataChannel} takes them */
|
|
36
|
+
function holdEvents(dc) {
|
|
37
|
+
if (held.has(dc)) return;
|
|
38
|
+
dc.binaryType = "arraybuffer";
|
|
39
|
+
const events = [];
|
|
40
|
+
const listener = (ev) => {
|
|
41
|
+
events.push(ev);
|
|
42
|
+
};
|
|
43
|
+
dc.addEventListener("message", listener);
|
|
44
|
+
dc.addEventListener("close", listener);
|
|
45
|
+
held.set(dc, {
|
|
46
|
+
events,
|
|
47
|
+
listener
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function takeHeld(dc) {
|
|
51
|
+
const h = held.get(dc);
|
|
52
|
+
if (!h) return [];
|
|
53
|
+
held.delete(dc);
|
|
54
|
+
dc.removeEventListener("message", h.listener);
|
|
55
|
+
dc.removeEventListener("close", h.listener);
|
|
56
|
+
return h.events;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
9
59
|
* Drive one `Duplex` over one `RTCDataChannel`. The DataChannel hosts a tiny
|
|
10
60
|
* in-band framing protocol:
|
|
11
61
|
*
|
|
@@ -13,7 +63,9 @@ const textDecoder = new TextDecoder();
|
|
|
13
63
|
*
|
|
14
64
|
* Types are `DATA` (0x00, body bytes), `END` (0x01, signals half-close — the
|
|
15
65
|
* sender is done emitting; the channel stays open for the other direction),
|
|
16
|
-
*
|
|
66
|
+
* `ERROR` (0x02, followed by a serialised `Error`) and `CREDIT` (0x03, a
|
|
67
|
+
* big-endian u32: payload bytes the receiver's consumer has pulled, which the
|
|
68
|
+
* sender may now send again; see {@link RECEIVE_WINDOW}).
|
|
17
69
|
*
|
|
18
70
|
* `RTCDataChannel` has no native half-close, so `END` is emitted by the
|
|
19
71
|
* sender once its input iterator exhausts; the channel is only physically
|
|
@@ -27,8 +79,42 @@ async function* runStream(dc, input) {
|
|
|
27
79
|
const incoming = makeInboundQueue();
|
|
28
80
|
let peerEnded = false;
|
|
29
81
|
let localEnded = false;
|
|
82
|
+
let credit = RECEIVE_WINDOW;
|
|
83
|
+
let pulled = 0;
|
|
84
|
+
let wakeSender = null;
|
|
85
|
+
const nudge = () => {
|
|
86
|
+
const w = wakeSender;
|
|
87
|
+
wakeSender = null;
|
|
88
|
+
w?.();
|
|
89
|
+
};
|
|
90
|
+
const stalled = () => new Promise((r) => {
|
|
91
|
+
wakeSender = r;
|
|
92
|
+
});
|
|
93
|
+
dc.bufferedAmountLowThreshold = LOW_WATER_MARK;
|
|
94
|
+
const sendRaw = (bytes) => {
|
|
95
|
+
dc.send(bytes);
|
|
96
|
+
};
|
|
97
|
+
/** set when this call is abandoned (cancelled, or the peer failed): the sender stops waiting */
|
|
98
|
+
let aborted = false;
|
|
99
|
+
/** waits for credit for `n` bytes and room in the send buffer; false once the call is over */
|
|
100
|
+
const room = async (n) => {
|
|
101
|
+
while (!aborted && dc.readyState === "open" && (credit < n || dc.bufferedAmount > 1048576)) await stalled();
|
|
102
|
+
return !aborted && dc.readyState === "open";
|
|
103
|
+
};
|
|
104
|
+
/** returns credit for what our consumer pulled, half a window at a time */
|
|
105
|
+
const consumed = (n) => {
|
|
106
|
+
pulled += n;
|
|
107
|
+
if (pulled < 2097152 || dc.readyState !== "open") return;
|
|
108
|
+
const frame = /* @__PURE__ */ new Uint8Array(5);
|
|
109
|
+
frame[0] = TYPE_CREDIT;
|
|
110
|
+
new DataView(frame.buffer).setUint32(1, pulled);
|
|
111
|
+
pulled = 0;
|
|
112
|
+
try {
|
|
113
|
+
sendRaw(frame);
|
|
114
|
+
} catch {}
|
|
115
|
+
};
|
|
30
116
|
const maybeClose = () => {
|
|
31
|
-
if (peerEnded && localEnded) try {
|
|
117
|
+
if (peerEnded && localEnded && !answering.has(dc)) try {
|
|
32
118
|
dc.close();
|
|
33
119
|
} catch {}
|
|
34
120
|
};
|
|
@@ -49,6 +135,9 @@ async function* runStream(dc, input) {
|
|
|
49
135
|
peerEnded = true;
|
|
50
136
|
incoming.done();
|
|
51
137
|
maybeClose();
|
|
138
|
+
} else if (type === TYPE_CREDIT && payload.byteLength >= 4) {
|
|
139
|
+
credit += new DataView(payload.buffer, payload.byteOffset, 4).getUint32(0);
|
|
140
|
+
nudge();
|
|
52
141
|
} else if (type === TYPE_ERROR) {
|
|
53
142
|
let err;
|
|
54
143
|
try {
|
|
@@ -62,6 +151,7 @@ async function* runStream(dc, input) {
|
|
|
62
151
|
}
|
|
63
152
|
};
|
|
64
153
|
const onClose = () => {
|
|
154
|
+
nudge();
|
|
65
155
|
if (!peerEnded) {
|
|
66
156
|
incoming.done(new TransportClosedError());
|
|
67
157
|
peerEnded = true;
|
|
@@ -69,14 +159,26 @@ async function* runStream(dc, input) {
|
|
|
69
159
|
};
|
|
70
160
|
dc.addEventListener("message", onMessage);
|
|
71
161
|
dc.addEventListener("close", onClose);
|
|
162
|
+
dc.addEventListener("bufferedamountlow", nudge);
|
|
163
|
+
for (const ev of takeHeld(dc)) if (ev.type === "message") onMessage(ev);
|
|
164
|
+
else onClose();
|
|
165
|
+
if (dc.readyState === "closed") onClose();
|
|
166
|
+
let inboundFinished = false;
|
|
167
|
+
const detach = () => {
|
|
168
|
+
if (!inboundFinished || !localEnded) return;
|
|
169
|
+
dc.removeEventListener("message", onMessage);
|
|
170
|
+
dc.removeEventListener("close", onClose);
|
|
171
|
+
dc.removeEventListener("bufferedamountlow", nudge);
|
|
172
|
+
};
|
|
72
173
|
const outbound = (async () => {
|
|
73
174
|
try {
|
|
74
175
|
for await (const chunk of toChunks(16383)(input)) {
|
|
75
|
-
if (
|
|
176
|
+
if (!await room(chunk.byteLength)) return;
|
|
177
|
+
credit -= chunk.byteLength;
|
|
76
178
|
const framed = new Uint8Array(chunk.byteLength + 1);
|
|
77
179
|
framed[0] = TYPE_DATA;
|
|
78
180
|
framed.set(chunk, 1);
|
|
79
|
-
|
|
181
|
+
sendRaw(framed);
|
|
80
182
|
}
|
|
81
183
|
if (dc.readyState === "open") {
|
|
82
184
|
const end = new Uint8Array([TYPE_END]);
|
|
@@ -96,20 +198,26 @@ async function* runStream(dc, input) {
|
|
|
96
198
|
} finally {
|
|
97
199
|
localEnded = true;
|
|
98
200
|
maybeClose();
|
|
201
|
+
detach();
|
|
99
202
|
}
|
|
100
203
|
})();
|
|
101
204
|
let inboundDrained = false;
|
|
102
205
|
try {
|
|
103
|
-
for await (const chunk of incoming.iterate())
|
|
206
|
+
for await (const chunk of incoming.iterate()) {
|
|
207
|
+
yield chunk;
|
|
208
|
+
consumed(chunk.byteLength);
|
|
209
|
+
}
|
|
104
210
|
inboundDrained = true;
|
|
105
211
|
} finally {
|
|
106
|
-
|
|
107
|
-
|
|
212
|
+
inboundFinished = true;
|
|
213
|
+
detach();
|
|
108
214
|
if (!inboundDrained) {
|
|
109
|
-
|
|
215
|
+
aborted = true;
|
|
216
|
+
nudge();
|
|
110
217
|
try {
|
|
111
218
|
dc.close();
|
|
112
219
|
} catch {}
|
|
220
|
+
await outbound.catch(() => {});
|
|
113
221
|
}
|
|
114
222
|
}
|
|
115
223
|
}
|
|
@@ -161,6 +269,210 @@ function makeInboundQueue() {
|
|
|
161
269
|
};
|
|
162
270
|
}
|
|
163
271
|
//#endregion
|
|
272
|
+
//#region src/port-mux.ts
|
|
273
|
+
/** The label prefix of a port's data channel: channels without it are someone else's. */
|
|
274
|
+
const PORT_LABEL_PREFIX = "webrun-port/";
|
|
275
|
+
/**
|
|
276
|
+
* The largest message a data channel delivers between any two browsers (Firefox to Chrome cuts
|
|
277
|
+
* off at 16 KiB). A post past it fails the port with a `RangeError` rather than vanishing.
|
|
278
|
+
*/
|
|
279
|
+
const DEFAULT_PORT_MAX_FRAME_BYTES = 16384;
|
|
280
|
+
/** What one message on a port may carry before the stream tier chunks: 256 bytes under the frame limit (spec D10). */
|
|
281
|
+
const DEFAULT_PORT_MAX_MESSAGE_SIZE = 16128;
|
|
282
|
+
/** `whenDrained` resolves once the channel's `bufferedAmount` is at most this. */
|
|
283
|
+
const PORT_DRAIN_LOW_WATER = 262144;
|
|
284
|
+
let counter = 0;
|
|
285
|
+
/** Inbound port channels a serving mux has taken: on one connection, each port is answered once. */
|
|
286
|
+
const claimed = /* @__PURE__ */ new WeakSet();
|
|
287
|
+
/**
|
|
288
|
+
* Native MessagePorts over WebRTC: every port is its own `RTCDataChannel` (ordered, reliable),
|
|
289
|
+
* labelled `webrun-port/…`. Hand it to `webrun-rpc` as a port source and its stream tier runs one
|
|
290
|
+
* call per port, with its backpressure: a producer stays one confirmed chunk ahead of its
|
|
291
|
+
* consumer, where this package's `connect` / `serve` allow a 4 MiB window.
|
|
292
|
+
*
|
|
293
|
+
* ```ts
|
|
294
|
+
* const codec = { encode: serialize, decode: deserialize }; // webrun-msgpack
|
|
295
|
+
* await serve({ mux: overPorts((onPort) => webrtcPortMux({ pc, codec, onPort })) }, handler);
|
|
296
|
+
* const { call } = await connect({ mux: overPorts(() => webrtcPortMux({ pc, codec })) });
|
|
297
|
+
* ```
|
|
298
|
+
*
|
|
299
|
+
* Messages that arrive before a port's first listener are held for it and delivered after that
|
|
300
|
+
* tick, to every listener added by then.
|
|
301
|
+
*/
|
|
302
|
+
async function webrtcPortMux(options) {
|
|
303
|
+
const { pc, codec, onPort } = options;
|
|
304
|
+
const maxFrameBytes = options.maxFrameBytes ?? 16384;
|
|
305
|
+
const maxMessageSize = options.maxMessageSize ?? 16128;
|
|
306
|
+
const live = /* @__PURE__ */ new Set();
|
|
307
|
+
let closed = false;
|
|
308
|
+
const connectionGone = new AbortController();
|
|
309
|
+
const onConnectionState = () => {
|
|
310
|
+
if (pc.connectionState === "failed" || pc.connectionState === "closed") connectionGone.abort(/* @__PURE__ */ new Error(`webrun-streams-webrtc: the connection is ${pc.connectionState}`));
|
|
311
|
+
};
|
|
312
|
+
pc.addEventListener("connectionstatechange", onConnectionState);
|
|
313
|
+
onConnectionState();
|
|
314
|
+
const wrap = (dc) => {
|
|
315
|
+
dc.binaryType = "arraybuffer";
|
|
316
|
+
dc.bufferedAmountLowThreshold = PORT_DRAIN_LOW_WATER;
|
|
317
|
+
const life = new AbortController();
|
|
318
|
+
const end = (reason) => {
|
|
319
|
+
if (!life.signal.aborted) life.abort(reason);
|
|
320
|
+
};
|
|
321
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
322
|
+
let held = [];
|
|
323
|
+
const deliver = (data) => {
|
|
324
|
+
if (closeSignal.aborted) return;
|
|
325
|
+
const event = new MessageEvent("message", { data });
|
|
326
|
+
for (const l of [...listeners]) try {
|
|
327
|
+
Promise.resolve(l(event)).catch(() => void 0);
|
|
328
|
+
} catch {}
|
|
329
|
+
};
|
|
330
|
+
const onMessage = (ev) => {
|
|
331
|
+
if (closeSignal.aborted) return;
|
|
332
|
+
let data;
|
|
333
|
+
try {
|
|
334
|
+
const raw = ev.data;
|
|
335
|
+
data = codec.decode(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
|
|
336
|
+
} catch (err) {
|
|
337
|
+
end(new Error("webrun-streams-webrtc: a frame the port's codec cannot decode", { cause: err }));
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (held) held.push(data);
|
|
341
|
+
else deliver(data);
|
|
342
|
+
};
|
|
343
|
+
const onClose = () => end(/* @__PURE__ */ new Error("webrun-streams-webrtc: the data channel closed"));
|
|
344
|
+
const onError = (ev) => end(/* @__PURE__ */ new Error(`webrun-streams-webrtc: the data channel failed: ${ev.error?.message ?? "unknown"}`));
|
|
345
|
+
dc.addEventListener("message", onMessage);
|
|
346
|
+
dc.addEventListener("close", onClose);
|
|
347
|
+
dc.addEventListener("error", onError);
|
|
348
|
+
if (dc.readyState === "closing" || dc.readyState === "closed") onClose();
|
|
349
|
+
const closeSignal = AbortSignal.any([life.signal, connectionGone.signal]);
|
|
350
|
+
const cleanUp = () => {
|
|
351
|
+
live.delete(port);
|
|
352
|
+
dc.removeEventListener("message", onMessage);
|
|
353
|
+
listeners.clear();
|
|
354
|
+
held = void 0;
|
|
355
|
+
if (dc.readyState !== "closed") dc.close();
|
|
356
|
+
};
|
|
357
|
+
const port = {
|
|
358
|
+
closeSignal,
|
|
359
|
+
get bufferedAmount() {
|
|
360
|
+
return dc.bufferedAmount;
|
|
361
|
+
},
|
|
362
|
+
whenDrained() {
|
|
363
|
+
if (closeSignal.aborted || dc.bufferedAmount <= 262144) return Promise.resolve();
|
|
364
|
+
return new Promise((resolve) => {
|
|
365
|
+
const done = () => {
|
|
366
|
+
dc.removeEventListener("bufferedamountlow", done);
|
|
367
|
+
closeSignal.removeEventListener("abort", done);
|
|
368
|
+
resolve();
|
|
369
|
+
};
|
|
370
|
+
dc.addEventListener("bufferedamountlow", done);
|
|
371
|
+
closeSignal.addEventListener("abort", done);
|
|
372
|
+
});
|
|
373
|
+
},
|
|
374
|
+
postMessage(message) {
|
|
375
|
+
if (closeSignal.aborted || dc.readyState !== "open") return;
|
|
376
|
+
const bytes = codec.encode(message);
|
|
377
|
+
if (bytes.byteLength > maxFrameBytes) {
|
|
378
|
+
const err = /* @__PURE__ */ new RangeError(`webrun-streams-webrtc: a ${bytes.byteLength}-byte message exceeds maxFrameBytes (${maxFrameBytes})`);
|
|
379
|
+
end(err);
|
|
380
|
+
throw err;
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
dc.send(bytes);
|
|
384
|
+
} catch (err) {
|
|
385
|
+
end(err instanceof Error ? err : new Error(String(err)));
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
addEventListener(_type, listener) {
|
|
389
|
+
listeners.add(listener);
|
|
390
|
+
if (held) {
|
|
391
|
+
const pending = held;
|
|
392
|
+
held = void 0;
|
|
393
|
+
queueMicrotask(() => {
|
|
394
|
+
for (const data of pending) deliver(data);
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
removeEventListener(_type, listener) {
|
|
399
|
+
listeners.delete(listener);
|
|
400
|
+
},
|
|
401
|
+
async close() {
|
|
402
|
+
end(/* @__PURE__ */ new Error("webrun-streams-webrtc: port closed"));
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
live.add(port);
|
|
406
|
+
if (closeSignal.aborted) cleanUp();
|
|
407
|
+
else closeSignal.addEventListener("abort", cleanUp, { once: true });
|
|
408
|
+
return port;
|
|
409
|
+
};
|
|
410
|
+
const onChannel = (ev) => {
|
|
411
|
+
const dc = ev.channel;
|
|
412
|
+
if (!dc.label.startsWith("webrun-port/")) return;
|
|
413
|
+
if (!onPort || closed || claimed.has(dc)) return;
|
|
414
|
+
claimed.add(dc);
|
|
415
|
+
const port = wrap(dc);
|
|
416
|
+
let accepted = false;
|
|
417
|
+
try {
|
|
418
|
+
accepted = onPort(port) !== false;
|
|
419
|
+
} catch {
|
|
420
|
+
accepted = false;
|
|
421
|
+
}
|
|
422
|
+
if (!accepted) port.close();
|
|
423
|
+
};
|
|
424
|
+
pc.addEventListener("datachannel", onChannel);
|
|
425
|
+
return {
|
|
426
|
+
maxMessageSize,
|
|
427
|
+
async openPort(_meta, opts) {
|
|
428
|
+
if (closed) throw new Error("webrun-streams-webrtc: port mux closed");
|
|
429
|
+
const signal = opts?.signal;
|
|
430
|
+
signal?.throwIfAborted();
|
|
431
|
+
if (connectionGone.signal.aborted) throw connectionGone.signal.reason;
|
|
432
|
+
const dc = pc.createDataChannel(`${PORT_LABEL_PREFIX}${(counter++).toString(36)}`, { ordered: true });
|
|
433
|
+
const port = wrap(dc);
|
|
434
|
+
await new Promise((resolve, reject) => {
|
|
435
|
+
if (port.closeSignal.aborted) return reject(port.closeSignal.reason);
|
|
436
|
+
if (dc.readyState === "open") return resolve();
|
|
437
|
+
const settle = () => {
|
|
438
|
+
dc.removeEventListener("open", done);
|
|
439
|
+
port.closeSignal.removeEventListener("abort", fail);
|
|
440
|
+
signal?.removeEventListener("abort", cancel);
|
|
441
|
+
};
|
|
442
|
+
const done = () => {
|
|
443
|
+
settle();
|
|
444
|
+
resolve();
|
|
445
|
+
};
|
|
446
|
+
const fail = () => {
|
|
447
|
+
settle();
|
|
448
|
+
reject(port.closeSignal.reason);
|
|
449
|
+
};
|
|
450
|
+
const cancel = () => {
|
|
451
|
+
settle();
|
|
452
|
+
port.close();
|
|
453
|
+
reject(signal?.reason);
|
|
454
|
+
};
|
|
455
|
+
dc.addEventListener("open", done);
|
|
456
|
+
port.closeSignal.addEventListener("abort", fail, { once: true });
|
|
457
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
458
|
+
});
|
|
459
|
+
if (signal) {
|
|
460
|
+
const onAbort = () => void port.close();
|
|
461
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
462
|
+
port.closeSignal.addEventListener("abort", () => signal.removeEventListener("abort", onAbort), { once: true });
|
|
463
|
+
}
|
|
464
|
+
return port;
|
|
465
|
+
},
|
|
466
|
+
async close() {
|
|
467
|
+
if (closed) return;
|
|
468
|
+
closed = true;
|
|
469
|
+
pc.removeEventListener("datachannel", onChannel);
|
|
470
|
+
pc.removeEventListener("connectionstatechange", onConnectionState);
|
|
471
|
+
await Promise.allSettled([...live].map((p) => p.close()));
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
//#endregion
|
|
164
476
|
//#region src/connect-serve.ts
|
|
165
477
|
/**
|
|
166
478
|
* Caller-side: each `call(input)` invocation opens a new `RTCDataChannel` on
|
|
@@ -183,6 +495,7 @@ const connect = async ({ pc }) => {
|
|
|
183
495
|
})();
|
|
184
496
|
const label = `webrun/${Date.now().toString(36)}/${(counter++).toString(36)}`;
|
|
185
497
|
const dc = pc.createDataChannel(label);
|
|
498
|
+
holdEvents(dc);
|
|
186
499
|
open.add(dc);
|
|
187
500
|
dc.addEventListener("close", () => open.delete(dc));
|
|
188
501
|
return (async function* () {
|
|
@@ -208,12 +521,23 @@ const connect = async ({ pc }) => {
|
|
|
208
521
|
const serve = async ({ pc }, handler) => {
|
|
209
522
|
const onChannel = (ev) => {
|
|
210
523
|
const dc = ev.channel;
|
|
524
|
+
if (dc.label.startsWith("webrun-port/")) return;
|
|
525
|
+
holdEvents(dc);
|
|
526
|
+
markAnswering(dc);
|
|
211
527
|
let inputFromPeer = null;
|
|
212
528
|
(async () => {
|
|
213
529
|
await waitForOpen(dc);
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
530
|
+
const peek = peekInput(dc);
|
|
531
|
+
inputFromPeer = peek;
|
|
532
|
+
const handlerOutput = handler(peek.input);
|
|
533
|
+
const out = (async function* () {
|
|
534
|
+
try {
|
|
535
|
+
yield* handlerOutput;
|
|
536
|
+
} finally {
|
|
537
|
+
peek.release();
|
|
538
|
+
}
|
|
539
|
+
})();
|
|
540
|
+
for await (const chunk of duplexOverDataChannel(dc, out)) await inputFromPeer.deliver(chunk);
|
|
217
541
|
inputFromPeer.done();
|
|
218
542
|
})().catch(() => {
|
|
219
543
|
inputFromPeer?.done();
|
|
@@ -273,40 +597,51 @@ function peekInput(_dc) {
|
|
|
273
597
|
const slots = [];
|
|
274
598
|
let wake = null;
|
|
275
599
|
let closed = false;
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
const slot = slots.shift();
|
|
288
|
-
if (!slot) continue;
|
|
289
|
-
if (slot.type === "done") return;
|
|
290
|
-
yield slot.value;
|
|
600
|
+
const input = (async function* () {
|
|
601
|
+
try {
|
|
602
|
+
while (true) {
|
|
603
|
+
if (slots.length === 0) {
|
|
604
|
+
await new Promise((r) => {
|
|
605
|
+
wake = r;
|
|
606
|
+
});
|
|
607
|
+
wake = null;
|
|
608
|
+
continue;
|
|
291
609
|
}
|
|
292
|
-
|
|
293
|
-
|
|
610
|
+
const slot = slots.shift();
|
|
611
|
+
if (!slot) continue;
|
|
612
|
+
if (slot.type === "done") return;
|
|
613
|
+
slot.taken();
|
|
614
|
+
yield slot.value;
|
|
294
615
|
}
|
|
295
|
-
}
|
|
616
|
+
} finally {
|
|
617
|
+
release();
|
|
618
|
+
}
|
|
619
|
+
})();
|
|
620
|
+
function release() {
|
|
621
|
+
closed = true;
|
|
622
|
+
for (const s of slots.splice(0)) if (s.type === "value") s.taken();
|
|
623
|
+
wake?.();
|
|
624
|
+
}
|
|
625
|
+
return {
|
|
626
|
+
input,
|
|
296
627
|
deliver(chunk) {
|
|
297
|
-
if (closed) return;
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
628
|
+
if (closed) return Promise.resolve();
|
|
629
|
+
return new Promise((taken) => {
|
|
630
|
+
slots.push({
|
|
631
|
+
type: "value",
|
|
632
|
+
value: chunk,
|
|
633
|
+
taken
|
|
634
|
+
});
|
|
635
|
+
wake?.();
|
|
301
636
|
});
|
|
302
|
-
wake?.();
|
|
303
637
|
},
|
|
304
638
|
done() {
|
|
305
639
|
if (closed) return;
|
|
306
640
|
slots.push({ type: "done" });
|
|
307
641
|
wake?.();
|
|
308
|
-
}
|
|
642
|
+
},
|
|
643
|
+
release
|
|
309
644
|
};
|
|
310
645
|
}
|
|
311
646
|
//#endregion
|
|
312
|
-
export { connect, duplexOverDataChannel, serve };
|
|
647
|
+
export { DEFAULT_PORT_MAX_FRAME_BYTES, DEFAULT_PORT_MAX_MESSAGE_SIZE, PORT_DRAIN_LOW_WATER, PORT_LABEL_PREFIX, connect, duplexOverDataChannel, serve, webrtcPortMux };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** The label prefix of a port's data channel: channels without it are someone else's. */
|
|
2
|
+
export declare const PORT_LABEL_PREFIX = "webrun-port/";
|
|
3
|
+
/**
|
|
4
|
+
* The largest message a data channel delivers between any two browsers (Firefox to Chrome cuts
|
|
5
|
+
* off at 16 KiB). A post past it fails the port with a `RangeError` rather than vanishing.
|
|
6
|
+
*/
|
|
7
|
+
export declare const DEFAULT_PORT_MAX_FRAME_BYTES: number;
|
|
8
|
+
/** What one message on a port may carry before the stream tier chunks: 256 bytes under the frame limit (spec D10). */
|
|
9
|
+
export declare const DEFAULT_PORT_MAX_MESSAGE_SIZE: number;
|
|
10
|
+
/** `whenDrained` resolves once the channel's `bufferedAmount` is at most this. */
|
|
11
|
+
export declare const PORT_DRAIN_LOW_WATER: number;
|
|
12
|
+
/**
|
|
13
|
+
* How a port's messages become bytes and back: any value the stream tier posts. `webrun-msgpack`'s
|
|
14
|
+
* `{ encode: serialize, decode: deserialize }` fits.
|
|
15
|
+
*/
|
|
16
|
+
export interface ValueCodec {
|
|
17
|
+
encode(value: unknown): Uint8Array;
|
|
18
|
+
decode(bytes: Uint8Array): unknown;
|
|
19
|
+
}
|
|
20
|
+
type Listener = (event: MessageEvent) => void | Promise<void>;
|
|
21
|
+
/** One port: a data channel as a `MessageTarget` of values, with its close signal on it. */
|
|
22
|
+
export interface DataChannelPort {
|
|
23
|
+
addEventListener(type: "message", listener: Listener): void;
|
|
24
|
+
removeEventListener(type: "message", listener: Listener): void;
|
|
25
|
+
/** Sends one message. `RangeError`, failing the port, past `maxFrameBytes`. */
|
|
26
|
+
postMessage(message: unknown): void;
|
|
27
|
+
close(): Promise<void>;
|
|
28
|
+
readonly bufferedAmount: number;
|
|
29
|
+
whenDrained(): Promise<void>;
|
|
30
|
+
/** Aborts when the channel closes or errs, the connection fails, or the port is closed here. */
|
|
31
|
+
readonly closeSignal: AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
export interface WebRtcPortMuxOptions {
|
|
34
|
+
/** A connected `RTCPeerConnection` with SCTP negotiated. Signalling is the caller's. */
|
|
35
|
+
pc: RTCPeerConnection;
|
|
36
|
+
/** Encodes each message; both ends must agree. */
|
|
37
|
+
codec: ValueCodec;
|
|
38
|
+
/**
|
|
39
|
+
* Called for each port the peer opens (an inbound channel with the port label). `false` refuses
|
|
40
|
+
* it. A mux without `onPort` (a caller's) ignores inbound ports, leaving them to the serving
|
|
41
|
+
* mux on the same connection; of several serving muxes on one connection, the first takes each.
|
|
42
|
+
*/
|
|
43
|
+
onPort?: (port: DataChannelPort) => boolean | undefined;
|
|
44
|
+
/** Reported as `maxMessageSize`. Default {@link DEFAULT_PORT_MAX_MESSAGE_SIZE}. */
|
|
45
|
+
maxMessageSize?: number;
|
|
46
|
+
/** Default {@link DEFAULT_PORT_MAX_FRAME_BYTES}. */
|
|
47
|
+
maxFrameBytes?: number;
|
|
48
|
+
}
|
|
49
|
+
/** A `webrun-rpc` `PortMux` by shape; this package imports nothing from it. */
|
|
50
|
+
export interface WebRtcPortMux {
|
|
51
|
+
openPort(meta?: unknown, options?: {
|
|
52
|
+
signal?: AbortSignal;
|
|
53
|
+
}): Promise<DataChannelPort>;
|
|
54
|
+
close(reason?: unknown): Promise<void>;
|
|
55
|
+
readonly maxMessageSize: number;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Native MessagePorts over WebRTC: every port is its own `RTCDataChannel` (ordered, reliable),
|
|
59
|
+
* labelled `webrun-port/…`. Hand it to `webrun-rpc` as a port source and its stream tier runs one
|
|
60
|
+
* call per port, with its backpressure: a producer stays one confirmed chunk ahead of its
|
|
61
|
+
* consumer, where this package's `connect` / `serve` allow a 4 MiB window.
|
|
62
|
+
*
|
|
63
|
+
* ```ts
|
|
64
|
+
* const codec = { encode: serialize, decode: deserialize }; // webrun-msgpack
|
|
65
|
+
* await serve({ mux: overPorts((onPort) => webrtcPortMux({ pc, codec, onPort })) }, handler);
|
|
66
|
+
* const { call } = await connect({ mux: overPorts(() => webrtcPortMux({ pc, codec })) });
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* Messages that arrive before a port's first listener are held for it and delivered after that
|
|
70
|
+
* tick, to every listener added by then.
|
|
71
|
+
*/
|
|
72
|
+
export declare function webrtcPortMux(options: WebRtcPortMuxOptions): Promise<WebRtcPortMux>;
|
|
73
|
+
export {};
|
|
74
|
+
//# sourceMappingURL=port-mux.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"port-mux.d.ts","sourceRoot":"","sources":["../src/port-mux.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAEhD;;;GAGG;AACH,eAAO,MAAM,4BAA4B,QAAY,CAAC;AAEtD,sHAAsH;AACtH,eAAO,MAAM,6BAA6B,QAAqC,CAAC;AAEhF,kFAAkF;AAClF,eAAO,MAAM,oBAAoB,QAAa,CAAC;AAE/C;;;GAGG;AACH,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,CAAC;IACnC,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC;CACpC;AAED,KAAK,QAAQ,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE9D,4FAA4F;AAC5F,MAAM,WAAW,eAAe;IAC9B,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC5D,mBAAmB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC/D,+EAA+E;IAC/E,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACpC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,gGAAgG;IAChG,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;CACnC;AAED,MAAM,WAAW,oBAAoB;IACnC,wFAAwF;IACxF,EAAE,EAAE,iBAAiB,CAAC;IACtB,kDAAkD;IAClD,KAAK,EAAE,UAAU,CAAC;IAClB;;;;OAIG;IACH,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,OAAO,GAAG,SAAS,CAAC;IACxD,mFAAmF;IACnF,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oDAAoD;IACpD,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,+EAA+E;AAC/E,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IACvF,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;CACjC;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC,CA6MzF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/webrun-streams-webrtc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "WebRTC DataChannel-backed Connect/Serve adapter (native multi-stream) in the webrun-streams-* family",
|
|
@@ -30,19 +30,21 @@
|
|
|
30
30
|
"src"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@statewalker/webrun-streams": "^0.
|
|
33
|
+
"@statewalker/webrun-streams": "^0.3.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@biomejs/biome": "^2.5.15",
|
|
37
37
|
"@roamhq/wrtc": "^0.10.0",
|
|
38
38
|
"@types/node": "^26.6.4",
|
|
39
|
-
"@vitest/browser-playwright": "^5.0.
|
|
39
|
+
"@vitest/browser-playwright": "^5.0.5",
|
|
40
40
|
"playwright": "^1.63.0",
|
|
41
41
|
"rimraf": "^6.1.3",
|
|
42
42
|
"rolldown": "^1.2.12",
|
|
43
43
|
"typescript": "^7.0.2",
|
|
44
|
-
"vitest": "^5.0.
|
|
45
|
-
"@statewalker/webrun-
|
|
44
|
+
"vitest": "^5.0.5",
|
|
45
|
+
"@statewalker/webrun-msgpack": "^0.10.0",
|
|
46
|
+
"@statewalker/webrun-streams-conformance": "^0.4.0",
|
|
47
|
+
"@statewalker/webrun-rpc": "^0.11.0"
|
|
46
48
|
},
|
|
47
49
|
"sideEffects": false,
|
|
48
50
|
"publishConfig": {
|