libp2p 0.43.4 → 0.44.0-44b30cc8

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 (105) hide show
  1. package/dist/index.min.js +30 -30
  2. package/dist/src/autonat/index.d.ts +1 -2
  3. package/dist/src/autonat/index.d.ts.map +1 -1
  4. package/dist/src/autonat/index.js +4 -6
  5. package/dist/src/autonat/index.js.map +1 -1
  6. package/dist/src/circuit-relay/transport/reservation-store.d.ts +1 -1
  7. package/dist/src/circuit-relay/transport/reservation-store.d.ts.map +1 -1
  8. package/dist/src/circuit-relay/utils.d.ts.map +1 -1
  9. package/dist/src/circuit-relay/utils.js +3 -1
  10. package/dist/src/circuit-relay/utils.js.map +1 -1
  11. package/dist/src/components.d.ts +1 -6
  12. package/dist/src/components.d.ts.map +1 -1
  13. package/dist/src/components.js +0 -10
  14. package/dist/src/components.js.map +1 -1
  15. package/dist/src/config.d.ts.map +1 -1
  16. package/dist/src/config.js +0 -9
  17. package/dist/src/config.js.map +1 -1
  18. package/dist/src/connection-manager/auto-dial.d.ts +36 -0
  19. package/dist/src/connection-manager/auto-dial.d.ts.map +1 -0
  20. package/dist/src/connection-manager/auto-dial.js +122 -0
  21. package/dist/src/connection-manager/auto-dial.js.map +1 -0
  22. package/dist/src/connection-manager/connection-pruner.d.ts +28 -0
  23. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -0
  24. package/dist/src/connection-manager/connection-pruner.js +96 -0
  25. package/dist/src/connection-manager/connection-pruner.js.map +1 -0
  26. package/dist/src/connection-manager/constants.d.ts +49 -0
  27. package/dist/src/connection-manager/constants.d.ts.map +1 -0
  28. package/dist/src/connection-manager/constants.js +49 -0
  29. package/dist/src/connection-manager/constants.js.map +1 -0
  30. package/dist/src/connection-manager/dial-queue.d.ts +77 -0
  31. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -0
  32. package/dist/src/connection-manager/dial-queue.js +366 -0
  33. package/dist/src/connection-manager/dial-queue.js.map +1 -0
  34. package/dist/src/connection-manager/index.d.ts +64 -69
  35. package/dist/src/connection-manager/index.d.ts.map +1 -1
  36. package/dist/src/connection-manager/index.js +116 -234
  37. package/dist/src/connection-manager/index.js.map +1 -1
  38. package/dist/src/connection-manager/utils.d.ts +9 -0
  39. package/dist/src/connection-manager/utils.d.ts.map +1 -0
  40. package/dist/src/connection-manager/utils.js +66 -0
  41. package/dist/src/connection-manager/utils.js.map +1 -0
  42. package/dist/src/fetch/index.js +3 -3
  43. package/dist/src/fetch/index.js.map +1 -1
  44. package/dist/src/identify/index.js +5 -5
  45. package/dist/src/identify/index.js.map +1 -1
  46. package/dist/src/insecure/index.d.ts.map +1 -1
  47. package/dist/src/insecure/index.js +3 -1
  48. package/dist/src/insecure/index.js.map +1 -1
  49. package/dist/src/libp2p.d.ts +4 -2
  50. package/dist/src/libp2p.d.ts.map +1 -1
  51. package/dist/src/libp2p.js +7 -13
  52. package/dist/src/libp2p.js.map +1 -1
  53. package/dist/src/upgrader.d.ts +8 -8
  54. package/dist/src/upgrader.d.ts.map +1 -1
  55. package/dist/src/upgrader.js +2 -1
  56. package/dist/src/upgrader.js.map +1 -1
  57. package/package.json +40 -40
  58. package/src/autonat/index.ts +6 -9
  59. package/src/circuit-relay/transport/reservation-store.ts +1 -1
  60. package/src/circuit-relay/utils.ts +3 -1
  61. package/src/components.ts +1 -17
  62. package/src/config.ts +0 -9
  63. package/src/connection-manager/auto-dial.ts +170 -0
  64. package/src/connection-manager/connection-pruner.ts +137 -0
  65. package/src/connection-manager/constants.ts +60 -0
  66. package/src/connection-manager/dial-queue.ts +504 -0
  67. package/src/connection-manager/index.ts +189 -323
  68. package/src/connection-manager/utils.ts +76 -0
  69. package/src/fetch/index.ts +4 -4
  70. package/src/identify/index.ts +5 -5
  71. package/src/insecure/index.ts +9 -5
  72. package/src/libp2p.ts +9 -15
  73. package/src/upgrader.ts +14 -11
  74. package/src/version.ts +1 -1
  75. package/dist/src/connection-manager/auto-dialler.d.ts +0 -42
  76. package/dist/src/connection-manager/auto-dialler.d.ts.map +0 -1
  77. package/dist/src/connection-manager/auto-dialler.js +0 -105
  78. package/dist/src/connection-manager/auto-dialler.js.map +0 -1
  79. package/dist/src/connection-manager/dialer/dial-request.d.ts +0 -27
  80. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +0 -1
  81. package/dist/src/connection-manager/dialer/dial-request.js +0 -114
  82. package/dist/src/connection-manager/dialer/dial-request.js.map +0 -1
  83. package/dist/src/connection-manager/dialer/index.d.ts +0 -121
  84. package/dist/src/connection-manager/dialer/index.d.ts.map +0 -1
  85. package/dist/src/connection-manager/dialer/index.js +0 -324
  86. package/dist/src/connection-manager/dialer/index.js.map +0 -1
  87. package/dist/src/connection-manager/latency-monitor.d.ts +0 -120
  88. package/dist/src/connection-manager/latency-monitor.d.ts.map +0 -1
  89. package/dist/src/connection-manager/latency-monitor.js +0 -220
  90. package/dist/src/connection-manager/latency-monitor.js.map +0 -1
  91. package/dist/src/connection-manager/visibility-change-emitter.d.ts +0 -66
  92. package/dist/src/connection-manager/visibility-change-emitter.d.ts.map +0 -1
  93. package/dist/src/connection-manager/visibility-change-emitter.js +0 -118
  94. package/dist/src/connection-manager/visibility-change-emitter.js.map +0 -1
  95. package/dist/src/constants.d.ts +0 -27
  96. package/dist/src/constants.d.ts.map +0 -1
  97. package/dist/src/constants.js +0 -31
  98. package/dist/src/constants.js.map +0 -1
  99. package/dist/typedoc-urls.json +0 -41
  100. package/src/connection-manager/auto-dialler.ts +0 -158
  101. package/src/connection-manager/dialer/dial-request.ts +0 -144
  102. package/src/connection-manager/dialer/index.ts +0 -461
  103. package/src/connection-manager/latency-monitor.ts +0 -319
  104. package/src/connection-manager/visibility-change-emitter.ts +0 -135
  105. package/src/constants.ts +0 -36
@@ -1,69 +1,91 @@
1
1
  import { logger } from '@libp2p/logger'
2
2
  import { CodeError } from '@libp2p/interfaces/errors'
3
- import mergeOptions from 'merge-options'
4
- import { LatencyMonitor, SummaryObject } from './latency-monitor.js'
5
3
  import type { AbortOptions } from '@libp2p/interfaces'
6
4
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
7
5
  import type { Startable } from '@libp2p/interfaces/startable'
8
6
  import { codes } from '../errors.js'
9
- import { isPeerId, PeerId } from '@libp2p/interface-peer-id'
7
+ import type { PeerId } from '@libp2p/interface-peer-id'
10
8
  import { setMaxListeners } from 'events'
11
9
  import type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'
12
- import type { ConnectionManager, ConnectionManagerEvents, Dialer } from '@libp2p/interface-connection-manager'
13
- import * as STATUS from '@libp2p/interface-connection/status'
10
+ import type { ConnectionManager, ConnectionManagerEvents, PendingDial } from '@libp2p/interface-connection-manager'
14
11
  import type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'
15
- import { multiaddr, Multiaddr, Resolver } from '@multiformats/multiaddr'
16
- import { PeerMap } from '@libp2p/peer-collections'
17
- import { TimeoutController } from 'timeout-abort-controller'
12
+ import { Multiaddr, Resolver, multiaddr } from '@multiformats/multiaddr'
18
13
  import { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'
19
14
  import { RateLimiterMemory } from 'rate-limiter-flexible'
20
15
  import type { Metrics } from '@libp2p/interface-metrics'
21
- import type { Upgrader } from '@libp2p/interface-transport'
16
+ import type { TransportManager, Upgrader } from '@libp2p/interface-transport'
22
17
  import { getPeerAddress } from '../get-peer.js'
18
+ import { AutoDial } from './auto-dial.js'
19
+ import { DialQueue } from './dial-queue.js'
20
+ import { ConnectionPruner } from './connection-pruner.js'
21
+ import type { ConnectionGater } from '@libp2p/interface-connection-gater'
22
+ import { PeerMap } from '@libp2p/peer-collections'
23
+ import { publicAddressesFirst } from '@libp2p/utils/address-sort'
24
+ import { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_PRIORITY, DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, MIN_CONNECTIONS } from './constants.js'
25
+ import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
23
26
 
24
27
  const log = logger('libp2p:connection-manager')
25
28
 
26
- export interface ConnectionManagerConfig {
29
+ const DEFAULT_DIAL_PRIORITY = 50
30
+
31
+ export interface ConnectionManagerInit {
27
32
  /**
28
- * The maximum number of connections libp2p is willing to have before it starts disconnecting. Defaults to `Infinity`
33
+ * The maximum number of connections libp2p is willing to have before it starts
34
+ * pruning connections to reduce resource usage. (default: 300)
29
35
  */
30
- maxConnections: number
36
+ maxConnections?: number
31
37
 
32
38
  /**
33
- * The minimum number of connections below which libp2p not activate preemptive disconnections. Defaults to `0`.
39
+ * The minimum number of connections below which libp2p will start to dial peers
40
+ * from the peer book. Setting this to 0 effectively disables this behaviour.
41
+ * (default: 50)
34
42
  */
35
- minConnections: number
43
+ minConnections?: number
36
44
 
37
45
  /**
38
- * Sets the maximum event loop delay (measured in milliseconds) this node is willing to endure before it starts disconnecting peers. Defaults to `Infinity`.
46
+ * How long to wait between attempting to keep our number of concurrent connections
47
+ * above minConnections (default: 5000)
39
48
  */
40
- maxEventLoopDelay?: number
49
+ autoDialInterval?: number
41
50
 
42
51
  /**
43
- * Sets the poll interval (in milliseconds) for assessing the current state and determining if this peer needs to force a disconnect. Defaults to `2000` (2 seconds).
52
+ * When dialling peers from the peer book to keep the number of open connections
53
+ * above `minConnections`, add dials for this many peers to the dial queue
54
+ * at once. (default: 25)
44
55
  */
45
- pollInterval?: number
56
+ autoDialConcurrency?: number
46
57
 
47
58
  /**
48
- * How long to wait between attempting to keep our number of concurrent connections
49
- * above minConnections
59
+ * To allow user dials to take priority over auto dials, use this value as the
60
+ * dial priority. (default: 0)
50
61
  */
51
- autoDialInterval: number
62
+ autoDialPriority?: number
52
63
 
53
64
  /**
54
- * Sort the known addresses of a peer before trying to dial
65
+ * Sort the known addresses of a peer before trying to dial, By default public
66
+ * addresses will be dialled before private (e.g. loopback or LAN) addresses.
55
67
  */
56
68
  addressSorter?: AddressSorter
57
69
 
58
70
  /**
59
- * Number of max concurrent dials
71
+ * The maximum number of dials across all peers to execute in parallel.
72
+ * (default: 100)
60
73
  */
61
74
  maxParallelDials?: number
62
75
 
63
76
  /**
64
- * Number of max addresses to dial for a given peer
77
+ * To prevent individual peers with large amounts of multiaddrs swamping the
78
+ * dial queue, this value controls how many addresses to dial in parallel per
79
+ * peer. So for example if two peers have 10 addresses and this value is set
80
+ * at 5, we will dial 5 addresses from each at a time. (default: 10)
65
81
  */
66
- maxAddrsToDial?: number
82
+ maxParallelDialsPerPeer?: number
83
+
84
+ /**
85
+ * Maximum number of addresses allowed for a given peer - if a peer has more
86
+ * addresses than this then the dial will fail. (default: 25)
87
+ */
88
+ maxPeerAddrsToDial?: number
67
89
 
68
90
  /**
69
91
  * How long a dial attempt is allowed to take, including DNS resolution
@@ -73,26 +95,15 @@ export interface ConnectionManagerConfig {
73
95
 
74
96
  /**
75
97
  * When a new inbound connection is opened, the upgrade process (e.g. protect,
76
- * encrypt, multiplex etc) must complete within this number of ms.
77
- */
78
- inboundUpgradeTimeout: number
79
-
80
- /**
81
- * Number of max concurrent dials per peer
98
+ * encrypt, multiplex etc) must complete within this number of ms. (default: 30s)
82
99
  */
83
- maxDialsPerPeer?: number
100
+ inboundUpgradeTimeout?: number
84
101
 
85
102
  /**
86
- * Multiaddr resolvers to use when dialing
103
+ * Multiaddr resolvers to use when dialling
87
104
  */
88
105
  resolvers?: Record<string, Resolver>
89
106
 
90
- /**
91
- * On startup we try to dial any peer that has previously been
92
- * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)
93
- */
94
- startupReconnectTimeout?: number
95
-
96
107
  /**
97
108
  * A list of multiaddrs that will always be allowed (except if they are in the
98
109
  * deny list) to open connections to this node even if we've reached maxConnections
@@ -107,103 +118,152 @@ export interface ConnectionManagerConfig {
107
118
 
108
119
  /**
109
120
  * If more than this many connections are opened per second by a single
110
- * host, reject subsequent connections
121
+ * host, reject subsequent connections. (default: 5)
111
122
  */
112
123
  inboundConnectionThreshold?: number
113
124
 
114
125
  /**
115
126
  * The maximum number of parallel incoming connections allowed that have yet to
116
- * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc
127
+ * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc.
128
+ * (default: 10)
117
129
  */
118
130
  maxIncomingPendingConnections?: number
119
131
  }
120
132
 
121
- const defaultOptions: Partial<ConnectionManagerConfig> = {
122
- maxConnections: Infinity,
123
- minConnections: 0,
124
- maxEventLoopDelay: Infinity,
125
- pollInterval: 2000,
126
- autoDialInterval: 10000,
127
- inboundConnectionThreshold: 5,
128
- maxIncomingPendingConnections: 10
133
+ const defaultOptions = {
134
+ minConnections: MIN_CONNECTIONS,
135
+ maxConnections: MAX_CONNECTIONS,
136
+ inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,
137
+ maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS,
138
+ autoDialConcurrency: AUTO_DIAL_CONCURRENCY,
139
+ autoDialPriority: AUTO_DIAL_PRIORITY
129
140
  }
130
141
 
131
- const STARTUP_RECONNECT_TIMEOUT = 60000
132
-
133
142
  export interface DefaultConnectionManagerComponents {
134
143
  peerId: PeerId
135
144
  metrics?: Metrics
136
145
  upgrader: Upgrader
137
146
  peerStore: PeerStore
138
- dialer: Dialer
147
+ transportManager: TransportManager
148
+ connectionGater: ConnectionGater
139
149
  }
140
150
 
141
- export type ConnectionManagerInit = ConnectionManagerConfig
151
+ export interface OpenConnectionOptions extends AbortOptions {
152
+ priority?: number
153
+ }
142
154
 
143
155
  /**
144
156
  * Responsible for managing known connections.
145
157
  */
146
158
  export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEvents> implements ConnectionManager, Startable {
147
- private readonly components: DefaultConnectionManagerComponents
148
- private readonly opts: ConnectionManagerInit
149
- private readonly connections: Map<string, Connection[]>
150
159
  private started: boolean
151
- private readonly latencyMonitor?: LatencyMonitor
152
- private readonly startupReconnectTimeout: number
153
- private connectOnStartupController?: TimeoutController
154
- private readonly dialTimeout: number
160
+ private readonly connections: PeerMap<Connection[]>
155
161
  private readonly allow: Multiaddr[]
156
162
  private readonly deny: Multiaddr[]
157
- private readonly inboundConnectionRateLimiter: RateLimiterMemory
163
+ private readonly maxIncomingPendingConnections: number
158
164
  private incomingPendingConnections: number
165
+ private readonly maxConnections: number
159
166
 
160
- constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerConfig) {
167
+ public readonly dialQueue: DialQueue
168
+ public readonly autoDial: AutoDial
169
+ public readonly connectionPruner: ConnectionPruner
170
+ private readonly inboundConnectionRateLimiter: RateLimiterMemory
171
+
172
+ private readonly peerStore: PeerStore
173
+ private readonly metrics?: Metrics
174
+
175
+ constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerInit = {}) {
161
176
  super()
162
177
 
163
- this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)
178
+ this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections
179
+ const minConnections = init.minConnections ?? defaultOptions.minConnections
164
180
 
165
- if (this.opts.maxConnections < this.opts.minConnections) {
181
+ if (this.maxConnections < minConnections) {
166
182
  throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS)
167
183
  }
168
184
 
169
- log('options: %o', this.opts)
170
-
171
- this.components = components
172
-
173
185
  /**
174
186
  * Map of connections per peer
175
187
  */
176
- this.connections = new Map()
188
+ this.connections = new PeerMap()
177
189
 
178
190
  this.started = false
179
191
 
180
- if (init.maxEventLoopDelay != null && init.maxEventLoopDelay > 0 && init.maxEventLoopDelay !== Infinity) {
181
- this.latencyMonitor = new LatencyMonitor({
182
- latencyCheckIntervalMs: init.pollInterval,
183
- dataEmitIntervalMs: init.pollInterval
184
- })
185
- }
186
-
187
192
  try {
188
193
  // This emitter gets listened to a lot
189
194
  setMaxListeners?.(Infinity, this)
190
195
  } catch {}
191
196
 
197
+ this.peerStore = components.peerStore
198
+ this.metrics = components.metrics
199
+
192
200
  this.onConnect = this.onConnect.bind(this)
193
201
  this.onDisconnect = this.onDisconnect.bind(this)
194
202
 
195
- this.startupReconnectTimeout = init.startupReconnectTimeout ?? STARTUP_RECONNECT_TIMEOUT
196
- this.dialTimeout = init.dialTimeout ?? 30000
197
-
203
+ // allow/deny lists
198
204
  this.allow = (init.allow ?? []).map(ma => multiaddr(ma))
199
205
  this.deny = (init.deny ?? []).map(ma => multiaddr(ma))
200
206
 
207
+ this.incomingPendingConnections = 0
208
+ this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections
209
+
210
+ // controls individual peers trying to dial us too quickly
201
211
  this.inboundConnectionRateLimiter = new RateLimiterMemory({
202
- points: this.opts.inboundConnectionThreshold,
212
+ points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,
203
213
  duration: 1
204
214
  })
205
215
 
206
- this.incomingPendingConnections = 0
216
+ // controls what happens when we don't have enough connections
217
+ this.autoDial = new AutoDial({
218
+ connectionManager: this,
219
+ peerStore: components.peerStore
220
+ }, {
221
+ minConnections,
222
+ autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,
223
+ autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority
224
+ })
225
+ // check the min connection limit whenever a peer disconnects
226
+ this.addEventListener('peer:disconnect', () => {
227
+ this.autoDial.autoDial()
228
+ .catch(err => {
229
+ log.error(err)
230
+ })
231
+ })
232
+
233
+ // controls what happens when we have too many connections
234
+ this.connectionPruner = new ConnectionPruner({
235
+ connectionManager: this,
236
+ peerStore: components.peerStore
237
+ }, {
238
+ maxConnections: this.maxConnections,
239
+ allow: this.allow
240
+ })
241
+ // check the max connection limit whenever a peer connects
242
+ this.addEventListener('peer:connect', () => {
243
+ this.connectionPruner.maybePruneConnections()
244
+ .catch(err => {
245
+ log.error(err)
246
+ })
247
+ })
248
+
249
+ this.dialQueue = new DialQueue({
250
+ peerId: components.peerId,
251
+ metrics: components.metrics,
252
+ peerStore: components.peerStore,
253
+ transportManager: components.transportManager,
254
+ connectionGater: components.connectionGater
255
+ }, {
256
+ addressSorter: init.addressSorter ?? publicAddressesFirst,
257
+ maxParallelDials: init.maxParallelDials ?? MAX_PARALLEL_DIALS,
258
+ maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? MAX_PEER_ADDRS_TO_DIAL,
259
+ dialTimeout: init.dialTimeout ?? DIAL_TIMEOUT,
260
+ resolvers: init.resolvers ?? {
261
+ dnsaddr: dnsaddrResolver
262
+ }
263
+ })
264
+
265
+ components.upgrader.addEventListener('connection', this.onConnect)
266
+ components.upgrader.addEventListener('connectionEnd', this.onDisconnect)
207
267
  }
208
268
 
209
269
  isStarted (): boolean {
@@ -216,7 +276,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
216
276
  */
217
277
  async start (): Promise<void> {
218
278
  // track inbound/outbound connections
219
- this.components.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {
279
+ this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {
220
280
  calculate: () => {
221
281
  const metric = {
222
282
  inbound: 0,
@@ -238,7 +298,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
238
298
  })
239
299
 
240
300
  // track total number of streams per protocol
241
- this.components.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {
301
+ this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {
242
302
  label: 'protocol',
243
303
  calculate: () => {
244
304
  const metric: Record<string, number> = {}
@@ -258,7 +318,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
258
318
  })
259
319
 
260
320
  // track 90th percentile of streams per protocol
261
- this.components.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {
321
+ this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {
262
322
  label: 'protocol',
263
323
  calculate: () => {
264
324
  const allStreams: Record<string, number[]> = {}
@@ -293,26 +353,20 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
293
353
  }
294
354
  })
295
355
 
296
- // latency monitor
297
- this.latencyMonitor?.start()
298
- this._onLatencyMeasure = this._onLatencyMeasure.bind(this)
299
- this.latencyMonitor?.addEventListener('data', this._onLatencyMeasure)
356
+ this.autoDial.start()
300
357
 
301
358
  this.started = true
302
359
  log('started')
303
360
  }
304
361
 
305
362
  async afterStart (): Promise<void> {
306
- this.components.upgrader.addEventListener('connection', this.onConnect)
307
- this.components.upgrader.addEventListener('connectionEnd', this.onDisconnect)
308
-
309
363
  // re-connect to any peers with the KEEP_ALIVE tag
310
364
  void Promise.resolve()
311
365
  .then(async () => {
312
366
  const keepAlivePeers: PeerId[] = []
313
367
 
314
- for (const peer of await this.components.peerStore.all()) {
315
- const tags = await this.components.peerStore.getTags(peer.id)
368
+ for (const peer of await this.peerStore.all()) {
369
+ const tags = await this.peerStore.getTags(peer.id)
316
370
  const hasKeepAlive = tags.filter(tag => tag.name === KEEP_ALIVE).length > 0
317
371
 
318
372
  if (hasKeepAlive) {
@@ -320,19 +374,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
320
374
  }
321
375
  }
322
376
 
323
- this.connectOnStartupController?.clear()
324
- this.connectOnStartupController = new TimeoutController(this.startupReconnectTimeout)
325
-
326
- try {
327
- // fails on node < 15.4
328
- setMaxListeners?.(Infinity, this.connectOnStartupController.signal)
329
- } catch {}
330
-
331
377
  await Promise.all(
332
378
  keepAlivePeers.map(async peer => {
333
- await this.openConnection(peer, {
334
- signal: this.connectOnStartupController?.signal
335
- })
379
+ await this.openConnection(peer)
336
380
  .catch(err => {
337
381
  log.error(err)
338
382
  })
@@ -342,34 +386,17 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
342
386
  .catch(err => {
343
387
  log.error(err)
344
388
  })
345
- .finally(() => {
346
- this.connectOnStartupController?.clear()
347
- })
348
- }
349
389
 
350
- async beforeStop (): Promise<void> {
351
- // if we are still dialing KEEP_ALIVE peers, abort those dials
352
- this.connectOnStartupController?.abort()
353
- this.components.upgrader.removeEventListener('connection', this.onConnect)
354
- this.components.upgrader.removeEventListener('connectionEnd', this.onDisconnect)
390
+ this.autoDial.afterStart()
355
391
  }
356
392
 
357
393
  /**
358
394
  * Stops the Connection Manager
359
395
  */
360
396
  async stop (): Promise<void> {
361
- this.latencyMonitor?.removeEventListener('data', this._onLatencyMeasure)
362
- this.latencyMonitor?.stop()
363
-
364
- this.started = false
365
- await this._close()
366
- log('stopped')
367
- }
397
+ this.dialQueue.stop()
398
+ this.autoDial.stop()
368
399
 
369
- /**
370
- * Cleans up the connections
371
- */
372
- async _close (): Promise<void> {
373
400
  // Close all connections we're tracking
374
401
  const tasks: Array<Promise<void>> = []
375
402
  for (const connectionList of this.connections.values()) {
@@ -387,6 +414,8 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
387
414
  log('closing %d connections', tasks.length)
388
415
  await Promise.all(tasks)
389
416
  this.connections.clear()
417
+
418
+ log('stopped')
390
419
  }
391
420
 
392
421
  onConnect (evt: CustomEvent<Connection>): void {
@@ -408,23 +437,18 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
408
437
  }
409
438
 
410
439
  const peerId = connection.remotePeer
411
- const peerIdStr = peerId.toString()
412
- const storedConns = this.connections.get(peerIdStr)
440
+ const storedConns = this.connections.get(peerId)
413
441
 
414
442
  if (storedConns != null) {
415
443
  storedConns.push(connection)
416
444
  } else {
417
- this.connections.set(peerIdStr, [connection])
445
+ this.connections.set(peerId, [connection])
418
446
  }
419
447
 
420
448
  if (peerId.publicKey != null) {
421
- await this.components.peerStore.keyBook.set(peerId, peerId.publicKey)
449
+ await this.peerStore.keyBook.set(peerId, peerId.publicKey)
422
450
  }
423
451
 
424
- const numConnections = this.getConnections().length
425
- const toPrune = numConnections - this.opts.maxConnections
426
-
427
- await this._checkMaxLimit('maxConnections', numConnections, toPrune)
428
452
  this.dispatchEvent(new CustomEvent<Connection>('peer:connect', { detail: connection }))
429
453
  }
430
454
 
@@ -439,7 +463,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
439
463
  return
440
464
  }
441
465
 
442
- const peerId = connection.remotePeer.toString()
466
+ const peerId = connection.remotePeer
443
467
  let storedConn = this.connections.get(peerId)
444
468
 
445
469
  if (storedConn != null && storedConn.length > 1) {
@@ -453,7 +477,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
453
477
 
454
478
  getConnections (peerId?: PeerId): Connection[] {
455
479
  if (peerId != null) {
456
- return this.connections.get(peerId.toString()) ?? []
480
+ return this.connections.get(peerId) ?? []
457
481
  }
458
482
 
459
483
  let conns: Connection[] = []
@@ -465,19 +489,15 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
465
489
  return conns
466
490
  }
467
491
 
468
- getConnectionsMap (): Map<string, Connection[]> {
492
+ getConnectionsMap (): PeerMap<Connection[]> {
469
493
  return this.connections
470
494
  }
471
495
 
472
- async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise<Connection> {
473
- const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)
474
-
475
- if (peerId == null && multiaddrs.length === 0) {
476
- throw new CodeError('Can only open connections to PeerIds or Multiaddrs', codes.ERR_INVALID_PARAMETERS)
477
- }
496
+ async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {
497
+ const { peerId } = getPeerAddress(peerIdOrMultiaddr)
478
498
 
479
499
  if (peerId != null) {
480
- log('dial to', peerId)
500
+ log('dial %p', peerId)
481
501
  const existingConnections = this.getConnections(peerId)
482
502
 
483
503
  if (existingConnections.length > 0) {
@@ -487,53 +507,37 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
487
507
  }
488
508
  }
489
509
 
490
- let timeoutController: TimeoutController | undefined
491
-
492
- if (options?.signal == null) {
493
- timeoutController = new TimeoutController(this.dialTimeout)
494
- options.signal = timeoutController.signal
510
+ const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {
511
+ ...options,
512
+ priority: options.priority ?? DEFAULT_DIAL_PRIORITY
513
+ })
514
+ let peerConnections = this.connections.get(connection.remotePeer)
495
515
 
496
- try {
497
- // fails on node < 15.4
498
- setMaxListeners?.(Infinity, timeoutController.signal)
499
- } catch {}
516
+ if (peerConnections == null) {
517
+ peerConnections = []
518
+ this.connections.set(connection.remotePeer, peerConnections)
500
519
  }
501
520
 
502
- try {
503
- // @ts-expect-error until https://github.com/libp2p/js-libp2p-interfaces/pull/351 is merged
504
- const connection = await this.components.dialer.dial(peerIdOrMultiaddr, options)
505
- let peerConnections = this.connections.get(connection.remotePeer.toString())
506
-
507
- if (peerConnections == null) {
508
- peerConnections = []
509
- this.connections.set(connection.remotePeer.toString(), peerConnections)
510
- }
511
-
512
- // we get notified of connections via the Upgrader emitting "connection"
513
- // events, double check we aren't already tracking this connection before
514
- // storing it
515
- let trackedConnection = false
521
+ // we get notified of connections via the Upgrader emitting "connection"
522
+ // events, double check we aren't already tracking this connection before
523
+ // storing it
524
+ let trackedConnection = false
516
525
 
517
- for (const conn of peerConnections) {
518
- if (conn.id === connection.id) {
519
- trackedConnection = true
520
- }
521
- }
522
-
523
- if (!trackedConnection) {
524
- peerConnections.push(connection)
526
+ for (const conn of peerConnections) {
527
+ if (conn.id === connection.id) {
528
+ trackedConnection = true
525
529
  }
530
+ }
526
531
 
527
- return connection
528
- } finally {
529
- if (timeoutController != null) {
530
- timeoutController.clear()
531
- }
532
+ if (!trackedConnection) {
533
+ peerConnections.push(connection)
532
534
  }
535
+
536
+ return connection
533
537
  }
534
538
 
535
539
  async closeConnections (peerId: PeerId): Promise<void> {
536
- const connections = this.connections.get(peerId.toString()) ?? []
540
+ const connections = this.connections.get(peerId) ?? []
537
541
 
538
542
  await Promise.all(
539
543
  connections.map(async connection => {
@@ -542,148 +546,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
542
546
  )
543
547
  }
544
548
 
545
- /**
546
- * Get all open connections with a peer
547
- */
548
- getAll (peerId: PeerId): Connection[] {
549
- if (!isPeerId(peerId)) {
550
- throw new CodeError('peerId must be an instance of peer-id', codes.ERR_INVALID_PARAMETERS)
551
- }
552
-
553
- const id = peerId.toString()
554
- const connections = this.connections.get(id)
555
-
556
- // Return all open connections
557
- if (connections != null) {
558
- return connections.filter(connection => connection.stat.status === STATUS.OPEN)
559
- }
560
-
561
- return []
562
- }
563
-
564
- /**
565
- * If the event loop is slow, maybe close a connection
566
- */
567
- _onLatencyMeasure (evt: CustomEvent<SummaryObject>): void {
568
- const { detail: summary } = evt
569
-
570
- this._checkMaxLimit('maxEventLoopDelay', summary.avgMs, 1)
571
- .catch(err => {
572
- log.error(err)
573
- })
574
- }
575
-
576
- /**
577
- * If the `value` of `name` has exceeded its limit, maybe close a connection
578
- */
579
- async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1): Promise<void> {
580
- const limit = this.opts[name]
581
-
582
- if (limit == null) {
583
- log.trace('limit %s was not set so it cannot be applied', name)
584
- return
585
- }
586
- if (limit === Infinity) {
587
- log.trace('limit %s is Infinity so it cannot be applied', name)
588
- return
589
- }
590
-
591
- log.trace('checking limit of %s. current value: %d of %d', name, value, limit)
592
- if (value > limit) {
593
- log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.peerId, name, value, limit, toPrune)
594
- await this._pruneConnections(toPrune)
595
- }
596
- }
597
-
598
- /**
599
- * If we have more connections than our maximum, select some excess connections
600
- * to prune based on peer value
601
- */
602
- async _pruneConnections (toPrune: number): Promise<void> {
603
- const connections = this.getConnections()
604
- const peerValues = new PeerMap<number>()
605
-
606
- // work out peer values
607
- for (const connection of connections) {
608
- const remotePeer = connection.remotePeer
609
-
610
- if (peerValues.has(remotePeer)) {
611
- continue
612
- }
613
-
614
- const tags = await this.components.peerStore.getTags(remotePeer)
615
-
616
- // sum all tag values
617
- peerValues.set(remotePeer, tags.reduce((acc, curr) => {
618
- return acc + curr.value
619
- }, 0))
620
- }
621
-
622
- // sort by value, lowest to highest
623
- const sortedConnections = connections.sort((a, b) => {
624
- const peerAValue = peerValues.get(a.remotePeer) ?? 0
625
- const peerBValue = peerValues.get(b.remotePeer) ?? 0
626
-
627
- if (peerAValue > peerBValue) {
628
- return 1
629
- }
630
-
631
- if (peerAValue < peerBValue) {
632
- return -1
633
- }
634
-
635
- // if the peers have an equal tag value then we want to close short-lived connections first
636
- const connectionALifespan = a.stat.timeline.open
637
- const connectionBLifespan = b.stat.timeline.open
638
-
639
- if (connectionALifespan < connectionBLifespan) {
640
- return 1
641
- }
642
-
643
- if (connectionALifespan > connectionBLifespan) {
644
- return -1
645
- }
646
-
647
- return 0
648
- })
649
-
650
- // close some connections
651
- const toClose = []
652
-
653
- for (const connection of sortedConnections) {
654
- log('too many connections open - closing a connection to %p', connection.remotePeer)
655
- // check allow list
656
- const connectionInAllowList = this.allow.some((ma) => {
657
- return connection.remoteAddr.toString().startsWith(ma.toString())
658
- })
659
-
660
- // Connections in the allow list should be excluded from pruning
661
- if (!connectionInAllowList) {
662
- toClose.push(connection)
663
- }
664
-
665
- if (toClose.length === toPrune) {
666
- break
667
- }
668
- }
669
-
670
- // close connections
671
- await Promise.all(
672
- toClose.map(async connection => {
673
- try {
674
- await connection.close()
675
- } catch (err) {
676
- log.error(err)
677
- }
678
-
679
- // TODO: should not need to invoke this manually
680
- this.onDisconnect(new CustomEvent<Connection>('connectionEnd', {
681
- detail: connection
682
- }))
683
- })
684
- )
685
- }
686
-
687
549
  async acceptIncomingConnection (maConn: MultiaddrConnection): Promise<boolean> {
688
550
  // check deny list
689
551
  const denyConnection = this.deny.some(ma => {
@@ -707,7 +569,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
707
569
  }
708
570
 
709
571
  // check pending connections
710
- if (this.incomingPendingConnections === this.opts.maxIncomingPendingConnections) {
572
+ if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {
711
573
  log('connection from %s refused - incomingPendingConnections exceeded by peer %s', maConn.remoteAddr)
712
574
  return false
713
575
  }
@@ -723,7 +585,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
723
585
  }
724
586
  }
725
587
 
726
- if (this.getConnections().length < this.opts.maxConnections) {
588
+ if (this.getConnections().length < this.maxConnections) {
727
589
  this.incomingPendingConnections++
728
590
 
729
591
  return true
@@ -736,4 +598,8 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
736
598
  afterUpgradeInbound (): void {
737
599
  this.incomingPendingConnections--
738
600
  }
601
+
602
+ getDialQueue (): PendingDial[] {
603
+ return this.dialQueue.pendingDials
604
+ }
739
605
  }