@minip2p/core 0.8.3 → 0.10.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/src/sdk.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /* oxlint-disable default-case, func-style, max-classes-per-file, no-await-in-loop, no-empty-function, no-loop-func, no-use-before-define, promise/avoid-new, promise/prefer-await-to-callbacks, promise/prefer-await-to-then, typescript/no-invalid-void-type, unicorn/consistent-function-scoping, unicorn/no-new-array, unicorn/no-useless-spread, unicorn/no-useless-undefined -- Promise adapters, sequential async iterators, void event payloads, snapshot fan-out, and bounded queues are deliberate SDK internals. */
2
2
 
3
- import type { BackendConnectTarget, Minip2pBackend } from "./backend.js";
3
+ import type {
4
+ BackendClosed,
5
+ BackendConnectTarget,
6
+ Minip2pBackend,
7
+ } from "./backend.js";
4
8
  import {
5
9
  AbortError,
6
10
  ClosedError,
@@ -16,14 +20,20 @@ import {
16
20
  TimeoutError,
17
21
  WriteBufferFullError,
18
22
  } from "./errors.js";
19
- import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
23
+ import {
24
+ CloseOutcome,
25
+ ConnectionCloseReason_Tags,
26
+ P2pEvent_Tags,
27
+ PathKind_Tags,
28
+ } from "./types.js";
20
29
  import type {
21
30
  Bytes,
22
- CloseReason,
31
+ ConnectionCloseReason,
23
32
  ConnectionInfo,
24
33
  ConnectOptions,
25
34
  ConnectResult,
26
35
  ConnectTarget,
36
+ EndpointCloseReport,
27
37
  EventsOptions,
28
38
  IdentifyInfo,
29
39
  InboundStreamMeta,
@@ -37,6 +47,7 @@ import type {
37
47
  P2pEventTag,
38
48
  Path,
39
49
  PathKind,
50
+ RawConnectionCloseReason,
40
51
  Reachability,
41
52
  RelayReservationInfo,
42
53
  Unsubscribe,
@@ -48,6 +59,11 @@ declare const TextEncoder: new () => {
48
59
  };
49
60
 
50
61
  const DEFAULT_TIMEOUT_MS = 65_000;
62
+ /**
63
+ * Default close drain: the Rust `minip2p::DEFAULT_CLOSE_TIMEOUT` (500 ms)
64
+ * that `Endpoint::close` and native's `DEFAULT_STOP_TIMEOUT_MS` use.
65
+ */
66
+ const DEFAULT_CLOSE_TIMEOUT_MS = 500;
51
67
  const EVENT_QUEUE_CAP = 4096;
52
68
  const EVENT_FLUSH_BATCH = 256;
53
69
  const CONNECT_TERMINAL_CAP = 1024;
@@ -328,6 +344,33 @@ class StreamTable<Value> {
328
344
  }
329
345
  }
330
346
 
347
+ /** Every connection a native event names. */
348
+ const connectionsOf = (event: P2pEvent): number[] => {
349
+ if (!("inner" in event)) {
350
+ return [];
351
+ }
352
+ const { inner } = event;
353
+ return [
354
+ "connId" in inner ? inner.connId : undefined,
355
+ "oldConnId" in inner ? inner.oldConnId : undefined,
356
+ "newConnId" in inner ? inner.newConnId : undefined,
357
+ ].filter((id): id is number => typeof id === "number");
358
+ };
359
+
360
+ /**
361
+ * Native events that leave a connection unseen. Anything else naming it is
362
+ * something the application acts on or must hear about, so it keeps the
363
+ * connection's events.
364
+ */
365
+ const UNSEEN_CONNECTION_TAGS: ReadonlySet<string> = new Set<P2pEvent["tag"]>([
366
+ P2pEvent_Tags.PeerReady,
367
+ P2pEvent_Tags.IdentifyReceived,
368
+ P2pEvent_Tags.EndpointError,
369
+ P2pEvent_Tags.StreamRemoteWriteClosed,
370
+ P2pEvent_Tags.StreamWriteStopped,
371
+ P2pEvent_Tags.StreamClosed,
372
+ ]);
373
+
331
374
  /** The native per-stream event an item carries, if any. */
332
375
  const streamEventOf = (
333
376
  item: QueueItem
@@ -348,6 +391,15 @@ const streamEventOf = (
348
391
  * A peer-opened stream that closes without data before its `StreamReady`
349
392
  * is dispatched leaves the queue whole, so a peer opening and closing
350
393
  * streams cannot grow it; its events still reach `release`.
394
+ *
395
+ * Connections follow the same rule (ADR 0012): one that ends without data
396
+ * before any of its events was dispatched, whichever side dialed it, leaves
397
+ * with every event naming it. One replaced instead folds into its
398
+ * successor: its queued `ConnectionEstablished` is renamed to the successor
399
+ * and the `ConnectionReplaced` goes (as it does when the capacity already
400
+ * dropped that `ConnectionEstablished`). A connection the application knows
401
+ * otherwise -- a stream it opened, a ping result, an attempt or path event
402
+ * naming it -- is kept.
351
403
  */
352
404
  class EventQueue {
353
405
  readonly #items = new Map<number, QueueItem>();
@@ -359,6 +411,14 @@ class EventQueue {
359
411
  * queued item ids; `undefined` once one carried data.
360
412
  */
361
413
  readonly #unseen = new StreamTable<number[] | undefined>();
414
+ /** Connections whose `ConnectionEstablished` is queued and unseen. */
415
+ readonly #unseenConnections = new Set<number>();
416
+ /**
417
+ * Live connections the application learned of outside the queue, so a
418
+ * later replacement fold must not make them unseen; each leaves with its
419
+ * end.
420
+ */
421
+ readonly #knownConnections = new Set<number>();
362
422
  readonly #capacity: number;
363
423
  readonly #release: (item: QueueItem) => void;
364
424
  #next = 0;
@@ -380,14 +440,14 @@ class EventQueue {
380
440
  const merged =
381
441
  newest === undefined ? undefined : coalesceData(newest, item);
382
442
  if (merged !== undefined && this.#newest !== undefined) {
383
- // A data event retires no adapter IDs, so the absorbed one needs no
384
- // `eventHandled`.
385
443
  this.#items.set(this.#newest, merged);
444
+ // The absorbed event is handled: its adapter state goes now.
445
+ this.#release(item);
386
446
  return undefined;
387
447
  }
388
448
  const id = this.#next;
389
449
  this.#next += 1;
390
- if (this.#elideUnseen(item, id)) {
450
+ if (this.#elideUnseen(item, id) || this.#elideConnection(item)) {
391
451
  return undefined;
392
452
  }
393
453
  this.#items.set(id, item);
@@ -410,15 +470,114 @@ class EventQueue {
410
470
  return undefined;
411
471
  }
412
472
  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);
473
+ if (item?.source === "native") {
474
+ if (item.event.tag === P2pEvent_Tags.StreamReady) {
475
+ this.#unseen.delete(item.event.inner.connId, item.event.inner.streamId);
476
+ }
477
+ for (const connId of connectionsOf(item.event)) {
478
+ this.#unseenConnections.delete(connId);
479
+ }
418
480
  }
419
481
  return item;
420
482
  }
421
483
 
484
+ /** The application learned of `connId` outside the queue. */
485
+ markConnectionSeen(connId: number): void {
486
+ this.#unseenConnections.delete(connId);
487
+ this.#knownConnections.add(connId);
488
+ }
489
+
490
+ /**
491
+ * Records `item` against the unseen connections it names. Returns whether
492
+ * it ended or replaced one that carried no data, which leaves the queue
493
+ * with that connection's items instead.
494
+ */
495
+ #elideConnection(item: QueueItem): boolean {
496
+ if (item.source !== "native") {
497
+ return false;
498
+ }
499
+ const { event } = item;
500
+ switch (event.tag) {
501
+ case P2pEvent_Tags.ConnectionEstablished: {
502
+ if (!this.#knownConnections.has(event.inner.connId)) {
503
+ this.#unseenConnections.add(event.inner.connId);
504
+ }
505
+ return false;
506
+ }
507
+ case P2pEvent_Tags.ConnectionClosed: {
508
+ this.#knownConnections.delete(event.inner.connId);
509
+ if (!this.#unseenConnections.delete(event.inner.connId)) {
510
+ return false;
511
+ }
512
+ this.#removeConnection(event.inner.connId);
513
+ this.#release(item);
514
+ return true;
515
+ }
516
+ case P2pEvent_Tags.ConnectionReplaced: {
517
+ const { newConnId, oldConnId } = event.inner;
518
+ this.#knownConnections.delete(oldConnId);
519
+ if (!this.#unseenConnections.delete(oldConnId)) {
520
+ return false;
521
+ }
522
+ this.#renameOpening(oldConnId, newConnId);
523
+ this.#removeConnection(oldConnId);
524
+ if (!this.#knownConnections.has(newConnId)) {
525
+ this.#unseenConnections.add(newConnId);
526
+ }
527
+ this.#release(item);
528
+ return true;
529
+ }
530
+ case P2pEvent_Tags.StreamReady: {
531
+ if (event.inner.initiatedLocally) {
532
+ this.#unseenConnections.delete(event.inner.connId);
533
+ }
534
+ return false;
535
+ }
536
+ default: {
537
+ if (!UNSEEN_CONNECTION_TAGS.has(event.tag)) {
538
+ for (const connId of connectionsOf(event)) {
539
+ this.#unseenConnections.delete(connId);
540
+ }
541
+ }
542
+ return false;
543
+ }
544
+ }
545
+ }
546
+
547
+ /** Renames the queued `ConnectionEstablished` of `from` to `to`. */
548
+ #renameOpening(from: number, to: number): void {
549
+ for (const [id, queued] of this.#items) {
550
+ if (
551
+ queued.source === "native" &&
552
+ queued.event.tag === P2pEvent_Tags.ConnectionEstablished &&
553
+ queued.event.inner.connId === from
554
+ ) {
555
+ this.#items.set(id, {
556
+ event: {
557
+ ...queued.event,
558
+ inner: { ...queued.event.inner, connId: to },
559
+ },
560
+ source: "native",
561
+ });
562
+ return;
563
+ }
564
+ }
565
+ }
566
+
567
+ /** Removes every queued item naming `connId`, releasing each. */
568
+ #removeConnection(connId: number): void {
569
+ for (const [id, queued] of [...this.#items]) {
570
+ if (
571
+ queued.source === "native" &&
572
+ connectionsOf(queued.event).includes(connId)
573
+ ) {
574
+ this.#remove(id);
575
+ this.#release(queued);
576
+ }
577
+ }
578
+ this.#unseen.takeConnection(connId);
579
+ }
580
+
422
581
  /**
423
582
  * Records `item` (as `id`) against an unseen peer stream. Returns whether
424
583
  * it closed one that carried no data, which leaves the queue whole.
@@ -971,7 +1130,7 @@ export class Minip2pBase {
971
1130
  readonly #relayAddrs: readonly string[];
972
1131
  readonly #named = new Map<EventKind, Set<(payload: AnyPayload) => void>>();
973
1132
  readonly #catchAll = new Set<CatchAllHandler>();
974
- readonly #closeHandlers = new Set<(reason: CloseReason) => void>();
1133
+ readonly #closeHandlers = new Set<(report: EndpointCloseReport) => void>();
975
1134
  readonly #waiters = new Set<EventWaiter>();
976
1135
  readonly #queue = new EventQueue(EVENT_QUEUE_CAP, (item) => {
977
1136
  this.#releaseQueueItem(item);
@@ -984,6 +1143,9 @@ export class Minip2pBase {
984
1143
  #dropped = 0;
985
1144
  #flushScheduled = false;
986
1145
  #closed = false;
1146
+ /** Settles once the native drain finished and close observers ran. */
1147
+ #closing: Promise<EndpointCloseReport> | undefined;
1148
+ #closeReported = false;
987
1149
 
988
1150
  protected constructor(
989
1151
  backend: Minip2pBackend,
@@ -996,7 +1158,7 @@ export class Minip2pBase {
996
1158
  this.#enqueueNative(event);
997
1159
  });
998
1160
  } catch (error) {
999
- backend.close();
1161
+ void backend.close(0);
1000
1162
  throw error;
1001
1163
  }
1002
1164
  }
@@ -1152,21 +1314,43 @@ export class Minip2pBase {
1152
1314
  });
1153
1315
  }
1154
1316
 
1155
- /** Registers a one-shot endpoint shutdown observer. */
1156
- onClose(handler: (reason: CloseReason) => void): Unsubscribe {
1157
- if (this.#closed) {
1317
+ /**
1318
+ * Registers a one-shot endpoint shutdown observer. It stays registered
1319
+ * through the native close drain and fires once that finishes, with the
1320
+ * same report {@link close} resolves with. A no-op once it has fired.
1321
+ */
1322
+ onClose(handler: (report: EndpointCloseReport) => void): Unsubscribe {
1323
+ if (this.#closeReported) {
1158
1324
  return () => {};
1159
1325
  }
1160
1326
  return subscribe(this.#closeHandlers, handler);
1161
1327
  }
1162
1328
 
1163
- /** Idempotently stops the endpoint and rejects outstanding operations. */
1164
- close(): void {
1165
- this.#teardown({ reason: "close" }, new ClosedError());
1329
+ /**
1330
+ * Stops the endpoint: rejects outstanding operations and drops listeners
1331
+ * at once, then has native disconnect peers and drain for up to
1332
+ * `timeoutMs` (default 500; `0` tears down at once, best effort). Resolves
1333
+ * with the close report once the drain finished, after `onClose`
1334
+ * observers ran; it never rejects. The deadline bounds teardown time only,
1335
+ * not delivery of accepted writes: QUIC discards queued writes and TCP may
1336
+ * abort. Idempotent: a later call returns the same promise, including
1337
+ * after a driver failure closed the endpoint.
1338
+ */
1339
+ close(
1340
+ timeoutMs: number = DEFAULT_CLOSE_TIMEOUT_MS
1341
+ ): Promise<EndpointCloseReport> {
1342
+ assertTimeout(timeoutMs);
1343
+ return this.#teardown(new ClosedError(), timeoutMs);
1166
1344
  }
1167
1345
 
1346
+ /** Starts {@link close} with the default drain, without waiting for it. */
1168
1347
  [Symbol.dispose](): void {
1169
- this.close();
1348
+ void this.close();
1349
+ }
1350
+
1351
+ /** {@link close} with the default drain, for `await using`. */
1352
+ async [Symbol.asyncDispose](): Promise<void> {
1353
+ await this.close();
1170
1354
  }
1171
1355
 
1172
1356
  /** Returns this endpoint's base58 peer ID. */
@@ -1237,17 +1421,27 @@ export class Minip2pBase {
1237
1421
  return this.#backend.reachability();
1238
1422
  }
1239
1423
 
1240
- /** Returns the authoritative active path to `peerId`, if connected. */
1424
+ /**
1425
+ * Returns the path of `peerId`'s established connection; `undefined` only
1426
+ * while the peer is not connected.
1427
+ */
1241
1428
  path(peerId: string): Path | undefined {
1242
1429
  this.#assertOpen();
1243
1430
  const path = this.#backend.path(peerId);
1244
1431
  return path === undefined ? undefined : normalizePath(path);
1245
1432
  }
1246
1433
 
1247
- /** Returns the transport connection selected for `peerId`, if connected. */
1434
+ /**
1435
+ * Returns a snapshot of `peerId`'s established connection: its connection
1436
+ * ID, remote address, path, and Identify protocols once ready;
1437
+ * `undefined` while the peer is not connected.
1438
+ */
1248
1439
  connectionInfo(peerId: string): ConnectionInfo | undefined {
1249
1440
  this.#assertOpen();
1250
- return this.#backend.connectionInfo(peerId);
1441
+ const info = this.#backend.connectionInfo(peerId);
1442
+ return info === undefined
1443
+ ? undefined
1444
+ : { ...info, path: normalizePath(info.path) };
1251
1445
  }
1252
1446
 
1253
1447
  /** Returns whether the native driver is accepting work. */
@@ -1376,6 +1570,8 @@ export class Minip2pBase {
1376
1570
  let identity: { readonly connId: number; readonly streamId: number };
1377
1571
  try {
1378
1572
  identity = this.#backend.openStream(peerId, protocolId);
1573
+ // The application now knows the connection: its end must reach it.
1574
+ this.#queue.markConnectionSeen(identity.connId);
1379
1575
  } catch (error) {
1380
1576
  return Promise.reject(
1381
1577
  new OpenStreamError({
@@ -1713,13 +1909,17 @@ export class Minip2pBase {
1713
1909
  }
1714
1910
 
1715
1911
  #dispatchNative(event: P2pEvent): void {
1912
+ // Backends resolve `close` with it instead of delivering it.
1913
+ if (event.tag === P2pEvent_Tags.EndpointClosed) {
1914
+ return;
1915
+ }
1716
1916
  if (event.tag === P2pEvent_Tags.DriverFailed) {
1717
1917
  const failure = new DriverFailedError(
1718
1918
  event.inner.kind,
1719
1919
  event.inner.detail
1720
1920
  );
1721
1921
  this.#dispatch("driverFailed", event.inner, event.inner);
1722
- this.#teardown({ error: failure, reason: "driverFailed" }, failure);
1922
+ void this.#teardown(failure, 0);
1723
1923
  return;
1724
1924
  }
1725
1925
 
@@ -2088,47 +2288,72 @@ export class Minip2pBase {
2088
2288
  }
2089
2289
  }
2090
2290
 
2091
- #teardown(reason: CloseReason, error: Error): void {
2092
- if (this.#closed) {
2093
- return;
2291
+ /**
2292
+ * Closes the endpoint once, rejecting what is outstanding with `cause`;
2293
+ * later calls return the first call's promise. A
2294
+ * {@link DriverFailedError} cause reports a `driverFailed` close.
2295
+ */
2296
+ #teardown(
2297
+ cause: ClosedError | DriverFailedError,
2298
+ timeoutMs: number
2299
+ ): Promise<EndpointCloseReport> {
2300
+ if (this.#closing !== undefined) {
2301
+ return this.#closing;
2094
2302
  }
2095
2303
  this.#closed = true;
2096
- const closeHandlers = [...this.#closeHandlers];
2097
- this.#closeHandlers.clear();
2098
2304
  this.#clearQueue();
2099
2305
  this.#dropped = 0;
2100
2306
  this.#named.clear();
2101
2307
  this.#catchAll.clear();
2308
+ // Native is asked to close before anything below can call back in: a
2309
+ // re-entrant close returns this promise.
2310
+ let closed: Promise<BackendClosed>;
2311
+ try {
2312
+ closed = this.#backend.close(timeoutMs);
2313
+ } catch {
2314
+ closed = Promise.resolve({
2315
+ outcome: CloseOutcome.Failed,
2316
+ unfinished: [],
2317
+ });
2318
+ }
2319
+ const closing = closed.then(({ outcome, unfinished }) => {
2320
+ const report: EndpointCloseReport =
2321
+ cause instanceof DriverFailedError
2322
+ ? { error: cause, reason: "driverFailed", unfinished }
2323
+ : { outcome, reason: "close", unfinished };
2324
+ this.#closeReported = true;
2325
+ const closeHandlers = [...this.#closeHandlers];
2326
+ this.#closeHandlers.clear();
2327
+ for (const handler of closeHandlers) {
2328
+ try {
2329
+ handler(report);
2330
+ } catch {
2331
+ // Close notification is outside the now-closed event queue.
2332
+ }
2333
+ }
2334
+ return report;
2335
+ });
2336
+ this.#closing = closing;
2102
2337
  for (const waiter of [...this.#waiters]) {
2103
- this.#settleWaiter(waiter, error);
2338
+ this.#settleWaiter(waiter, cause);
2104
2339
  }
2105
2340
  for (const attempt of this.#connects.values()) {
2106
- attempt.settle?.({ error, ok: false });
2341
+ attempt.settle?.({ error: cause, ok: false });
2107
2342
  }
2108
2343
  this.#connects.clear();
2109
2344
  this.#terminalConnects.clear();
2110
2345
  for (const pending of this.#pendingOpens.takeAll()) {
2111
2346
  clearPendingOpen(pending);
2112
- pending.reject(error);
2347
+ pending.reject(cause);
2113
2348
  }
2114
2349
  for (const stream of this.#streams.takeAll()) {
2115
- stream.terminal(error);
2350
+ stream.terminal(cause);
2116
2351
  }
2117
2352
  for (const ping of this.#pings.values()) {
2118
- ping.cancel(error);
2353
+ ping.cancel(cause);
2119
2354
  }
2120
2355
  this.#pings.clear();
2121
- try {
2122
- this.#backend.close();
2123
- } finally {
2124
- for (const handler of closeHandlers) {
2125
- try {
2126
- handler(reason);
2127
- } catch {
2128
- // Close notification is outside the now-closed event queue.
2129
- }
2130
- }
2131
- }
2356
+ return closing;
2132
2357
  }
2133
2358
 
2134
2359
  #assertOpen(): void {
@@ -2170,6 +2395,7 @@ function toBackendTarget(target: ConnectTarget): BackendConnectTarget {
2170
2395
  type UnnamedEventTag =
2171
2396
  | StreamP2pEvent["tag"]
2172
2397
  | typeof P2pEvent_Tags.DriverFailed
2398
+ | typeof P2pEvent_Tags.EndpointClosed
2173
2399
  | typeof P2pEvent_Tags.StreamReady;
2174
2400
  type NamedEventTag = Exclude<P2pEventTag, UnnamedEventTag>;
2175
2401
 
@@ -2209,6 +2435,8 @@ const SDK_EVENT_NAMES: {
2209
2435
  [P2pEvent_Tags.PeerUpdated]: "peerUpdated",
2210
2436
  [P2pEvent_Tags.PeerExpired]: "peerExpired",
2211
2437
  [P2pEvent_Tags.DiscoveryDialFailed]: "discoveryDialFailed",
2438
+ [P2pEvent_Tags.MdnsFailed]: "mdnsFailed",
2439
+ [P2pEvent_Tags.MdnsRecovered]: "mdnsRecovered",
2212
2440
  [P2pEvent_Tags.DiscoveryProtocolViolation]: "discoveryProtocolViolation",
2213
2441
  };
2214
2442
 
@@ -2219,6 +2447,7 @@ function normalizeEvent(
2219
2447
  | {
2220
2448
  readonly tag:
2221
2449
  | typeof P2pEvent_Tags.DriverFailed
2450
+ | typeof P2pEvent_Tags.EndpointClosed
2222
2451
  | typeof P2pEvent_Tags.StreamReady;
2223
2452
  }
2224
2453
  >
@@ -2230,7 +2459,8 @@ function normalizeEvent(
2230
2459
  payload: AnyPayload;
2231
2460
  } {
2232
2461
  const type = SDK_EVENT_NAMES[event.tag];
2233
- let payload: unknown = event.inner;
2462
+ // A native variant without fields arrives without `inner`.
2463
+ let payload: unknown = "inner" in event ? event.inner : {};
2234
2464
  if (event.tag === P2pEvent_Tags.PathEstablished) {
2235
2465
  payload = { ...event.inner, path: normalizePath(event.inner.path) };
2236
2466
  } else if (event.tag === P2pEvent_Tags.InboundPathEstablished) {
@@ -2241,17 +2471,44 @@ function normalizeEvent(
2241
2471
  from: normalizePath(event.inner.from),
2242
2472
  to: normalizePath(event.inner.to),
2243
2473
  };
2474
+ } else if (event.tag === P2pEvent_Tags.ConnectionClosed) {
2475
+ payload = {
2476
+ ...event.inner,
2477
+ reason: normalizeCloseReason(event.inner.reason),
2478
+ };
2244
2479
  }
2245
2480
  return { payload: payload as AnyPayload, type };
2246
2481
  }
2247
2482
 
2483
+ function normalizeCloseReason(
2484
+ reason: RawConnectionCloseReason
2485
+ ): ConnectionCloseReason {
2486
+ switch (reason.tag) {
2487
+ case ConnectionCloseReason_Tags.Local: {
2488
+ return { kind: "local" };
2489
+ }
2490
+ case ConnectionCloseReason_Tags.Remote: {
2491
+ return { code: reason.inner.code, kind: "remote" };
2492
+ }
2493
+ case ConnectionCloseReason_Tags.TimedOut: {
2494
+ return { kind: "timedOut" };
2495
+ }
2496
+ case ConnectionCloseReason_Tags.Stalled: {
2497
+ return { kind: "stalled" };
2498
+ }
2499
+ case ConnectionCloseReason_Tags.Error: {
2500
+ return { kind: "error", message: reason.inner.message };
2501
+ }
2502
+ }
2503
+ }
2504
+
2248
2505
  function normalizePath(path: PathKind): Path {
2249
2506
  switch (path.tag) {
2250
- case PathKind_Tags.DirectDialed: {
2251
- return { kind: "directDialed" };
2507
+ case PathKind_Tags.Direct: {
2508
+ return { kind: "direct" };
2252
2509
  }
2253
- case PathKind_Tags.DirectPunched: {
2254
- return { kind: "directPunched" };
2510
+ case PathKind_Tags.Punched: {
2511
+ return { kind: "punched" };
2255
2512
  }
2256
2513
  case PathKind_Tags.Relayed: {
2257
2514
  return { kind: "relayed", relayPeerId: path.inner.relayPeerId };
@@ -0,0 +1,78 @@
1
+ import { P2pEvent_Tags } from "./types.js";
2
+ import type { P2pEvent } from "./types.js";
3
+
4
+ /** The public stream a backend event names, when it names one. */
5
+ export const eventStream = (
6
+ event: P2pEvent
7
+ ): { readonly connId: number; readonly streamId: number } | undefined => {
8
+ switch (event.tag) {
9
+ case P2pEvent_Tags.StreamReady:
10
+ case P2pEvent_Tags.StreamData:
11
+ case P2pEvent_Tags.StreamWriteAccepted:
12
+ case P2pEvent_Tags.StreamWriteStopped:
13
+ case P2pEvent_Tags.StreamRemoteWriteClosed:
14
+ case P2pEvent_Tags.StreamClosed: {
15
+ return event.inner;
16
+ }
17
+ default: {
18
+ return undefined;
19
+ }
20
+ }
21
+ };
22
+
23
+ /**
24
+ * Native identities of streams whose events the SDK has not finished
25
+ * handling: the acknowledgement-only handle that outlives a stream's
26
+ * connection (ADR 0012).
27
+ *
28
+ * An adapter releases a connection's public ID as soon as it normalizes the
29
+ * event that ends it, so stream operations behind that event fail. Bytes the
30
+ * stream already delivered still hold the ended connection's native slot
31
+ * until they are acknowledged or abandoned, though, and the SDK may only get
32
+ * to them afterwards: dispatching a late `StreamReady`, discarding data for
33
+ * a stream it no longer tracks, or reading bytes kept after a FIN. Each
34
+ * normalized stream event holds its stream's handle until `eventHandled`, so
35
+ * those paths still reach native; a stream consumer captured while it was
36
+ * held keeps working after. With no event left in flight, the handle goes.
37
+ */
38
+ export class SettleHandles<Native> {
39
+ readonly #handles = new Map<
40
+ number,
41
+ Map<number, { native: Native; held: number }>
42
+ >();
43
+
44
+ /** Holds `native` for the stream of one normalized event. */
45
+ hold(connId: number, streamId: number, native: Native): void {
46
+ let streams = this.#handles.get(connId);
47
+ if (streams === undefined) {
48
+ streams = new Map();
49
+ this.#handles.set(connId, streams);
50
+ }
51
+ const handle = streams.get(streamId);
52
+ if (handle === undefined) {
53
+ streams.set(streamId, { held: 1, native });
54
+ } else {
55
+ handle.held += 1;
56
+ }
57
+ }
58
+
59
+ /** Releases one event's hold, once the SDK handled it. */
60
+ release(connId: number, streamId: number): void {
61
+ const streams = this.#handles.get(connId);
62
+ const handle = streams?.get(streamId);
63
+ if (streams === undefined || handle === undefined) {
64
+ return;
65
+ }
66
+ handle.held -= 1;
67
+ if (handle.held === 0) {
68
+ streams.delete(streamId);
69
+ if (streams.size === 0) {
70
+ this.#handles.delete(connId);
71
+ }
72
+ }
73
+ }
74
+
75
+ get(connId: number, streamId: number): Native | undefined {
76
+ return this.#handles.get(connId)?.get(streamId)?.native;
77
+ }
78
+ }