@minip2p/core 0.7.4 → 0.7.6

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/sdk.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  PeerDisconnectedError,
15
15
  StreamClosedError,
16
16
  TimeoutError,
17
+ WriteBufferFullError,
17
18
  } from "./errors.js";
18
19
  import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
19
20
  import type {
@@ -33,6 +34,7 @@ import type {
33
34
  OnceOptions,
34
35
  OpOptions,
35
36
  P2pEvent,
37
+ P2pEventTag,
36
38
  Path,
37
39
  PathKind,
38
40
  Reachability,
@@ -49,8 +51,29 @@ const DEFAULT_TIMEOUT_MS = 65_000;
49
51
  const EVENT_QUEUE_CAP = 4096;
50
52
  const EVENT_FLUSH_BATCH = 256;
51
53
  const CONNECT_TERMINAL_CAP = 1024;
52
- const STREAM_CHUNK_CAP = 64;
53
- const STREAM_BYTE_CAP = 1024 * 1024;
54
+ /** Default per-stream write high-water mark: one Yamux stream send cap. */
55
+ const DEFAULT_WRITE_HIGH_WATER_MARK = 256 * 1024;
56
+
57
+ /** Native events routed to one {@link Stream} after it became ready. */
58
+ const STREAM_EVENT_TAGS = [
59
+ P2pEvent_Tags.StreamData,
60
+ P2pEvent_Tags.StreamRemoteWriteClosed,
61
+ P2pEvent_Tags.StreamWriteAccepted,
62
+ P2pEvent_Tags.StreamWriteStopped,
63
+ P2pEvent_Tags.StreamClosed,
64
+ ] as const;
65
+ type StreamP2pEvent = Extract<
66
+ P2pEvent,
67
+ { readonly tag: (typeof STREAM_EVENT_TAGS)[number] }
68
+ >;
69
+ const isStreamEvent = (event: P2pEvent): event is StreamP2pEvent =>
70
+ (STREAM_EVENT_TAGS as readonly string[]).includes(event.tag);
71
+
72
+ interface PendingWrite {
73
+ readonly data: Uint8Array;
74
+ readonly resolve: () => void;
75
+ readonly reject: (error: unknown) => void;
76
+ }
54
77
 
55
78
  type EventKind = keyof Minip2pNamedEventMap;
56
79
  type AnyPayload = Minip2pNamedEventMap[EventKind];
@@ -163,6 +186,289 @@ class BoundedQueue<Item> {
163
186
  }
164
187
  }
165
188
 
189
+ /** An unbounded queue whose `shift` is O(1), unlike `Array#shift`. */
190
+ class Fifo<Item> {
191
+ #items: (Item | undefined)[] = [];
192
+ #head = 0;
193
+
194
+ get length(): number {
195
+ return this.#items.length - this.#head;
196
+ }
197
+
198
+ push(item: Item): void {
199
+ this.#items.push(item);
200
+ }
201
+
202
+ shift(): Item | undefined {
203
+ if (this.#head === this.#items.length) {
204
+ return undefined;
205
+ }
206
+ const item = this.#items[this.#head];
207
+ this.#items[this.#head] = undefined;
208
+ this.#head += 1;
209
+ // Drop the consumed prefix once it is at least half the array.
210
+ if (this.#head * 2 >= this.#items.length) {
211
+ this.#items = this.#items.slice(this.#head);
212
+ this.#head = 0;
213
+ }
214
+ return item;
215
+ }
216
+
217
+ clear(): void {
218
+ this.#items = [];
219
+ this.#head = 0;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Native events that are never dropped, because stream and connection state
225
+ * depends on each one (ADR 0012), plus the driver failure that ends them.
226
+ */
227
+ const LOSSLESS_TAGS: ReadonlySet<string> = new Set<string>([
228
+ P2pEvent_Tags.StreamReady,
229
+ ...STREAM_EVENT_TAGS,
230
+ P2pEvent_Tags.ConnectionClosed,
231
+ P2pEvent_Tags.ConnectionReplaced,
232
+ P2pEvent_Tags.DriverFailed,
233
+ ]);
234
+
235
+ type StreamReadyEvent = Extract<
236
+ P2pEvent,
237
+ { readonly tag: typeof P2pEvent_Tags.StreamReady }
238
+ >;
239
+
240
+ type StreamDataEvent = Extract<
241
+ P2pEvent,
242
+ { readonly tag: typeof P2pEvent_Tags.StreamData }
243
+ >;
244
+
245
+ /** Returns `next` appended to `last` when both are data for one stream. */
246
+ const coalesceData = (
247
+ last: QueueItem,
248
+ next: QueueItem
249
+ ): QueueItem | undefined => {
250
+ if (
251
+ last.source !== "native" ||
252
+ next.source !== "native" ||
253
+ last.event.tag !== P2pEvent_Tags.StreamData ||
254
+ next.event.tag !== P2pEvent_Tags.StreamData
255
+ ) {
256
+ return undefined;
257
+ }
258
+ const { inner } = last.event;
259
+ const { inner: added } = next.event;
260
+ if (
261
+ inner.peerId !== added.peerId ||
262
+ inner.connId !== added.connId ||
263
+ inner.streamId !== added.streamId
264
+ ) {
265
+ return undefined;
266
+ }
267
+ const data = new Uint8Array(inner.data.byteLength + added.data.byteLength);
268
+ data.set(new Uint8Array(inner.data));
269
+ data.set(new Uint8Array(added.data), inner.data.byteLength);
270
+ const event: StreamDataEvent = {
271
+ inner: { ...inner, data: data.buffer },
272
+ tag: P2pEvent_Tags.StreamData,
273
+ };
274
+ return { event, source: "native" };
275
+ };
276
+
277
+ /**
278
+ * Values keyed by a stream's public connection and stream IDs, without
279
+ * building a key per lookup. Public connection IDs never repeat and each
280
+ * names one peer's connection, so the pair names the stream.
281
+ */
282
+ class StreamTable<Value> {
283
+ readonly #byConnection = new Map<number, Map<number, Value>>();
284
+
285
+ get(connId: number, streamId: number): Value | undefined {
286
+ return this.#byConnection.get(connId)?.get(streamId);
287
+ }
288
+
289
+ has(connId: number, streamId: number): boolean {
290
+ return this.#byConnection.get(connId)?.has(streamId) ?? false;
291
+ }
292
+
293
+ set(connId: number, streamId: number, value: Value): void {
294
+ let streams = this.#byConnection.get(connId);
295
+ if (streams === undefined) {
296
+ streams = new Map();
297
+ this.#byConnection.set(connId, streams);
298
+ }
299
+ streams.set(streamId, value);
300
+ }
301
+
302
+ delete(connId: number, streamId: number): void {
303
+ const streams = this.#byConnection.get(connId);
304
+ if (streams?.delete(streamId) === true && streams.size === 0) {
305
+ this.#byConnection.delete(connId);
306
+ }
307
+ }
308
+
309
+ /** Removes and returns every value on `connId`. */
310
+ takeConnection(connId: number): Value[] {
311
+ const streams = this.#byConnection.get(connId);
312
+ this.#byConnection.delete(connId);
313
+ return streams === undefined ? [] : [...streams.values()];
314
+ }
315
+
316
+ /** A snapshot of every value. */
317
+ values(): Value[] {
318
+ return [...this.#byConnection.values()].flatMap((streams) => [
319
+ ...streams.values(),
320
+ ]);
321
+ }
322
+
323
+ /** Removes and returns every value. */
324
+ takeAll(): Value[] {
325
+ const values = this.values();
326
+ this.#byConnection.clear();
327
+ return values;
328
+ }
329
+ }
330
+
331
+ /** The native per-stream event an item carries, if any. */
332
+ const streamEventOf = (
333
+ item: QueueItem
334
+ ): StreamP2pEvent | StreamReadyEvent | undefined =>
335
+ item.source === "native" &&
336
+ (item.event.tag === P2pEvent_Tags.StreamReady || isStreamEvent(item.event))
337
+ ? item.event
338
+ : undefined;
339
+
340
+ /**
341
+ * The endpoint's shared event queue, in delivery order.
342
+ *
343
+ * Stream events and connection-end events (plus `DriverFailed`) never drop,
344
+ * and adjacent data for one stream coalesces into one event, so native
345
+ * receive budgets bound them; they do not count against the capacity. Past `capacity` other items, the oldest
346
+ * gossipsub message is dropped first, then the oldest other item.
347
+ *
348
+ * A peer-opened stream that closes without data before its `StreamReady`
349
+ * is dispatched leaves the queue whole, so a peer opening and closing
350
+ * streams cannot grow it; its events still reach `release`.
351
+ */
352
+ class EventQueue {
353
+ readonly #items = new Map<number, QueueItem>();
354
+ /** Droppable messages, then other droppable items, oldest first. */
355
+ readonly #messages = new Set<number>();
356
+ readonly #others = new Set<number>();
357
+ /**
358
+ * Peer-opened streams whose `StreamReady` is still queued, with their
359
+ * queued item ids; `undefined` once one carried data.
360
+ */
361
+ readonly #unseen = new StreamTable<number[] | undefined>();
362
+ readonly #capacity: number;
363
+ readonly #release: (item: QueueItem) => void;
364
+ #next = 0;
365
+ #newest: number | undefined;
366
+
367
+ constructor(capacity: number, release: (item: QueueItem) => void) {
368
+ this.#capacity = capacity;
369
+ this.#release = release;
370
+ }
371
+
372
+ get length(): number {
373
+ return this.#items.size;
374
+ }
375
+
376
+ /** Appends `item`, returning the item dropped to make room, if any. */
377
+ push(item: QueueItem): QueueItem | undefined {
378
+ const newest =
379
+ this.#newest === undefined ? undefined : this.#items.get(this.#newest);
380
+ const merged =
381
+ newest === undefined ? undefined : coalesceData(newest, item);
382
+ if (merged !== undefined && this.#newest !== undefined) {
383
+ // A data event retires no adapter IDs, so the absorbed one needs no
384
+ // `eventHandled`.
385
+ this.#items.set(this.#newest, merged);
386
+ return undefined;
387
+ }
388
+ const id = this.#next;
389
+ this.#next += 1;
390
+ if (this.#elideUnseen(item, id)) {
391
+ return undefined;
392
+ }
393
+ this.#items.set(id, item);
394
+ this.#newest = id;
395
+ if (item.source === "native" && item.event.tag === P2pEvent_Tags.Message) {
396
+ this.#messages.add(id);
397
+ } else if (item.source !== "native" || !LOSSLESS_TAGS.has(item.event.tag)) {
398
+ this.#others.add(id);
399
+ }
400
+ if (this.#messages.size + this.#others.size <= this.#capacity) {
401
+ return undefined;
402
+ }
403
+ const [victim] = this.#messages.size > 0 ? this.#messages : this.#others;
404
+ return victim === undefined ? undefined : this.#remove(victim);
405
+ }
406
+
407
+ shift(): QueueItem | undefined {
408
+ const [oldest] = this.#items.keys();
409
+ if (oldest === undefined) {
410
+ return undefined;
411
+ }
412
+ const item = this.#remove(oldest);
413
+ if (
414
+ item?.source === "native" &&
415
+ item.event.tag === P2pEvent_Tags.StreamReady
416
+ ) {
417
+ this.#unseen.delete(item.event.inner.connId, item.event.inner.streamId);
418
+ }
419
+ return item;
420
+ }
421
+
422
+ /**
423
+ * Records `item` (as `id`) against an unseen peer stream. Returns whether
424
+ * it closed one that carried no data, which leaves the queue whole.
425
+ */
426
+ #elideUnseen(item: QueueItem, id: number): boolean {
427
+ const event = streamEventOf(item);
428
+ if (event === undefined) {
429
+ return false;
430
+ }
431
+ const { connId, streamId } = event.inner;
432
+ if (event.tag === P2pEvent_Tags.StreamReady) {
433
+ if (!event.inner.initiatedLocally) {
434
+ this.#unseen.set(connId, streamId, [id]);
435
+ }
436
+ return false;
437
+ }
438
+ if (!this.#unseen.has(connId, streamId)) {
439
+ return false;
440
+ }
441
+ const ids = this.#unseen.get(connId, streamId);
442
+ if (event.tag === P2pEvent_Tags.StreamData) {
443
+ this.#unseen.set(connId, streamId, undefined);
444
+ } else if (ids !== undefined && event.tag === P2pEvent_Tags.StreamClosed) {
445
+ this.#unseen.delete(connId, streamId);
446
+ for (const queued of ids) {
447
+ const removed = this.#remove(queued);
448
+ if (removed !== undefined) {
449
+ this.#release(removed);
450
+ }
451
+ }
452
+ this.#release(item);
453
+ return true;
454
+ } else {
455
+ ids?.push(id);
456
+ }
457
+ return false;
458
+ }
459
+
460
+ #remove(id: number): QueueItem | undefined {
461
+ const item = this.#items.get(id);
462
+ this.#items.delete(id);
463
+ this.#messages.delete(id);
464
+ this.#others.delete(id);
465
+ if (this.#newest === id) {
466
+ this.#newest = undefined;
467
+ }
468
+ return item;
469
+ }
470
+ }
471
+
166
472
  /** A negotiated custom-protocol stream with exclusive pull or flowing reads. */
167
473
  export class Stream {
168
474
  /** Remote peer that owns the other end of this stream. */
@@ -177,16 +483,32 @@ export class Stream {
177
483
  readonly initiatedLocally: boolean;
178
484
  readonly #backend: Minip2pBackend;
179
485
  readonly #onTerminal: () => void;
486
+ readonly #consume: (bytes: number) => void;
180
487
  readonly #listeners = new Map<
181
488
  keyof StreamEventMap,
182
489
  Set<(payload: StreamEventMap[keyof StreamEventMap]) => void>
183
490
  >();
184
- readonly #fifo: Uint8Array[] = [];
491
+ readonly #fifo = new Fifo<Uint8Array>();
185
492
  readonly #reads: PendingRead[] = [];
186
493
  #fifoBytes = 0;
187
494
  #mode: "pull" | "flowing" | undefined;
188
495
  #receiveState: StreamReceiveState = { kind: "receiving" };
189
496
  #closed = false;
497
+ /** Writes not yet accepted by native, oldest (possibly in flight) first. */
498
+ readonly #writes: PendingWrite[] = [];
499
+ #writeBytes = 0;
500
+ /** Native holds the head write's tail until `StreamWriteAccepted`. */
501
+ #writeInFlight = false;
502
+ /** Why later writes fail: `closeWrite`, a remote stop, or a terminal. */
503
+ #writeEnded: Error | undefined;
504
+ #closeWriteQueued = false;
505
+
506
+ /**
507
+ * Most bytes the stream buffers before {@link write} rejects with
508
+ * {@link WriteBufferFullError}, counting the write native is still taking.
509
+ * A write into an empty buffer is always admitted, whatever its size.
510
+ */
511
+ writeHighWaterMark = DEFAULT_WRITE_HIGH_WATER_MARK;
190
512
 
191
513
  constructor(
192
514
  backend: Minip2pBackend,
@@ -195,6 +517,7 @@ export class Stream {
195
517
  ) {
196
518
  this.#backend = backend;
197
519
  this.#onTerminal = onTerminal;
520
+ this.#consume = streamConsumer(backend, meta);
198
521
  this.peerId = meta.peerId;
199
522
  this.protocolId = meta.protocolId;
200
523
  this.streamId = meta.streamId;
@@ -202,7 +525,16 @@ export class Stream {
202
525
  this.initiatedLocally = meta.initiatedLocally;
203
526
  }
204
527
 
205
- /** Subscribes to stream lifecycle or data events. */
528
+ /**
529
+ * Subscribes to stream lifecycle or data events.
530
+ *
531
+ * A chunk counts as consumed once every `data` handler has returned, and
532
+ * only consumed bytes let the sender continue: a stream delivers at most
533
+ * one receive window that has not been consumed. An `async` handler is
534
+ * consumed when it returns its Promise, not when that Promise settles; to
535
+ * hold the sender back while asynchronous work runs, use {@link read}
536
+ * instead.
537
+ */
206
538
  on<Kind extends keyof StreamEventMap>(
207
539
  type: Kind,
208
540
  handler: (payload: StreamEventMap[Kind]) => void
@@ -239,6 +571,11 @@ export class Stream {
239
571
  /**
240
572
  * Reads the next buffered chunk, or `undefined` after the remote write side
241
573
  * closes. Pull reads and flowing `data` handlers are mutually exclusive.
574
+ *
575
+ * Returning a chunk consumes it, which lets the sender continue: the
576
+ * stream delivers at most one receive window that has not been read, so a
577
+ * reader that stops calling `read()` stalls its sender rather than
578
+ * buffering without bound.
242
579
  */
243
580
  read(): Promise<Uint8Array | undefined> {
244
581
  if (this.#mode === "flowing") {
@@ -250,56 +587,110 @@ export class Stream {
250
587
  if (this.#receiveState.kind === "failed") {
251
588
  return Promise.reject(this.#receiveState.error);
252
589
  }
253
- const buffered = this.#shift();
254
- if (buffered !== undefined) {
590
+ const buffered = this.#take();
591
+ if (buffered !== undefined || this.#receiveState.kind === "eof") {
255
592
  return Promise.resolve(buffered);
256
593
  }
257
- if (this.#receiveState.kind === "eof") {
258
- return Promise.resolve(this.#shift());
259
- }
260
594
  return new Promise((resolve, reject) => {
261
595
  this.#reads.push({ reject, resolve });
262
596
  });
263
597
  }
264
598
 
265
- /** Writes UTF-8 text or bytes to the stream. */
266
- write(data: string | Bytes): void {
599
+ /**
600
+ * Writes UTF-8 text or bytes to the stream, resolving once native has
601
+ * accepted every byte. Writes are delivered in call order.
602
+ *
603
+ * Rejects with {@link WriteBufferFullError} when the stream already
604
+ * buffers {@link writeHighWaterMark} bytes (a first write is always
605
+ * admitted, so a payload larger than the mark can still be sent), and with
606
+ * a closed error after `closeWrite()`, a remote stop, or the stream
607
+ * closing.
608
+ *
609
+ * A write queued behind a pending one keeps a reference to `data`, and
610
+ * native reads it only when the write reaches the head of the queue: leave
611
+ * the buffer untouched until the Promise settles.
612
+ */
613
+ write(data: string | Bytes): Promise<void> {
267
614
  if (this.#closed) {
268
- throw new ClosedError();
615
+ return Promise.reject(new ClosedError());
269
616
  }
270
- this.#backend.sendStream(
271
- this.peerId,
272
- this.connId,
273
- this.streamId,
274
- toUint8Array(data)
275
- );
617
+ if (this.#writeEnded !== undefined) {
618
+ return Promise.reject(this.#writeEnded);
619
+ }
620
+ const bytes = toUint8Array(data);
621
+ if (
622
+ this.#writeBytes > 0 &&
623
+ this.#writeBytes + bytes.byteLength > this.writeHighWaterMark
624
+ ) {
625
+ return Promise.reject(
626
+ new WriteBufferFullError(this.#writeBytes, this.writeHighWaterMark)
627
+ );
628
+ }
629
+ return new Promise((resolve, reject) => {
630
+ this.#writes.push({ data: bytes, reject, resolve });
631
+ this.#writeBytes += bytes.byteLength;
632
+ this.#pumpWrites();
633
+ });
276
634
  }
277
635
 
278
- /** Half-closes the local write side while keeping reads available. */
636
+ /**
637
+ * Half-closes the local write side once every earlier write has been
638
+ * accepted, keeping reads available. Later writes reject.
639
+ *
640
+ * With no write pending the close goes to native now and throws if native
641
+ * refuses it. Behind pending writes it is queued, and a close native then
642
+ * refuses is reported by the stream's terminal event instead.
643
+ */
279
644
  closeWrite(): void {
280
- if (!this.#closed) {
645
+ if (this.#closed || this.#writeEnded !== undefined) {
646
+ return;
647
+ }
648
+ this.#writeEnded = new StreamClosedError("The stream write side closed");
649
+ if (this.#writes.length === 0) {
281
650
  this.#backend.closeStreamWrite(this.peerId, this.connId, this.streamId);
651
+ return;
282
652
  }
653
+ this.#closeWriteQueued = true;
283
654
  }
284
655
 
285
- /** Abruptly resets the stream and emits `closed`. */
656
+ /**
657
+ * Abruptly resets the stream and emits `closed`. On a stream that already
658
+ * closed, discards unread bytes instead.
659
+ */
286
660
  reset(): void {
287
- if (!this.#closed) {
288
- this.#backend.resetStream(this.peerId, this.connId, this.streamId);
289
- this.terminal();
661
+ if (this.#closed) {
662
+ this.#discardUnread();
663
+ return;
290
664
  }
665
+ this.#backend.resetStream(this.peerId, this.connId, this.streamId);
666
+ this.terminal();
291
667
  }
292
668
 
293
- /** Relinquishes the stream and requests a reset while it remains active. */
669
+ /**
670
+ * Relinquishes the stream and requests a reset while it remains active.
671
+ * On a stream that already closed, discards unread bytes instead.
672
+ */
294
673
  abandon(): void {
295
- if (!this.#closed) {
296
- try {
297
- this.#backend.abandonStream(this.peerId, this.connId, this.streamId);
298
- } catch {
299
- // A native close can overtake its queued terminal event.
300
- }
301
- this.terminal();
674
+ if (this.#closed) {
675
+ this.#discardUnread();
676
+ return;
677
+ }
678
+ try {
679
+ this.#backend.abandonStream(this.peerId, this.connId, this.streamId);
680
+ } catch {
681
+ // A native close can overtake its queued terminal event.
302
682
  }
683
+ this.terminal();
684
+ }
685
+
686
+ /**
687
+ * A cleanly closed stream keeps unread bytes for later reads, and they
688
+ * hold its native stream slot until consumed; discarding them releases it.
689
+ */
690
+ #discardUnread(): void {
691
+ this.#consumed(this.#fifoBytes);
692
+ this.#fifo.clear();
693
+ this.#fifoBytes = 0;
303
694
  }
304
695
 
305
696
  [Symbol.dispose](): void {
@@ -330,26 +721,49 @@ export class Stream {
330
721
  const read = this.#reads.shift();
331
722
  if (read !== undefined) {
332
723
  read.resolve(chunk);
724
+ this.#consumed(chunk.byteLength);
333
725
  return;
334
726
  }
335
727
  if (this.#mode === "flowing") {
336
- this.#emit("data", chunk);
337
- return;
338
- }
339
- if (
340
- this.#fifo.length >= STREAM_CHUNK_CAP ||
341
- this.#fifoBytes + chunk.byteLength > STREAM_BYTE_CAP
342
- ) {
343
- this.#emit("dataOverflow", {
344
- droppedBytes: chunk.byteLength,
345
- droppedChunks: 1,
346
- });
728
+ this.#emitData(chunk);
347
729
  return;
348
730
  }
731
+ // Unbounded here, because native delivers at most one receive window
732
+ // that has not been consumed.
349
733
  this.#fifo.push(chunk);
350
734
  this.#fifoBytes += chunk.byteLength;
351
735
  }
352
736
 
737
+ /**
738
+ * Native accepted the whole in-flight write.
739
+ * @internal
740
+ */
741
+ writeAccepted(): void {
742
+ if (!this.#writeInFlight) {
743
+ return;
744
+ }
745
+ this.#writeInFlight = false;
746
+ this.#settleHead();
747
+ this.#pumpWrites();
748
+ }
749
+
750
+ /**
751
+ * The remote asked this side to stop writing.
752
+ * @internal
753
+ */
754
+ writeStopped(errorCode: bigint): void {
755
+ if (this.#closed) {
756
+ return;
757
+ }
758
+ const error = new StreamClosedError(
759
+ `The remote stopped reading this stream (code ${errorCode})`
760
+ );
761
+ this.#writeEnded ??= error;
762
+ this.#closeWriteQueued = false;
763
+ this.#failWrites(error);
764
+ this.#emit("writeStopped", { errorCode });
765
+ }
766
+
353
767
  /** @internal */
354
768
  remoteWriteClosed(): void {
355
769
  if (this.#closed || this.#receiveState.kind !== "receiving") {
@@ -373,18 +787,18 @@ export class Stream {
373
787
  return;
374
788
  }
375
789
  this.#closed = true;
790
+ this.#failWrites(error);
376
791
  // StreamClosed carries no cause. Once the remote FIN establishes EOF,
377
792
  // later full closure cannot reinterpret that receive-side outcome.
378
793
  const hasRemoteEof =
379
794
  options.preserveRemoteEof === true && this.#receiveState.kind === "eof";
380
795
  if (!hasRemoteEof) {
381
796
  this.#receiveState = { error, kind: "failed" };
382
- this.#fifo.length = 0;
383
- this.#fifoBytes = 0;
797
+ this.#discardUnread();
384
798
  }
385
799
  for (const read of this.#reads.splice(0)) {
386
800
  if (hasRemoteEof) {
387
- read.resolve(this.#shift());
801
+ read.resolve(this.#take());
388
802
  } else {
389
803
  read.reject(error);
390
804
  }
@@ -394,23 +808,111 @@ export class Stream {
394
808
  this.#onTerminal();
395
809
  }
396
810
 
811
+ /**
812
+ * Hands queued writes to native one at a time. A write native accepts only
813
+ * in part stays at the head until `StreamWriteAccepted`, which keeps
814
+ * writes, and the queued close, in order.
815
+ */
816
+ #pumpWrites(): void {
817
+ while (!this.#writeInFlight && !this.#closed) {
818
+ const [head] = this.#writes;
819
+ if (head === undefined) {
820
+ if (this.#closeWriteQueued) {
821
+ this.#closeWriteQueued = false;
822
+ try {
823
+ this.#backend.closeStreamWrite(
824
+ this.peerId,
825
+ this.connId,
826
+ this.streamId
827
+ );
828
+ } catch {
829
+ // A deferred close has no caller left to throw to; the stream
830
+ // already ended, and its terminal event reports that.
831
+ }
832
+ }
833
+ return;
834
+ }
835
+ let accepted: boolean;
836
+ try {
837
+ accepted = this.#backend.sendStream(
838
+ this.peerId,
839
+ this.connId,
840
+ this.streamId,
841
+ head.data
842
+ );
843
+ } catch (error) {
844
+ this.#failWrites(error);
845
+ return;
846
+ }
847
+ if (!accepted) {
848
+ this.#writeInFlight = true;
849
+ return;
850
+ }
851
+ this.#settleHead();
852
+ }
853
+ }
854
+
855
+ #settleHead(): void {
856
+ const head = this.#writes.shift();
857
+ if (head !== undefined) {
858
+ this.#writeBytes -= head.data.byteLength;
859
+ head.resolve();
860
+ }
861
+ }
862
+
863
+ #failWrites(error: unknown): void {
864
+ this.#writeInFlight = false;
865
+ this.#writeBytes = 0;
866
+ for (const write of this.#writes.splice(0)) {
867
+ write.reject(error);
868
+ }
869
+ }
870
+
871
+ /**
872
+ * Hands buffered chunks to `data` handlers. After a clean close the
873
+ * buffer still holds the bytes that arrived before EOF (a failed stream
874
+ * has already discarded them), so a late handler drains it too.
875
+ */
397
876
  #flushFlowing(): void {
398
- while (this.#fifo.length > 0 && !this.#closed) {
399
- const chunk = this.#shift();
877
+ while (this.#fifo.length > 0) {
878
+ const chunk = this.#fifo.shift();
400
879
  if (chunk !== undefined) {
401
- this.#emit("data", chunk);
880
+ this.#fifoBytes -= chunk.byteLength;
881
+ this.#emitData(chunk);
402
882
  }
403
883
  }
404
884
  }
405
885
 
406
- #shift(): Uint8Array | undefined {
886
+ /** Hands `chunk` to every `data` handler; it is consumed once they return. */
887
+ #emitData(chunk: Uint8Array): void {
888
+ // Counted first: a handler may transfer the buffer, detaching it.
889
+ const bytes = chunk.byteLength;
890
+ this.#emit("data", chunk);
891
+ this.#consumed(bytes);
892
+ }
893
+
894
+ /** Takes the oldest buffered chunk for a reader, consuming it. */
895
+ #take(): Uint8Array | undefined {
407
896
  const chunk = this.#fifo.shift();
408
897
  if (chunk !== undefined) {
409
898
  this.#fifoBytes -= chunk.byteLength;
899
+ this.#consumed(chunk.byteLength);
410
900
  }
411
901
  return chunk;
412
902
  }
413
903
 
904
+ /** Acknowledges consumed bytes to native, letting the sender continue. */
905
+ #consumed(bytes: number): void {
906
+ if (bytes === 0) {
907
+ return;
908
+ }
909
+ try {
910
+ this.#consume(bytes);
911
+ } catch {
912
+ // The stream or its connection is already gone natively.
913
+ }
914
+ }
915
+
414
916
  #emit<Kind extends keyof StreamEventMap>(
415
917
  type: Kind,
416
918
  payload?: StreamEventMap[Kind]
@@ -425,6 +927,33 @@ export class Stream {
425
927
  }
426
928
  }
427
929
 
930
+ /**
931
+ * The backend's acknowledgement function for a stream. A connection whose
932
+ * end the adapter already saw has nothing left to settle.
933
+ */
934
+ const streamConsumer = (
935
+ backend: Minip2pBackend,
936
+ meta: InboundStreamMeta
937
+ ): ((bytes: number) => void) => {
938
+ try {
939
+ return backend.streamConsumer(meta.connId, meta.streamId);
940
+ } catch {
941
+ return () => {};
942
+ }
943
+ };
944
+
945
+ /** Acknowledges data that arrived for a stream the SDK no longer tracks. */
946
+ const consumeUntracked = (
947
+ backend: Minip2pBackend,
948
+ inner: StreamDataEvent["inner"]
949
+ ): void => {
950
+ try {
951
+ backend.streamConsumer(inner.connId, inner.streamId)(inner.data.byteLength);
952
+ } catch {
953
+ // Settled already, or its connection is gone: nothing to release.
954
+ }
955
+ };
956
+
428
957
  /** Events emitted by a negotiated {@link Stream}. */
429
958
  export interface StreamEventMap {
430
959
  /** A received binary chunk. */
@@ -433,11 +962,8 @@ export interface StreamEventMap {
433
962
  remoteWriteClosed: void;
434
963
  /** The stream reached a terminal state. */
435
964
  closed: void;
436
- /** Incoming data exceeded the bounded pull-read buffer. */
437
- dataOverflow: {
438
- readonly droppedChunks: number;
439
- readonly droppedBytes: number;
440
- };
965
+ /** The remote asked this side to stop writing; pending writes rejected. */
966
+ writeStopped: { readonly errorCode: bigint };
441
967
  }
442
968
 
443
969
  /**
@@ -452,11 +978,13 @@ export class Minip2pBase {
452
978
  readonly #catchAll = new Set<CatchAllHandler>();
453
979
  readonly #closeHandlers = new Set<(reason: CloseReason) => void>();
454
980
  readonly #waiters = new Set<EventWaiter>();
455
- readonly #queue = new BoundedQueue<QueueItem>(EVENT_QUEUE_CAP);
981
+ readonly #queue = new EventQueue(EVENT_QUEUE_CAP, (item) => {
982
+ this.#releaseQueueItem(item);
983
+ });
456
984
  readonly #connects = new Map<number, ConnectAttempt>();
457
985
  readonly #terminalConnects = new Set<number>();
458
- readonly #streams = new Map<string, Stream>();
459
- readonly #pendingOpens = new Map<string, PendingOpen>();
986
+ readonly #streams = new StreamTable<Stream>();
987
+ readonly #pendingOpens = new StreamTable<PendingOpen>();
460
988
  readonly #pings = new Map<string, PingOperation>();
461
989
  #dropped = 0;
462
990
  #flushScheduled = false;
@@ -879,8 +1407,10 @@ export class Minip2pBase {
879
1407
  pending.removeAbort = listenAbort(options.signal, () => {
880
1408
  this.#expireOpen(pending, new AbortError());
881
1409
  });
882
- const key = pendingOpenKey(peerId, identity.connId, identity.streamId);
883
- const overwritten = this.#pendingOpens.get(key);
1410
+ const overwritten = this.#pendingOpens.get(
1411
+ identity.connId,
1412
+ identity.streamId
1413
+ );
884
1414
  if (overwritten !== undefined) {
885
1415
  clearPendingOpen(overwritten);
886
1416
  overwritten.reject(
@@ -893,7 +1423,7 @@ export class Minip2pBase {
893
1423
  })
894
1424
  );
895
1425
  }
896
- this.#pendingOpens.set(key, pending);
1426
+ this.#pendingOpens.set(identity.connId, identity.streamId, pending);
897
1427
  });
898
1428
  }
899
1429
 
@@ -1095,7 +1625,7 @@ export class Minip2pBase {
1095
1625
  this.#connectResultsLost(event.inner.terminalConnectIds);
1096
1626
  }
1097
1627
  }
1098
- for (const pending of this.#pendingOpens.values()) {
1628
+ for (const pending of this.#pendingOpens.takeAll()) {
1099
1629
  clearPendingOpen(pending);
1100
1630
  pending.reject(error);
1101
1631
  try {
@@ -1108,7 +1638,6 @@ export class Minip2pBase {
1108
1638
  // The operation is already failed; native cleanup is best effort.
1109
1639
  }
1110
1640
  }
1111
- this.#pendingOpens.clear();
1112
1641
  }
1113
1642
 
1114
1643
  #enqueueNative(event: P2pEvent): void {
@@ -1204,11 +1733,7 @@ export class Minip2pBase {
1204
1733
  this.#streamReady(event.inner);
1205
1734
  return;
1206
1735
  }
1207
- if (
1208
- event.tag === P2pEvent_Tags.StreamData ||
1209
- event.tag === P2pEvent_Tags.StreamRemoteWriteClosed ||
1210
- event.tag === P2pEvent_Tags.StreamClosed
1211
- ) {
1736
+ if (isStreamEvent(event)) {
1212
1737
  this.#streamEvent(event);
1213
1738
  return;
1214
1739
  }
@@ -1217,7 +1742,6 @@ export class Minip2pBase {
1217
1742
  }
1218
1743
  if (event.tag === P2pEvent_Tags.ConnectionClosed) {
1219
1744
  this.#connectionEnded(
1220
- event.inner.peerId,
1221
1745
  event.inner.connId,
1222
1746
  new PeerDisconnectedError(event.inner.peerId, "stream"),
1223
1747
  new PeerDisconnectedError(event.inner.peerId, "openStream")
@@ -1227,7 +1751,6 @@ export class Minip2pBase {
1227
1751
  // Native ends the replaced connection's streams without per-stream
1228
1752
  // terminal events, so they end here.
1229
1753
  this.#connectionEnded(
1230
- event.inner.peerId,
1231
1754
  event.inner.oldConnId,
1232
1755
  new StreamClosedError("The stream's connection was replaced"),
1233
1756
  new StreamClosedError(
@@ -1243,13 +1766,11 @@ export class Minip2pBase {
1243
1766
  }
1244
1767
 
1245
1768
  const normalized = normalizeEvent(event);
1246
- if (normalized !== undefined) {
1247
- this.#dispatch(
1248
- normalized.type as never,
1249
- normalized.payload as never,
1250
- normalized.payload as never
1251
- );
1252
- }
1769
+ this.#dispatch(
1770
+ normalized.type as never,
1771
+ normalized.payload as never,
1772
+ normalized.payload as never
1773
+ );
1253
1774
  }
1254
1775
 
1255
1776
  #dispatch<Kind extends EventKind>(
@@ -1260,11 +1781,13 @@ export class Minip2pBase {
1260
1781
  : never
1261
1782
  ): boolean {
1262
1783
  let claimed = false;
1263
- const result = eventResult(type, payload);
1264
- for (const waiter of [...this.#waiters]) {
1784
+ // Built only once a waiter of this type is found.
1785
+ let result: ({ readonly type: Kind } & typeof payload) | undefined;
1786
+ for (const waiter of this.#waiters.size > 0 ? [...this.#waiters] : []) {
1265
1787
  if (waiter.type !== type) {
1266
1788
  continue;
1267
1789
  }
1790
+ result ??= eventResult(type, payload);
1268
1791
  let matched = false;
1269
1792
  try {
1270
1793
  matched = waiter.predicate(result as never);
@@ -1292,7 +1815,8 @@ export class Minip2pBase {
1292
1815
  this.#handlerFailed(type, payload, error);
1293
1816
  }
1294
1817
  }
1295
- if (type !== "stream") {
1818
+ if (type !== "stream" && this.#catchAll.size > 0) {
1819
+ // Its own object: a waiter's resolved event is never a catch-all's.
1296
1820
  const catchEvent = eventResult(
1297
1821
  type as keyof Minip2pCatchAllEventMap,
1298
1822
  catchPayload as Minip2pCatchAllEventMap[keyof Minip2pCatchAllEventMap]
@@ -1323,15 +1847,13 @@ export class Minip2pBase {
1323
1847
  }
1324
1848
 
1325
1849
  #streamReady(meta: InboundStreamMeta): void {
1326
- const key = streamKey(meta.peerId, meta.connId, meta.streamId);
1327
1850
  const stream = new Stream(this.#backend, meta, () => {
1328
- this.#streams.delete(key);
1851
+ this.#streams.delete(meta.connId, meta.streamId);
1329
1852
  });
1330
- this.#streams.set(key, stream);
1331
- const pendingKey = pendingOpenKey(meta.peerId, meta.connId, meta.streamId);
1332
- const pending = this.#pendingOpens.get(pendingKey);
1853
+ this.#streams.set(meta.connId, meta.streamId, stream);
1854
+ const pending = this.#pendingOpens.get(meta.connId, meta.streamId);
1333
1855
  if (pending !== undefined && meta.initiatedLocally) {
1334
- this.#pendingOpens.delete(pendingKey);
1856
+ this.#pendingOpens.delete(meta.connId, meta.streamId);
1335
1857
  clearPendingOpen(pending);
1336
1858
  pending.resolve(stream);
1337
1859
  return;
@@ -1366,24 +1888,13 @@ export class Minip2pBase {
1366
1888
  }
1367
1889
  }
1368
1890
 
1369
- #streamEvent(
1370
- event: Extract<
1371
- P2pEvent,
1372
- {
1373
- readonly tag:
1374
- | typeof P2pEvent_Tags.StreamData
1375
- | typeof P2pEvent_Tags.StreamRemoteWriteClosed
1376
- | typeof P2pEvent_Tags.StreamClosed;
1377
- }
1378
- >
1379
- ): void {
1380
- const { peerId, connId, streamId } = event.inner;
1381
- const stream = this.#streams.get(streamKey(peerId, connId, streamId));
1891
+ #streamEvent(event: StreamP2pEvent): void {
1892
+ const { connId, streamId } = event.inner;
1893
+ const stream = this.#streams.get(connId, streamId);
1382
1894
  if (event.tag === P2pEvent_Tags.StreamClosed) {
1383
- const pendingKey = pendingOpenKey(peerId, connId, streamId);
1384
- const pending = this.#pendingOpens.get(pendingKey);
1895
+ const pending = this.#pendingOpens.get(connId, streamId);
1385
1896
  if (pending !== undefined) {
1386
- this.#pendingOpens.delete(pendingKey);
1897
+ this.#pendingOpens.delete(connId, streamId);
1387
1898
  clearPendingOpen(pending);
1388
1899
  pending.reject(new StreamClosedError());
1389
1900
  }
@@ -1391,7 +1902,18 @@ export class Minip2pBase {
1391
1902
  preserveRemoteEof: true,
1392
1903
  });
1393
1904
  } else if (event.tag === P2pEvent_Tags.StreamData) {
1394
- stream?.receive(event.inner.data);
1905
+ if (stream === undefined) {
1906
+ // Nothing will read it, so it is consumed now: an abandon that
1907
+ // native refused (the stream had already closed there) leaves the
1908
+ // bytes holding the native stream slot otherwise.
1909
+ consumeUntracked(this.#backend, event.inner);
1910
+ } else {
1911
+ stream.receive(event.inner.data);
1912
+ }
1913
+ } else if (event.tag === P2pEvent_Tags.StreamWriteAccepted) {
1914
+ stream?.writeAccepted();
1915
+ } else if (event.tag === P2pEvent_Tags.StreamWriteStopped) {
1916
+ stream?.writeStopped(event.inner.errorCode);
1395
1917
  } else {
1396
1918
  stream?.remoteWriteClosed();
1397
1919
  }
@@ -1406,12 +1928,14 @@ export class Minip2pBase {
1406
1928
  if (error.streamId === undefined) {
1407
1929
  return;
1408
1930
  }
1409
- const candidates = [...this.#pendingOpens.values()].filter(
1410
- (pending) =>
1411
- pending.streamId === error.streamId &&
1412
- (error.peerId === undefined || error.peerId === pending.peerId) &&
1413
- (error.connId === undefined || error.connId === pending.connId)
1414
- );
1931
+ const candidates = this.#pendingOpens
1932
+ .values()
1933
+ .filter(
1934
+ (pending) =>
1935
+ pending.streamId === error.streamId &&
1936
+ (error.peerId === undefined || error.peerId === pending.peerId) &&
1937
+ (error.connId === undefined || error.connId === pending.connId)
1938
+ );
1415
1939
  if (candidates.length !== 1) {
1416
1940
  return;
1417
1941
  }
@@ -1419,9 +1943,7 @@ export class Minip2pBase {
1419
1943
  if (pending === undefined) {
1420
1944
  return;
1421
1945
  }
1422
- this.#pendingOpens.delete(
1423
- pendingOpenKey(pending.peerId, pending.connId, pending.streamId)
1424
- );
1946
+ this.#pendingOpens.delete(pending.connId, pending.streamId);
1425
1947
  clearPendingOpen(pending);
1426
1948
  pending.reject(
1427
1949
  new OpenStreamError({
@@ -1435,26 +1957,13 @@ export class Minip2pBase {
1435
1957
  }
1436
1958
 
1437
1959
  /** Ends every stream and pending open on a closed or replaced connection. */
1438
- #connectionEnded(
1439
- peerId: string,
1440
- connId: number,
1441
- streamError: Error,
1442
- openError: Error
1443
- ): void {
1444
- for (const [key, stream] of [...this.#streams]) {
1445
- if (stream.peerId === peerId && stream.connId === connId) {
1446
- stream.terminal(streamError);
1447
- this.#streams.delete(key);
1448
- }
1960
+ #connectionEnded(connId: number, streamError: Error, openError: Error): void {
1961
+ for (const stream of this.#streams.takeConnection(connId)) {
1962
+ stream.terminal(streamError);
1449
1963
  }
1450
- for (const pending of [...this.#pendingOpens.values()]) {
1451
- if (pending.peerId === peerId && pending.connId === connId) {
1452
- this.#pendingOpens.delete(
1453
- pendingOpenKey(pending.peerId, pending.connId, pending.streamId)
1454
- );
1455
- clearPendingOpen(pending);
1456
- pending.reject(openError);
1457
- }
1964
+ for (const pending of this.#pendingOpens.takeConnection(connId)) {
1965
+ clearPendingOpen(pending);
1966
+ pending.reject(openError);
1458
1967
  }
1459
1968
  }
1460
1969
 
@@ -1551,15 +2060,10 @@ export class Minip2pBase {
1551
2060
  }
1552
2061
 
1553
2062
  #expireOpen(pending: PendingOpen, error: unknown): void {
1554
- const key = pendingOpenKey(
1555
- pending.peerId,
1556
- pending.connId,
1557
- pending.streamId
1558
- );
1559
- if (this.#pendingOpens.get(key) !== pending) {
2063
+ if (this.#pendingOpens.get(pending.connId, pending.streamId) !== pending) {
1560
2064
  return;
1561
2065
  }
1562
- this.#pendingOpens.delete(key);
2066
+ this.#pendingOpens.delete(pending.connId, pending.streamId);
1563
2067
  clearPendingOpen(pending);
1564
2068
  pending.reject(error);
1565
2069
  try {
@@ -1613,15 +2117,13 @@ export class Minip2pBase {
1613
2117
  }
1614
2118
  this.#connects.clear();
1615
2119
  this.#terminalConnects.clear();
1616
- for (const pending of this.#pendingOpens.values()) {
2120
+ for (const pending of this.#pendingOpens.takeAll()) {
1617
2121
  clearPendingOpen(pending);
1618
2122
  pending.reject(error);
1619
2123
  }
1620
- this.#pendingOpens.clear();
1621
- for (const stream of this.#streams.values()) {
2124
+ for (const stream of this.#streams.takeAll()) {
1622
2125
  stream.terminal(error);
1623
2126
  }
1624
- this.#streams.clear();
1625
2127
  for (const ping of this.#pings.values()) {
1626
2128
  ping.cancel(error);
1627
2129
  }
@@ -1674,63 +2176,70 @@ function toBackendTarget(target: ConnectTarget): BackendConnectTarget {
1674
2176
  : { kind: "peer", peerId: target };
1675
2177
  }
1676
2178
 
2179
+ /** Native events the SDK handles itself rather than dispatching by name. */
2180
+ type UnnamedEventTag =
2181
+ | StreamP2pEvent["tag"]
2182
+ | typeof P2pEvent_Tags.DriverFailed
2183
+ | typeof P2pEvent_Tags.StreamReady;
2184
+ type NamedEventTag = Exclude<P2pEventTag, UnnamedEventTag>;
2185
+
2186
+ /**
2187
+ * SDK event names for every native event that dispatches by name. Each name
2188
+ * is its tag uncapitalized, so a wrong mapping fails to compile.
2189
+ */
2190
+ const SDK_EVENT_NAMES: {
2191
+ readonly [Tag in NamedEventTag]: Uncapitalize<Tag>;
2192
+ } = {
2193
+ [P2pEvent_Tags.EventsDropped]: "eventsDropped",
2194
+ [P2pEvent_Tags.ConnectionEstablished]: "connectionEstablished",
2195
+ [P2pEvent_Tags.ConnectionClosed]: "connectionClosed",
2196
+ [P2pEvent_Tags.ConnectionReplaced]: "connectionReplaced",
2197
+ [P2pEvent_Tags.PeerReady]: "peerReady",
2198
+ [P2pEvent_Tags.IdentifyReceived]: "identifyReceived",
2199
+ [P2pEvent_Tags.PingRttMeasured]: "pingRttMeasured",
2200
+ [P2pEvent_Tags.PingTimeout]: "pingTimeout",
2201
+ [P2pEvent_Tags.EndpointError]: "endpointError",
2202
+ [P2pEvent_Tags.ReachabilityChanged]: "reachabilityChanged",
2203
+ [P2pEvent_Tags.PublicAddressesChanged]: "publicAddressesChanged",
2204
+ [P2pEvent_Tags.RelayReserved]: "relayReserved",
2205
+ [P2pEvent_Tags.RelayReservationLost]: "relayReservationLost",
2206
+ [P2pEvent_Tags.PathEstablished]: "pathEstablished",
2207
+ [P2pEvent_Tags.InboundPathEstablished]: "inboundPathEstablished",
2208
+ [P2pEvent_Tags.PathUpgraded]: "pathUpgraded",
2209
+ [P2pEvent_Tags.HolePunchFailed]: "holePunchFailed",
2210
+ [P2pEvent_Tags.ConnectFailed]: "connectFailed",
2211
+ [P2pEvent_Tags.ConnectCancelled]: "connectCancelled",
2212
+ [P2pEvent_Tags.InboundDirectUpgrade]: "inboundDirectUpgrade",
2213
+ [P2pEvent_Tags.Message]: "message",
2214
+ [P2pEvent_Tags.PeerSubscribed]: "peerSubscribed",
2215
+ [P2pEvent_Tags.PeerUnsubscribed]: "peerUnsubscribed",
2216
+ [P2pEvent_Tags.GossipsubOutboundFailure]: "gossipsubOutboundFailure",
2217
+ [P2pEvent_Tags.GossipsubProtocolViolation]: "gossipsubProtocolViolation",
2218
+ [P2pEvent_Tags.PeerDiscovered]: "peerDiscovered",
2219
+ [P2pEvent_Tags.PeerUpdated]: "peerUpdated",
2220
+ [P2pEvent_Tags.PeerExpired]: "peerExpired",
2221
+ [P2pEvent_Tags.DiscoveryDialFailed]: "discoveryDialFailed",
2222
+ [P2pEvent_Tags.DiscoveryProtocolViolation]: "discoveryProtocolViolation",
2223
+ };
2224
+
1677
2225
  function normalizeEvent(
1678
2226
  event: Exclude<
1679
2227
  P2pEvent,
1680
- {
1681
- readonly tag:
1682
- | typeof P2pEvent_Tags.DriverFailed
1683
- | typeof P2pEvent_Tags.StreamReady
1684
- | typeof P2pEvent_Tags.StreamData
1685
- | typeof P2pEvent_Tags.StreamRemoteWriteClosed
1686
- | typeof P2pEvent_Tags.StreamClosed;
1687
- }
2228
+ | StreamP2pEvent
2229
+ | {
2230
+ readonly tag:
2231
+ | typeof P2pEvent_Tags.DriverFailed
2232
+ | typeof P2pEvent_Tags.StreamReady;
2233
+ }
1688
2234
  >
1689
- ):
1690
- | {
1691
- type: Exclude<
1692
- EventKind,
1693
- "stream" | "queueOverflow" | "handlerError" | "driverFailed"
1694
- >;
1695
- payload: AnyPayload;
1696
- }
1697
- | undefined {
1698
- const names: Partial<Record<string, EventKind>> = {
1699
- [P2pEvent_Tags.EventsDropped]: "eventsDropped",
1700
- [P2pEvent_Tags.ConnectionEstablished]: "connectionEstablished",
1701
- [P2pEvent_Tags.ConnectionClosed]: "connectionClosed",
1702
- [P2pEvent_Tags.ConnectionReplaced]: "connectionReplaced",
1703
- [P2pEvent_Tags.PeerReady]: "peerReady",
1704
- [P2pEvent_Tags.IdentifyReceived]: "identifyReceived",
1705
- [P2pEvent_Tags.PingRttMeasured]: "pingRttMeasured",
1706
- [P2pEvent_Tags.PingTimeout]: "pingTimeout",
1707
- [P2pEvent_Tags.EndpointError]: "endpointError",
1708
- [P2pEvent_Tags.ReachabilityChanged]: "reachabilityChanged",
1709
- [P2pEvent_Tags.PublicAddressesChanged]: "publicAddressesChanged",
1710
- [P2pEvent_Tags.RelayReserved]: "relayReserved",
1711
- [P2pEvent_Tags.RelayReservationLost]: "relayReservationLost",
1712
- [P2pEvent_Tags.PathEstablished]: "pathEstablished",
1713
- [P2pEvent_Tags.InboundPathEstablished]: "inboundPathEstablished",
1714
- [P2pEvent_Tags.PathUpgraded]: "pathUpgraded",
1715
- [P2pEvent_Tags.HolePunchFailed]: "holePunchFailed",
1716
- [P2pEvent_Tags.ConnectFailed]: "connectFailed",
1717
- [P2pEvent_Tags.ConnectCancelled]: "connectCancelled",
1718
- [P2pEvent_Tags.InboundDirectUpgrade]: "inboundDirectUpgrade",
1719
- [P2pEvent_Tags.Message]: "message",
1720
- [P2pEvent_Tags.PeerSubscribed]: "peerSubscribed",
1721
- [P2pEvent_Tags.PeerUnsubscribed]: "peerUnsubscribed",
1722
- [P2pEvent_Tags.GossipsubOutboundFailure]: "gossipsubOutboundFailure",
1723
- [P2pEvent_Tags.GossipsubProtocolViolation]: "gossipsubProtocolViolation",
1724
- [P2pEvent_Tags.PeerDiscovered]: "peerDiscovered",
1725
- [P2pEvent_Tags.PeerUpdated]: "peerUpdated",
1726
- [P2pEvent_Tags.PeerExpired]: "peerExpired",
1727
- [P2pEvent_Tags.DiscoveryDialFailed]: "discoveryDialFailed",
1728
- [P2pEvent_Tags.DiscoveryProtocolViolation]: "discoveryProtocolViolation",
1729
- };
1730
- const type = names[event.tag];
1731
- if (type === undefined) {
1732
- return undefined;
1733
- }
2235
+ ): {
2236
+ type: Exclude<
2237
+ EventKind,
2238
+ "stream" | "queueOverflow" | "handlerError" | "driverFailed"
2239
+ >;
2240
+ payload: AnyPayload;
2241
+ } {
2242
+ const type = SDK_EVENT_NAMES[event.tag];
1734
2243
  let payload: unknown = event.inner;
1735
2244
  if (event.tag === P2pEvent_Tags.PathEstablished) {
1736
2245
  payload = { ...event.inner, path: normalizePath(event.inner.path) };
@@ -1743,7 +2252,7 @@ function normalizeEvent(
1743
2252
  to: normalizePath(event.inner.to),
1744
2253
  };
1745
2254
  }
1746
- return { payload: payload as AnyPayload, type: type as never };
2255
+ return { payload: payload as AnyPayload, type };
1747
2256
  }
1748
2257
 
1749
2258
  function normalizePath(path: PathKind): Path {
@@ -1760,18 +2269,6 @@ function normalizePath(path: PathKind): Path {
1760
2269
  }
1761
2270
  }
1762
2271
 
1763
- function streamKey(peerId: string, connId: number, streamId: number): string {
1764
- return `${peerId}\u0000${connId}\u0000${streamId}`;
1765
- }
1766
-
1767
- function pendingOpenKey(
1768
- peerId: string,
1769
- connId: number,
1770
- streamId: number
1771
- ): string {
1772
- return streamKey(peerId, connId, streamId);
1773
- }
1774
-
1775
2272
  function streamMeta(stream: Stream): InboundStreamMeta {
1776
2273
  return {
1777
2274
  connId: stream.connId,