libp2p 1.9.4 → 2.0.0-d101aac4b

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.
Files changed (100) hide show
  1. package/dist/index.min.js +17 -18
  2. package/dist/src/components.d.ts.map +1 -1
  3. package/dist/src/components.js +4 -3
  4. package/dist/src/components.js.map +1 -1
  5. package/dist/src/config.d.ts +1 -1
  6. package/dist/src/config.d.ts.map +1 -1
  7. package/dist/src/config.js +2 -7
  8. package/dist/src/config.js.map +1 -1
  9. package/dist/src/connection/index.d.ts +3 -3
  10. package/dist/src/connection/index.d.ts.map +1 -1
  11. package/dist/src/connection/index.js +7 -7
  12. package/dist/src/connection/index.js.map +1 -1
  13. package/dist/src/connection-manager/connection-pruner.js +1 -1
  14. package/dist/src/connection-manager/constants.browser.d.ts +0 -8
  15. package/dist/src/connection-manager/constants.browser.d.ts.map +1 -1
  16. package/dist/src/connection-manager/constants.browser.js +0 -8
  17. package/dist/src/connection-manager/constants.browser.js.map +1 -1
  18. package/dist/src/connection-manager/constants.d.ts +0 -8
  19. package/dist/src/connection-manager/constants.d.ts.map +1 -1
  20. package/dist/src/connection-manager/constants.defaults.d.ts +12 -22
  21. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  22. package/dist/src/connection-manager/constants.defaults.js +12 -22
  23. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  24. package/dist/src/connection-manager/constants.js +0 -8
  25. package/dist/src/connection-manager/constants.js.map +1 -1
  26. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  27. package/dist/src/connection-manager/dial-queue.js +29 -15
  28. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  29. package/dist/src/connection-manager/index.d.ts +47 -50
  30. package/dist/src/connection-manager/index.d.ts.map +1 -1
  31. package/dist/src/connection-manager/index.js +23 -57
  32. package/dist/src/connection-manager/index.js.map +1 -1
  33. package/dist/src/connection-manager/reconnect-queue.d.ts +35 -0
  34. package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -0
  35. package/dist/src/connection-manager/reconnect-queue.js +104 -0
  36. package/dist/src/connection-manager/reconnect-queue.js.map +1 -0
  37. package/dist/src/connection-monitor.d.ts +1 -0
  38. package/dist/src/connection-monitor.d.ts.map +1 -1
  39. package/dist/src/connection-monitor.js +15 -5
  40. package/dist/src/connection-monitor.js.map +1 -1
  41. package/dist/src/content-routing.js +6 -6
  42. package/dist/src/content-routing.js.map +1 -1
  43. package/dist/src/errors.d.ts +41 -61
  44. package/dist/src/errors.d.ts.map +1 -1
  45. package/dist/src/errors.js +84 -63
  46. package/dist/src/errors.js.map +1 -1
  47. package/dist/src/get-peer.d.ts.map +1 -1
  48. package/dist/src/get-peer.js +4 -5
  49. package/dist/src/get-peer.js.map +1 -1
  50. package/dist/src/index.d.ts +27 -9
  51. package/dist/src/index.d.ts.map +1 -1
  52. package/dist/src/index.js +10 -3
  53. package/dist/src/index.js.map +1 -1
  54. package/dist/src/libp2p.d.ts +11 -10
  55. package/dist/src/libp2p.d.ts.map +1 -1
  56. package/dist/src/libp2p.js +13 -31
  57. package/dist/src/libp2p.js.map +1 -1
  58. package/dist/src/peer-routing.js +8 -8
  59. package/dist/src/peer-routing.js.map +1 -1
  60. package/dist/src/registrar.js +7 -7
  61. package/dist/src/registrar.js.map +1 -1
  62. package/dist/src/transport-manager.d.ts.map +1 -1
  63. package/dist/src/transport-manager.js +15 -23
  64. package/dist/src/transport-manager.js.map +1 -1
  65. package/dist/src/upgrader.d.ts +8 -8
  66. package/dist/src/upgrader.d.ts.map +1 -1
  67. package/dist/src/upgrader.js +51 -51
  68. package/dist/src/upgrader.js.map +1 -1
  69. package/dist/src/version.d.ts +1 -1
  70. package/dist/src/version.d.ts.map +1 -1
  71. package/dist/src/version.js +1 -1
  72. package/dist/src/version.js.map +1 -1
  73. package/package.json +21 -21
  74. package/src/components.ts +4 -3
  75. package/src/config.ts +4 -10
  76. package/src/connection/index.ts +9 -9
  77. package/src/connection-manager/connection-pruner.ts +1 -1
  78. package/src/connection-manager/constants.browser.ts +0 -10
  79. package/src/connection-manager/constants.defaults.ts +14 -27
  80. package/src/connection-manager/constants.ts +0 -10
  81. package/src/connection-manager/dial-queue.ts +30 -15
  82. package/src/connection-manager/index.ts +80 -118
  83. package/src/connection-manager/reconnect-queue.ts +134 -0
  84. package/src/connection-monitor.ts +15 -6
  85. package/src/content-routing.ts +6 -6
  86. package/src/errors.ts +96 -61
  87. package/src/get-peer.ts +4 -5
  88. package/src/index.ts +42 -12
  89. package/src/libp2p.ts +22 -36
  90. package/src/peer-routing.ts +8 -8
  91. package/src/registrar.ts +7 -7
  92. package/src/transport-manager.ts +15 -23
  93. package/src/upgrader.ts +55 -56
  94. package/src/version.ts +1 -1
  95. package/dist/src/connection-manager/auto-dial.d.ts +0 -47
  96. package/dist/src/connection-manager/auto-dial.d.ts.map +0 -1
  97. package/dist/src/connection-manager/auto-dial.js +0 -223
  98. package/dist/src/connection-manager/auto-dial.js.map +0 -1
  99. package/dist/typedoc-urls.json +0 -14
  100. package/src/connection-manager/auto-dial.ts +0 -285
@@ -1,10 +1,5 @@
1
1
  export * from './constants.defaults.js'
2
2
 
3
- /**
4
- * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#minConnections
5
- */
6
- export const MIN_CONNECTIONS = 5
7
-
8
3
  /**
9
4
  * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections
10
5
  */
@@ -14,8 +9,3 @@ export const MAX_CONNECTIONS = 100
14
9
  * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials
15
10
  */
16
11
  export const MAX_PARALLEL_DIALS = 50
17
-
18
- /**
19
- * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialPeerRetryThreshold
20
- */
21
- export const AUTO_DIAL_PEER_RETRY_THRESHOLD = 1000 * 60 * 7
@@ -13,31 +13,6 @@ export const INBOUND_UPGRADE_TIMEOUT = 2e3
13
13
  */
14
14
  export const MAX_PEER_ADDRS_TO_DIAL = 25
15
15
 
16
- /**
17
- * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialInterval
18
- */
19
- export const AUTO_DIAL_INTERVAL = 5000
20
-
21
- /**
22
- * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialConcurrency
23
- */
24
- export const AUTO_DIAL_CONCURRENCY = 25
25
-
26
- /**
27
- * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialPriority
28
- */
29
- export const AUTO_DIAL_PRIORITY = 0
30
-
31
- /**
32
- * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialMaxQueueLength
33
- */
34
- export const AUTO_DIAL_MAX_QUEUE_LENGTH = 100
35
-
36
- /**
37
- * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialDiscoveredPeersDebounce
38
- */
39
- export const AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE = 10
40
-
41
16
  /**
42
17
  * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundConnectionThreshold
43
18
  */
@@ -48,16 +23,28 @@ export const INBOUND_CONNECTION_THRESHOLD = 5
48
23
  */
49
24
  export const MAX_INCOMING_PENDING_CONNECTIONS = 10
50
25
 
26
+ /**
27
+ * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelReconnects
28
+ */
29
+ export const MAX_PARALLEL_RECONNECTS = 5
30
+
51
31
  /**
52
32
  * Store as part of the peer store metadata for a given peer, the value for this
53
- * key is a timestamp of the last time a dial attempted failed with the relevant
54
- * peer stored as a string.
33
+ * key is a timestamp of the last time a dial attempt failed with the timestamp
34
+ * stored as a string.
55
35
  *
56
36
  * Used to insure we do not endlessly try to auto dial peers we have recently
57
37
  * failed to dial.
58
38
  */
59
39
  export const LAST_DIAL_FAILURE_KEY = 'last-dial-failure'
60
40
 
41
+ /**
42
+ * Store as part of the peer store metadata for a given peer, the value for this
43
+ * key is a timestamp of the last time a dial attempt succeeded with the
44
+ * timestamp stored as a string.
45
+ */
46
+ export const LAST_DIAL_SUCCESS_KEY = 'last-dial-success'
47
+
61
48
  /**
62
49
  * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxDialQueueLength
63
50
  */
@@ -1,10 +1,5 @@
1
1
  export * from './constants.defaults.js'
2
2
 
3
- /**
4
- * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#minConnections
5
- */
6
- export const MIN_CONNECTIONS = 50
7
-
8
3
  /**
9
4
  * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections
10
5
  */
@@ -14,8 +9,3 @@ export const MAX_CONNECTIONS = 300
14
9
  * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials
15
10
  */
16
11
  export const MAX_PARALLEL_DIALS = 100
17
-
18
- /**
19
- * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialPeerRetryThreshold
20
- */
21
- export const AUTO_DIAL_PEER_RETRY_THRESHOLD = 1000 * 60
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable max-depth */
2
- import { CodeError, AggregateCodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface'
2
+ import { TimeoutError, DialError, setMaxListeners } from '@libp2p/interface'
3
3
  import { PeerMap } from '@libp2p/peer-collections'
4
4
  import { defaultAddressSort } from '@libp2p/utils/address-sort'
5
5
  import { PriorityQueue, type PriorityQueueJobOptions } from '@libp2p/utils/priority-queue'
@@ -9,14 +9,15 @@ import { Circuit } from '@multiformats/multiaddr-matcher'
9
9
  import { type ClearableSignal, anySignal } from 'any-signal'
10
10
  import { CustomProgressEvent } from 'progress-events'
11
11
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
12
- import { codes } from '../errors.js'
12
+ import { DialDeniedError, NoValidAddressesError } from '../errors.js'
13
13
  import { getPeerAddress } from '../get-peer.js'
14
14
  import {
15
15
  DIAL_TIMEOUT,
16
16
  MAX_PARALLEL_DIALS,
17
17
  MAX_PEER_ADDRS_TO_DIAL,
18
18
  LAST_DIAL_FAILURE_KEY,
19
- MAX_DIAL_QUEUE_LENGTH
19
+ MAX_DIAL_QUEUE_LENGTH,
20
+ LAST_DIAL_SUCCESS_KEY
20
21
  } from './constants.js'
21
22
  import { resolveMultiaddrs } from './utils.js'
22
23
  import { DEFAULT_DIAL_PRIORITY } from './index.js'
@@ -192,7 +193,7 @@ export class DialQueue {
192
193
  }
193
194
 
194
195
  if (this.queue.size >= this.maxDialQueueLength) {
195
- throw new CodeError('Dial queue is full', 'ERR_DIAL_QUEUE_FULL')
196
+ throw new DialError('Dial queue is full')
196
197
  }
197
198
 
198
199
  this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()))
@@ -231,7 +232,7 @@ export class DialQueue {
231
232
  if (dialed === this.maxPeerAddrsToDial) {
232
233
  this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId)
233
234
 
234
- throw new CodeError('Peer had more than maxPeerAddrsToDial', codes.ERR_TOO_MANY_ADDRESSES)
235
+ throw new DialError('Peer had more than maxPeerAddrsToDial')
235
236
  }
236
237
 
237
238
  dialed++
@@ -244,6 +245,20 @@ export class DialQueue {
244
245
 
245
246
  this.log('dial to %a succeeded', address.multiaddr)
246
247
 
248
+ // record the successful dial and the address
249
+ try {
250
+ await this.components.peerStore.merge(conn.remotePeer, {
251
+ multiaddrs: [
252
+ conn.remoteAddr
253
+ ],
254
+ metadata: {
255
+ [LAST_DIAL_SUCCESS_KEY]: uint8ArrayFromString(Date.now().toString())
256
+ }
257
+ })
258
+ } catch (err: any) {
259
+ this.log.error('could not update last dial failure key for %p', peerId, err)
260
+ }
261
+
247
262
  return conn
248
263
  } catch (err: any) {
249
264
  this.log.error('dial failed to %a', address.multiaddr, err)
@@ -251,7 +266,7 @@ export class DialQueue {
251
266
  if (peerId != null) {
252
267
  // record the failed dial
253
268
  try {
254
- await this.components.peerStore.patch(peerId, {
269
+ await this.components.peerStore.merge(peerId, {
255
270
  metadata: {
256
271
  [LAST_DIAL_FAILURE_KEY]: uint8ArrayFromString(Date.now().toString())
257
272
  }
@@ -263,7 +278,7 @@ export class DialQueue {
263
278
 
264
279
  // the user/dial timeout/shutdown controller signal aborted
265
280
  if (signal.aborted) {
266
- throw new CodeError(err.message, ERR_TIMEOUT)
281
+ throw new TimeoutError(err.message)
267
282
  }
268
283
 
269
284
  errors.push(err)
@@ -274,7 +289,7 @@ export class DialQueue {
274
289
  throw errors[0]
275
290
  }
276
291
 
277
- throw new AggregateCodeError(errors, 'All multiaddr dials failed', codes.ERR_TRANSPORT_DIAL_FAILED)
292
+ throw new AggregateError(errors, 'All multiaddr dials failed')
278
293
  } finally {
279
294
  // clean up abort signals/controllers
280
295
  signal.clear()
@@ -312,11 +327,11 @@ export class DialQueue {
312
327
  // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it
313
328
  if (peerId != null) {
314
329
  if (this.components.peerId.equals(peerId)) {
315
- throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF)
330
+ throw new DialError('Tried to dial self')
316
331
  }
317
332
 
318
333
  if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {
319
- throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED)
334
+ throw new DialDeniedError('The dial request is blocked by gater.allowDialPeer')
320
335
  }
321
336
 
322
337
  // if just a peer id was passed, load available multiaddrs for this peer
@@ -328,7 +343,7 @@ export class DialQueue {
328
343
  addrs.push(...peer.addresses)
329
344
  this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()))
330
345
  } catch (err: any) {
331
- if (err.code !== codes.ERR_NOT_FOUND) {
346
+ if (err.name !== 'NotFoundError') {
332
347
  throw err
333
348
  }
334
349
  }
@@ -349,7 +364,7 @@ export class DialQueue {
349
364
  isCertified: false
350
365
  })))
351
366
  } catch (err: any) {
352
- if (err.code !== codes.ERR_NO_ROUTERS_AVAILABLE) {
367
+ if (err.name !== 'NoPeerRoutersError') {
353
368
  this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err)
354
369
  }
355
370
  }
@@ -437,7 +452,7 @@ export class DialQueue {
437
452
 
438
453
  // make sure we actually have some addresses to dial
439
454
  if (dedupedMultiaddrs.length === 0) {
440
- throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES)
455
+ throw new NoValidAddressesError('The dial request has no valid addresses')
441
456
  }
442
457
 
443
458
  const gatedAdrs: Address[] = []
@@ -454,7 +469,7 @@ export class DialQueue {
454
469
 
455
470
  // make sure we actually have some addresses to dial
456
471
  if (sortedGatedAddrs.length === 0) {
457
- throw new CodeError('The connection gater denied all addresses in the dial request', codes.ERR_NO_VALID_ADDRESSES)
472
+ throw new DialDeniedError('The connection gater denied all addresses in the dial request')
458
473
  }
459
474
 
460
475
  this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()))
@@ -471,7 +486,7 @@ export class DialQueue {
471
486
  try {
472
487
  const addresses = await this.calculateMultiaddrs(undefined, new Set(multiaddr.map(ma => ma.toString())), options)
473
488
 
474
- if (options.runOnTransientConnection === false) {
489
+ if (options.runOnLimitedConnection === false) {
475
490
  // return true if any resolved multiaddrs are not relay addresses
476
491
  return addresses.find(addr => {
477
492
  return !Circuit.matches(addr.multiaddr)
@@ -1,17 +1,16 @@
1
- import { CodeError, KEEP_ALIVE } from '@libp2p/interface'
1
+ import { InvalidParametersError, NotStartedError, start, stop } from '@libp2p/interface'
2
2
  import { PeerMap } from '@libp2p/peer-collections'
3
3
  import { defaultAddressSort } from '@libp2p/utils/address-sort'
4
4
  import { RateLimiter } from '@libp2p/utils/rate-limiter'
5
5
  import { type Multiaddr, type Resolver, multiaddr } from '@multiformats/multiaddr'
6
6
  import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
7
7
  import { CustomProgressEvent } from 'progress-events'
8
- import { codes } from '../errors.js'
9
8
  import { getPeerAddress } from '../get-peer.js'
10
- import { AutoDial } from './auto-dial.js'
11
9
  import { ConnectionPruner } from './connection-pruner.js'
12
- import { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PEER_RETRY_THRESHOLD, AUTO_DIAL_PRIORITY, DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, MIN_CONNECTIONS } from './constants.js'
10
+ import { DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL } from './constants.js'
13
11
  import { DialQueue } from './dial-queue.js'
14
- import type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, Peer, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions } from '@libp2p/interface'
12
+ import { ReconnectQueue } from './reconnect-queue.js'
13
+ import type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions } from '@libp2p/interface'
15
14
  import type { ConnectionManager, OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'
16
15
  import type { JobStatus } from '@libp2p/utils/queue'
17
16
 
@@ -19,57 +18,13 @@ export const DEFAULT_DIAL_PRIORITY = 50
19
18
 
20
19
  export interface ConnectionManagerInit {
21
20
  /**
22
- * The maximum number of connections libp2p is willing to have before it starts
23
- * pruning connections to reduce resource usage. (default: 300, 100 in browsers)
21
+ * The maximum number of connections libp2p is willing to have before it
22
+ * starts pruning connections to reduce resource usage.
23
+ *
24
+ * @default 300/100
24
25
  */
25
26
  maxConnections?: number
26
27
 
27
- /**
28
- * The minimum number of connections below which libp2p will start to dial peers
29
- * from the peer book. Setting this to 0 effectively disables this behaviour.
30
- * (default: 50, 5 in browsers)
31
- */
32
- minConnections?: number
33
-
34
- /**
35
- * How long to wait between attempting to keep our number of concurrent connections
36
- * above minConnections (default: 5000)
37
- */
38
- autoDialInterval?: number
39
-
40
- /**
41
- * When dialling peers from the peer book to keep the number of open connections
42
- * above `minConnections`, add dials for this many peers to the dial queue
43
- * at once. (default: 25)
44
- */
45
- autoDialConcurrency?: number
46
-
47
- /**
48
- * To allow user dials to take priority over auto dials, use this value as the
49
- * dial priority. (default: 0)
50
- */
51
- autoDialPriority?: number
52
-
53
- /**
54
- * Limit the maximum number of peers to dial when trying to keep the number of
55
- * open connections above `minConnections`. (default: 100)
56
- */
57
- autoDialMaxQueueLength?: number
58
-
59
- /**
60
- * When we've failed to dial a peer, do not autodial them again within this
61
- * number of ms. (default: 1 minute, 7 minutes in browsers)
62
- */
63
- autoDialPeerRetryThreshold?: number
64
-
65
- /**
66
- * Newly discovered peers may be auto-dialed to increase the number of open
67
- * connections, but they can be discovered in quick succession so add a small
68
- * delay before attempting to dial them in case more peers have been
69
- * discovered. (default: 10ms)
70
- */
71
- autoDialDiscoveredPeersDebounce?: number
72
-
73
28
  /**
74
29
  * Sort the known addresses of a peer before trying to dial, By default public
75
30
  * addresses will be dialled before private (e.g. loopback or LAN) addresses.
@@ -78,7 +33,8 @@ export interface ConnectionManagerInit {
78
33
 
79
34
  /**
80
35
  * The maximum number of dials across all peers to execute in parallel.
81
- * (default: 100, 50 in browsers)
36
+ *
37
+ * @default 100/50
82
38
  */
83
39
  maxParallelDials?: number
84
40
 
@@ -106,7 +62,9 @@ export interface ConnectionManagerInit {
106
62
 
107
63
  /**
108
64
  * When a new inbound connection is opened, the upgrade process (e.g. protect,
109
- * encrypt, multiplex etc) must complete within this number of ms. (default: 30s)
65
+ * encrypt, multiplex etc) must complete within this number of ms.
66
+ *
67
+ * @default 30000
110
68
  */
111
69
  inboundUpgradeTimeout?: number
112
70
 
@@ -117,7 +75,8 @@ export interface ConnectionManagerInit {
117
75
 
118
76
  /**
119
77
  * A list of multiaddrs that will always be allowed (except if they are in the
120
- * deny list) to open connections to this node even if we've reached maxConnections
78
+ * deny list) to open connections to this node even if we've reached
79
+ * maxConnections
121
80
  */
122
81
  allow?: string[]
123
82
 
@@ -134,23 +93,52 @@ export interface ConnectionManagerInit {
134
93
  inboundConnectionThreshold?: number
135
94
 
136
95
  /**
137
- * The maximum number of parallel incoming connections allowed that have yet to
138
- * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc.
139
- * (default: 10)
96
+ * The maximum number of parallel incoming connections allowed that have yet
97
+ * to complete the connection upgrade - e.g. choosing connection encryption,
98
+ * muxer, etc.
99
+ *
100
+ * @default 10
140
101
  */
141
102
  maxIncomingPendingConnections?: number
103
+
104
+ /**
105
+ * When a peer tagged with `KEEP_ALIVE` disconnects, attempt to redial them
106
+ * this many times.
107
+ *
108
+ * @default 5
109
+ */
110
+ reconnectRetries?: number
111
+
112
+ /**
113
+ * When a peer tagged with `KEEP_ALIVE` disconnects, wait this long between
114
+ * each retry. Note this will be multiplied by `reconnectFactor` to create an
115
+ * increasing retry backoff.
116
+ *
117
+ * @default 1000
118
+ */
119
+ reconnectRetryInterval?: number
120
+
121
+ /**
122
+ * When a peer tagged with `KEEP_ALIVE` disconnects, apply this multiplication
123
+ * factor to the time interval between each retry.
124
+ *
125
+ * @default 2
126
+ */
127
+ reconnectBackoffFactor?: number
128
+
129
+ /**
130
+ * When a peers tagged with `KEEP_ALIVE` disconnect, reconnect to this many at
131
+ * once.
132
+ *
133
+ * @default 5
134
+ */
135
+ maxParallelReconnects?: number
142
136
  }
143
137
 
144
138
  const defaultOptions = {
145
- minConnections: MIN_CONNECTIONS,
146
139
  maxConnections: MAX_CONNECTIONS,
147
140
  inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,
148
- maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS,
149
- autoDialConcurrency: AUTO_DIAL_CONCURRENCY,
150
- autoDialPriority: AUTO_DIAL_PRIORITY,
151
- autoDialMaxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH,
152
- autoDialPeerRetryThreshold: AUTO_DIAL_PEER_RETRY_THRESHOLD,
153
- autoDialDiscoveredPeersDebounce: AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE
141
+ maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS
154
142
  }
155
143
 
156
144
  export interface DefaultConnectionManagerComponents {
@@ -177,7 +165,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
177
165
  private readonly maxConnections: number
178
166
 
179
167
  public readonly dialQueue: DialQueue
180
- public readonly autoDial: AutoDial
168
+ public readonly reconnectQueue: ReconnectQueue
181
169
  public readonly connectionPruner: ConnectionPruner
182
170
  private readonly inboundConnectionRateLimiter: RateLimiter
183
171
  private readonly peerStore: PeerStore
@@ -187,10 +175,9 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
187
175
 
188
176
  constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerInit = {}) {
189
177
  this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections
190
- const minConnections = init.minConnections ?? defaultOptions.minConnections
191
178
 
192
- if (this.maxConnections < minConnections) {
193
- throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS)
179
+ if (this.maxConnections < 1) {
180
+ throw new InvalidParametersError('Connection Manager maxConnections must be greater than 0')
194
181
  }
195
182
 
196
183
  /**
@@ -222,21 +209,6 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
222
209
  duration: 1
223
210
  })
224
211
 
225
- // controls what happens when we don't have enough connections
226
- this.autoDial = new AutoDial({
227
- connectionManager: this,
228
- peerStore: components.peerStore,
229
- events: components.events,
230
- logger: components.logger
231
- }, {
232
- minConnections,
233
- autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,
234
- autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority,
235
- autoDialPeerRetryThreshold: init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold,
236
- autoDialDiscoveredPeersDebounce: init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce,
237
- maxQueueLength: init.autoDialMaxQueueLength ?? defaultOptions.autoDialMaxQueueLength
238
- })
239
-
240
212
  // controls what happens when we have too many connections
241
213
  this.connectionPruner = new ConnectionPruner({
242
214
  connectionManager: this,
@@ -259,6 +231,18 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
259
231
  },
260
232
  connections: this.connections
261
233
  })
234
+
235
+ this.reconnectQueue = new ReconnectQueue({
236
+ events: components.events,
237
+ peerStore: components.peerStore,
238
+ logger: components.logger,
239
+ connectionManager: this
240
+ }, {
241
+ retries: init.reconnectRetries,
242
+ retryInterval: init.reconnectRetryInterval,
243
+ backoffFactor: init.reconnectBackoffFactor,
244
+ maxParallelReconnects: init.maxParallelReconnects
245
+ })
262
246
  }
263
247
 
264
248
  readonly [Symbol.toStringTag] = '@libp2p/connection-manager'
@@ -350,45 +334,23 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
350
334
  }
351
335
  })
352
336
 
353
- this.dialQueue.start()
354
- this.autoDial.start()
337
+ await start(
338
+ this.dialQueue,
339
+ this.reconnectQueue
340
+ )
355
341
 
356
342
  this.started = true
357
343
  this.log('started')
358
344
  }
359
345
 
360
- async afterStart (): Promise<void> {
361
- // re-connect to any peers with the KEEP_ALIVE tag
362
- void Promise.resolve()
363
- .then(async () => {
364
- const keepAlivePeers: Peer[] = await this.peerStore.all({
365
- filters: [(peer) => {
366
- return peer.tags.has(KEEP_ALIVE)
367
- }]
368
- })
369
-
370
- await Promise.all(
371
- keepAlivePeers.map(async peer => {
372
- await this.openConnection(peer.id)
373
- .catch(err => {
374
- this.log.error(err)
375
- })
376
- })
377
- )
378
- })
379
- .catch(err => {
380
- this.log.error(err)
381
- })
382
-
383
- this.autoDial.afterStart()
384
- }
385
-
386
346
  /**
387
347
  * Stops the Connection Manager
388
348
  */
389
349
  async stop (): Promise<void> {
390
- this.dialQueue.stop()
391
- this.autoDial.stop()
350
+ await stop(
351
+ this.reconnectQueue,
352
+ this.dialQueue
353
+ )
392
354
 
393
355
  // Close all connections we're tracking
394
356
  const tasks: Array<Promise<void>> = []
@@ -495,7 +457,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
495
457
 
496
458
  async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {
497
459
  if (!this.isStarted()) {
498
- throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED)
460
+ throw new NotStartedError('Not started')
499
461
  }
500
462
 
501
463
  options.signal?.throwIfAborted()
@@ -505,10 +467,10 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
505
467
  if (peerId != null && options.force !== true) {
506
468
  this.log('dial %p', peerId)
507
469
  const existingConnection = this.getConnections(peerId)
508
- .find(conn => !conn.transient)
470
+ .find(conn => conn.limits == null)
509
471
 
510
472
  if (existingConnection != null) {
511
- this.log('had an existing non-transient connection to %p', peerId)
473
+ this.log('had an existing non-limited connection to %p', peerId)
512
474
 
513
475
  options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
514
476
  return existingConnection