@statewalker/webrun-streams-signaling 0.2.0 → 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 +60 -27
- package/dist/byte-channel.d.ts +46 -5
- package/dist/byte-channel.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +277 -95
- package/dist/message-target.d.ts +10 -12
- package/dist/message-target.d.ts.map +1 -1
- package/dist/peer-connection.d.ts +2 -0
- package/dist/peer-connection.d.ts.map +1 -1
- package/dist/peer-manager.d.ts +13 -1
- package/dist/peer-manager.d.ts.map +1 -1
- package/dist/qr-signaling.d.ts.map +1 -1
- package/dist/room-manager.d.ts +3 -2
- package/dist/room-manager.d.ts.map +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +9 -4
- package/src/byte-channel.ts +172 -33
- package/src/index.ts +8 -1
- package/src/message-target.ts +63 -68
- package/src/peer-connection.ts +13 -0
- package/src/peer-manager.ts +64 -10
- package/src/qr-signaling.ts +54 -12
- package/src/room-manager.ts +4 -4
- package/src/types.ts +8 -1
package/dist/room-manager.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* injected via {@link RoomManagerOptions.roomFactory} (production:
|
|
11
11
|
* `() => new Room()`), so this module never hard-imports it.
|
|
12
12
|
*/
|
|
13
|
+
import { type ByteChannelFromRoomOptions } from "./byte-channel.js";
|
|
13
14
|
import type { ByteChannel, RoomManagerOptions } from "./types.js";
|
|
14
15
|
export declare class RoomManager {
|
|
15
16
|
private readonly options;
|
|
@@ -23,8 +24,8 @@ export declare class RoomManager {
|
|
|
23
24
|
join(room: string): Promise<void>;
|
|
24
25
|
/** Observe participant identities: those already present, then joiners. */
|
|
25
26
|
participants(): AsyncIterable<string>;
|
|
26
|
-
/** Open a {@link ByteChannel} to a specific participant. */
|
|
27
|
-
channelTo(peerId: string): Promise<ByteChannel>;
|
|
27
|
+
/** Open a {@link ByteChannel} to a specific participant (see {@link byteChannelFromRoom}). */
|
|
28
|
+
channelTo(peerId: string, options?: ByteChannelFromRoomOptions): Promise<ByteChannel>;
|
|
28
29
|
/** Leave the room: unsubscribe and disconnect. */
|
|
29
30
|
leave(): Promise<void>;
|
|
30
31
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"room-manager.d.ts","sourceRoot":"","sources":["../src/room-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;
|
|
1
|
+
{"version":3,"file":"room-manager.d.ts","sourceRoot":"","sources":["../src/room-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,KAAK,0BAA0B,EAAuB,MAAM,mBAAmB,CAAC;AACzF,OAAO,KAAK,EAAE,WAAW,EAAY,kBAAkB,EAAuB,MAAM,YAAY,CAAC;AAGjG,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,IAAI,CAAyB;IAErC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAgB;IACrC,OAAO,CAAC,IAAI,CAA6C;IACzD,OAAO,CAAC,eAAe,CAA6B;IACpD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;IAElD,YAAY,OAAO,EAAE,kBAAkB,EAEtC;IAED,sEAAsE;IAChE,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAmBtC;IAED,2EAA2E;IAC3E,YAAY,IAAI,aAAa,CAAC,MAAM,CAAC,CAyCpC;IAED,8FAA8F;IACxF,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,0BAA0B,GAAG,OAAO,CAAC,WAAW,CAAC,CAG1F;IAED,kDAAkD;IAC5C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAQ3B;CACF"}
|
package/dist/types.d.ts
CHANGED
|
@@ -18,6 +18,13 @@ export type ByteChannel = {
|
|
|
18
18
|
recv: AsyncIterable<Uint8Array>;
|
|
19
19
|
closed: Promise<void>;
|
|
20
20
|
close(): void;
|
|
21
|
+
/** Bytes sent and not yet written out, where the transport can tell. */
|
|
22
|
+
readonly bufferedAmount?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Resolves once the transport can take more (`bufferedAmount` at most a
|
|
25
|
+
* low-water mark) or the channel closed. Absent where it cannot tell.
|
|
26
|
+
*/
|
|
27
|
+
whenDrained?(): Promise<void>;
|
|
21
28
|
};
|
|
22
29
|
/** WebRTC peer role in the connection. */
|
|
23
30
|
export type PeerRole = "initiator" | "responder";
|
|
@@ -143,6 +150,7 @@ export interface RoomLocalParticipantLike {
|
|
|
143
150
|
publishData(data: Uint8Array, opts?: {
|
|
144
151
|
reliable?: boolean;
|
|
145
152
|
destinationIdentities?: string[];
|
|
153
|
+
topic?: string;
|
|
146
154
|
}): Promise<void>;
|
|
147
155
|
}
|
|
148
156
|
export interface RoomLike {
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAAC;IAC9B,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IAChC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,KAAK,IAAI,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAAC;IAC9B,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,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BAAkB;IACjC,oDAAoD;IACpD,GAAG,EAAE,MAAM,CAAC;IACZ,kFAAkF;IAClF,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5C,0EAA0E;IAC1E,WAAW,EAAE,MAAM,QAAQ,CAAC;CAC7B;AAED,oFAAoF;AACpF,eAAO,MAAM,UAAU;aACrB,oBAAoB,EAAE,sBAAsB;aAC5C,uBAAuB,EAAE,yBAAyB;aAClD,YAAY,EAAE,cAAc;aAC5B,YAAY,EAAE,cAAc;CACpB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/webrun-streams-signaling",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Generic P2P signaling/connection-setup (PeerManager, QrSignaling, RoomManager) yielding ByteChannels",
|
|
@@ -37,6 +37,9 @@
|
|
|
37
37
|
"optional": true
|
|
38
38
|
}
|
|
39
39
|
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@statewalker/webrun-streams": "^0.5.0"
|
|
42
|
+
},
|
|
40
43
|
"devDependencies": {
|
|
41
44
|
"@biomejs/biome": "^2.5.15",
|
|
42
45
|
"@types/node": "^26.6.4",
|
|
@@ -45,9 +48,9 @@
|
|
|
45
48
|
"rolldown": "^1.2.12",
|
|
46
49
|
"typescript": "^7.0.2",
|
|
47
50
|
"vitest": "^5.0.5",
|
|
48
|
-
"@statewalker/webrun-msgpack": "^0.
|
|
49
|
-
"@statewalker/webrun-
|
|
50
|
-
"@statewalker/webrun-
|
|
51
|
+
"@statewalker/webrun-msgpack": "^0.12.0",
|
|
52
|
+
"@statewalker/webrun-rpc": "^0.13.0",
|
|
53
|
+
"@statewalker/webrun-streams-conformance": "^0.6.0"
|
|
51
54
|
},
|
|
52
55
|
"sideEffects": false,
|
|
53
56
|
"publishConfig": {
|
|
@@ -57,6 +60,8 @@
|
|
|
57
60
|
"scripts": {
|
|
58
61
|
"build": "rimraf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",
|
|
59
62
|
"test": "vitest run",
|
|
63
|
+
"typecheck": "tsc --noEmit",
|
|
64
|
+
"typecheck:tests": "tsc -p tsconfig.tests.json",
|
|
60
65
|
"lint": "biome check src tests"
|
|
61
66
|
}
|
|
62
67
|
}
|
package/src/byte-channel.ts
CHANGED
|
@@ -11,103 +11,242 @@ import { makeByteQueue, toBytes } from "./byte-queue.js";
|
|
|
11
11
|
import type { ByteChannel, RoomLike } from "./types.js";
|
|
12
12
|
import { ROOM_EVENT } from "./types.js";
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* `whenDrained` resolves once the bytes sent and not yet written out are at
|
|
16
|
+
* most this: the transport can take more. The same mark the ws, peerjs,
|
|
17
|
+
* livekit and webrtc adapters use.
|
|
18
|
+
*/
|
|
19
|
+
export const DRAIN_LOW_WATER = 256 * 1024;
|
|
20
|
+
|
|
14
21
|
/**
|
|
15
22
|
* Wrap an established `RTCDataChannel` as a {@link ByteChannel}. Outbound bytes
|
|
16
|
-
* go through `channel.send`; inbound `message` events feed `recv`.
|
|
23
|
+
* go through `channel.send`; inbound `message` events feed `recv`. A message
|
|
24
|
+
* that is not bytes, or a `send` that fails (a closed channel, Chrome's full
|
|
25
|
+
* send queue), ends the channel: the stream above it lost a message.
|
|
26
|
+
* `bufferedAmount` is the data channel's; `whenDrained` waits for its
|
|
27
|
+
* `bufferedamountlow`.
|
|
17
28
|
*/
|
|
18
29
|
export function byteChannelFromDataChannel(channel: RTCDataChannel): ByteChannel {
|
|
19
30
|
const queue = makeByteQueue();
|
|
20
31
|
let closedResolve!: () => void;
|
|
32
|
+
let ended = false;
|
|
21
33
|
const closed = new Promise<void>((r) => {
|
|
22
34
|
closedResolve = r;
|
|
23
35
|
});
|
|
36
|
+
const drainWaiters = new Set<() => void>();
|
|
24
37
|
|
|
25
|
-
const onMessage = (ev: MessageEvent): void =>
|
|
26
|
-
|
|
38
|
+
const onMessage = (ev: MessageEvent): void => {
|
|
39
|
+
if (ended) return;
|
|
40
|
+
let bytes: Uint8Array;
|
|
41
|
+
try {
|
|
42
|
+
bytes = toBytes(ev.data);
|
|
43
|
+
} catch {
|
|
44
|
+
close();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
queue.push(bytes);
|
|
48
|
+
};
|
|
49
|
+
const onDrained = (): void => {
|
|
50
|
+
for (const w of [...drainWaiters]) w();
|
|
51
|
+
drainWaiters.clear();
|
|
52
|
+
};
|
|
53
|
+
const end = (): void => {
|
|
54
|
+
if (ended) return;
|
|
55
|
+
ended = true;
|
|
56
|
+
channel.removeEventListener("message", onMessage as EventListener);
|
|
57
|
+
channel.removeEventListener("close", end);
|
|
58
|
+
channel.removeEventListener("bufferedamountlow", onDrained);
|
|
27
59
|
queue.done();
|
|
28
60
|
closedResolve();
|
|
61
|
+
onDrained();
|
|
62
|
+
};
|
|
63
|
+
const close = (): void => {
|
|
64
|
+
end();
|
|
65
|
+
try {
|
|
66
|
+
channel.close();
|
|
67
|
+
} catch {
|
|
68
|
+
/* ignore */
|
|
69
|
+
}
|
|
29
70
|
};
|
|
30
71
|
|
|
31
72
|
channel.binaryType = "arraybuffer";
|
|
73
|
+
channel.bufferedAmountLowThreshold = DRAIN_LOW_WATER;
|
|
32
74
|
channel.addEventListener("message", onMessage as EventListener);
|
|
33
|
-
channel.addEventListener("close",
|
|
75
|
+
channel.addEventListener("close", end);
|
|
76
|
+
channel.addEventListener("bufferedamountlow", onDrained);
|
|
34
77
|
|
|
35
78
|
return {
|
|
36
79
|
send(bytes) {
|
|
80
|
+
if (ended) return;
|
|
37
81
|
try {
|
|
38
82
|
// Cast around the DOM lib's `ArrayBufferView<ArrayBuffer>` overload:
|
|
39
83
|
// a plain `Uint8Array` is `ArrayBufferLike`-backed at the type level.
|
|
40
84
|
channel.send(bytes as unknown as ArrayBufferView<ArrayBuffer>);
|
|
41
85
|
} catch {
|
|
42
|
-
|
|
86
|
+
close();
|
|
43
87
|
}
|
|
44
88
|
},
|
|
45
89
|
recv: queue.recv,
|
|
46
90
|
closed,
|
|
47
|
-
close
|
|
48
|
-
|
|
49
|
-
channel.
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
queue.done();
|
|
56
|
-
closedResolve();
|
|
91
|
+
close,
|
|
92
|
+
get bufferedAmount() {
|
|
93
|
+
return channel.bufferedAmount ?? 0;
|
|
94
|
+
},
|
|
95
|
+
whenDrained() {
|
|
96
|
+
if (ended || (channel.bufferedAmount ?? 0) <= DRAIN_LOW_WATER) return Promise.resolve();
|
|
97
|
+
return new Promise<void>((resolve) => drainWaiters.add(resolve));
|
|
57
98
|
},
|
|
58
99
|
};
|
|
59
100
|
}
|
|
60
101
|
|
|
102
|
+
/**
|
|
103
|
+
* The topic a {@link byteChannelFromRoom} channel's packets carry, the same
|
|
104
|
+
* default as `webrun-streams-livekit`'s `messageTargetOverLiveKit`; packets on
|
|
105
|
+
* other topics are someone else's. The goodbye goes on this topic with
|
|
106
|
+
* `/close` appended, as there.
|
|
107
|
+
*/
|
|
108
|
+
export const DEFAULT_ROOM_TOPIC = "webrun/port-stack";
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The largest packet a {@link byteChannelFromRoom} channel publishes, as in
|
|
112
|
+
* `webrun-streams-livekit`: livekit-client (2.x) refuses a larger one.
|
|
113
|
+
*/
|
|
114
|
+
export const DEFAULT_ROOM_MAX_FRAME_BYTES = 64_000;
|
|
115
|
+
|
|
116
|
+
/** Options for {@link byteChannelFromRoom}. */
|
|
117
|
+
export interface ByteChannelFromRoomOptions {
|
|
118
|
+
/**
|
|
119
|
+
* The data topic, default {@link DEFAULT_ROOM_TOPIC}; the goodbye uses it
|
|
120
|
+
* with `/close` appended. Both ends must agree. Use another to run two
|
|
121
|
+
* channels to the same participant.
|
|
122
|
+
*/
|
|
123
|
+
topic?: string;
|
|
124
|
+
/** The largest packet sent; past it `send` ends the channel and throws `RangeError`. Default {@link DEFAULT_ROOM_MAX_FRAME_BYTES}. */
|
|
125
|
+
maxFrameBytes?: number;
|
|
126
|
+
}
|
|
127
|
+
|
|
61
128
|
/**
|
|
62
129
|
* Build a {@link ByteChannel} to a single room participant over a LiveKit-style
|
|
63
|
-
* `Room`. Outbound bytes are published to `peerId
|
|
64
|
-
* events from `peerId`
|
|
65
|
-
*
|
|
130
|
+
* `Room`. Outbound bytes are published reliably to `peerId` on the channel's
|
|
131
|
+
* topic; inbound `dataReceived` events from `peerId` on that topic feed
|
|
132
|
+
* `recv`. The packets and the goodbye follow `webrun-streams-livekit`'s
|
|
133
|
+
* conventions, so the port stack over this channel talks to one over
|
|
134
|
+
* `messageTargetOverLiveKit` with the same topic.
|
|
135
|
+
*
|
|
136
|
+
* The channel ends when the room disconnects, the participant leaves, the
|
|
137
|
+
* peer's goodbye arrives, a reliable publish fails, or a `send` exceeds
|
|
138
|
+
* `maxFrameBytes`. When it ends on this side, a goodbye on the close topic
|
|
139
|
+
* ends the peer's channel too: the room stays connected, so nothing else would.
|
|
140
|
+
* `bufferedAmount` counts bytes whose publish has not settled.
|
|
66
141
|
*/
|
|
67
|
-
export function byteChannelFromRoom(
|
|
142
|
+
export function byteChannelFromRoom(
|
|
143
|
+
room: RoomLike,
|
|
144
|
+
peerId: string,
|
|
145
|
+
options: ByteChannelFromRoomOptions = {},
|
|
146
|
+
): ByteChannel {
|
|
147
|
+
const topic = options.topic ?? DEFAULT_ROOM_TOPIC;
|
|
148
|
+
const closeTopic = `${topic}/close`;
|
|
149
|
+
const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_ROOM_MAX_FRAME_BYTES;
|
|
68
150
|
const queue = makeByteQueue();
|
|
69
151
|
let closedResolve!: () => void;
|
|
70
152
|
const closed = new Promise<void>((r) => {
|
|
71
153
|
closedResolve = r;
|
|
72
154
|
});
|
|
73
155
|
let ended = false;
|
|
156
|
+
let inFlight = 0;
|
|
157
|
+
const drainWaiters = new Set<() => void>();
|
|
158
|
+
const wakeDrainWaiters = (): void => {
|
|
159
|
+
if (inFlight > DRAIN_LOW_WATER && !ended) return;
|
|
160
|
+
for (const w of [...drainWaiters]) w();
|
|
161
|
+
drainWaiters.clear();
|
|
162
|
+
};
|
|
74
163
|
|
|
75
164
|
const onData = (...args: unknown[]): void => {
|
|
76
|
-
const payload = args[
|
|
77
|
-
|
|
165
|
+
const [payload, participant, , packetTopic] = args as [
|
|
166
|
+
unknown,
|
|
167
|
+
{ identity?: string } | undefined,
|
|
168
|
+
unknown,
|
|
169
|
+
string | undefined,
|
|
170
|
+
];
|
|
78
171
|
// A packet with no participant is the server's, not the peer's.
|
|
79
|
-
if (participant?.identity !== peerId) return;
|
|
80
|
-
if (
|
|
172
|
+
if (ended || participant?.identity !== peerId) return;
|
|
173
|
+
if (packetTopic === closeTopic) {
|
|
174
|
+
end(false);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (packetTopic !== topic || payload == null) return;
|
|
178
|
+
let bytes: Uint8Array;
|
|
179
|
+
try {
|
|
180
|
+
bytes = toBytes(payload);
|
|
181
|
+
} catch {
|
|
182
|
+
end(true);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
queue.push(bytes);
|
|
81
186
|
};
|
|
82
187
|
const onParticipantDisconnected = (...args: unknown[]): void => {
|
|
83
|
-
if ((args[0] as { identity?: string } | undefined)?.identity === peerId) end();
|
|
188
|
+
if ((args[0] as { identity?: string } | undefined)?.identity === peerId) end(false);
|
|
84
189
|
};
|
|
85
|
-
|
|
86
|
-
//
|
|
87
|
-
|
|
190
|
+
const onDisconnected = (): void => end(false);
|
|
191
|
+
// The channel ends with the room, with the peer, or with the peer's
|
|
192
|
+
// goodbye: otherwise nothing above it would ever learn the other end is gone.
|
|
193
|
+
/** `tellPeer`: it ended on this side, and the room is still there to say so. */
|
|
194
|
+
const end = (tellPeer: boolean): void => {
|
|
88
195
|
if (ended) return;
|
|
89
196
|
ended = true;
|
|
90
197
|
room.off(ROOM_EVENT.dataReceived, onData);
|
|
91
198
|
room.off(ROOM_EVENT.participantDisconnected, onParticipantDisconnected);
|
|
92
|
-
room.off(ROOM_EVENT.disconnected,
|
|
199
|
+
room.off(ROOM_EVENT.disconnected, onDisconnected);
|
|
93
200
|
queue.done();
|
|
94
201
|
closedResolve();
|
|
202
|
+
wakeDrainWaiters();
|
|
203
|
+
if (tellPeer) {
|
|
204
|
+
room.localParticipant
|
|
205
|
+
.publishData(new Uint8Array(0), {
|
|
206
|
+
reliable: true,
|
|
207
|
+
destinationIdentities: [peerId],
|
|
208
|
+
topic: closeTopic,
|
|
209
|
+
})
|
|
210
|
+
.catch(() => undefined);
|
|
211
|
+
}
|
|
95
212
|
};
|
|
96
213
|
|
|
97
214
|
room.on(ROOM_EVENT.dataReceived, onData);
|
|
98
215
|
room.on(ROOM_EVENT.participantDisconnected, onParticipantDisconnected);
|
|
99
|
-
room.on(ROOM_EVENT.disconnected,
|
|
216
|
+
room.on(ROOM_EVENT.disconnected, onDisconnected);
|
|
100
217
|
|
|
101
218
|
return {
|
|
102
219
|
send(bytes) {
|
|
103
220
|
if (ended) return;
|
|
104
|
-
|
|
105
|
-
|
|
221
|
+
if (bytes.byteLength > maxFrameBytes) {
|
|
222
|
+
end(true);
|
|
223
|
+
throw new RangeError(
|
|
224
|
+
`webrun-streams-signaling: a ${bytes.byteLength}-byte packet exceeds maxFrameBytes (${maxFrameBytes})`,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
const size = bytes.byteLength;
|
|
228
|
+
inFlight += size;
|
|
229
|
+
room.localParticipant
|
|
230
|
+
.publishData(bytes, { reliable: true, destinationIdentities: [peerId], topic })
|
|
106
231
|
// A reliable publish that fails lost a message: the stream above is broken.
|
|
107
|
-
.
|
|
232
|
+
.then(
|
|
233
|
+
() => undefined,
|
|
234
|
+
() => end(true),
|
|
235
|
+
)
|
|
236
|
+
.finally(() => {
|
|
237
|
+
inFlight -= size;
|
|
238
|
+
wakeDrainWaiters();
|
|
239
|
+
});
|
|
108
240
|
},
|
|
109
241
|
recv: queue.recv,
|
|
110
242
|
closed,
|
|
111
|
-
close: end,
|
|
243
|
+
close: () => end(true),
|
|
244
|
+
get bufferedAmount() {
|
|
245
|
+
return inFlight;
|
|
246
|
+
},
|
|
247
|
+
whenDrained() {
|
|
248
|
+
if (ended || inFlight <= DRAIN_LOW_WATER) return Promise.resolve();
|
|
249
|
+
return new Promise<void>((resolve) => drainWaiters.add(resolve));
|
|
250
|
+
},
|
|
112
251
|
};
|
|
113
252
|
}
|
package/src/index.ts
CHANGED
|
@@ -14,7 +14,14 @@
|
|
|
14
14
|
* @packageDocumentation
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
export {
|
|
17
|
+
export {
|
|
18
|
+
type ByteChannelFromRoomOptions,
|
|
19
|
+
byteChannelFromDataChannel,
|
|
20
|
+
byteChannelFromRoom,
|
|
21
|
+
DEFAULT_ROOM_MAX_FRAME_BYTES,
|
|
22
|
+
DEFAULT_ROOM_TOPIC,
|
|
23
|
+
DRAIN_LOW_WATER,
|
|
24
|
+
} from "./byte-channel.js";
|
|
18
25
|
export * from "./message-target.js";
|
|
19
26
|
export { PeerConnection } from "./peer-connection.js";
|
|
20
27
|
export { PeerManager, type PeerManagerOptions } from "./peer-manager.js";
|
package/src/message-target.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type MessagePipe,
|
|
3
|
+
type MessagePipeTarget,
|
|
4
|
+
newMessagePipe,
|
|
5
|
+
} from "@statewalker/webrun-streams";
|
|
1
6
|
import type { ByteChannel } from "./types.js";
|
|
2
7
|
|
|
3
|
-
type Listener = (event: MessageEvent) => void | Promise<void>;
|
|
4
|
-
|
|
5
8
|
/**
|
|
6
9
|
* The payload ceiling for a channel over an `RTCDataChannel` (`PeerManager`,
|
|
7
10
|
* `QrSignaling`, `PeerConnection`): 16 KiB, the message size every browser
|
|
@@ -13,22 +16,23 @@ type Listener = (event: MessageEvent) => void | Promise<void>;
|
|
|
13
16
|
export const DEFAULT_MAX_MESSAGE_SIZE = 16 * 1024 - 256;
|
|
14
17
|
|
|
15
18
|
/** What `messageTargetOverByteChannel` gives: a pipe of bytes, its life, and its payload ceiling. */
|
|
16
|
-
export interface ByteChannelMessageTarget {
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
close(): Promise<void>;
|
|
25
|
-
};
|
|
19
|
+
export interface ByteChannelMessageTarget extends MessagePipe {
|
|
20
|
+
/**
|
|
21
|
+
* A `MessageTarget` (as `@statewalker/webrun-rpc` defines it) of bytes, one
|
|
22
|
+
* channel message each. `bufferedAmount` is the channel's (0 where it cannot
|
|
23
|
+
* tell); `whenDrained` is the channel's, or resolves at once over a channel
|
|
24
|
+
* without one.
|
|
25
|
+
*/
|
|
26
|
+
target: MessagePipeTarget;
|
|
26
27
|
/** Aborts when the channel closes. Pass it as `overPipe`'s `signal`. */
|
|
27
28
|
signal: AbortSignal;
|
|
28
29
|
/** Pass as `overPipe`'s `maxMessageSize`. */
|
|
29
30
|
maxMessageSize: number;
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
/** How long a closed channel's `recv` may take to hand over what it still holds before the pipe ends. */
|
|
34
|
+
const CLOSE_DRAIN_MS = 50;
|
|
35
|
+
|
|
32
36
|
/**
|
|
33
37
|
* A `ByteChannel` this package hands back (`PeerManager`, `QrSignaling`,
|
|
34
38
|
* `RoomManager`) as a pipe for `webrun-rpc`'s port stack:
|
|
@@ -47,66 +51,57 @@ export interface ByteChannelMessageTarget {
|
|
|
47
51
|
*/
|
|
48
52
|
export function messageTargetOverByteChannel(
|
|
49
53
|
channel: ByteChannel,
|
|
50
|
-
options: { maxMessageSize?: number } = {},
|
|
54
|
+
options: { maxMessageSize?: number; maxFrameBytes?: number } = {},
|
|
51
55
|
): ByteChannelMessageTarget {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const event = new MessageEvent("message", { data: bytes.slice() });
|
|
65
|
-
for (const listener of [...listeners]) {
|
|
66
|
-
try {
|
|
67
|
-
Promise.resolve(listener(event)).catch(() => undefined);
|
|
68
|
-
} catch {}
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
end(new Error("webrun-streams-signaling: the channel closed"));
|
|
72
|
-
})().catch((err: unknown) =>
|
|
73
|
-
end(err instanceof Error ? err : new Error(String(err), { cause: err })),
|
|
74
|
-
);
|
|
75
|
-
return {
|
|
76
|
-
signal: life.signal,
|
|
77
|
-
maxMessageSize: options.maxMessageSize ?? DEFAULT_MAX_MESSAGE_SIZE,
|
|
78
|
-
target: {
|
|
79
|
-
addEventListener: (_type, listener) => {
|
|
80
|
-
listeners.add(listener);
|
|
81
|
-
},
|
|
82
|
-
removeEventListener: (_type, listener) => {
|
|
83
|
-
listeners.delete(listener);
|
|
84
|
-
},
|
|
85
|
-
postMessage(message) {
|
|
86
|
-
const bytes =
|
|
87
|
-
message instanceof Uint8Array
|
|
88
|
-
? message
|
|
89
|
-
: message instanceof ArrayBuffer
|
|
90
|
-
? new Uint8Array(message)
|
|
91
|
-
: ArrayBuffer.isView(message)
|
|
92
|
-
? new Uint8Array(message.buffer, message.byteOffset, message.byteLength)
|
|
93
|
-
: undefined;
|
|
94
|
-
if (!bytes) {
|
|
95
|
-
throw new TypeError(
|
|
96
|
-
`webrun-streams-signaling: a byte pipe carries Uint8Array, ArrayBuffer or a view, got ${Object.prototype.toString.call(message)}`,
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
if (life.signal.aborted) return; // `signal` says so
|
|
100
|
-
channel.send(bytes.slice());
|
|
101
|
-
},
|
|
102
|
-
async close() {
|
|
103
|
-
listeners.clear();
|
|
104
|
-
closedHere = true;
|
|
105
|
-
end(new Error("webrun-streams-signaling: closed locally"));
|
|
56
|
+
const control = newMessagePipe(
|
|
57
|
+
{
|
|
58
|
+
send: (bytes) => channel.send(bytes),
|
|
59
|
+
bufferedAmount: () => channel.bufferedAmount ?? 0,
|
|
60
|
+
...(channel.whenDrained
|
|
61
|
+
? {
|
|
62
|
+
isDrained: () => false,
|
|
63
|
+
whenDrained: () => channel.whenDrained?.() ?? Promise.resolve(),
|
|
64
|
+
}
|
|
65
|
+
: { isDrained: () => true }),
|
|
66
|
+
close: (local) => {
|
|
67
|
+
if (!local) return;
|
|
106
68
|
try {
|
|
107
69
|
channel.close();
|
|
108
70
|
} catch {}
|
|
109
71
|
},
|
|
110
72
|
},
|
|
111
|
-
|
|
73
|
+
{
|
|
74
|
+
name: "webrun-streams-signaling",
|
|
75
|
+
maxMessageSize: options.maxMessageSize ?? DEFAULT_MAX_MESSAGE_SIZE,
|
|
76
|
+
maxFrameBytes: options.maxFrameBytes,
|
|
77
|
+
// The channel may queue what is sent, and reuse what it hands out.
|
|
78
|
+
copyOnSend: true,
|
|
79
|
+
copyOnDeliver: true,
|
|
80
|
+
},
|
|
81
|
+
);
|
|
82
|
+
const closedMessage = "webrun-streams-signaling: the channel closed";
|
|
83
|
+
const reading = (async () => {
|
|
84
|
+
for await (const bytes of channel.recv) {
|
|
85
|
+
// The channel closing ends `recv` after what it already holds; only a
|
|
86
|
+
// close on this side stops delivery at once.
|
|
87
|
+
if (control.ended) break;
|
|
88
|
+
control.deliver(bytes);
|
|
89
|
+
}
|
|
90
|
+
})();
|
|
91
|
+
reading.then(
|
|
92
|
+
() => control.end(new Error(closedMessage)),
|
|
93
|
+
// A `recv` that fails leaves the channel open: end as local, which closes it.
|
|
94
|
+
(err: unknown) =>
|
|
95
|
+
control.end(err instanceof Error ? err : new Error(String(err), { cause: err }), true),
|
|
96
|
+
);
|
|
97
|
+
// What `recv` still holds when the channel closes is delivered first; a
|
|
98
|
+
// channel whose `recv` never ends still ends the pipe, shortly after.
|
|
99
|
+
void channel.closed.then(() => {
|
|
100
|
+
if (control.ended) return;
|
|
101
|
+
const timer = setTimeout(() => control.end(new Error(closedMessage)), CLOSE_DRAIN_MS) as {
|
|
102
|
+
unref?: () => void;
|
|
103
|
+
};
|
|
104
|
+
timer.unref?.();
|
|
105
|
+
});
|
|
106
|
+
return control.pipe as ByteChannelMessageTarget;
|
|
112
107
|
}
|
package/src/peer-connection.ts
CHANGED
|
@@ -68,6 +68,11 @@ export class PeerConnection {
|
|
|
68
68
|
return this.role;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/** Whether the remote description (the peer's offer or answer) has been applied. */
|
|
72
|
+
hasRemoteDescription(): boolean {
|
|
73
|
+
return this.remoteDescriptionSet;
|
|
74
|
+
}
|
|
75
|
+
|
|
71
76
|
getDataChannel(): RTCDataChannel | null {
|
|
72
77
|
return this.dataChannel;
|
|
73
78
|
}
|
|
@@ -318,6 +323,7 @@ export class PeerConnection {
|
|
|
318
323
|
const cleanup = () => {
|
|
319
324
|
this.off("open", onOpen);
|
|
320
325
|
this.off("error", onError);
|
|
326
|
+
this.off("stateChange", onState);
|
|
321
327
|
clearTimeout(timer);
|
|
322
328
|
};
|
|
323
329
|
const onOpen = () => {
|
|
@@ -330,8 +336,15 @@ export class PeerConnection {
|
|
|
330
336
|
cleanup();
|
|
331
337
|
reject(error);
|
|
332
338
|
};
|
|
339
|
+
// Closed before the channel opened: it never will.
|
|
340
|
+
const onState = (state: ConnectionState) => {
|
|
341
|
+
if (state !== "closed") return;
|
|
342
|
+
cleanup();
|
|
343
|
+
reject(new Error("Connection closed before the data channel opened"));
|
|
344
|
+
};
|
|
333
345
|
this.on("open", onOpen);
|
|
334
346
|
this.on("error", onError);
|
|
347
|
+
this.on("stateChange", onState);
|
|
335
348
|
const timer = setTimeout(() => {
|
|
336
349
|
cleanup();
|
|
337
350
|
reject(new Error(`Connection timeout after ${timeout}ms`));
|