@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.
@@ -17,7 +17,16 @@ import type {
17
17
  WebRtcConnectionOptions,
18
18
  } from "./types.js";
19
19
 
20
- export type PeerManagerOptions = WebRtcConnectionOptions;
20
+ export type PeerManagerOptions = WebRtcConnectionOptions & {
21
+ /**
22
+ * Called when a connection fails with no caller to tell: a signal it
23
+ * rejects (an offer during glare, malformed SDP or candidates), or an
24
+ * inbound connection whose channel never opens. The connection has already
25
+ * been closed and forgotten, so the peer can dial again. Errors are dropped
26
+ * when unset. A failed `connect()` rejects instead.
27
+ */
28
+ onError?: (error: Error, peerId: string) => void;
29
+ };
21
30
 
22
31
  export class PeerManager {
23
32
  private readonly signaling: SignalingTransport;
@@ -34,10 +43,19 @@ export class PeerManager {
34
43
 
35
44
  /** Dial `peerId` and resolve with the established channel. */
36
45
  async connect(peerId: string): Promise<ByteChannel> {
46
+ // Dialing again replaces whatever connection to this peer there was.
47
+ const previous = this.connections.get(peerId);
48
+ if (previous) this.forget(peerId, previous);
37
49
  const pc = this.makeConnection(peerId, "initiator");
38
50
  const channel = pc.open();
39
- await pc.connect();
40
- return channel;
51
+ try {
52
+ await pc.connect();
53
+ return await channel;
54
+ } catch (err) {
55
+ channel.catch(() => undefined);
56
+ this.forget(peerId, pc);
57
+ throw err;
58
+ }
41
59
  }
42
60
 
43
61
  /** Register a handler for inbound connections. Returns an unsubscribe fn. */
@@ -49,30 +67,66 @@ export class PeerManager {
49
67
  /** Tear down all connections and stop listening for signaling. */
50
68
  close(): void {
51
69
  this.unsubscribe();
52
- for (const pc of this.connections.values()) pc.close();
70
+ const all = [...this.connections.values()];
53
71
  this.connections.clear();
72
+ for (const pc of all) pc.close();
54
73
  this.connectionHandlers.clear();
55
74
  }
56
75
 
57
76
  private makeConnection(peerId: string, role: "initiator" | "responder"): PeerConnection {
58
77
  const pc = new PeerConnection(role, this.options);
59
78
  pc.on("signal", (msg) => this.signaling.send(peerId, msg));
60
- pc.on("close", () => this.connections.delete(peerId));
79
+ pc.on("close", () => this.forget(peerId, pc));
80
+ // A failed connection never recovers: forget it so the peer's next offer
81
+ // starts a new one instead of reaching this one.
82
+ pc.on("stateChange", (state) => {
83
+ if (state === "failed" || state === "closed") this.forget(peerId, pc);
84
+ });
61
85
  this.connections.set(peerId, pc);
62
86
  return pc;
63
87
  }
64
88
 
89
+ /** Close `pc` and drop it, unless a newer connection to `peerId` replaced it. */
90
+ private forget(peerId: string, pc: PeerConnection): void {
91
+ if (this.connections.get(peerId) !== pc) return;
92
+ this.connections.delete(peerId);
93
+ pc.close();
94
+ }
95
+
96
+ private fail(peerId: string, pc: PeerConnection, err: unknown): void {
97
+ const live = this.connections.get(peerId) === pc;
98
+ this.forget(peerId, pc);
99
+ if (!live) return; // closed on purpose meanwhile
100
+ const error = err instanceof Error ? err : new Error(String(err), { cause: err });
101
+ try {
102
+ this.options.onError?.(error, peerId);
103
+ } catch {}
104
+ }
105
+
65
106
  private onSignal(from: string, msg: SignalingMessage): void {
66
107
  let pc = this.connections.get(from);
108
+ // A connection makes one offer, so a new offer from a peer we answered
109
+ // before, or whose answer we already applied, means it started over: the
110
+ // old connection is stale. (An offer to an initiator still waiting for
111
+ // its answer is glare: handleSignal rejects it below.)
112
+ if (pc && msg.type === "offer" && (pc.getRole() === "responder" || pc.hasRemoteDescription())) {
113
+ this.forget(from, pc);
114
+ pc = undefined;
115
+ }
67
116
  if (!pc) {
68
117
  // Only an inbound offer starts a new responder connection; stray
69
118
  // candidates/answers for an unknown peer are ignored.
70
119
  if (msg.type !== "offer") return;
71
- pc = this.makeConnection(from, "responder");
72
- void pc.open().then((channel) => {
73
- for (const handler of this.connectionHandlers) handler(from, channel);
74
- });
120
+ const responder = this.makeConnection(from, "responder");
121
+ pc = responder;
122
+ responder.open().then(
123
+ (channel) => {
124
+ for (const handler of this.connectionHandlers) handler(from, channel);
125
+ },
126
+ (err: unknown) => this.fail(from, responder, err),
127
+ );
75
128
  }
76
- void pc.handleSignal(msg);
129
+ const target = pc;
130
+ target.handleSignal(msg).catch((err: unknown) => this.fail(from, target, err));
77
131
  }
78
132
  }
@@ -67,15 +67,49 @@ function expandSdp(compressed: string): string {
67
67
  return `${lines.join("\r\n")}\r\n`;
68
68
  }
69
69
 
70
- /** Compress an ICE candidate to its essential parts. */
70
+ /**
71
+ * Candidate attributes after `typ` that a connection needs: the related
72
+ * address of a srflx/relay candidate and the TCP type of a TCP one. Others
73
+ * (`generation`, `ufrag`, `network-id`, ...) are dropped to keep the QR small.
74
+ */
75
+ const KEPT_CANDIDATE_ATTRIBUTES = new Set(["raddr", "rport", "tcptype"]);
76
+
77
+ /** An `sdpMLineIndex` as it travels: empty for null. */
78
+ function indexToString(index: number | null): string {
79
+ return index == null ? "" : String(index);
80
+ }
81
+
82
+ function indexFromString(text: string | undefined): number | null {
83
+ if (!text) return null;
84
+ const index = Number.parseInt(text, 10);
85
+ return Number.isNaN(index) ? null : index;
86
+ }
87
+
88
+ /**
89
+ * Compress an ICE candidate to its essential parts. A candidate that carries
90
+ * attributes a connection needs (see {@link KEPT_CANDIDATE_ATTRIBUTES}) goes
91
+ * in the raw (`R:`) form, with only those attributes kept.
92
+ */
71
93
  function compressCandidate(candidate: IceCandidate): string {
72
94
  const { candidate: c, sdpMid, sdpMLineIndex } = candidate;
73
- const match = c.match(/candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)/);
95
+ const index = indexToString(sdpMLineIndex);
96
+ const match = c.match(
97
+ /candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)(.*)$/,
98
+ );
74
99
  if (!match) {
75
- return `R:${sdpMid ?? ""}:${sdpMLineIndex ?? 0}:${c}`;
100
+ return `R:${sdpMid ?? ""}:${index}:${c}`;
76
101
  }
77
- const [, foundation, component, protocol, priority, ip, port, type] = match;
78
- return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${sdpMLineIndex ?? 0}`;
102
+ const [base, foundation, component, protocol, priority, ip, port, type, rest] = match;
103
+ const words = rest.trim().split(/\s+/).filter(Boolean);
104
+ const kept: string[] = [];
105
+ for (let i = 0; i + 1 < words.length; i += 2) {
106
+ if (KEPT_CANDIDATE_ATTRIBUTES.has(words[i])) kept.push(words[i], words[i + 1]);
107
+ }
108
+ if (kept.length) {
109
+ const head = base.slice(0, base.length - rest.length);
110
+ return `R:${sdpMid ?? ""}:${index}:${head} ${kept.join(" ")}`;
111
+ }
112
+ return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${index}`;
79
113
  }
80
114
 
81
115
  /** Expand a compressed ICE candidate. */
@@ -85,7 +119,7 @@ function expandCandidate(compressed: string): IceCandidate {
85
119
  return {
86
120
  candidate: rest.join(":"),
87
121
  sdpMid: sdpMid || null,
88
- sdpMLineIndex: Number.parseInt(sdpMLineIndexStr, 10) || null,
122
+ sdpMLineIndex: indexFromString(sdpMLineIndexStr),
89
123
  };
90
124
  }
91
125
  const parts = compressed.split("|");
@@ -98,7 +132,7 @@ function expandCandidate(compressed: string): IceCandidate {
98
132
  return {
99
133
  candidate,
100
134
  sdpMid: sdpMid || null,
101
- sdpMLineIndex: sdpMLineIndexStr ? Number.parseInt(sdpMLineIndexStr, 10) : null,
135
+ sdpMLineIndex: indexFromString(sdpMLineIndexStr),
102
136
  };
103
137
  }
104
138
 
@@ -181,7 +215,6 @@ export class QrSignaling {
181
215
  /** Create an offer QR; `accept(answerQr)` finishes the handshake. */
182
216
  async offer(): Promise<{ qr: string; accept(answerQr: string): Promise<ByteChannel> }> {
183
217
  const pc = new PeerConnection("initiator", this.connection);
184
- const channel = pc.open();
185
218
  await pc.connect();
186
219
  await pc.waitForIceGathering();
187
220
 
@@ -194,10 +227,19 @@ export class QrSignaling {
194
227
  return {
195
228
  qr,
196
229
  accept: async (answerQr: string): Promise<ByteChannel> => {
197
- const parsed = parseCompressedSignal(decodeSignal(answerQr));
198
- await pc.handleSignal({ type: "answer", sdp: parsed.description.sdp });
199
- for (const candidate of parsed.candidates) {
200
- await pc.handleSignal({ type: "candidate", candidate });
230
+ // The connection timeout starts here, not at offer time: the QR
231
+ // exchange between the two takes as long as the people take.
232
+ const channel = pc.open();
233
+ try {
234
+ const parsed = parseCompressedSignal(decodeSignal(answerQr));
235
+ await pc.handleSignal({ type: "answer", sdp: parsed.description.sdp });
236
+ for (const candidate of parsed.candidates) {
237
+ await pc.handleSignal({ type: "candidate", candidate });
238
+ }
239
+ } catch (err) {
240
+ channel.catch(() => undefined);
241
+ pc.close();
242
+ throw err;
201
243
  }
202
244
  return channel;
203
245
  },
@@ -11,7 +11,7 @@
11
11
  * `() => new Room()`), so this module never hard-imports it.
12
12
  */
13
13
 
14
- import { byteChannelFromRoom } from "./byte-channel.js";
14
+ import { type ByteChannelFromRoomOptions, byteChannelFromRoom } from "./byte-channel.js";
15
15
  import type { ByteChannel, RoomLike, RoomManagerOptions, RoomParticipantLike } from "./types.js";
16
16
  import { ROOM_EVENT } from "./types.js";
17
17
 
@@ -94,10 +94,10 @@ export class RoomManager {
94
94
  };
95
95
  }
96
96
 
97
- /** Open a {@link ByteChannel} to a specific participant. */
98
- async channelTo(peerId: string): Promise<ByteChannel> {
97
+ /** Open a {@link ByteChannel} to a specific participant (see {@link byteChannelFromRoom}). */
98
+ async channelTo(peerId: string, options?: ByteChannelFromRoomOptions): Promise<ByteChannel> {
99
99
  if (!this.room) throw new Error("channelTo() before join()");
100
- return byteChannelFromRoom(this.room, peerId);
100
+ return byteChannelFromRoom(this.room, peerId, options);
101
101
  }
102
102
 
103
103
  /** Leave the room: unsubscribe and disconnect. */
package/src/types.ts CHANGED
@@ -19,6 +19,13 @@ export type ByteChannel = {
19
19
  recv: AsyncIterable<Uint8Array>;
20
20
  closed: Promise<void>;
21
21
  close(): void;
22
+ /** Bytes sent and not yet written out, where the transport can tell. */
23
+ readonly bufferedAmount?: number;
24
+ /**
25
+ * Resolves once the transport can take more (`bufferedAmount` at most a
26
+ * low-water mark) or the channel closed. Absent where it cannot tell.
27
+ */
28
+ whenDrained?(): Promise<void>;
22
29
  };
23
30
 
24
31
  /** WebRTC peer role in the connection. */
@@ -159,7 +166,7 @@ export interface RoomParticipantLike {
159
166
  export interface RoomLocalParticipantLike {
160
167
  publishData(
161
168
  data: Uint8Array,
162
- opts?: { reliable?: boolean; destinationIdentities?: string[] },
169
+ opts?: { reliable?: boolean; destinationIdentities?: string[]; topic?: string },
163
170
  ): Promise<void>;
164
171
  }
165
172