@minip2p/core 0.6.0 → 0.7.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,10 +1,12 @@
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 { Minip2pBackend } from "./backend.js";
3
+ import type { BackendConnectTarget, Minip2pBackend } from "./backend.js";
4
4
  import {
5
5
  AbortError,
6
6
  ClosedError,
7
+ ConnectCancelledError,
7
8
  ConnectFailedError,
9
+ ConnectResultLostError,
8
10
  ConnectResultUnavailableError,
9
11
  DriverFailedError,
10
12
  EventQueueOverflowError,
@@ -17,7 +19,10 @@ import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
17
19
  import type {
18
20
  Bytes,
19
21
  CloseReason,
22
+ ConnectionInfo,
23
+ ConnectOptions,
20
24
  ConnectResult,
25
+ ConnectTarget,
21
26
  EventsOptions,
22
27
  IdentifyInfo,
23
28
  InboundStreamMeta,
@@ -77,14 +82,14 @@ type ConnectTerminal =
77
82
  }
78
83
  | {
79
84
  readonly ok: false;
80
- readonly error: ConnectFailedError;
85
+ readonly error: Error;
81
86
  };
82
87
 
88
+ // A tracked Connection attempt holds either its not-yet-consumed terminal or
89
+ // at most one local wait. The attempt outlives a wait that ends early.
83
90
  interface ConnectAttempt {
84
91
  terminal?: ConnectTerminal;
85
- waiting: boolean;
86
- resolve?: (result: ConnectResult) => void;
87
- reject?: (error: unknown) => void;
92
+ settle?: (terminal: ConnectTerminal) => void;
88
93
  }
89
94
 
90
95
  interface PendingOpen {
@@ -711,6 +716,12 @@ export class Minip2pBase {
711
716
  return path === undefined ? undefined : normalizePath(path);
712
717
  }
713
718
 
719
+ /** Returns the transport connection selected for `peerId`, if connected. */
720
+ connectionInfo(peerId: string): ConnectionInfo | undefined {
721
+ this.#assertOpen();
722
+ return this.#backend.connectionInfo(peerId);
723
+ }
724
+
714
725
  /** Returns whether the native driver is accepting work. */
715
726
  isRunning(): boolean {
716
727
  return !this.#closed && this.#backend.isRunning();
@@ -869,108 +880,119 @@ export class Minip2pBase {
869
880
  });
870
881
  }
871
882
 
872
- /** Starts an advanced NAT-orchestrated connection attempt. */
873
- startConnect(peerId: string): number {
874
- this.#assertOpen();
875
- return this.#rememberConnect(this.#backend.connect(peerId));
876
- }
877
-
878
- /** Starts a connection attempt with an explicit ordered address set. */
879
- startConnectWithAddrs(peerId: string, addresses: readonly string[]): number {
880
- this.#assertOpen();
881
- return this.#rememberConnect(
882
- this.#backend.connectWithAddrs(peerId, addresses)
883
- );
884
- }
885
-
886
- /** Starts a connection attempt from one full peer multiaddress. */
887
- startConnectAddr(address: string): number {
883
+ /**
884
+ * Starts one Connection attempt toward `target` and returns its Connect ID.
885
+ *
886
+ * Every internal dial, relay fallback, and path upgrade belongs to that ID,
887
+ * and the attempt ends with exactly one terminal event: `pathEstablished`,
888
+ * `connectFailed`, or `connectCancelled`. Only malformed targets throw.
889
+ */
890
+ startConnect(target: ConnectTarget): number {
888
891
  this.#assertOpen();
889
- return this.#rememberConnect(this.#backend.connectAddr(address));
890
- }
891
-
892
- /** Connects to a known peer and resolves with its first usable path. */
893
- connect(peerId: string, options: OpOptions = {}): Promise<ConnectResult> {
894
- return this.#primaryConnect(this.startConnect(peerId), options);
895
- }
896
-
897
- /** Connects using an explicit ordered address set. */
898
- connectWithAddrs(
899
- peerId: string,
900
- addresses: readonly string[],
901
- options: OpOptions = {}
902
- ): Promise<ConnectResult> {
903
- return this.#primaryConnect(
904
- this.startConnectWithAddrs(peerId, addresses),
905
- options
906
- );
892
+ const connectId = this.#backend.connect(toBackendTarget(target));
893
+ this.#connects.set(connectId, {});
894
+ return connectId;
907
895
  }
908
896
 
909
- /** Connects using one full peer multiaddress. */
910
- connectAddr(
911
- address: string,
912
- options: OpOptions = {}
897
+ /**
898
+ * Connects to `target` and resolves with the attempt's first usable path.
899
+ * Use {@link startConnect} instead when a timed-out attempt must stay
900
+ * reachable by its Connect ID.
901
+ */
902
+ connect(
903
+ target: ConnectTarget,
904
+ options: ConnectOptions = {}
913
905
  ): Promise<ConnectResult> {
914
- return this.#primaryConnect(this.startConnectAddr(address), options);
906
+ this.#assertOpen();
907
+ // Validate before admitting, so a bad option never orphans an attempt.
908
+ assertTimeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
909
+ if (options.signal?.aborted === true) {
910
+ return Promise.reject(new AbortError());
911
+ }
912
+ return this.waitConnectResult(this.startConnect(target), options);
915
913
  }
916
914
 
917
- /** Consumes the terminal result for a `startConnect*` attempt. */
915
+ /**
916
+ * Waits for the terminal outcome of a {@link startConnect} attempt.
917
+ *
918
+ * One wait per attempt may be pending. A timeout ends only this wait (unless
919
+ * `cancelOnTimeout` is set); the attempt keeps running and a later call can
920
+ * still consume its outcome. Aborting `signal` issues {@link cancelConnect}
921
+ * and the wait settles from the attempt's terminal: {@link
922
+ * ConnectCancelledError}, or the real outcome if the attempt had already
923
+ * settled. A terminal lost to event-delivery overflow rejects with
924
+ * {@link ConnectResultLostError}; recover state from `connectedPeers()` and
925
+ * `path()`.
926
+ */
918
927
  waitConnectResult(
919
928
  connectId: number,
920
- options: OpOptions = {}
929
+ options: ConnectOptions = {}
921
930
  ): Promise<ConnectResult> {
922
931
  this.#assertOpen();
923
932
  assertId(connectId, "connectId");
933
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
934
+ assertTimeout(timeoutMs);
924
935
  const attempt = this.#connects.get(connectId);
925
- if (attempt === undefined || attempt.waiting) {
936
+ if (attempt === undefined || attempt.settle !== undefined) {
926
937
  return Promise.reject(new ConnectResultUnavailableError(connectId));
927
938
  }
928
- if (attempt.terminal !== undefined) {
929
- this.#connects.delete(connectId);
930
- this.#terminalConnects.delete(connectId);
931
- return attempt.terminal.ok
932
- ? Promise.resolve(attempt.terminal.result)
933
- : Promise.reject(attempt.terminal.error);
934
- }
935
- attempt.waiting = true;
936
- const result = new Promise<ConnectResult>((resolve, reject) => {
937
- attempt.resolve = resolve;
938
- attempt.reject = reject;
939
- });
940
- return withOptions(result, options, () => {
941
- this.cancelConnect(connectId);
942
- }).finally(() => {
943
- this.#connects.delete(connectId);
939
+ const { terminal } = attempt;
940
+ if (terminal !== undefined) {
941
+ this.#forgetConnect(connectId);
942
+ return terminal.ok
943
+ ? Promise.resolve(terminal.result)
944
+ : Promise.reject(terminal.error);
945
+ }
946
+ return new Promise((resolve, reject) => {
947
+ let timer: ReturnType<typeof setTimeout> | undefined;
948
+ const stopWaiting = () => {
949
+ clearTimeout(timer);
950
+ removeAbort?.();
951
+ attempt.settle = undefined;
952
+ };
953
+ // Abort only requests cancellation. Drop the local timeout so it cannot
954
+ // reject with TimeoutError before the terminal settles this wait.
955
+ const cancelForAbort = () => {
956
+ clearTimeout(timer);
957
+ this.#requestCancel(connectId);
958
+ };
959
+ const removeAbort = listenAbort(options.signal, cancelForAbort);
960
+ if (timeoutMs > 0) {
961
+ // Ends this wait only; the attempt stays tracked for its terminal.
962
+ timer = setTimeout(() => {
963
+ stopWaiting();
964
+ reject(new TimeoutError(timeoutMs));
965
+ if (options.cancelOnTimeout === true) {
966
+ this.#requestCancel(connectId);
967
+ }
968
+ }, timeoutMs);
969
+ }
970
+ if (options.signal?.aborted === true) {
971
+ cancelForAbort();
972
+ }
973
+ attempt.settle = (outcome) => {
974
+ stopWaiting();
975
+ if (outcome.ok) {
976
+ resolve(outcome.result);
977
+ } else {
978
+ reject(outcome.error);
979
+ }
980
+ };
944
981
  });
945
982
  }
946
983
 
947
- /** Cancels an in-flight advanced connection attempt. */
984
+ /**
985
+ * Requests cancellation of a Connection attempt. Idempotent; unknown or
986
+ * settled IDs are a no-op.
987
+ *
988
+ * Local waits settle from the attempt's terminal event: `connectCancelled`,
989
+ * or its real outcome if it had already settled. Never disconnects an
990
+ * established connection; use {@link disconnect} for that.
991
+ */
948
992
  cancelConnect(connectId: number): void {
949
993
  this.#assertOpen();
950
994
  assertId(connectId, "connectId");
951
995
  this.#backend.cancelConnect(connectId);
952
- const attempt = this.#connects.get(connectId);
953
- attempt?.reject?.(new AbortError("The connection attempt was cancelled"));
954
- this.#connects.delete(connectId);
955
- this.#terminalConnects.delete(connectId);
956
- }
957
-
958
- /** Starts direct transport dials for every applicable local address family. */
959
- dial(address: string): number[] {
960
- this.#assertOpen();
961
- return this.#backend.dial(address);
962
- }
963
-
964
- /** Starts a direct IPv4 transport dial. */
965
- dialIp4(address: string): number {
966
- this.#assertOpen();
967
- return this.#backend.dialIp4(address);
968
- }
969
-
970
- /** Starts a direct IPv6 transport dial. */
971
- dialIp6(address: string): number {
972
- this.#assertOpen();
973
- return this.#backend.dialIp6(address);
974
996
  }
975
997
 
976
998
  /** Closes the active connection to `peerId`. */
@@ -979,18 +1001,6 @@ export class Minip2pBase {
979
1001
  this.#backend.disconnect(peerId);
980
1002
  }
981
1003
 
982
- #rememberConnect(connectId: number): number {
983
- this.#connects.set(connectId, { waiting: false });
984
- return connectId;
985
- }
986
-
987
- #primaryConnect(
988
- connectId: number,
989
- options: OpOptions
990
- ): Promise<ConnectResult> {
991
- return this.waitConnectResult(connectId, options);
992
- }
993
-
994
1004
  #runPing(peerId: string): PingOperation {
995
1005
  let settled = false;
996
1006
  let rejectOperation: (error: unknown) => void = () => {};
@@ -1049,7 +1059,7 @@ export class Minip2pBase {
1049
1059
  }
1050
1060
  }
1051
1061
 
1052
- #handleQueueOverflow(): void {
1062
+ #handleQueueOverflow(dropped: QueueItem): void {
1053
1063
  const error = new EventQueueOverflowError();
1054
1064
  for (const waiter of [...this.#waiters]) {
1055
1065
  this.#settleWaiter(waiter, error);
@@ -1058,11 +1068,14 @@ export class Minip2pBase {
1058
1068
  ping.cancel(error);
1059
1069
  }
1060
1070
  this.#pings.clear();
1061
- for (const [connectId, attempt] of [...this.#connects]) {
1062
- if (attempt.terminal === undefined) {
1063
- attempt.reject?.(error);
1064
- this.#connects.delete(connectId);
1065
- this.#terminalConnects.delete(connectId);
1071
+ // Connection attempts correlate exactly: only a dropped terminal, or a
1072
+ // dropped native loss report naming it, settles its attempt.
1073
+ if (dropped.source === "native") {
1074
+ const { event } = dropped;
1075
+ if (isConnectTerminal(event)) {
1076
+ this.#connectResultsLost([event.inner.connectId]);
1077
+ } else if (event.tag === P2pEvent_Tags.EventsDropped) {
1078
+ this.#connectResultsLost(event.inner.terminalConnectIds);
1066
1079
  }
1067
1080
  }
1068
1081
  for (const pending of this.#pendingOpens.values()) {
@@ -1085,7 +1098,7 @@ export class Minip2pBase {
1085
1098
  if (dropped !== undefined) {
1086
1099
  this.#releaseQueueItem(dropped);
1087
1100
  this.#dropped += 1;
1088
- this.#handleQueueOverflow();
1101
+ this.#handleQueueOverflow(dropped);
1089
1102
  }
1090
1103
  this.#scheduleFlush();
1091
1104
  }
@@ -1101,7 +1114,7 @@ export class Minip2pBase {
1101
1114
  if (dropped !== undefined) {
1102
1115
  this.#releaseQueueItem(dropped);
1103
1116
  this.#dropped += 1;
1104
- this.#handleQueueOverflow();
1117
+ this.#handleQueueOverflow(dropped);
1105
1118
  }
1106
1119
  this.#scheduleFlush();
1107
1120
  }
@@ -1184,12 +1197,12 @@ export class Minip2pBase {
1184
1197
  if (event.tag === P2pEvent_Tags.ConnectionClosed) {
1185
1198
  this.#connectionClosed(event.inner.peerId, event.inner.connId);
1186
1199
  }
1187
- if (
1188
- event.tag === P2pEvent_Tags.PathEstablished ||
1189
- event.tag === P2pEvent_Tags.ConnectFailed
1190
- ) {
1200
+ if (isConnectTerminal(event)) {
1191
1201
  this.#connectTerminal(event);
1192
1202
  }
1203
+ if (event.tag === P2pEvent_Tags.EventsDropped) {
1204
+ this.#connectResultsLost(event.inner.terminalConnectIds);
1205
+ }
1193
1206
 
1194
1207
  const normalized = normalizeEvent(event);
1195
1208
  if (normalized !== undefined) {
@@ -1401,16 +1414,7 @@ export class Minip2pBase {
1401
1414
  }
1402
1415
  }
1403
1416
 
1404
- #connectTerminal(
1405
- event: Extract<
1406
- P2pEvent,
1407
- {
1408
- readonly tag:
1409
- | typeof P2pEvent_Tags.PathEstablished
1410
- | typeof P2pEvent_Tags.ConnectFailed;
1411
- }
1412
- >
1413
- ): void {
1417
+ #connectTerminal(event: ConnectTerminalEvent): void {
1414
1418
  const attempt = this.#connects.get(event.inner.connectId);
1415
1419
  if (attempt === undefined) {
1416
1420
  return;
@@ -1426,35 +1430,82 @@ export class Minip2pBase {
1426
1430
  },
1427
1431
  }
1428
1432
  : {
1429
- error: new ConnectFailedError(
1430
- event.inner.connectId,
1431
- event.inner.peerId,
1432
- event.inner.kind,
1433
- event.inner.detail
1434
- ),
1433
+ error:
1434
+ event.tag === P2pEvent_Tags.ConnectCancelled
1435
+ ? new ConnectCancelledError(
1436
+ event.inner.connectId,
1437
+ event.inner.peerId
1438
+ )
1439
+ : new ConnectFailedError(
1440
+ event.inner.connectId,
1441
+ event.inner.peerId,
1442
+ event.inner.kind,
1443
+ event.inner.detail
1444
+ ),
1435
1445
  ok: false,
1436
1446
  };
1437
- if (attempt.waiting) {
1438
- if (terminal.ok) {
1439
- attempt.resolve?.(terminal.result);
1440
- } else {
1441
- attempt.reject?.(terminal.error);
1447
+ this.#settleConnect(event.inner.connectId, attempt, terminal);
1448
+ }
1449
+
1450
+ // Terminals dropped by either event carry settle exactly their attempts
1451
+ // with a delivery-loss error so waits cannot hang. Both carries name every
1452
+ // dropped terminal, so every other attempt still receives its own.
1453
+ #connectResultsLost(connectIds: readonly number[]): void {
1454
+ for (const connectId of connectIds) {
1455
+ const attempt = this.#connects.get(connectId);
1456
+ if (attempt === undefined || attempt.terminal !== undefined) {
1457
+ continue;
1442
1458
  }
1443
- } else {
1444
- attempt.terminal = terminal;
1445
- this.#terminalConnects.delete(event.inner.connectId);
1446
- this.#terminalConnects.add(event.inner.connectId);
1447
- while (this.#terminalConnects.size > CONNECT_TERMINAL_CAP) {
1448
- const oldest = this.#terminalConnects.values().next().value;
1449
- if (oldest === undefined) {
1450
- break;
1451
- }
1452
- this.#terminalConnects.delete(oldest);
1453
- this.#connects.delete(oldest);
1459
+ this.#settleConnect(connectId, attempt, {
1460
+ error: new ConnectResultLostError(connectId),
1461
+ ok: false,
1462
+ });
1463
+ }
1464
+ }
1465
+
1466
+ // Hands a terminal to the pending wait, or keeps it for a later one.
1467
+ #settleConnect(
1468
+ connectId: number,
1469
+ attempt: ConnectAttempt,
1470
+ terminal: ConnectTerminal
1471
+ ): void {
1472
+ if (attempt.settle !== undefined) {
1473
+ this.#forgetConnect(connectId);
1474
+ attempt.settle(terminal);
1475
+ return;
1476
+ }
1477
+ attempt.terminal = terminal;
1478
+ this.#terminalConnects.delete(connectId);
1479
+ this.#terminalConnects.add(connectId);
1480
+ while (this.#terminalConnects.size > CONNECT_TERMINAL_CAP) {
1481
+ const oldest = this.#terminalConnects.values().next().value;
1482
+ if (oldest === undefined) {
1483
+ break;
1454
1484
  }
1485
+ this.#terminalConnects.delete(oldest);
1486
+ this.#connects.delete(oldest);
1487
+ }
1488
+ }
1489
+
1490
+ // Cancellation requested from a signal or timer has no caller to throw to.
1491
+ // Native cancel fails only once the endpoint stops, and teardown then
1492
+ // settles the wait.
1493
+ #requestCancel(connectId: number): void {
1494
+ if (this.#closed) {
1495
+ return;
1496
+ }
1497
+ try {
1498
+ this.#backend.cancelConnect(connectId);
1499
+ } catch {
1500
+ // Teardown settles every pending wait.
1455
1501
  }
1456
1502
  }
1457
1503
 
1504
+ #forgetConnect(connectId: number): void {
1505
+ this.#connects.delete(connectId);
1506
+ this.#terminalConnects.delete(connectId);
1507
+ }
1508
+
1458
1509
  #expireOpen(pending: PendingOpen, error: unknown): void {
1459
1510
  const key = pendingOpenKey(
1460
1511
  pending.peerId,
@@ -1510,7 +1561,7 @@ export class Minip2pBase {
1510
1561
  this.#settleWaiter(waiter, error);
1511
1562
  }
1512
1563
  for (const attempt of this.#connects.values()) {
1513
- attempt.reject?.(error);
1564
+ attempt.settle?.({ error, ok: false });
1514
1565
  }
1515
1566
  this.#connects.clear();
1516
1567
  this.#terminalConnects.clear();
@@ -1547,6 +1598,34 @@ export class Minip2pBase {
1547
1598
  }
1548
1599
  }
1549
1600
 
1601
+ type ConnectTerminalEvent = Extract<
1602
+ P2pEvent,
1603
+ {
1604
+ readonly tag:
1605
+ | typeof P2pEvent_Tags.PathEstablished
1606
+ | typeof P2pEvent_Tags.ConnectFailed
1607
+ | typeof P2pEvent_Tags.ConnectCancelled;
1608
+ }
1609
+ >;
1610
+
1611
+ function isConnectTerminal(event: P2pEvent): event is ConnectTerminalEvent {
1612
+ return (
1613
+ event.tag === P2pEvent_Tags.PathEstablished ||
1614
+ event.tag === P2pEvent_Tags.ConnectFailed ||
1615
+ event.tag === P2pEvent_Tags.ConnectCancelled
1616
+ );
1617
+ }
1618
+
1619
+ // A string starting with `/` is a multiaddress; any other string is a peer ID.
1620
+ function toBackendTarget(target: ConnectTarget): BackendConnectTarget {
1621
+ if (typeof target !== "string") {
1622
+ return { addresses: [...target], kind: "addresses" };
1623
+ }
1624
+ return target.startsWith("/")
1625
+ ? { addresses: [target], kind: "addresses" }
1626
+ : { kind: "peer", peerId: target };
1627
+ }
1628
+
1550
1629
  function normalizeEvent(
1551
1630
  event: Exclude<
1552
1631
  P2pEvent,
@@ -1585,8 +1664,8 @@ function normalizeEvent(
1585
1664
  [P2pEvent_Tags.InboundPathEstablished]: "inboundPathEstablished",
1586
1665
  [P2pEvent_Tags.PathUpgraded]: "pathUpgraded",
1587
1666
  [P2pEvent_Tags.HolePunchFailed]: "holePunchFailed",
1588
- [P2pEvent_Tags.FellBackToRelay]: "fellBackToRelay",
1589
1667
  [P2pEvent_Tags.ConnectFailed]: "connectFailed",
1668
+ [P2pEvent_Tags.ConnectCancelled]: "connectCancelled",
1590
1669
  [P2pEvent_Tags.InboundDirectUpgrade]: "inboundDirectUpgrade",
1591
1670
  [P2pEvent_Tags.Message]: "message",
1592
1671
  [P2pEvent_Tags.PeerSubscribed]: "peerSubscribed",
@@ -1721,13 +1800,11 @@ function listenAbort(
1721
1800
 
1722
1801
  function withOptions<Value>(
1723
1802
  promise: Promise<Value>,
1724
- options: OpOptions,
1725
- onCancel?: () => void
1803
+ options: OpOptions
1726
1804
  ): Promise<Value> {
1727
1805
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1728
1806
  assertTimeout(timeoutMs);
1729
1807
  if (options.signal?.aborted === true) {
1730
- onCancel?.();
1731
1808
  return Promise.reject(new AbortError());
1732
1809
  }
1733
1810
  return new Promise((resolve, reject) => {
@@ -1744,14 +1821,12 @@ function withOptions<Value>(
1744
1821
  };
1745
1822
  const removeAbort = listenAbort(options.signal, () => {
1746
1823
  finish(() => {
1747
- onCancel?.();
1748
1824
  reject(new AbortError());
1749
1825
  });
1750
1826
  });
1751
1827
  if (timeoutMs > 0) {
1752
1828
  timer = setTimeout(() => {
1753
1829
  finish(() => {
1754
- onCancel?.();
1755
1830
  reject(new TimeoutError(timeoutMs));
1756
1831
  });
1757
1832
  }, timeoutMs);