@minip2p/node 0.10.0 → 0.10.2

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/src/adapter.ts CHANGED
@@ -1,319 +1,29 @@
1
- /* oxlint-disable class-methods-use-this, func-style, max-classes-per-file, no-use-before-define -- The adapter keeps the contract-complete native endpoint, value conversion, and handle maps together at the binding boundary. */
1
+ /* oxlint-disable func-style, no-use-before-define -- Hoisted helpers keep the public entry points first. */
2
2
 
3
- import { Minip2pBase, StreamClosedError } from "@minip2p/core";
4
- import type {
5
- Bytes,
6
- IdentifyInfo,
7
- KnownPeerInfo,
8
- Minip2pConfig,
9
- Reachability,
10
- RelayReservationInfo,
11
- } from "@minip2p/core";
12
- import {
13
- ConnectionIdMap,
14
- EventDrain,
15
- NativeCloseLatch,
16
- P2pEvent_Tags,
17
- SettleHandles,
18
- eventStream,
19
- resolveEndpointConfig,
20
- typedFfiError,
21
- u64ToNumber,
22
- unfinishedPeers,
23
- } from "@minip2p/core/backend";
24
- import type {
25
- BackendClosed,
26
- BackendConnectionInfo,
27
- BackendConnectTarget,
28
- BackendOpenStream,
29
- Minip2pBackend,
30
- PathKind,
31
- P2pEvent,
32
- } from "@minip2p/core/backend";
3
+ import { Minip2pBase } from "@minip2p/core";
4
+ import type { Bytes, Minip2pConfig } from "@minip2p/core";
5
+ import { resolveEndpointConfig } from "@minip2p/core/backend";
6
+ import type { Minip2pBackend } from "@minip2p/core/backend";
7
+ import { SerdeBackend, typedNativeCall } from "@minip2p/core/serde-backend";
33
8
 
34
- import type {
35
- NativeEvent,
36
- NativeIdentifyInfo,
37
- NativeKnownPeerInfo,
38
- NativeRelayReservationInfo,
39
- } from "./native-shape.js";
40
9
  import { nativeBinding } from "./native.js";
41
- import type { NativeEndpoint } from "./native.js";
42
10
 
43
- /** Native drain batch size. */
44
- const DRAIN_LIMIT = 256;
45
-
46
- class NodeBackend implements Minip2pBackend {
47
- readonly #connectionIds = new ConnectionIdMap();
48
- readonly #endpoint: NativeEndpoint;
49
- readonly #streamIds = new StreamIdMap();
50
- /** Native stream identities while their events are in flight (ADR 0012). */
51
- readonly #settleHandles = new SettleHandles<[bigint, bigint]>();
52
- readonly #close = new NativeCloseLatch();
53
- #started = false;
54
-
55
- constructor(config: Minip2pConfig) {
56
- this.#endpoint = translateErrors(
57
- () =>
58
- new nativeBinding.NodeEndpoint(
59
- toUint8Array(config.secretKey),
60
- resolveEndpointConfig(config)
61
- )
62
- );
63
- }
64
-
65
- start(listener: (event: P2pEvent) => void): void {
66
- const events = new EventDrain(
67
- (limit) => this.#endpoint.drainEvents(limit),
68
- (event: NativeEvent) => {
69
- if (event.tag === P2pEvent_Tags.EndpointClosed) {
70
- events.stop();
71
- this.#close.settle({
72
- outcome: event.inner.outcome,
73
- unfinished: unfinishedPeers(event.inner.unfinished),
74
- });
75
- return;
76
- }
77
- // The SDK has stopped listening; only `EndpointClosed` matters now.
78
- if (this.#close.requested) {
79
- return;
80
- }
81
- const normalized = normalizeEvent(
82
- event,
83
- this.#connectionIds,
84
- this.#streamIds
85
- );
86
- const stream = eventStream(normalized);
87
- const native = nativeStreamOf(event);
88
- if (stream !== undefined && native !== undefined) {
89
- this.#settleHandles.hold(stream.connId, stream.streamId, native);
90
- }
91
- listener(normalized);
92
- },
93
- DRAIN_LIMIT,
94
- // One check-phase turn keeps native callbacks out of the caller's stack
95
- // without paying the timer granularity for every bounded batch.
96
- (task) => {
97
- setImmediate(task);
98
- }
99
- );
100
- translateErrors(() => {
101
- this.#endpoint.start(() => {
102
- events.ring();
103
- });
104
- });
105
- this.#started = true;
106
- }
107
-
108
- eventHandled(event: P2pEvent): void {
109
- releaseTerminalIds(event, this.#streamIds);
110
- const stream = eventStream(event);
111
- if (stream !== undefined) {
112
- this.#settleHandles.release(stream.connId, stream.streamId);
113
- }
114
- }
115
-
116
- close(timeoutMs: number): Promise<BackendClosed> {
117
- return this.#close.close(this.#started, () => {
118
- this.#endpoint.close(timeoutMs);
119
- });
120
- }
121
-
122
- peerId(): string {
123
- return this.#endpoint.peerId();
124
- }
125
-
126
- listenAddrs(): string[] {
127
- return this.#endpoint.listenAddrs();
128
- }
129
-
130
- isRunning(): boolean {
131
- return this.#endpoint.isRunning();
132
- }
133
-
134
- connectedPeers(): string[] {
135
- return translateErrors(() => this.#endpoint.connectedPeers());
136
- }
137
-
138
- isPeerReady(peerId: string): boolean {
139
- return translateErrors(() => this.#endpoint.isPeerReady(peerId));
140
- }
141
-
142
- peerInfo(peerId: string): IdentifyInfo | undefined {
143
- const info = translateErrors(() => this.#endpoint.peerInfo(peerId));
144
- return info === null ? undefined : identifyInfo(info);
145
- }
146
-
147
- knownPeers(): KnownPeerInfo[] {
148
- return translateErrors(() => this.#endpoint.knownPeers()).map(knownPeer);
149
- }
150
-
151
- discoveryNowMs(): number | undefined {
152
- const value = translateErrors(() => this.#endpoint.discoveryNowMs());
153
- return value === null ? undefined : u64ToNumber(value, "clock");
154
- }
155
-
156
- activeReservation(): RelayReservationInfo | undefined {
157
- const reservation = translateErrors(() =>
158
- this.#endpoint.activeReservation()
159
- );
160
- return reservation === null ? undefined : relayReservation(reservation);
161
- }
162
-
163
- path(peerId: string): PathKind | undefined {
164
- return translateErrors(() => this.#endpoint.path(peerId)) ?? undefined;
165
- }
166
-
167
- connectionInfo(peerId: string): BackendConnectionInfo | undefined {
168
- const info = translateErrors(() => this.#endpoint.connectionInfo(peerId));
169
- if (info === null) {
170
- return undefined;
171
- }
172
- const { connId, ...rest } = info;
173
- return {
174
- ...rest,
175
- connId: this.#connectionIds.toPublic(BigInt(connId)),
176
- };
177
- }
178
-
179
- circuitAddress(relayAddress: string, peerId: string): string {
180
- return circuitAddress(relayAddress, peerId);
181
- }
182
-
183
- reachability(): Reachability {
184
- return translateErrors(() => this.#endpoint.reachability());
185
- }
186
-
187
- setActive(active: boolean): void {
188
- this.#endpoint.setActive(active);
189
- }
190
-
191
- subscribe(topic: string): boolean {
192
- return translateErrors(() => this.#endpoint.subscribe(topic));
193
- }
194
-
195
- unsubscribe(topic: string): boolean {
196
- return translateErrors(() => this.#endpoint.unsubscribe(topic));
197
- }
198
-
199
- publish(topic: string, data: Uint8Array): void {
200
- translateErrors(() => {
201
- this.#endpoint.publish(topic, data);
202
- });
203
- }
204
-
205
- ping(peerId: string): void {
206
- translateErrors(() => {
207
- this.#endpoint.ping(peerId);
208
- });
209
- }
210
-
211
- addProtocol(protocolId: string): void {
212
- translateErrors(() => {
213
- this.#endpoint.addProtocol(protocolId);
214
- });
215
- }
216
-
217
- openStream(peerId: string, protocolId: string): BackendOpenStream {
218
- const stream = translateErrors(() =>
219
- this.#endpoint.openStream(peerId, protocolId)
220
- );
221
- const connId = this.#connectionIds.toPublic(BigInt(stream.connId));
222
- return {
223
- connId,
224
- streamId: this.#streamIds.toPublic(connId, BigInt(stream.streamId)),
225
- };
226
- }
227
-
228
- sendStream(connId: number, streamId: number, data: Uint8Array): boolean {
229
- return translateErrors(() =>
230
- this.#endpoint.sendStream(...this.#nativeStream(connId, streamId), data)
231
- );
232
- }
233
-
234
- closeStreamWrite(connId: number, streamId: number): void {
235
- translateErrors(() => {
236
- this.#endpoint.closeStreamWrite(...this.#nativeStream(connId, streamId));
237
- });
238
- }
239
-
240
- resetStream(connId: number, streamId: number): void {
241
- translateErrors(() => {
242
- this.#endpoint.resetStream(...this.#nativeStream(connId, streamId));
243
- });
244
- }
245
-
246
- abandonStream(connId: number, streamId: number): void {
247
- translateErrors(() => {
248
- this.#endpoint.abandonStream(...this.#settleStream(connId, streamId));
249
- });
250
- }
251
-
252
- streamConsumer(connId: number, streamId: number): (bytes: number) => void {
253
- const [nativeConn, nativeStream] = this.#settleStream(connId, streamId);
254
- return (bytes) => {
255
- translateErrors(() => {
256
- this.#endpoint.streamConsumed(nativeConn, nativeStream, bytes);
257
- });
258
- };
259
- }
260
-
261
- /**
262
- * Native connection and stream IDs for a public stream. Native names the
263
- * stream by both, so an operation for a connection that native already
264
- * replaced fails there instead of reaching a stream on the new connection.
265
- * A connection whose close or replacement this adapter has already drained
266
- * has no native ID, so the operation throws `StreamClosedError`.
267
- */
268
- #nativeStream(connId: number, streamId: number): [bigint, bigint] {
269
- return [
270
- this.#connectionIds.toNative(connId),
271
- this.#streamIds.toNative(streamId),
272
- ];
273
- }
274
-
275
- /**
276
- * Native IDs for settling a stream: acknowledging or abandoning its bytes.
277
- * Those still hold the native slot of a connection whose end this adapter
278
- * already drained, so a stream with events in flight resolves through its
279
- * settle handle once the live mapping is gone.
280
- */
281
- #settleStream(connId: number, streamId: number): [bigint, bigint] {
282
- try {
283
- return this.#nativeStream(connId, streamId);
284
- } catch (error) {
285
- const handle = this.#settleHandles.get(connId, streamId);
286
- if (handle === undefined) {
287
- throw error;
288
- }
289
- return handle;
290
- }
291
- }
292
-
293
- // Connect IDs are not mapped because they round-trip into native calls,
294
- // and native allocates them well inside the safe integer range.
295
- connect(target: BackendConnectTarget): number {
296
- return u64ToNumber(
297
- translateErrors(() =>
298
- this.#endpoint.connect(
299
- target.kind === "peer" ? target.peerId : [...target.addresses]
300
- )
301
- ),
302
- "connectId"
303
- );
304
- }
305
-
306
- cancelConnect(id: number): void {
307
- translateErrors(() => {
308
- this.#endpoint.cancelConnect(BigInt(id));
309
- });
310
- }
311
-
312
- disconnect(peerId: string): void {
313
- translateErrors(() => {
314
- this.#endpoint.disconnect(peerId);
315
- });
316
- }
11
+ function nodeBackend(config: Minip2pConfig): Minip2pBackend {
12
+ const endpoint = typedNativeCall(
13
+ () =>
14
+ new nativeBinding.NodeEndpoint(
15
+ toUint8Array(config.secretKey),
16
+ resolveEndpointConfig(config)
17
+ )
18
+ );
19
+ return new SerdeBackend(endpoint, {
20
+ circuitAddress,
21
+ // One check-phase turn keeps native callbacks out of the caller's stack
22
+ // without paying the timer granularity for every bounded batch.
23
+ schedule: (task) => {
24
+ setImmediate(task);
25
+ },
26
+ });
317
27
  }
318
28
 
319
29
  /** High-level Node.js owner for one native minip2p endpoint. */
@@ -324,7 +34,7 @@ export class Minip2p extends Minip2pBase {
324
34
 
325
35
  /** Constructs and starts a Node.js endpoint. */
326
36
  static create(config: Minip2pConfig): Minip2p {
327
- return new Minip2p(new NodeBackend(config), config.relays ?? []);
37
+ return new Minip2p(nodeBackend(config), config.relays ?? []);
328
38
  }
329
39
  }
330
40
 
@@ -335,392 +45,19 @@ export function generateSecretKey(): Uint8Array {
335
45
 
336
46
  /** Derives a peer ID from raw Ed25519 secret key material. */
337
47
  export function peerIdFromSecretKey(secretKey: Bytes): string {
338
- return translateErrors(() =>
48
+ return typedNativeCall(() =>
339
49
  nativeBinding.peerIdFromSecretKey(toUint8Array(secretKey))
340
50
  );
341
51
  }
342
52
 
343
53
  /** Builds a circuit multiaddress through a direct relay address. */
344
54
  export function circuitAddress(relayAddress: string, peerId: string): string {
345
- return translateErrors(() =>
55
+ return typedNativeCall(() =>
346
56
  nativeBinding.circuitAddress(relayAddress, peerId)
347
57
  );
348
58
  }
349
59
 
350
- /**
351
- * Rethrows a native `FfiError` as its typed SDK error. The addon tags each
352
- * error with the variant name as `code`, its detail field as `detail`, and
353
- * an `InvalidConfig`'s capability name as `capability`; untyped variants are
354
- * rethrown unchanged with those properties intact.
355
- */
356
- function translateErrors<T>(operation: () => T): T {
357
- try {
358
- return operation();
359
- } catch (error) {
360
- throw (
361
- typedFfiError({
362
- capability: stringProperty(error, "capability"),
363
- detail: stringProperty(error, "detail"),
364
- tag: stringProperty(error, "code"),
365
- }) ?? error
366
- );
367
- }
368
- }
369
-
370
- function stringProperty(value: unknown, key: string): string | undefined {
371
- if (value === null || typeof value !== "object") {
372
- return undefined;
373
- }
374
- const property: unknown = Reflect.get(value, key);
375
- return typeof property === "string" ? property : undefined;
376
- }
377
-
378
60
  /** A view napi-rs can read; the addon copies it before the call returns. */
379
61
  function toUint8Array(value: Bytes): Uint8Array {
380
62
  return value instanceof Uint8Array ? value : new Uint8Array(value);
381
63
  }
382
-
383
- /** Converts an Identify snapshot, copying its public key into an `ArrayBuffer`. */
384
- function identifyInfo({
385
- publicKey,
386
- ...info
387
- }: NativeIdentifyInfo): IdentifyInfo {
388
- return {
389
- ...info,
390
- ...(publicKey !== undefined && { publicKey: toArrayBuffer(publicKey) }),
391
- };
392
- }
393
-
394
- function knownPeer({
395
- beaconLastSeenAgeMs,
396
- mdnsLastSeenAgeMs,
397
- ...peer
398
- }: NativeKnownPeerInfo): KnownPeerInfo {
399
- return {
400
- ...peer,
401
- ...(beaconLastSeenAgeMs !== undefined && {
402
- beaconLastSeenAgeMs: u64ToNumber(
403
- beaconLastSeenAgeMs,
404
- "beaconLastSeenAgeMs"
405
- ),
406
- }),
407
- ...(mdnsLastSeenAgeMs !== undefined && {
408
- mdnsLastSeenAgeMs: u64ToNumber(mdnsLastSeenAgeMs, "mdnsLastSeenAgeMs"),
409
- }),
410
- };
411
- }
412
-
413
- function relayReservation({
414
- expiresUnixSecs,
415
- relayPeerId,
416
- }: NativeRelayReservationInfo): RelayReservationInfo {
417
- return {
418
- relayPeerId,
419
- ...(expiresUnixSecs !== undefined && {
420
- expiresUnixSecs: u64ToNumber(expiresUnixSecs, "expiresUnixSecs"),
421
- }),
422
- };
423
- }
424
-
425
- /** Event fields carrying a native connection ID. */
426
- const CONNECTION_ID_KEYS: ReadonlySet<string> = new Set([
427
- "connId",
428
- "oldConnId",
429
- "newConnId",
430
- ]);
431
-
432
- /**
433
- * Converts one value of a native `tag` event: integers to numbers, connection
434
- * IDs through the connection map, and bytes to `ArrayBuffer`s. A stream ID is
435
- * mapped together with the connection of the record that carries it.
436
- */
437
- function normalizeNativeValue(
438
- value: unknown,
439
- maps: NativeIdMaps,
440
- tag: string,
441
- key?: string
442
- ): unknown {
443
- if (typeof value === "bigint" || typeof value === "number") {
444
- if (key !== undefined && CONNECTION_ID_KEYS.has(key)) {
445
- return maps.connectionIds.toPublicInEvent(tag, key, BigInt(value));
446
- }
447
- // QUIC stop and close codes are 62-bit varints the remote picks: keep
448
- // them whole.
449
- if (key === "errorCode" || key === "code") {
450
- return BigInt(value);
451
- }
452
- return key === "streamId" ? value : u64ToNumber(value, key ?? "native u64");
453
- }
454
- if (value instanceof Uint8Array) {
455
- return toArrayBuffer(value);
456
- }
457
- if (Array.isArray(value)) {
458
- return value.map((item) => normalizeNativeValue(item, maps, tag));
459
- }
460
- if (value === null || typeof value !== "object") {
461
- return value;
462
- }
463
- const record: Record<string, unknown> = Object.fromEntries(
464
- Object.entries(value).map(([itemKey, item]) => [
465
- itemKey,
466
- normalizeNativeValue(item, maps, tag, itemKey),
467
- ])
468
- );
469
- const { connId, streamId } = record;
470
- if (typeof streamId === "bigint" || typeof streamId === "number") {
471
- // Public stream IDs are allocated per connection. A record without a
472
- // connection (an endpoint error, say) cannot name a public stream.
473
- if (typeof connId === "number") {
474
- record.streamId = maps.streamIds.toPublic(connId, BigInt(streamId));
475
- } else {
476
- delete record.streamId;
477
- }
478
- }
479
- return record;
480
- }
481
-
482
- /**
483
- * Converts one native event to its SDK backend form, then retires the IDs it
484
- * ends.
485
- */
486
- function normalizeEvent(
487
- event: NativeEvent,
488
- connectionIds: ConnectionIdMap,
489
- streamIds: StreamIdMap
490
- ): P2pEvent {
491
- const normalized = convertEvent(event, { connectionIds, streamIds });
492
- retireTerminalIds(normalized, connectionIds, streamIds);
493
- return normalized;
494
- }
495
-
496
- /**
497
- * Per-chunk and per-write events, and pubsub messages, convert field by
498
- * field. Identify snapshots go through the typed {@link identifyInfo}, and a
499
- * field-less event passes through by tag. The rest share the generic walk: the addon's serde shape is the SDK shape with
500
- * napi-rs integers and buffers (see `native-shape.ts`).
501
- */
502
- function convertEvent(event: NativeEvent, maps: NativeIdMaps): P2pEvent {
503
- switch (event.tag) {
504
- case P2pEvent_Tags.StreamData: {
505
- return {
506
- inner: {
507
- ...streamRef(event.inner, maps),
508
- data: toArrayBuffer(event.inner.data),
509
- },
510
- tag: event.tag,
511
- };
512
- }
513
- case P2pEvent_Tags.StreamWriteAccepted:
514
- case P2pEvent_Tags.StreamRemoteWriteClosed:
515
- case P2pEvent_Tags.StreamClosed: {
516
- return { inner: streamRef(event.inner, maps), tag: event.tag };
517
- }
518
- case P2pEvent_Tags.Message: {
519
- const { data, fromPeerId, seqno, signed, topics } = event.inner;
520
- return {
521
- inner: {
522
- data: toArrayBuffer(data),
523
- fromPeerId,
524
- seqno: toArrayBuffer(seqno),
525
- signed,
526
- topics,
527
- },
528
- tag: event.tag,
529
- };
530
- }
531
- case P2pEvent_Tags.IdentifyReceived: {
532
- return {
533
- inner: {
534
- connId: maps.connectionIds.toPublic(BigInt(event.inner.connId)),
535
- info: identifyInfo(event.inner.info),
536
- peerId: event.inner.peerId,
537
- },
538
- tag: event.tag,
539
- };
540
- }
541
- case P2pEvent_Tags.MdnsRecovered: {
542
- return { tag: event.tag };
543
- }
544
- default: {
545
- return {
546
- inner: normalizeNativeValue(event.inner, maps, event.tag),
547
- tag: event.tag,
548
- } as P2pEvent;
549
- }
550
- }
551
- }
552
-
553
- /** The native identity of the stream a native stream event names. */
554
- function nativeStreamOf(event: NativeEvent): [bigint, bigint] | undefined {
555
- switch (event.tag) {
556
- case P2pEvent_Tags.StreamReady:
557
- case P2pEvent_Tags.StreamData:
558
- case P2pEvent_Tags.StreamWriteAccepted:
559
- case P2pEvent_Tags.StreamWriteStopped:
560
- case P2pEvent_Tags.StreamRemoteWriteClosed:
561
- case P2pEvent_Tags.StreamClosed: {
562
- return [BigInt(event.inner.connId), BigInt(event.inner.streamId)];
563
- }
564
- default: {
565
- return undefined;
566
- }
567
- }
568
- }
569
-
570
- /** The public identity of the stream a native stream event names. */
571
- function streamRef(
572
- inner: {
573
- readonly peerId: string;
574
- readonly connId: number | bigint;
575
- readonly streamId: number | bigint;
576
- },
577
- maps: NativeIdMaps
578
- ): { peerId: string; connId: number; streamId: number } {
579
- const connId = maps.connectionIds.toPublic(BigInt(inner.connId));
580
- return {
581
- connId,
582
- peerId: inner.peerId,
583
- streamId: maps.streamIds.toPublic(connId, BigInt(inner.streamId)),
584
- };
585
- }
586
-
587
- /**
588
- * Stops new native events from reaching identifiers this event ends, so a
589
- * reused native ID gets a fresh public number. An ended connection is
590
- * released at once, so a stream operation queued behind its event throws
591
- * `StreamClosedError` without reaching native; stream numbers stay resolvable
592
- * until {@link releaseTerminalIds} runs after dispatch.
593
- */
594
- function retireTerminalIds(
595
- event: P2pEvent,
596
- connectionIds: ConnectionIdMap,
597
- streamIds: StreamIdMap
598
- ): void {
599
- const connId = endedConnection(event);
600
- if (connId !== undefined) {
601
- connectionIds.release(connId);
602
- streamIds.retireConnection(connId);
603
- }
604
- if (event.tag === P2pEvent_Tags.StreamClosed) {
605
- streamIds.retirePublic(event.inner.streamId);
606
- }
607
- }
608
-
609
- /** Frees stream identifiers this event ended, once the SDK dispatched it. */
610
- function releaseTerminalIds(event: P2pEvent, streamIds: StreamIdMap): void {
611
- const connId = endedConnection(event);
612
- if (connId !== undefined) {
613
- streamIds.deleteConnection(connId);
614
- }
615
- if (event.tag === P2pEvent_Tags.StreamClosed) {
616
- streamIds.deletePublic(event.inner.streamId);
617
- }
618
- }
619
-
620
- /**
621
- * The connection this event ends. A closed or replaced connection reports no
622
- * per-stream terminal events, so its streams end with it.
623
- */
624
- function endedConnection(event: P2pEvent): number | undefined {
625
- if (event.tag === P2pEvent_Tags.ConnectionClosed) {
626
- return event.inner.connId;
627
- }
628
- if (event.tag === P2pEvent_Tags.ConnectionReplaced) {
629
- return event.inner.oldConnId;
630
- }
631
- return undefined;
632
- }
633
-
634
- /** Copies native bytes unless they already own their whole `ArrayBuffer`. */
635
- function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
636
- if (
637
- bytes.buffer instanceof ArrayBuffer &&
638
- bytes.byteOffset === 0 &&
639
- bytes.byteLength === bytes.buffer.byteLength
640
- ) {
641
- return bytes.buffer;
642
- }
643
- return Uint8Array.from(bytes).buffer;
644
- }
645
-
646
- interface NativeIdMaps {
647
- readonly connectionIds: ConnectionIdMap;
648
- readonly streamIds: StreamIdMap;
649
- }
650
-
651
- /**
652
- * Maps native stream IDs, which are unique only within their connection, to
653
- * public numbers that never repeat. Each stream remembers its public
654
- * connection, so a closed or replaced connection frees every stream on it.
655
- */
656
- class StreamIdMap {
657
- /** Live public IDs by public connection, then native stream ID. */
658
- readonly #publicByNative = new Map<number, Map<bigint, number>>();
659
- readonly #streams = new Map<
660
- number,
661
- { readonly connId: number; readonly native: bigint }
662
- >();
663
- #next = 1;
664
-
665
- toPublic(connId: number, native: bigint): number {
666
- let byNative = this.#publicByNative.get(connId);
667
- const existing = byNative?.get(native);
668
- if (existing !== undefined) {
669
- return existing;
670
- }
671
- if (byNative === undefined) {
672
- byNative = new Map();
673
- this.#publicByNative.set(connId, byNative);
674
- }
675
- const publicId = this.#next;
676
- this.#next += 1;
677
- byNative.set(native, publicId);
678
- this.#streams.set(publicId, { connId, native });
679
- return publicId;
680
- }
681
-
682
- toNative(publicId: number): bigint {
683
- const stream = this.#streams.get(publicId);
684
- if (stream === undefined) {
685
- throw new StreamClosedError("The stream closed");
686
- }
687
- return stream.native;
688
- }
689
-
690
- deletePublic(publicId: number): void {
691
- this.retirePublic(publicId);
692
- this.#streams.delete(publicId);
693
- }
694
-
695
- retirePublic(publicId: number): void {
696
- const stream = this.#streams.get(publicId);
697
- if (stream === undefined) {
698
- return;
699
- }
700
- const byNative = this.#publicByNative.get(stream.connId);
701
- if (byNative?.get(stream.native) === publicId) {
702
- byNative.delete(stream.native);
703
- if (byNative.size === 0) {
704
- this.#publicByNative.delete(stream.connId);
705
- }
706
- }
707
- }
708
-
709
- deleteConnection(connId: number): void {
710
- for (const publicId of this.#onConnection(connId)) {
711
- this.deletePublic(publicId);
712
- }
713
- }
714
-
715
- retireConnection(connId: number): void {
716
- for (const publicId of this.#onConnection(connId)) {
717
- this.retirePublic(publicId);
718
- }
719
- }
720
-
721
- #onConnection(connId: number): number[] {
722
- return [...this.#streams]
723
- .filter(([, stream]) => stream.connId === connId)
724
- .map(([publicId]) => publicId);
725
- }
726
- }