@statewalker/webrun-streams-peerjs 0.2.4 → 0.4.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 +106 -67
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +79 -124
- package/dist/message-target.d.ts +67 -0
- package/dist/message-target.d.ts.map +1 -0
- package/package.json +11 -7
- package/src/index.ts +7 -6
- package/src/message-target.ts +175 -0
- package/dist/byte-channel.d.ts +0 -9
- package/dist/byte-channel.d.ts.map +0 -1
- package/dist/connect-serve.d.ts +0 -29
- package/dist/connect-serve.d.ts.map +0 -1
- package/src/byte-channel.ts +0 -112
- package/src/connect-serve.ts +0 -71
package/README.md
CHANGED
|
@@ -2,81 +2,106 @@
|
|
|
2
2
|
|
|
3
3
|
## What it is
|
|
4
4
|
|
|
5
|
-
A `
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
A PeerJS [`DataConnection`](https://peerjs.com/docs/#dataconnection) as a pipe of bytes for
|
|
6
|
+
`@statewalker/webrun-rpc`'s port stack. `messageTargetOverPeerJs(conn)` turns one open raw
|
|
7
|
+
connection into `{ target, signal, maxMessageSize }`: a `MessageTarget` whose messages are
|
|
8
|
+
`Uint8Array`s (one data channel message each), a signal that aborts when the connection closes or
|
|
9
|
+
fails, and the payload ceiling the connection can carry. Hand all three to `webrun-rpc`'s
|
|
10
|
+
`overPipe` with `msgpackCodec`, and `webrun-rpc`'s `connect` / `serve` run many concurrent calls
|
|
11
|
+
over the connection, one port per call. Your handler is an ordinary `Duplex`,
|
|
12
|
+
`(input: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>`, the same function you would
|
|
13
|
+
run over a WebSocket or a `MessagePort`.
|
|
10
14
|
|
|
11
15
|
## Why it exists
|
|
12
16
|
|
|
13
17
|
PeerJS is the least-effort route to a browser-to-browser connection: it ships a public broker, so
|
|
14
18
|
you get a working peer link without running signalling infrastructure. What it hands you is one
|
|
15
|
-
message pipe with no request framing, no concurrency, no half-close and no error propagation.
|
|
16
|
-
|
|
17
|
-
|
|
19
|
+
message pipe with no request framing, no concurrency, no half-close and no error propagation.
|
|
20
|
+
`webrun-rpc`'s port stack supplies those over any pipe of messages. What it needs from the
|
|
21
|
+
transport is the pipe, word of the pipe's death, and the largest message that survives the trip.
|
|
22
|
+
A PeerJS connection gets the last one wrong silently: a message past the data channel's ceiling
|
|
23
|
+
arrives as nothing, with no error on either side. This package supplies all three, checks the
|
|
24
|
+
connection options that would otherwise corrupt streams without an error, and nothing else. A
|
|
25
|
+
handler prototyped over PeerJS runs unchanged over any other transport.
|
|
18
26
|
|
|
19
27
|
## How to use
|
|
20
28
|
|
|
21
29
|
```sh
|
|
22
|
-
pnpm add @statewalker/webrun-streams-peerjs peerjs
|
|
30
|
+
pnpm add @statewalker/webrun-streams-peerjs peerjs @statewalker/webrun-rpc @statewalker/webrun-msgpack
|
|
23
31
|
```
|
|
24
32
|
|
|
25
33
|
`peerjs` is a required peer dependency (`^1.5.5`). You create and own the `Peer`, its broker
|
|
26
34
|
configuration and its connections. Browser only in practice: PeerJS needs WebRTC. One entry point,
|
|
27
35
|
`.`, ESM only.
|
|
28
36
|
|
|
29
|
-
**Connections must use `serialization: "raw"
|
|
30
|
-
|
|
31
|
-
|
|
37
|
+
**Connections must be open, use `serialization: "raw"` and be `reliable: true`.** With any other
|
|
38
|
+
serialization PeerJS encodes the bytes itself; PeerJS's default `reliable: false` means unordered
|
|
39
|
+
delivery, which would reorder envelopes and corrupt every stream without an error; a connection
|
|
40
|
+
that is not yet open would drop posts, and one already closed would never abort the signal.
|
|
41
|
+
`messageTargetOverPeerJs` checks all three and throws.
|
|
32
42
|
|
|
33
43
|
| Export | Purpose |
|
|
34
44
|
| --- | --- |
|
|
35
|
-
| `
|
|
36
|
-
| `
|
|
37
|
-
| `
|
|
38
|
-
| `
|
|
39
|
-
| `byteChannelFromPeerJs(conn)` | The `ByteChannel` both use, for driving `emulateMux` yourself. |
|
|
45
|
+
| `messageTargetOverPeerJs(conn, options?)` | One open raw, reliable connection as a `PeerJsMessageTarget`, `{ target, signal, maxMessageSize }`: a `MessageTarget` of bytes with `bufferedAmount` / `whenDrained()`, a signal that aborts when the connection closes or fails or a post exceeds `maxFrameBytes`, and the payload ceiling to give `overPipe`. |
|
|
46
|
+
| `MessageTargetOverPeerJsOptions` | `maxFrameBytes` (the largest message the connection carries; default `DEFAULT_MAX_FRAME_BYTES`) and `maxMessageSize` (the payload ceiling to report; default `maxFrameBytes` − 256). |
|
|
47
|
+
| `PeerJsMessageTarget` | The result type above. |
|
|
48
|
+
| `DEFAULT_MAX_FRAME_BYTES`, `DEFAULT_MAX_MESSAGE_SIZE`, `DRAIN_LOW_WATER` | 16 KiB, 16 KiB − 256, 256 KiB: the defaults of the above. |
|
|
40
49
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`
|
|
44
|
-
|
|
45
|
-
`serve` takes the `Peer` because it accepts many inbound connections; `connect` takes one
|
|
46
|
-
connection you already opened.
|
|
50
|
+
Both ends must run the port stack with the same codec. Pass all three of `target`, `signal` and
|
|
51
|
+
`maxMessageSize` to `overPipe`: `signal` closes the multiplexer when the connection dies, and
|
|
52
|
+
`maxMessageSize` chunks bodies under the frame limit.
|
|
47
53
|
|
|
48
54
|
## Examples
|
|
49
55
|
|
|
50
56
|
### Serving
|
|
51
57
|
|
|
52
58
|
```ts
|
|
59
|
+
import { msgpackCodec } from "@statewalker/webrun-msgpack";
|
|
60
|
+
import { overPipe, serve } from "@statewalker/webrun-rpc";
|
|
61
|
+
import { messageTargetOverPeerJs } from "@statewalker/webrun-streams-peerjs";
|
|
53
62
|
import { Peer } from "peerjs";
|
|
54
|
-
import { serve } from "@statewalker/webrun-streams-peerjs";
|
|
55
63
|
|
|
56
64
|
const peer = new Peer("my-server-id");
|
|
57
|
-
await new Promise((resolve) => peer.on("open", resolve));
|
|
65
|
+
await new Promise<void>((resolve) => peer.on("open", () => resolve()));
|
|
58
66
|
|
|
59
|
-
|
|
67
|
+
async function* echo(input: AsyncIterable<Uint8Array> | Iterable<Uint8Array>) {
|
|
60
68
|
for await (const chunk of input) yield chunk;
|
|
61
|
-
}
|
|
69
|
+
}
|
|
62
70
|
|
|
63
|
-
|
|
64
|
-
|
|
71
|
+
peer.on("connection", (conn) => {
|
|
72
|
+
const ready = () => {
|
|
73
|
+
const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
|
|
74
|
+
void serve(
|
|
75
|
+
{ mux: overPipe(target, { codec: msgpackCodec, side: "responder", signal, maxMessageSize }) },
|
|
76
|
+
echo,
|
|
77
|
+
);
|
|
78
|
+
};
|
|
79
|
+
if (conn.open) ready();
|
|
80
|
+
else conn.on("open", ready);
|
|
81
|
+
});
|
|
65
82
|
```
|
|
66
83
|
|
|
84
|
+
The caller must open the connection raw and reliable; one opened otherwise makes
|
|
85
|
+
`messageTargetOverPeerJs` throw inside `ready`, and that connection is not served.
|
|
86
|
+
|
|
67
87
|
### Calling
|
|
68
88
|
|
|
69
89
|
```ts
|
|
90
|
+
import { msgpackCodec } from "@statewalker/webrun-msgpack";
|
|
91
|
+
import { connect, overPipe } from "@statewalker/webrun-rpc";
|
|
92
|
+
import { messageTargetOverPeerJs } from "@statewalker/webrun-streams-peerjs";
|
|
70
93
|
import { Peer } from "peerjs";
|
|
71
|
-
import { connect } from "@statewalker/webrun-streams-peerjs";
|
|
72
94
|
|
|
73
95
|
const peer = new Peer();
|
|
74
|
-
await new Promise((resolve) => peer.on("open", resolve));
|
|
96
|
+
await new Promise<void>((resolve) => peer.on("open", () => resolve()));
|
|
75
97
|
|
|
76
|
-
const conn = peer.connect("my-server-id", { serialization: "raw" });
|
|
77
|
-
await new Promise((resolve) => conn.on("open", resolve));
|
|
98
|
+
const conn = peer.connect("my-server-id", { serialization: "raw", reliable: true });
|
|
99
|
+
await new Promise<void>((resolve) => conn.on("open", () => resolve()));
|
|
78
100
|
|
|
79
|
-
const {
|
|
101
|
+
const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
|
|
102
|
+
const { call, close } = await connect({
|
|
103
|
+
mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
|
|
104
|
+
});
|
|
80
105
|
|
|
81
106
|
for await (const chunk of call([new TextEncoder().encode("ping")])) {
|
|
82
107
|
console.log(new TextDecoder().decode(chunk)); // "ping"
|
|
@@ -93,48 +118,56 @@ import { fetchOverDuplex } from "@statewalker/webrun-http-streams";
|
|
|
93
118
|
const response = await fetchOverDuplex(call, new Request("http://peer/api/todo"));
|
|
94
119
|
```
|
|
95
120
|
|
|
96
|
-
### Driving the mux yourself
|
|
97
|
-
|
|
98
|
-
```ts
|
|
99
|
-
import { emulateMux } from "@statewalker/webrun-streams";
|
|
100
|
-
import { byteChannelFromPeerJs } from "@statewalker/webrun-streams-peerjs";
|
|
101
|
-
|
|
102
|
-
const channel = byteChannelFromPeerJs(conn); // conn opened with serialization: "raw"
|
|
103
|
-
const mux = emulateMux(channel, { side: "initiator" });
|
|
104
|
-
// mux.call(input), mux.serve(handler), mux.close()
|
|
105
|
-
```
|
|
106
|
-
|
|
107
121
|
## Internals
|
|
108
122
|
|
|
109
123
|
```
|
|
110
124
|
handler / caller (Duplex)
|
|
111
125
|
│
|
|
112
|
-
|
|
126
|
+
webrun-rpc connect / serve: one stream per port
|
|
127
|
+
│
|
|
128
|
+
overPipe + msgpackCodec (webrun-rpc): a port per call, framing, chunking to maxMessageSize
|
|
113
129
|
│
|
|
114
|
-
|
|
130
|
+
messageTargetOverPeerJs: one MessageTarget per DataConnection
|
|
115
131
|
│ out: conn.send(bytes) in: "data" events
|
|
116
132
|
▼
|
|
117
|
-
PeerJS DataConnection (serialization: "raw") ── WebRTC data channel
|
|
133
|
+
PeerJS DataConnection (serialization: "raw", reliable) ── WebRTC data channel
|
|
118
134
|
```
|
|
119
135
|
|
|
120
|
-
###
|
|
136
|
+
### The message ceiling (measured)
|
|
137
|
+
|
|
138
|
+
PeerJS hands a raw message to the data channel unchanged. Between two Chromiums a message of
|
|
139
|
+
262,143 bytes arrives; one of 262,145 arrives as nothing, with no throw and no error event, and
|
|
140
|
+
the connection silently closes (`tests/message-ceiling.test.ts`, `test:browser`). Firefox to
|
|
141
|
+
Chrome cuts off at 16,384, as PeerJS itself records. So the pipe defaults to `maxFrameBytes`
|
|
142
|
+
16 KiB, reports `maxMessageSize` 256 bytes under it (the port stack's framing adds up to 134), and
|
|
143
|
+
a post past `maxFrameBytes` ends the pipe and throws a `RangeError` instead of vanishing. Raise
|
|
144
|
+
`maxFrameBytes` only for peers known to allow more.
|
|
145
|
+
|
|
146
|
+
### What the pipe accepts, and what it refuses
|
|
147
|
+
|
|
148
|
+
Inbound `data` may be a `Uint8Array`, an `ArrayBuffer` or any `ArrayBufferView`; each is copied
|
|
149
|
+
into a fresh `Uint8Array`, since PeerJS may reuse the buffer it hands out. Anything else (a
|
|
150
|
+
`Blob`, a string) ends the pipe with a `TypeError` and closes the connection: dropping it would
|
|
151
|
+
lose an envelope and hang its call. Messages that reach no listener are dropped, as on a
|
|
152
|
+
`MessagePort`.
|
|
121
153
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
154
|
+
Outbound, `postMessage` throws a `TypeError` for anything but bytes, so a codec breaking its
|
|
155
|
+
contract is not papered over. After the connection has closed it is a no-op: `signal` already says
|
|
156
|
+
so. Each message is copied before `conn.send`, because PeerJS may queue it past its own buffer
|
|
157
|
+
threshold.
|
|
126
158
|
|
|
127
|
-
### What closes the
|
|
159
|
+
### What closes the pipe, and what you see
|
|
128
160
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
throw the `TypeError` above inside the connection's `open` handler, and that connection is not
|
|
134
|
-
served.
|
|
161
|
+
`signal` aborts on the connection's `close` event (`webrun-streams-peerjs: the connection
|
|
162
|
+
closed`), on its `error` event (`webrun-streams-peerjs: the connection failed: <message>`), on an
|
|
163
|
+
oversized post, or on inbound data that is not bytes. `overPipe` closes the multiplexer on it,
|
|
164
|
+
which fails every call in flight.
|
|
135
165
|
|
|
136
|
-
|
|
137
|
-
|
|
166
|
+
`target.close()` waits up to 5 s for PeerJS's queue and the data channel's `bufferedAmount` to
|
|
167
|
+
empty before calling `conn.close()`, because `conn.close()` tears the peer connection down at once
|
|
168
|
+
and discards what they still hold, the multiplexer's last close envelopes among it.
|
|
169
|
+
`whenDrained()` polls the same two (neither reports emptying) every 5 ms and resolves once
|
|
170
|
+
PeerJS's queue is empty and `bufferedAmount` is at most `DRAIN_LOW_WATER`, or the pipe ended.
|
|
138
171
|
|
|
139
172
|
### Conformance runs in a browser against a local broker
|
|
140
173
|
|
|
@@ -143,19 +176,25 @@ pnpm --filter @statewalker/webrun-streams-peerjs test:browser # runs the suite
|
|
|
143
176
|
pnpm --filter @statewalker/webrun-streams-peerjs test # reports it skipped
|
|
144
177
|
```
|
|
145
178
|
|
|
146
|
-
The `@statewalker/webrun-streams-conformance` suite runs in headless Chromium through Playwright
|
|
179
|
+
The `@statewalker/webrun-streams-conformance` suite runs in headless Chromium through Playwright,
|
|
180
|
+
over the port stack (`overPipe` + `msgpackCodec`, with the pipe's 16 KiB-safe `maxMessageSize`, so
|
|
181
|
+
L6's 256 KiB body crosses as chunks under the cross-browser frame limit). L6 asserts the port
|
|
182
|
+
stack's bound: a consumer that stops reading lets the producer get at most one 4 KiB chunk ahead (measured 0).
|
|
147
183
|
A Vitest global setup starts the reference broker (the [`peer`](https://www.npmjs.com/package/peer)
|
|
148
184
|
package's `PeerServer`) on a loopback port in a child process, so runs need no internet access.
|
|
149
185
|
The broker runs out of process because, hosted in-process, it keeps the test run alive after the
|
|
150
186
|
last test: its `close()` waits on the browser's WebSockets and it holds client-expiry timers with
|
|
151
187
|
no public way to clear them. Under plain `pnpm test` (Node) the suite is skipped: the full PeerJS
|
|
152
|
-
handshake hangs there.
|
|
188
|
+
handshake hangs there. The browser run also includes the message-ceiling measurement.
|
|
189
|
+
`message-target.test.ts` runs in Node against a structural fake connection and pins the pipe's
|
|
190
|
+
contract.
|
|
153
191
|
|
|
154
192
|
### Dependencies
|
|
155
193
|
|
|
156
|
-
-
|
|
157
|
-
|
|
158
|
-
- `
|
|
194
|
+
- `peerjs` (peer): you supply and own the `Peer`. `src/` imports only its `DataConnection` type.
|
|
195
|
+
- `@statewalker/webrun-streams` at runtime, for `newMessagePipe`: the pipe module every transport adapter shares (listeners, delivery, life, the byte check, the frame ceiling, drain, close), so a pipe rule is fixed once for all of them (#151). The target is a `MessageTarget` by shape and carries its own `closeSignal` and `maxMessageSize`, so `overPipe(target, { codec, side })` needs nothing else.
|
|
196
|
+
`@statewalker/webrun-rpc` and `@statewalker/webrun-msgpack` are dev dependencies of the tests;
|
|
197
|
+
consumers supply their own `webrun-rpc` and codec.
|
|
159
198
|
- Dev only: `peer` (the local broker), `@vitest/browser-playwright` and `playwright` (the browser
|
|
160
199
|
run), `@statewalker/webrun-streams-conformance` (the suite).
|
|
161
200
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export { type ConnectPeerJsParams, connect, type ServePeerJsParams, serve, } from "./connect-serve.js";
|
|
1
|
+
export { DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DRAIN_LOW_WATER, type MessageTargetOverPeerJsOptions, messageTargetOverPeerJs, type PeerJsMessageTarget, } from "./message-target.js";
|
|
3
2
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,eAAe,EACf,KAAK,8BAA8B,EACnC,uBAAuB,EACvB,KAAK,mBAAmB,GACzB,MAAM,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,133 +1,88 @@
|
|
|
1
|
-
import {
|
|
2
|
-
//#region src/
|
|
1
|
+
import { DEFAULT_DRAIN_LOW_WATER, DEFAULT_DRAIN_POLL_MS, newMessagePipe } from "@statewalker/webrun-streams";
|
|
2
|
+
//#region src/message-target.ts
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* `
|
|
4
|
+
* The largest message a raw `DataConnection` delivers between any two
|
|
5
|
+
* browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
|
|
6
|
+
* bytes", and `-webrtc` chunks to the same 16 KiB. Chromium to Chromium
|
|
7
|
+
* carries up to 256 KiB, and one byte past that is measured to arrive as
|
|
8
|
+
* nothing at all, with no error on either side and the connection closed
|
|
9
|
+
* (`tests/message-ceiling.test.ts`). Raise it with `maxFrameBytes` only for
|
|
10
|
+
* peers known to allow more.
|
|
7
11
|
*/
|
|
8
|
-
|
|
12
|
+
const DEFAULT_MAX_FRAME_BYTES = 16384;
|
|
13
|
+
/**
|
|
14
|
+
* The margin spec D10 asks for: the port stack's framing adds up to 134 bytes
|
|
15
|
+
* (measured 123-128) on top of each payload, so payloads stay 256 below the
|
|
16
|
+
* frame limit.
|
|
17
|
+
*/
|
|
18
|
+
const FRAMING_MARGIN = 256;
|
|
19
|
+
/** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
|
|
20
|
+
const DEFAULT_MAX_MESSAGE_SIZE = 16128;
|
|
21
|
+
/**
|
|
22
|
+
* `whenDrained` resolves once PeerJS's own queue is empty and the data
|
|
23
|
+
* channel's `bufferedAmount` is at most this: the channel can take more.
|
|
24
|
+
* Waiting for zero would pause a sender that waits before every frame.
|
|
25
|
+
*/
|
|
26
|
+
const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
|
|
27
|
+
/** How long `close()` waits for queued messages to be written out. */
|
|
28
|
+
const CLOSE_FLUSH_MS = 5e3;
|
|
29
|
+
/**
|
|
30
|
+
* One open PeerJS `DataConnection` as a pipe of messages, for a multiplexer to
|
|
31
|
+
* run over:
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
|
|
35
|
+
* const { call } = await connect({
|
|
36
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* The connection must be open, use `serialization: "raw"` (PeerJS hands each
|
|
41
|
+
* message to the data channel unchanged) and be `reliable` (ordered); anything
|
|
42
|
+
* else throws. Inbound messages arrive
|
|
43
|
+
* as `Uint8Array` copies. Anything else (a `Blob`, a string) ends the pipe
|
|
44
|
+
* with a `TypeError`: dropping it would lose an envelope and hang its call.
|
|
45
|
+
*/
|
|
46
|
+
function messageTargetOverPeerJs(conn, options = {}) {
|
|
9
47
|
const serialization = conn.serialization;
|
|
10
|
-
if (serialization !== "raw") throw new TypeError(`
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
};
|
|
29
|
-
const onData = (data) => {
|
|
30
|
-
if (data instanceof Uint8Array) {
|
|
31
|
-
deliver(new Uint8Array(data));
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
if (data instanceof ArrayBuffer) {
|
|
35
|
-
deliver(new Uint8Array(data));
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
if (ArrayBuffer.isView(data)) {
|
|
39
|
-
const view = data;
|
|
40
|
-
deliver(new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)));
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
if (typeof Blob !== "undefined" && data instanceof Blob) data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
|
|
44
|
-
};
|
|
45
|
-
const onClose = () => {
|
|
46
|
-
if (isClosed) return;
|
|
47
|
-
isClosed = true;
|
|
48
|
-
conn.off("data", onData);
|
|
49
|
-
conn.off("close", onClose);
|
|
50
|
-
if (pending) {
|
|
51
|
-
const r = pending;
|
|
52
|
-
pending = null;
|
|
53
|
-
r({
|
|
54
|
-
value: void 0,
|
|
55
|
-
done: true
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
closedResolve();
|
|
59
|
-
};
|
|
60
|
-
conn.on("data", onData);
|
|
61
|
-
conn.on("close", onClose);
|
|
62
|
-
return {
|
|
63
|
-
send(bytes) {
|
|
64
|
-
if (isClosed) return;
|
|
65
|
-
if (!conn.open) return;
|
|
66
|
-
conn.send(bytes);
|
|
48
|
+
if (serialization !== "raw") throw new TypeError(`messageTargetOverPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`);
|
|
49
|
+
if (conn.reliable !== true) throw new TypeError("messageTargetOverPeerJs: DataConnection must be opened with `reliable: true` (ordered delivery)");
|
|
50
|
+
if (!conn.open) throw new Error("messageTargetOverPeerJs: DataConnection is not open; wait for its `open` event");
|
|
51
|
+
const maxFrameBytes = options.maxFrameBytes ?? 16384;
|
|
52
|
+
const maxMessageSize = options.maxMessageSize ?? maxFrameBytes - FRAMING_MARGIN;
|
|
53
|
+
const internals = conn;
|
|
54
|
+
const held = () => (internals.bufferSize ?? 0) > 0 || (internals.dataChannel?.bufferedAmount ?? 0) > 0;
|
|
55
|
+
const onData = (data) => control.deliver(data);
|
|
56
|
+
const onClose = () => control.end(/* @__PURE__ */ new Error("webrun-streams-peerjs: the connection closed"));
|
|
57
|
+
const onError = (err) => control.end(new Error(`webrun-streams-peerjs: the connection failed: ${err?.message ?? String(err)}`, { cause: err }), true);
|
|
58
|
+
const control = newMessagePipe({
|
|
59
|
+
send: (bytes) => conn.send(bytes),
|
|
60
|
+
canSend: () => conn.open,
|
|
61
|
+
bufferedAmount: () => internals.dataChannel?.bufferedAmount ?? 0,
|
|
62
|
+
isDrained: () => !(internals.bufferSize ?? 0) && (internals.dataChannel?.bufferedAmount ?? 0) <= DRAIN_LOW_WATER,
|
|
63
|
+
flush: async () => {
|
|
64
|
+
const deadline = Date.now() + CLOSE_FLUSH_MS;
|
|
65
|
+
while (!control.ended && Date.now() < deadline && held()) await new Promise((resolve) => setTimeout(resolve, DEFAULT_DRAIN_POLL_MS));
|
|
67
66
|
},
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
});
|
|
74
|
-
if (isClosed) return Promise.resolve({
|
|
75
|
-
value: void 0,
|
|
76
|
-
done: true
|
|
77
|
-
});
|
|
78
|
-
return new Promise((resolve) => {
|
|
79
|
-
pending = resolve;
|
|
80
|
-
});
|
|
81
|
-
} };
|
|
82
|
-
} },
|
|
83
|
-
closed,
|
|
84
|
-
close() {
|
|
85
|
-
try {
|
|
67
|
+
close: (local) => {
|
|
68
|
+
conn.off("data", onData);
|
|
69
|
+
conn.off("close", onClose);
|
|
70
|
+
conn.off("error", onError);
|
|
71
|
+
if (local) try {
|
|
86
72
|
conn.close();
|
|
87
73
|
} catch {}
|
|
88
|
-
onClose();
|
|
89
74
|
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const mux = emulateMux(channel, {
|
|
97
|
-
...muxOpts,
|
|
98
|
-
side: "initiator"
|
|
75
|
+
}, {
|
|
76
|
+
name: "webrun-streams-peerjs",
|
|
77
|
+
maxFrameBytes,
|
|
78
|
+
maxMessageSize,
|
|
79
|
+
copyOnSend: true,
|
|
80
|
+
copyOnDeliver: true
|
|
99
81
|
});
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
};
|
|
106
|
-
};
|
|
107
|
-
const serve = async ({ peer, mux: muxOpts }, handler) => {
|
|
108
|
-
const muxes = [];
|
|
109
|
-
const onConnection = (conn) => {
|
|
110
|
-
const ready = () => {
|
|
111
|
-
const channel = byteChannelFromPeerJs(conn);
|
|
112
|
-
const mux = emulateMux(channel, {
|
|
113
|
-
...muxOpts,
|
|
114
|
-
side: "responder"
|
|
115
|
-
});
|
|
116
|
-
mux.serve(handler);
|
|
117
|
-
muxes.push(mux);
|
|
118
|
-
channel.closed.then(() => mux.close());
|
|
119
|
-
};
|
|
120
|
-
if (conn.open) ready();
|
|
121
|
-
else conn.on("open", ready);
|
|
122
|
-
};
|
|
123
|
-
peer.on("connection", onConnection);
|
|
124
|
-
let torn = false;
|
|
125
|
-
return async () => {
|
|
126
|
-
if (torn) return;
|
|
127
|
-
torn = true;
|
|
128
|
-
peer.off("connection", onConnection);
|
|
129
|
-
await Promise.all(muxes.map((m) => m.close()));
|
|
130
|
-
};
|
|
131
|
-
};
|
|
82
|
+
conn.on("data", onData);
|
|
83
|
+
conn.on("close", onClose);
|
|
84
|
+
conn.on("error", onError);
|
|
85
|
+
return control.pipe;
|
|
86
|
+
}
|
|
132
87
|
//#endregion
|
|
133
|
-
export {
|
|
88
|
+
export { DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_SIZE, DRAIN_LOW_WATER, messageTargetOverPeerJs };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type MessagePipe, type MessagePipeTarget } from "@statewalker/webrun-streams";
|
|
2
|
+
import type { DataConnection } from "peerjs";
|
|
3
|
+
/**
|
|
4
|
+
* The largest message a raw `DataConnection` delivers between any two
|
|
5
|
+
* browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
|
|
6
|
+
* bytes", and `-webrtc` chunks to the same 16 KiB. Chromium to Chromium
|
|
7
|
+
* carries up to 256 KiB, and one byte past that is measured to arrive as
|
|
8
|
+
* nothing at all, with no error on either side and the connection closed
|
|
9
|
+
* (`tests/message-ceiling.test.ts`). Raise it with `maxFrameBytes` only for
|
|
10
|
+
* peers known to allow more.
|
|
11
|
+
*/
|
|
12
|
+
export declare const DEFAULT_MAX_FRAME_BYTES: number;
|
|
13
|
+
/** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
|
|
14
|
+
export declare const DEFAULT_MAX_MESSAGE_SIZE: number;
|
|
15
|
+
/**
|
|
16
|
+
* `whenDrained` resolves once PeerJS's own queue is empty and the data
|
|
17
|
+
* channel's `bufferedAmount` is at most this: the channel can take more.
|
|
18
|
+
* Waiting for zero would pause a sender that waits before every frame.
|
|
19
|
+
*/
|
|
20
|
+
export declare const DRAIN_LOW_WATER: number;
|
|
21
|
+
export interface MessageTargetOverPeerJsOptions {
|
|
22
|
+
/**
|
|
23
|
+
* The largest message the connection carries. A post past it ends the pipe
|
|
24
|
+
* with a `RangeError` rather than letting the data channel drop it
|
|
25
|
+
* silently. Default {@link DEFAULT_MAX_FRAME_BYTES}.
|
|
26
|
+
*/
|
|
27
|
+
maxFrameBytes?: number;
|
|
28
|
+
/** The payload ceiling to report. Default `maxFrameBytes` less 256. */
|
|
29
|
+
maxMessageSize?: number;
|
|
30
|
+
}
|
|
31
|
+
/** What `messageTargetOverPeerJs` gives: a pipe of bytes, its life, and its payload ceiling. */
|
|
32
|
+
export interface PeerJsMessageTarget extends MessagePipe {
|
|
33
|
+
/**
|
|
34
|
+
* A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
|
|
35
|
+
* are `Uint8Array`s, one data channel message each. A post past
|
|
36
|
+
* `maxFrameBytes` throws `RangeError` and ends the pipe; `bufferedAmount` is
|
|
37
|
+
* the data channel's; `whenDrained` waits for PeerJS's own queue to empty
|
|
38
|
+
* and `bufferedAmount` to reach {@link DRAIN_LOW_WATER}.
|
|
39
|
+
*/
|
|
40
|
+
target: MessagePipeTarget;
|
|
41
|
+
/**
|
|
42
|
+
* Aborts when the connection closes or fails, or a post exceeds
|
|
43
|
+
* `maxFrameBytes`. Pass it as `overPipe`'s `signal`.
|
|
44
|
+
*/
|
|
45
|
+
signal: AbortSignal;
|
|
46
|
+
/** Pass as `overPipe`'s `maxMessageSize`, so bodies are chunked under the frame limit. */
|
|
47
|
+
maxMessageSize: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* One open PeerJS `DataConnection` as a pipe of messages, for a multiplexer to
|
|
51
|
+
* run over:
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
|
|
55
|
+
* const { call } = await connect({
|
|
56
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* The connection must be open, use `serialization: "raw"` (PeerJS hands each
|
|
61
|
+
* message to the data channel unchanged) and be `reliable` (ordered); anything
|
|
62
|
+
* else throws. Inbound messages arrive
|
|
63
|
+
* as `Uint8Array` copies. Anything else (a `Blob`, a string) ends the pipe
|
|
64
|
+
* with a `TypeError`: dropping it would lose an envelope and hang its call.
|
|
65
|
+
*/
|
|
66
|
+
export declare function messageTargetOverPeerJs(conn: DataConnection, options?: MessageTargetOverPeerJsOptions): PeerJsMessageTarget;
|
|
67
|
+
//# sourceMappingURL=message-target.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message-target.d.ts","sourceRoot":"","sources":["../src/message-target.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EAChB,KAAK,iBAAiB,EAEvB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C;;;;;;;;GAQG;AACH,eAAO,MAAM,uBAAuB,QAAY,CAAC;AASjD,kFAAkF;AAClF,eAAO,MAAM,wBAAwB,QAA2C,CAAC;AAEjF;;;;GAIG;AACH,eAAO,MAAM,eAAe,QAA0B,CAAC;AAIvD,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,gGAAgG;AAChG,MAAM,WAAW,mBAAoB,SAAQ,WAAW;IACtD;;;;;;OAMG;IACH,MAAM,EAAE,iBAAiB,CAAC;IAC1B;;;OAGG;IACH,MAAM,EAAE,WAAW,CAAC;IACpB,0FAA0F;IAC1F,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,cAAc,EACpB,OAAO,GAAE,8BAAmC,GAC3C,mBAAmB,CAqFrB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/webrun-streams-peerjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "PeerJS DataConnection-backed Connect/Serve adapter in the webrun-streams-* family",
|
|
@@ -29,25 +29,27 @@
|
|
|
29
29
|
"dist",
|
|
30
30
|
"src"
|
|
31
31
|
],
|
|
32
|
-
"dependencies": {
|
|
33
|
-
"@statewalker/webrun-streams": "^0.2.3"
|
|
34
|
-
},
|
|
35
32
|
"peerDependencies": {
|
|
36
33
|
"peerjs": "^1.5.5"
|
|
37
34
|
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@statewalker/webrun-streams": "^0.5.0"
|
|
37
|
+
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@biomejs/biome": "^2.5.15",
|
|
40
40
|
"@roamhq/wrtc": "^0.10.0",
|
|
41
41
|
"@types/node": "^26.6.4",
|
|
42
|
-
"@vitest/browser-playwright": "^5.0.
|
|
42
|
+
"@vitest/browser-playwright": "^5.0.5",
|
|
43
43
|
"peer": "^1.0.2",
|
|
44
44
|
"peerjs": "^1.5.5",
|
|
45
45
|
"playwright": "^1.63.0",
|
|
46
46
|
"rimraf": "^6.1.3",
|
|
47
47
|
"rolldown": "^1.2.12",
|
|
48
48
|
"typescript": "^7.0.2",
|
|
49
|
-
"vitest": "^5.0.
|
|
50
|
-
"@statewalker/webrun-
|
|
49
|
+
"vitest": "^5.0.5",
|
|
50
|
+
"@statewalker/webrun-rpc": "^0.13.0",
|
|
51
|
+
"@statewalker/webrun-msgpack": "^0.12.0",
|
|
52
|
+
"@statewalker/webrun-streams-conformance": "^0.6.0"
|
|
51
53
|
},
|
|
52
54
|
"sideEffects": false,
|
|
53
55
|
"publishConfig": {
|
|
@@ -58,6 +60,8 @@
|
|
|
58
60
|
"build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
|
|
59
61
|
"test": "vitest run",
|
|
60
62
|
"test:browser": "vitest run --config vitest.browser.config.ts",
|
|
63
|
+
"typecheck": "tsc --noEmit",
|
|
64
|
+
"typecheck:tests": "tsc -p tsconfig.tests.json",
|
|
61
65
|
"lint": "biome check src tests"
|
|
62
66
|
}
|
|
63
67
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export { byteChannelFromPeerJs } from "./byte-channel.js";
|
|
2
1
|
export {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
DEFAULT_MAX_FRAME_BYTES,
|
|
3
|
+
DEFAULT_MAX_MESSAGE_SIZE,
|
|
4
|
+
DRAIN_LOW_WATER,
|
|
5
|
+
type MessageTargetOverPeerJsOptions,
|
|
6
|
+
messageTargetOverPeerJs,
|
|
7
|
+
type PeerJsMessageTarget,
|
|
8
|
+
} from "./message-target.js";
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_DRAIN_LOW_WATER,
|
|
3
|
+
DEFAULT_DRAIN_POLL_MS,
|
|
4
|
+
type MessagePipe,
|
|
5
|
+
type MessagePipeTarget,
|
|
6
|
+
newMessagePipe,
|
|
7
|
+
} from "@statewalker/webrun-streams";
|
|
8
|
+
import type { DataConnection } from "peerjs";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The largest message a raw `DataConnection` delivers between any two
|
|
12
|
+
* browsers: PeerJS records Firefox-to-Chrome messages "cut off after 16384
|
|
13
|
+
* bytes", and `-webrtc` chunks to the same 16 KiB. Chromium to Chromium
|
|
14
|
+
* carries up to 256 KiB, and one byte past that is measured to arrive as
|
|
15
|
+
* nothing at all, with no error on either side and the connection closed
|
|
16
|
+
* (`tests/message-ceiling.test.ts`). Raise it with `maxFrameBytes` only for
|
|
17
|
+
* peers known to allow more.
|
|
18
|
+
*/
|
|
19
|
+
export const DEFAULT_MAX_FRAME_BYTES = 16 * 1024;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The margin spec D10 asks for: the port stack's framing adds up to 134 bytes
|
|
23
|
+
* (measured 123-128) on top of each payload, so payloads stay 256 below the
|
|
24
|
+
* frame limit.
|
|
25
|
+
*/
|
|
26
|
+
const FRAMING_MARGIN = 256;
|
|
27
|
+
|
|
28
|
+
/** `DEFAULT_MAX_FRAME_BYTES` less the framing margin: what to give `overPipe`. */
|
|
29
|
+
export const DEFAULT_MAX_MESSAGE_SIZE = DEFAULT_MAX_FRAME_BYTES - FRAMING_MARGIN;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `whenDrained` resolves once PeerJS's own queue is empty and the data
|
|
33
|
+
* channel's `bufferedAmount` is at most this: the channel can take more.
|
|
34
|
+
* Waiting for zero would pause a sender that waits before every frame.
|
|
35
|
+
*/
|
|
36
|
+
export const DRAIN_LOW_WATER = DEFAULT_DRAIN_LOW_WATER;
|
|
37
|
+
/** How long `close()` waits for queued messages to be written out. */
|
|
38
|
+
const CLOSE_FLUSH_MS = 5000;
|
|
39
|
+
|
|
40
|
+
export interface MessageTargetOverPeerJsOptions {
|
|
41
|
+
/**
|
|
42
|
+
* The largest message the connection carries. A post past it ends the pipe
|
|
43
|
+
* with a `RangeError` rather than letting the data channel drop it
|
|
44
|
+
* silently. Default {@link DEFAULT_MAX_FRAME_BYTES}.
|
|
45
|
+
*/
|
|
46
|
+
maxFrameBytes?: number;
|
|
47
|
+
/** The payload ceiling to report. Default `maxFrameBytes` less 256. */
|
|
48
|
+
maxMessageSize?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What `messageTargetOverPeerJs` gives: a pipe of bytes, its life, and its payload ceiling. */
|
|
52
|
+
export interface PeerJsMessageTarget extends MessagePipe {
|
|
53
|
+
/**
|
|
54
|
+
* A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) whose messages
|
|
55
|
+
* are `Uint8Array`s, one data channel message each. A post past
|
|
56
|
+
* `maxFrameBytes` throws `RangeError` and ends the pipe; `bufferedAmount` is
|
|
57
|
+
* the data channel's; `whenDrained` waits for PeerJS's own queue to empty
|
|
58
|
+
* and `bufferedAmount` to reach {@link DRAIN_LOW_WATER}.
|
|
59
|
+
*/
|
|
60
|
+
target: MessagePipeTarget;
|
|
61
|
+
/**
|
|
62
|
+
* Aborts when the connection closes or fails, or a post exceeds
|
|
63
|
+
* `maxFrameBytes`. Pass it as `overPipe`'s `signal`.
|
|
64
|
+
*/
|
|
65
|
+
signal: AbortSignal;
|
|
66
|
+
/** Pass as `overPipe`'s `maxMessageSize`, so bodies are chunked under the frame limit. */
|
|
67
|
+
maxMessageSize: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One open PeerJS `DataConnection` as a pipe of messages, for a multiplexer to
|
|
72
|
+
* run over:
|
|
73
|
+
*
|
|
74
|
+
* ```ts
|
|
75
|
+
* const { target, signal, maxMessageSize } = messageTargetOverPeerJs(conn);
|
|
76
|
+
* const { call } = await connect({
|
|
77
|
+
* mux: overPipe(target, { codec: msgpackCodec, side: "initiator", signal, maxMessageSize }),
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* The connection must be open, use `serialization: "raw"` (PeerJS hands each
|
|
82
|
+
* message to the data channel unchanged) and be `reliable` (ordered); anything
|
|
83
|
+
* else throws. Inbound messages arrive
|
|
84
|
+
* as `Uint8Array` copies. Anything else (a `Blob`, a string) ends the pipe
|
|
85
|
+
* with a `TypeError`: dropping it would lose an envelope and hang its call.
|
|
86
|
+
*/
|
|
87
|
+
export function messageTargetOverPeerJs(
|
|
88
|
+
conn: DataConnection,
|
|
89
|
+
options: MessageTargetOverPeerJsOptions = {},
|
|
90
|
+
): PeerJsMessageTarget {
|
|
91
|
+
const serialization = (conn as unknown as { serialization?: string }).serialization;
|
|
92
|
+
if (serialization !== "raw") {
|
|
93
|
+
throw new TypeError(
|
|
94
|
+
`messageTargetOverPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
// PeerJS's default `reliable: false` means `ordered: false`: envelopes would
|
|
98
|
+
// arrive out of order and corrupt every stream without an error.
|
|
99
|
+
if ((conn as unknown as { reliable?: boolean }).reliable !== true) {
|
|
100
|
+
throw new TypeError(
|
|
101
|
+
"messageTargetOverPeerJs: DataConnection must be opened with `reliable: true` (ordered delivery)",
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
// Not yet open, posts would be dropped; already closed, `close` has fired and
|
|
105
|
+
// the signal would never abort. Either way calls would hang.
|
|
106
|
+
if (!conn.open) {
|
|
107
|
+
throw new Error(
|
|
108
|
+
"messageTargetOverPeerJs: DataConnection is not open; wait for its `open` event",
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
112
|
+
const maxMessageSize = options.maxMessageSize ?? maxFrameBytes - FRAMING_MARGIN;
|
|
113
|
+
const internals = conn as unknown as {
|
|
114
|
+
bufferSize?: number;
|
|
115
|
+
dataChannel?: { bufferedAmount?: number };
|
|
116
|
+
};
|
|
117
|
+
const held = (): boolean =>
|
|
118
|
+
(internals.bufferSize ?? 0) > 0 || (internals.dataChannel?.bufferedAmount ?? 0) > 0;
|
|
119
|
+
|
|
120
|
+
const onData = (data: unknown): void => control.deliver(data);
|
|
121
|
+
const onClose = (): void =>
|
|
122
|
+
control.end(new Error("webrun-streams-peerjs: the connection closed"));
|
|
123
|
+
// Ended as local: an error is not always followed by `close`, and the
|
|
124
|
+
// connection must still be released, or the peer never learns the pipe is gone.
|
|
125
|
+
const onError = (err: unknown): void =>
|
|
126
|
+
control.end(
|
|
127
|
+
new Error(
|
|
128
|
+
`webrun-streams-peerjs: the connection failed: ${(err as Error)?.message ?? String(err)}`,
|
|
129
|
+
{ cause: err },
|
|
130
|
+
),
|
|
131
|
+
true,
|
|
132
|
+
);
|
|
133
|
+
const control = newMessagePipe(
|
|
134
|
+
{
|
|
135
|
+
send: (bytes) => conn.send(bytes),
|
|
136
|
+
canSend: () => conn.open,
|
|
137
|
+
bufferedAmount: () => internals.dataChannel?.bufferedAmount ?? 0,
|
|
138
|
+
isDrained: () =>
|
|
139
|
+
!(internals.bufferSize ?? 0) &&
|
|
140
|
+
(internals.dataChannel?.bufferedAmount ?? 0) <= DRAIN_LOW_WATER,
|
|
141
|
+
// `conn.close()` tears the peer connection down at once, discarding what
|
|
142
|
+
// PeerJS and the data channel still hold — the multiplexer's last close
|
|
143
|
+
// envelopes among it. Let that go out first, for at most CLOSE_FLUSH_MS.
|
|
144
|
+
flush: async () => {
|
|
145
|
+
const deadline = Date.now() + CLOSE_FLUSH_MS;
|
|
146
|
+
while (!control.ended && Date.now() < deadline && held()) {
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, DEFAULT_DRAIN_POLL_MS));
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
close: (local) => {
|
|
151
|
+
conn.off("data", onData);
|
|
152
|
+
conn.off("close", onClose);
|
|
153
|
+
conn.off("error", onError);
|
|
154
|
+
if (local) {
|
|
155
|
+
try {
|
|
156
|
+
conn.close();
|
|
157
|
+
} catch {}
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
name: "webrun-streams-peerjs",
|
|
163
|
+
maxFrameBytes,
|
|
164
|
+
maxMessageSize,
|
|
165
|
+
// PeerJS may queue a sent message past its own buffer threshold, and
|
|
166
|
+
// reuse the buffer it hands out.
|
|
167
|
+
copyOnSend: true,
|
|
168
|
+
copyOnDeliver: true,
|
|
169
|
+
},
|
|
170
|
+
);
|
|
171
|
+
conn.on("data", onData);
|
|
172
|
+
conn.on("close", onClose);
|
|
173
|
+
conn.on("error", onError);
|
|
174
|
+
return control.pipe as PeerJsMessageTarget;
|
|
175
|
+
}
|
package/dist/byte-channel.d.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
2
|
-
import type { DataConnection } from "peerjs";
|
|
3
|
-
/**
|
|
4
|
-
* Wrap an open PeerJS `DataConnection` into a `ByteChannel`. The connection
|
|
5
|
-
* MUST be constructed with `{ serialization: "raw" }` so payloads arrive as
|
|
6
|
-
* `Uint8Array` rather than PeerJS's own JSON envelopes.
|
|
7
|
-
*/
|
|
8
|
-
export declare function byteChannelFromPeerJs(conn: DataConnection): ByteChannel;
|
|
9
|
-
//# sourceMappingURL=byte-channel.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"byte-channel.d.ts","sourceRoot":"","sources":["../src/byte-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAE7C;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,cAAc,GAAG,WAAW,CAuGvE"}
|
package/dist/connect-serve.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { type Connect, type EmulateMuxOptions, type Serve } from "@statewalker/webrun-streams";
|
|
2
|
-
import type { DataConnection, Peer } from "peerjs";
|
|
3
|
-
export interface ConnectPeerJsParams {
|
|
4
|
-
/** Already-open `DataConnection` with `serialization: "raw"`. */
|
|
5
|
-
conn: DataConnection;
|
|
6
|
-
/**
|
|
7
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
8
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
9
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
10
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
11
|
-
* genuinely stalls.
|
|
12
|
-
*/
|
|
13
|
-
mux?: EmulateMuxOptions;
|
|
14
|
-
}
|
|
15
|
-
export interface ServePeerJsParams {
|
|
16
|
-
/** Connected `Peer`. The adapter listens for inbound `DataConnection`s. */
|
|
17
|
-
peer: Peer;
|
|
18
|
-
/**
|
|
19
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
20
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
21
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
22
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
23
|
-
* genuinely stalls.
|
|
24
|
-
*/
|
|
25
|
-
mux?: EmulateMuxOptions;
|
|
26
|
-
}
|
|
27
|
-
export declare const connect: Connect<ConnectPeerJsParams>;
|
|
28
|
-
export declare const serve: Serve<ServePeerJsParams>;
|
|
29
|
-
//# sourceMappingURL=connect-serve.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect-serve.d.ts","sourceRoot":"","sources":["../src/connect-serve.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,OAAO,EAEZ,KAAK,iBAAiB,EAEtB,KAAK,KAAK,EACX,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAGnD,MAAM,WAAW,mBAAmB;IAClC,iEAAiE;IACjE,IAAI,EAAE,cAAc,CAAC;IACrB;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,MAAM,WAAW,iBAAiB;IAChC,2EAA2E;IAC3E,IAAI,EAAE,IAAI,CAAC;IACX;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,iBAAiB,CAAC;CACzB;AAED,eAAO,MAAM,OAAO,EAAE,OAAO,CAAC,mBAAmB,CAShD,CAAC;AAEF,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,iBAAiB,CAuB1C,CAAC"}
|
package/src/byte-channel.ts
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
2
|
-
import type { DataConnection } from "peerjs";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Wrap an open PeerJS `DataConnection` into a `ByteChannel`. The connection
|
|
6
|
-
* MUST be constructed with `{ serialization: "raw" }` so payloads arrive as
|
|
7
|
-
* `Uint8Array` rather than PeerJS's own JSON envelopes.
|
|
8
|
-
*/
|
|
9
|
-
export function byteChannelFromPeerJs(conn: DataConnection): ByteChannel {
|
|
10
|
-
const serialization = (conn as unknown as { serialization?: string }).serialization;
|
|
11
|
-
if (serialization !== "raw") {
|
|
12
|
-
throw new TypeError(
|
|
13
|
-
`byteChannelFromPeerJs: DataConnection serialization is '${serialization}', expected 'raw'`,
|
|
14
|
-
);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
let closedResolve!: () => void;
|
|
18
|
-
const closed = new Promise<void>((r) => {
|
|
19
|
-
closedResolve = r;
|
|
20
|
-
});
|
|
21
|
-
let isClosed = false;
|
|
22
|
-
|
|
23
|
-
const queue: Uint8Array[] = [];
|
|
24
|
-
let pending: ((value: IteratorResult<Uint8Array>) => void) | null = null;
|
|
25
|
-
|
|
26
|
-
const deliver = (bytes: Uint8Array): void => {
|
|
27
|
-
if (isClosed) return;
|
|
28
|
-
if (pending) {
|
|
29
|
-
const r = pending;
|
|
30
|
-
pending = null;
|
|
31
|
-
r({ value: bytes, done: false });
|
|
32
|
-
} else {
|
|
33
|
-
queue.push(bytes);
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
const onData = (data: unknown): void => {
|
|
38
|
-
if (data instanceof Uint8Array) {
|
|
39
|
-
deliver(new Uint8Array(data));
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
if (data instanceof ArrayBuffer) {
|
|
43
|
-
deliver(new Uint8Array(data));
|
|
44
|
-
return;
|
|
45
|
-
}
|
|
46
|
-
if (ArrayBuffer.isView(data)) {
|
|
47
|
-
const view = data as ArrayBufferView;
|
|
48
|
-
deliver(
|
|
49
|
-
new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)),
|
|
50
|
-
);
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
54
|
-
void data.arrayBuffer().then((buf) => deliver(new Uint8Array(buf)));
|
|
55
|
-
}
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
const onClose = (): void => {
|
|
59
|
-
if (isClosed) return;
|
|
60
|
-
isClosed = true;
|
|
61
|
-
conn.off("data", onData);
|
|
62
|
-
conn.off("close", onClose);
|
|
63
|
-
if (pending) {
|
|
64
|
-
const r = pending;
|
|
65
|
-
pending = null;
|
|
66
|
-
r({ value: undefined, done: true } as IteratorResult<Uint8Array>);
|
|
67
|
-
}
|
|
68
|
-
closedResolve();
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
conn.on("data", onData);
|
|
72
|
-
conn.on("close", onClose);
|
|
73
|
-
|
|
74
|
-
const recv: AsyncIterable<Uint8Array> = {
|
|
75
|
-
[Symbol.asyncIterator]() {
|
|
76
|
-
return {
|
|
77
|
-
next(): Promise<IteratorResult<Uint8Array>> {
|
|
78
|
-
if (queue.length > 0) {
|
|
79
|
-
return Promise.resolve({ value: queue.shift() as Uint8Array, done: false });
|
|
80
|
-
}
|
|
81
|
-
if (isClosed) {
|
|
82
|
-
return Promise.resolve({
|
|
83
|
-
value: undefined,
|
|
84
|
-
done: true,
|
|
85
|
-
} as IteratorResult<Uint8Array>);
|
|
86
|
-
}
|
|
87
|
-
return new Promise<IteratorResult<Uint8Array>>((resolve) => {
|
|
88
|
-
pending = resolve;
|
|
89
|
-
});
|
|
90
|
-
},
|
|
91
|
-
};
|
|
92
|
-
},
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
return {
|
|
96
|
-
send(bytes) {
|
|
97
|
-
if (isClosed) return;
|
|
98
|
-
if (!conn.open) return;
|
|
99
|
-
conn.send(bytes);
|
|
100
|
-
},
|
|
101
|
-
recv,
|
|
102
|
-
closed,
|
|
103
|
-
close() {
|
|
104
|
-
try {
|
|
105
|
-
conn.close();
|
|
106
|
-
} catch {
|
|
107
|
-
/* ignore */
|
|
108
|
-
}
|
|
109
|
-
onClose();
|
|
110
|
-
},
|
|
111
|
-
};
|
|
112
|
-
}
|
package/src/connect-serve.ts
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
type Connect,
|
|
3
|
-
type Duplex,
|
|
4
|
-
type EmulateMuxOptions,
|
|
5
|
-
emulateMux,
|
|
6
|
-
type Serve,
|
|
7
|
-
} from "@statewalker/webrun-streams";
|
|
8
|
-
import type { DataConnection, Peer } from "peerjs";
|
|
9
|
-
import { byteChannelFromPeerJs } from "./byte-channel.js";
|
|
10
|
-
|
|
11
|
-
export interface ConnectPeerJsParams {
|
|
12
|
-
/** Already-open `DataConnection` with `serialization: "raw"`. */
|
|
13
|
-
conn: DataConnection;
|
|
14
|
-
/**
|
|
15
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
16
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
17
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
18
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
19
|
-
* genuinely stalls.
|
|
20
|
-
*/
|
|
21
|
-
mux?: EmulateMuxOptions;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export interface ServePeerJsParams {
|
|
25
|
-
/** Connected `Peer`. The adapter listens for inbound `DataConnection`s. */
|
|
26
|
-
peer: Peer;
|
|
27
|
-
/**
|
|
28
|
-
* Flow-control tuning forwarded to `emulateMux` — `mtu` and
|
|
29
|
-
* `maxStreamBuffer`, which is the credit this side advertises. `side` here
|
|
30
|
-
* wins over `mux.side`. Defaults are `emulateMux`'s own; the conformance
|
|
31
|
-
* suite's L6 uses this to run at a window small enough that a sender
|
|
32
|
-
* genuinely stalls.
|
|
33
|
-
*/
|
|
34
|
-
mux?: EmulateMuxOptions;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export const connect: Connect<ConnectPeerJsParams> = async ({ conn, mux: muxOpts }) => {
|
|
38
|
-
const channel = byteChannelFromPeerJs(conn);
|
|
39
|
-
const mux = emulateMux(channel, { ...muxOpts, side: "initiator" });
|
|
40
|
-
return {
|
|
41
|
-
call: mux.call,
|
|
42
|
-
async close() {
|
|
43
|
-
await mux.close();
|
|
44
|
-
},
|
|
45
|
-
};
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
export const serve: Serve<ServePeerJsParams> = async ({ peer, mux: muxOpts }, handler: Duplex) => {
|
|
49
|
-
const muxes: Array<{ close: () => Promise<void> }> = [];
|
|
50
|
-
|
|
51
|
-
const onConnection = (conn: DataConnection): void => {
|
|
52
|
-
const ready = (): void => {
|
|
53
|
-
const channel = byteChannelFromPeerJs(conn);
|
|
54
|
-
const mux = emulateMux(channel, { ...muxOpts, side: "responder" });
|
|
55
|
-
mux.serve(handler);
|
|
56
|
-
muxes.push(mux);
|
|
57
|
-
void channel.closed.then(() => mux.close());
|
|
58
|
-
};
|
|
59
|
-
if (conn.open) ready();
|
|
60
|
-
else conn.on("open", ready);
|
|
61
|
-
};
|
|
62
|
-
peer.on("connection", onConnection);
|
|
63
|
-
|
|
64
|
-
let torn = false;
|
|
65
|
-
return async () => {
|
|
66
|
-
if (torn) return;
|
|
67
|
-
torn = true;
|
|
68
|
-
peer.off("connection", onConnection);
|
|
69
|
-
await Promise.all(muxes.map((m) => m.close()));
|
|
70
|
-
};
|
|
71
|
-
};
|