@minip2p/core 0.11.2 → 0.11.4

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/errors.ts CHANGED
@@ -4,7 +4,9 @@ import type {
4
4
  ConfigCapability,
5
5
  DriverFailureKind,
6
6
  EndpointErrorKind,
7
+ IdentifyFailure,
7
8
  NatErrorKind,
9
+ PingFailure,
8
10
  } from "./types.js";
9
11
 
10
12
  /** Pubsub rejected a publish because its bounded native queue is full. */
@@ -167,18 +169,54 @@ export class PeerDisconnectedError extends Error {
167
169
  readonly peerId: string;
168
170
  readonly operation?: string;
169
171
 
170
- constructor(peerId: string, operation?: string) {
171
- super(
172
+ /** `reason`, when given, is appended to the message. */
173
+ constructor(peerId: string, operation?: string, reason?: string) {
174
+ const base =
172
175
  operation === undefined
173
176
  ? `Peer ${peerId} disconnected`
174
- : `Peer ${peerId} disconnected during ${operation}`
175
- );
177
+ : `Peer ${peerId} disconnected during ${operation}`;
178
+ super(reason === undefined ? base : `${base}: ${reason}`);
176
179
  this.name = "PeerDisconnectedError";
177
180
  this.peerId = peerId;
178
181
  this.operation = operation;
179
182
  }
180
183
  }
181
184
 
185
+ /** A ping attempt failed natively; `kind` (the `pingFailed` event's `cause`) says why. */
186
+ export class PingFailedError extends Error {
187
+ readonly peerId: string;
188
+ /** The connection the ping was sent on. */
189
+ readonly connId: number;
190
+ /** Why the ping failed. */
191
+ readonly kind: PingFailure;
192
+
193
+ constructor(options: { peerId: string; connId: number; cause: PingFailure }) {
194
+ super(`Ping to ${options.peerId} failed: ${options.cause}`);
195
+ this.name = "PingFailedError";
196
+ this.peerId = options.peerId;
197
+ this.connId = options.connId;
198
+ this.kind = options.cause;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * The peer's connection failed its first Identify, so it never became ready
204
+ * and was closed. `kind` is the `identifyFailed` event's `cause`. Rejects `waitPeerReady`; redial to try again.
205
+ */
206
+ export class IdentifyFailedError extends PeerDisconnectedError {
207
+ /** The connection whose first Identify failed. */
208
+ readonly connId: number;
209
+ /** Why Identify failed. */
210
+ readonly kind: IdentifyFailure;
211
+
212
+ constructor(peerId: string, connId: number, kind: IdentifyFailure) {
213
+ super(peerId, "waitPeerReady", `Identify failed (${kind})`);
214
+ this.name = "IdentifyFailedError";
215
+ this.connId = connId;
216
+ this.kind = kind;
217
+ }
218
+ }
219
+
182
220
  /** Outbound stream opening or protocol negotiation failed. */
183
221
  export class OpenStreamError extends Error {
184
222
  /** Machine-readable native error category, or a synchronous adapter error. */
package/src/index.ts CHANGED
@@ -8,11 +8,13 @@ export {
8
8
  ConnectResultUnavailableError,
9
9
  DriverFailedError,
10
10
  EventQueueOverflowError,
11
+ IdentifyFailedError,
11
12
  InvalidConfigError,
12
13
  MessageTooLargeError,
13
14
  NotPermittedError,
14
15
  OpenStreamError,
15
16
  PeerDisconnectedError,
17
+ PingFailedError,
16
18
  StreamClosedError,
17
19
  TimeoutError,
18
20
  WriteBufferFullError,
@@ -24,8 +26,10 @@ export {
24
26
  DiscoverySource,
25
27
  DriverFailureKind,
26
28
  EndpointErrorKind,
29
+ IdentifyFailure,
27
30
  MdnsFailureKind,
28
31
  NatErrorKind,
32
+ PingFailure,
29
33
  Reachability,
30
34
  type Bytes,
31
35
  type ConnectionCloseReason,
package/src/sdk.ts CHANGED
@@ -14,8 +14,10 @@ import {
14
14
  ConnectResultUnavailableError,
15
15
  DriverFailedError,
16
16
  EventQueueOverflowError,
17
+ IdentifyFailedError,
17
18
  OpenStreamError,
18
19
  PeerDisconnectedError,
20
+ PingFailedError,
19
21
  StreamClosedError,
20
22
  TimeoutError,
21
23
  WriteBufferFullError,
@@ -39,6 +41,7 @@ import type {
39
41
  InboundStreamMeta,
40
42
  KnownPeerInfo,
41
43
  Minip2pCatchAllEventMap,
44
+ Minip2pConfig,
42
45
  Minip2pEvent,
43
46
  Minip2pNamedEventMap,
44
47
  OnceOptions,
@@ -59,6 +62,13 @@ declare const TextEncoder: new () => {
59
62
  };
60
63
 
61
64
  const DEFAULT_TIMEOUT_MS = 65_000;
65
+ /** The native connect deadline and default first-Identify deadline. */
66
+ const CONNECT_DEADLINE_MS = 30_000;
67
+ const IDENTIFY_DEADLINE_MS = 30_000;
68
+ /** Margin a readiness wait keeps past the native deadlines. */
69
+ const READY_SLACK_MS = 5000;
70
+ /** The longest delay `setTimeout` honours; longer ones fire at once. */
71
+ const MAX_TIMER_MS = 2_147_483_647;
62
72
  /**
63
73
  * Default close drain: the Rust `minip2p::DEFAULT_CLOSE_TIMEOUT` (500 ms)
64
74
  * that `Endpoint::close` and native's `DEFAULT_STOP_TIMEOUT_MS` use.
@@ -155,7 +165,6 @@ type StreamReceiveState =
155
165
  interface PingOperation {
156
166
  readonly promise: Promise<number>;
157
167
  readonly cancel: (error: unknown) => void;
158
- callers: number;
159
168
  }
160
169
 
161
170
  class BoundedQueue<Item> {
@@ -365,6 +374,7 @@ const connectionsOf = (event: P2pEvent): number[] => {
365
374
  const UNSEEN_CONNECTION_TAGS: ReadonlySet<string> = new Set<P2pEvent["tag"]>([
366
375
  P2pEvent_Tags.PeerReady,
367
376
  P2pEvent_Tags.IdentifyReceived,
377
+ P2pEvent_Tags.IdentifyFailed,
368
378
  P2pEvent_Tags.EndpointError,
369
379
  P2pEvent_Tags.StreamRemoteWriteClosed,
370
380
  P2pEvent_Tags.StreamWriteStopped,
@@ -1128,6 +1138,8 @@ export interface StreamEventMap {
1128
1138
  export class Minip2pBase {
1129
1139
  readonly #backend: Minip2pBackend;
1130
1140
  readonly #relayAddrs: readonly string[];
1141
+ /** `waitPeerReady`'s default timeout: connect + Identify + slack. */
1142
+ readonly #readyTimeoutMs: number;
1131
1143
  readonly #named = new Map<EventKind, Set<(payload: AnyPayload) => void>>();
1132
1144
  readonly #catchAll = new Set<CatchAllHandler>();
1133
1145
  readonly #closeHandlers = new Set<(report: EndpointCloseReport) => void>();
@@ -1149,10 +1161,16 @@ export class Minip2pBase {
1149
1161
 
1150
1162
  protected constructor(
1151
1163
  backend: Minip2pBackend,
1152
- relayAddresses: readonly string[]
1164
+ config: Pick<Minip2pConfig, "relays" | "timeouts">
1153
1165
  ) {
1154
1166
  this.#backend = backend;
1155
- this.#relayAddrs = relayAddresses;
1167
+ this.#relayAddrs = config.relays ?? [];
1168
+ this.#readyTimeoutMs = Math.min(
1169
+ CONNECT_DEADLINE_MS +
1170
+ (config.timeouts?.identifyMs ?? IDENTIFY_DEADLINE_MS) +
1171
+ READY_SLACK_MS,
1172
+ MAX_TIMER_MS
1173
+ );
1156
1174
  try {
1157
1175
  backend.start((event) => {
1158
1176
  this.#enqueueNative(event);
@@ -1484,10 +1502,13 @@ export class Minip2pBase {
1484
1502
 
1485
1503
  /**
1486
1504
  * Waits until the peer's current connection is ready, or rejects if the
1487
- * peer disconnects.
1505
+ * peer disconnects: with `IdentifyFailedError` (a `PeerDisconnectedError`
1506
+ * whose `kind` is the cause) when that connection's first Identify failed.
1488
1507
  *
1489
1508
  * A `peerReady` resolves it only while its connection is still the peer's
1490
1509
  * current one, so a stale `peerReady` for a replaced connection does not.
1510
+ * The default timeout outlasts a connect plus the first-Identify deadline
1511
+ * (`timeouts.identifyMs`), so the native side settles readiness first.
1491
1512
  */
1492
1513
  waitPeerReady(
1493
1514
  peerId: string,
@@ -1508,6 +1529,7 @@ export class Minip2pBase {
1508
1529
  const removeExternalAbort = listenAbort(options.signal, () => {
1509
1530
  controller.abort();
1510
1531
  });
1532
+ const timeoutMs = options.timeoutMs ?? this.#readyTimeoutMs;
1511
1533
  // Events trail the native state, so a queued `peerReady` counts only if
1512
1534
  // its connection is still the peer's current one; a replaced
1513
1535
  // connection's readiness never resolves the wait.
@@ -1517,45 +1539,71 @@ export class Minip2pBase {
1517
1539
  event.peerId === peerId &&
1518
1540
  this.#backend.connectionInfo(peerId)?.connId === event.connId,
1519
1541
  signal: controller.signal,
1542
+ timeoutMs,
1520
1543
  }).then(({ protocols }) => ({ peerId, protocols }));
1544
+ // The failed connection may already be gone natively, so a failure
1545
+ // counts if it names the peer's current connection or, once native has
1546
+ // none, the last one this wait knew.
1547
+ let knownConnId = info?.connId;
1548
+ const identifyFailed = this.waitFor("identifyFailed", {
1549
+ ...options,
1550
+ predicate: (event) => {
1551
+ if (event.peerId !== peerId) {
1552
+ return false;
1553
+ }
1554
+ knownConnId =
1555
+ this.#backend.connectionInfo(peerId)?.connId ?? knownConnId;
1556
+ return (knownConnId ?? event.connId) === event.connId;
1557
+ },
1558
+ signal: controller.signal,
1559
+ timeoutMs,
1560
+ }).then(({ connId, cause }) => {
1561
+ throw new IdentifyFailedError(peerId, connId, cause);
1562
+ });
1521
1563
  const disconnected = this.waitFor("connectionClosed", {
1522
1564
  ...options,
1523
1565
  predicate: (event) =>
1524
1566
  event.peerId === peerId &&
1525
1567
  !this.#backend.connectedPeers().includes(peerId),
1526
1568
  signal: controller.signal,
1569
+ timeoutMs,
1527
1570
  }).then(() => {
1528
1571
  throw new PeerDisconnectedError(peerId, "waitPeerReady");
1529
1572
  });
1530
- return Promise.race([ready, disconnected]).finally(() => {
1573
+ return Promise.race([ready, identifyFailed, disconnected]).finally(() => {
1531
1574
  removeExternalAbort?.();
1532
1575
  controller.abort();
1533
1576
  });
1534
1577
  }
1535
1578
 
1536
- /** Measures round-trip latency in milliseconds, coalescing concurrent calls. */
1579
+ /**
1580
+ * Measures round-trip latency in milliseconds. Calls join the peer's
1581
+ * running attempt, including one whose earlier callers timed out or
1582
+ * aborted, until it ends. Rejects with {@link PingFailedError} when the native ping fails (its
1583
+ * `pingMs` deadline covers the open, negotiation and echo), and with
1584
+ * {@link PeerDisconnectedError} when the connection closes first, or with
1585
+ * {@link EventQueueOverflowError} when events are lost and its result may
1586
+ * be among them.
1587
+ */
1537
1588
  ping(peerId: string, options: OpOptions = {}): Promise<number> {
1538
1589
  this.#assertOpen();
1539
1590
  let operation = this.#pings.get(peerId);
1540
1591
  if (operation === undefined) {
1592
+ // Native events are flushed asynchronously, so none can arrive before
1593
+ // the operation below listens.
1594
+ this.#backend.ping(peerId);
1541
1595
  operation = this.#runPing(peerId);
1596
+ // Kept until its terminal event, even after every caller stops
1597
+ // waiting: a later call joins the native attempt still running, so an
1598
+ // older attempt's result never settles a newer one.
1542
1599
  this.#pings.set(peerId, operation);
1543
1600
  const current = operation;
1544
1601
  void operation.promise.then(
1545
1602
  () => this.#removePing(peerId, current),
1546
1603
  () => this.#removePing(peerId, current)
1547
1604
  );
1548
- this.#backend.ping(peerId);
1549
1605
  }
1550
- operation.callers += 1;
1551
- const current = operation;
1552
- return withOptions(operation.promise, options).finally(() => {
1553
- current.callers -= 1;
1554
- if (current.callers === 0 && this.#pings.get(peerId) === current) {
1555
- current.cancel(new AbortError("No ping callers remain"));
1556
- this.#pings.delete(peerId);
1557
- }
1558
- });
1606
+ return withOptions(operation.promise, options);
1559
1607
  }
1560
1608
 
1561
1609
  /** Opens and negotiates an application-protocol stream. */
@@ -1757,10 +1805,10 @@ export class Minip2pBase {
1757
1805
  resolve(event.rttMs);
1758
1806
  }
1759
1807
  });
1760
- const offTimeout = this.on("pingTimeout", (event) => {
1808
+ const offFailed = this.on("pingFailed", (event) => {
1761
1809
  if (event.peerId === peerId) {
1762
1810
  finish();
1763
- reject(new TimeoutError());
1811
+ reject(new PingFailedError(event));
1764
1812
  }
1765
1813
  });
1766
1814
  const offClosed = this.on("connectionClosed", (event) => {
@@ -1774,7 +1822,7 @@ export class Minip2pBase {
1774
1822
  });
1775
1823
  cleanup = () => {
1776
1824
  offRtt();
1777
- offTimeout();
1825
+ offFailed();
1778
1826
  offClosed();
1779
1827
  };
1780
1828
  const finish = () => {
@@ -1785,7 +1833,6 @@ export class Minip2pBase {
1785
1833
  };
1786
1834
  });
1787
1835
  return {
1788
- callers: 0,
1789
1836
  cancel: (error) => {
1790
1837
  if (!settled) {
1791
1838
  settled = true;
@@ -1960,6 +2007,12 @@ export class Minip2pBase {
1960
2007
  }
1961
2008
  if (event.tag === P2pEvent_Tags.EventsDropped) {
1962
2009
  this.#connectResultsLost(event.inner.terminalConnectIds);
2010
+ // A ping's result may be among the lost events, and a ping kept
2011
+ // without it would never settle, so end every pending ping.
2012
+ for (const ping of this.#pings.values()) {
2013
+ ping.cancel(new EventQueueOverflowError());
2014
+ }
2015
+ this.#pings.clear();
1963
2016
  }
1964
2017
 
1965
2018
  const normalized = normalizeEvent(event);
@@ -2415,8 +2468,9 @@ const SDK_EVENT_NAMES: {
2415
2468
  [P2pEvent_Tags.ConnectionReplaced]: "connectionReplaced",
2416
2469
  [P2pEvent_Tags.PeerReady]: "peerReady",
2417
2470
  [P2pEvent_Tags.IdentifyReceived]: "identifyReceived",
2471
+ [P2pEvent_Tags.IdentifyFailed]: "identifyFailed",
2418
2472
  [P2pEvent_Tags.PingRttMeasured]: "pingRttMeasured",
2419
- [P2pEvent_Tags.PingTimeout]: "pingTimeout",
2473
+ [P2pEvent_Tags.PingFailed]: "pingFailed",
2420
2474
  [P2pEvent_Tags.EndpointError]: "endpointError",
2421
2475
  [P2pEvent_Tags.ReachabilityChanged]: "reachabilityChanged",
2422
2476
  [P2pEvent_Tags.ListenAddressesChanged]: "listenAddressesChanged",
package/src/types.ts CHANGED
@@ -124,19 +124,38 @@ export interface Minip2pYamuxLimits {
124
124
 
125
125
  /**
126
126
  * Protocol deadline overrides, in milliseconds; omitted fields keep the native
127
- * default of 10 s. A zero makes `create` throw `InvalidConfigError` with
128
- * capability `Options`. Keep `identifyMs` at least `negotiationMs`: the first
129
- * Identify includes a negotiation.
127
+ * defaults (30 s for `negotiationMs` and `identifyMs`, 10 s for `pingMs`). A
128
+ * zero makes `create` throw `InvalidConfigError` with capability `Options`.
129
+ * `identifyMs` and `pingMs` each cover their own negotiation, which
130
+ * `negotiationMs` does not cut short.
130
131
  */
131
132
  export interface Minip2pTimeouts {
132
133
  /** How long an outbound stream may negotiate its protocol. */
133
134
  readonly negotiationMs?: number;
134
- /** How long a connection's first Identify may take before it is closed. */
135
+ /**
136
+ * How long a connection's first Identify (open, negotiation, reply) may
137
+ * take. A first Identify that fails or runs out this deadline closes the
138
+ * connection with `identifyFailed`; later Identify exchanges are not bound
139
+ * by it. `waitPeerReady`'s default timeout allows for it.
140
+ */
135
141
  readonly identifyMs?: number;
136
- /** How long a ping waits for its echo. */
142
+ /** How long a ping may take: opening its stream, negotiating it and the echo. */
137
143
  readonly pingMs?: number;
138
144
  }
139
145
 
146
+ /** Why a ping attempt failed; see the `pingFailed` event. */
147
+ export const PingFailure = {
148
+ /** The transport refused to open the ping stream. */
149
+ OpenFailed: "OpenFailed",
150
+ /** The peer refused the ping protocol, or broke its negotiation. */
151
+ Rejected: "Rejected",
152
+ /** The ping stream closed, was reset, or carried a bad echo first. */
153
+ StreamClosed: "StreamClosed",
154
+ /** The ping deadline (`pingMs`, from the ping call) ran out first. */
155
+ TimedOut: "TimedOut",
156
+ } as const;
157
+ export type PingFailure = (typeof PingFailure)[keyof typeof PingFailure];
158
+
140
159
  /** Coarse local reachability states. */
141
160
  export const Reachability = {
142
161
  Private: "Private",
@@ -173,6 +192,22 @@ export const MdnsFailureKind = {
173
192
  export type MdnsFailureKind =
174
193
  (typeof MdnsFailureKind)[keyof typeof MdnsFailureKind];
175
194
 
195
+ /** Why a connection's first Identify failed, reported by `identifyFailed`. */
196
+ export const IdentifyFailure = {
197
+ /** The stream was reset, or closed during negotiation, before the reply. */
198
+ ClosedEarly: "ClosedEarly",
199
+ /** The peer's negotiation or Identify reply was malformed. */
200
+ Malformed: "Malformed",
201
+ /** The transport refused to open the Identify stream. */
202
+ OpenFailed: "OpenFailed",
203
+ /** The peer refused Identify during protocol negotiation. */
204
+ Rejected: "Rejected",
205
+ /** The exchange did not finish within the Identify deadline. */
206
+ TimedOut: "TimedOut",
207
+ } as const;
208
+ export type IdentifyFailure =
209
+ (typeof IdentifyFailure)[keyof typeof IdentifyFailure];
210
+
176
211
  /** The part of an endpoint's configuration an `InvalidConfigError` names. */
177
212
  export const ConfigCapability = {
178
213
  /** Signed discovery or peer-book settings. */
@@ -373,14 +408,31 @@ export interface Minip2pNamedEventMap {
373
408
  readonly connId: number;
374
409
  readonly info: IdentifyInfo;
375
410
  };
411
+ /**
412
+ * The first Identify on `connId` failed, so it never becomes ready; its
413
+ * `connectionClosed` follows. Redial to try again.
414
+ */
415
+ identifyFailed: {
416
+ readonly peerId: string;
417
+ readonly connId: number;
418
+ readonly cause: IdentifyFailure;
419
+ };
376
420
  /** A ping round trip completed on `connId`. */
377
421
  pingRttMeasured: {
378
422
  readonly peerId: string;
379
423
  readonly connId: number;
380
424
  readonly rttMs: number;
381
425
  };
382
- /** A ping sent on `connId` timed out. */
383
- pingTimeout: { readonly peerId: string; readonly connId: number };
426
+ /**
427
+ * A ping attempt on `connId` ended without an echo, for `cause`. Every
428
+ * accepted ping ends in one `pingRttMeasured` or `pingFailed`, unless its
429
+ * connection closes first.
430
+ */
431
+ pingFailed: {
432
+ readonly peerId: string;
433
+ readonly connId: number;
434
+ readonly cause: PingFailure;
435
+ };
384
436
  stream: Stream;
385
437
  endpointError: {
386
438
  readonly kind: EndpointErrorKind;
@@ -683,6 +735,7 @@ export const P2pEvent_Tags = {
683
735
  GossipsubOutboundFailure: "GossipsubOutboundFailure",
684
736
  GossipsubProtocolViolation: "GossipsubProtocolViolation",
685
737
  HolePunchFailed: "HolePunchFailed",
738
+ IdentifyFailed: "IdentifyFailed",
686
739
  IdentifyReceived: "IdentifyReceived",
687
740
  InboundDirectUpgrade: "InboundDirectUpgrade",
688
741
  InboundPathEstablished: "InboundPathEstablished",
@@ -698,8 +751,8 @@ export const P2pEvent_Tags = {
698
751
  PeerSubscribed: "PeerSubscribed",
699
752
  PeerUnsubscribed: "PeerUnsubscribed",
700
753
  PeerUpdated: "PeerUpdated",
754
+ PingFailed: "PingFailed",
701
755
  PingRttMeasured: "PingRttMeasured",
702
- PingTimeout: "PingTimeout",
703
756
  PublicAddressesChanged: "PublicAddressesChanged",
704
757
  ReachabilityChanged: "ReachabilityChanged",
705
758
  RelayReservationLost: "RelayReservationLost",
@@ -755,13 +808,17 @@ export type P2pEvent =
755
808
  typeof P2pEvent_Tags.IdentifyReceived,
756
809
  Minip2pNamedEventMap["identifyReceived"]
757
810
  >
811
+ | RawEvent<
812
+ typeof P2pEvent_Tags.IdentifyFailed,
813
+ Minip2pNamedEventMap["identifyFailed"]
814
+ >
758
815
  | RawEvent<
759
816
  typeof P2pEvent_Tags.PingRttMeasured,
760
817
  Minip2pNamedEventMap["pingRttMeasured"]
761
818
  >
762
819
  | RawEvent<
763
- typeof P2pEvent_Tags.PingTimeout,
764
- Minip2pNamedEventMap["pingTimeout"]
820
+ typeof P2pEvent_Tags.PingFailed,
821
+ Minip2pNamedEventMap["pingFailed"]
765
822
  >
766
823
  | RawEvent<typeof P2pEvent_Tags.StreamReady, InboundStreamMeta>
767
824
  | RawEvent<