libp2p 0.40.0 → 0.41.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.
Files changed (78) hide show
  1. package/README.md +21 -2
  2. package/dist/src/address-manager/index.d.ts.map +1 -1
  3. package/dist/src/address-manager/index.js +1 -1
  4. package/dist/src/address-manager/index.js.map +1 -1
  5. package/dist/src/config.d.ts.map +1 -1
  6. package/dist/src/config.js +0 -11
  7. package/dist/src/config.js.map +1 -1
  8. package/dist/src/connection/index.d.ts +83 -0
  9. package/dist/src/connection/index.d.ts.map +1 -0
  10. package/dist/src/connection/index.js +96 -0
  11. package/dist/src/connection/index.js.map +1 -0
  12. package/dist/src/connection-manager/dialer/index.d.ts +13 -14
  13. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  14. package/dist/src/connection-manager/dialer/index.js +82 -62
  15. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  16. package/dist/src/connection-manager/index.d.ts +2 -10
  17. package/dist/src/connection-manager/index.d.ts.map +1 -1
  18. package/dist/src/connection-manager/index.js +21 -53
  19. package/dist/src/connection-manager/index.js.map +1 -1
  20. package/dist/src/fetch/index.d.ts.map +1 -1
  21. package/dist/src/fetch/index.js +15 -3
  22. package/dist/src/fetch/index.js.map +1 -1
  23. package/dist/src/get-peer.d.ts +2 -2
  24. package/dist/src/get-peer.d.ts.map +1 -1
  25. package/dist/src/get-peer.js +2 -5
  26. package/dist/src/get-peer.js.map +1 -1
  27. package/dist/src/index.d.ts +10 -6
  28. package/dist/src/index.d.ts.map +1 -1
  29. package/dist/src/index.js +7 -1
  30. package/dist/src/index.js.map +1 -1
  31. package/dist/src/keychain/index.d.ts +1 -1
  32. package/dist/src/keychain/index.d.ts.map +1 -1
  33. package/dist/src/libp2p.d.ts +3 -3
  34. package/dist/src/libp2p.d.ts.map +1 -1
  35. package/dist/src/libp2p.js +2 -3
  36. package/dist/src/libp2p.js.map +1 -1
  37. package/dist/src/registrar.d.ts +5 -0
  38. package/dist/src/registrar.d.ts.map +1 -1
  39. package/dist/src/registrar.js +25 -0
  40. package/dist/src/registrar.js.map +1 -1
  41. package/dist/src/transport-manager.d.ts.map +1 -1
  42. package/dist/src/transport-manager.js +1 -2
  43. package/dist/src/transport-manager.js.map +1 -1
  44. package/dist/src/upgrader.d.ts +1 -1
  45. package/dist/src/upgrader.d.ts.map +1 -1
  46. package/dist/src/upgrader.js +46 -59
  47. package/dist/src/upgrader.js.map +1 -1
  48. package/package.json +9 -10
  49. package/src/address-manager/index.ts +3 -2
  50. package/src/circuit/README.md +6 -6
  51. package/src/config.ts +0 -11
  52. package/src/connection/index.ts +171 -0
  53. package/src/connection-manager/dialer/index.ts +100 -75
  54. package/src/connection-manager/index.ts +21 -58
  55. package/src/fetch/index.ts +16 -3
  56. package/src/get-peer.ts +3 -7
  57. package/src/index.ts +15 -7
  58. package/src/keychain/index.ts +1 -1
  59. package/src/libp2p.ts +5 -6
  60. package/src/registrar.ts +29 -2
  61. package/src/transport-manager.ts +1 -2
  62. package/src/upgrader.ts +51 -64
  63. package/src/version.ts +1 -1
  64. package/dist/src/metrics/index.d.ts +0 -93
  65. package/dist/src/metrics/index.d.ts.map +0 -1
  66. package/dist/src/metrics/index.js +0 -234
  67. package/dist/src/metrics/index.js.map +0 -1
  68. package/dist/src/metrics/moving-average.d.ts +0 -14
  69. package/dist/src/metrics/moving-average.d.ts.map +0 -1
  70. package/dist/src/metrics/moving-average.js +0 -40
  71. package/dist/src/metrics/moving-average.js.map +0 -1
  72. package/dist/src/metrics/stats.d.ts +0 -87
  73. package/dist/src/metrics/stats.d.ts.map +0 -1
  74. package/dist/src/metrics/stats.js +0 -183
  75. package/dist/src/metrics/stats.js.map +0 -1
  76. package/src/metrics/index.ts +0 -311
  77. package/src/metrics/moving-average.ts +0 -53
  78. package/src/metrics/stats.ts +0 -238
@@ -2,8 +2,6 @@ import { logger } from '@libp2p/logger'
2
2
  import errCode from 'err-code'
3
3
  import mergeOptions from 'merge-options'
4
4
  import { LatencyMonitor, SummaryObject } from './latency-monitor.js'
5
- // @ts-expect-error retimer does not have types
6
- import retimer from 'retimer'
7
5
  import type { AbortOptions } from '@libp2p/interfaces'
8
6
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
9
7
  import type { Startable } from '@libp2p/interfaces/startable'
@@ -14,13 +12,14 @@ import type { Connection, MultiaddrConnection } from '@libp2p/interface-connecti
14
12
  import type { ConnectionManager, Dialer } from '@libp2p/interface-connection-manager'
15
13
  import * as STATUS from '@libp2p/interface-connection/status'
16
14
  import type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'
17
- import { multiaddr, Multiaddr, Resolver } from '@multiformats/multiaddr'
15
+ import { isMultiaddr, multiaddr, Multiaddr, Resolver } from '@multiformats/multiaddr'
18
16
  import { PeerMap } from '@libp2p/peer-collections'
19
17
  import { TimeoutController } from 'timeout-abort-controller'
20
18
  import { KEEP_ALIVE } from '@libp2p/interface-peer-store/tags'
21
19
  import { RateLimiterMemory } from 'rate-limiter-flexible'
22
20
  import type { Metrics } from '@libp2p/interface-metrics'
23
21
  import type { Upgrader } from '@libp2p/interface-transport'
22
+ import { getPeer } from '../get-peer.js'
24
23
 
25
24
  const log = logger('libp2p:connection-manager')
26
25
 
@@ -38,8 +37,6 @@ const defaultOptions: Partial<ConnectionManagerInit> = {
38
37
  maxIncomingPendingConnections: 10
39
38
  }
40
39
 
41
- const METRICS_SYSTEM = 'libp2p'
42
- const METRICS_COMPONENT = 'connection-manager'
43
40
  const STARTUP_RECONNECT_TIMEOUT = 60000
44
41
 
45
42
  export interface ConnectionManagerInit {
@@ -183,7 +180,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
183
180
  private readonly opts: Required<ConnectionManagerInit>
184
181
  private readonly connections: Map<string, Connection[]>
185
182
  private started: boolean
186
- private timer?: ReturnType<retimer>
187
183
  private readonly latencyMonitor: LatencyMonitor
188
184
  private readonly startupReconnectTimeout: number
189
185
  private connectOnStartupController?: TimeoutController
@@ -212,7 +208,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
212
208
  this.connections = new Map()
213
209
 
214
210
  this.started = false
215
- this._checkMetrics = this._checkMetrics.bind(this)
216
211
 
217
212
  this.latencyMonitor = new LatencyMonitor({
218
213
  latencyCheckIntervalMs: init.pollInterval,
@@ -250,17 +245,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
250
245
  * only event loop and connection limits will be monitored.
251
246
  */
252
247
  async start () {
253
- if (this.components.metrics != null) {
254
- this.timer = this.timer ?? retimer(this._checkMetrics, this.opts.pollInterval)
255
- }
256
-
257
248
  // track inbound/outbound connections
258
- this.components.metrics?.updateComponentMetric({
259
- system: METRICS_SYSTEM,
260
- component: METRICS_COMPONENT,
261
- metric: 'connections',
262
- label: 'direction',
263
- value: () => {
249
+ this.components.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {
250
+ calculate: () => {
264
251
  const metric = {
265
252
  inbound: 0,
266
253
  outbound: 0
@@ -281,12 +268,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
281
268
  })
282
269
 
283
270
  // track total number of streams per protocol
284
- this.components.metrics?.updateComponentMetric({
285
- system: METRICS_SYSTEM,
286
- component: METRICS_COMPONENT,
287
- metric: 'protocol-streams-total',
271
+ this.components.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {
288
272
  label: 'protocol',
289
- value: () => {
273
+ calculate: () => {
290
274
  const metric: Record<string, number> = {}
291
275
 
292
276
  for (const conns of this.connections.values()) {
@@ -304,12 +288,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
304
288
  })
305
289
 
306
290
  // track 90th percentile of streams per protocol
307
- this.components.metrics?.updateComponentMetric({
308
- system: METRICS_SYSTEM,
309
- component: METRICS_COMPONENT,
310
- metric: 'protocol-streams-per-connection-90th-percentile',
291
+ this.components.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {
311
292
  label: 'protocol',
312
- value: () => {
293
+ calculate: () => {
313
294
  const allStreams: Record<string, number[]> = {}
314
295
 
315
296
  for (const conns of this.connections.values()) {
@@ -407,8 +388,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
407
388
  * Stops the Connection Manager
408
389
  */
409
390
  async stop () {
410
- this.timer?.clear()
411
-
412
391
  this.latencyMonitor.removeEventListener('data', this._onLatencyMeasure)
413
392
  this.latencyMonitor.stop()
414
393
 
@@ -440,31 +419,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
440
419
  this.connections.clear()
441
420
  }
442
421
 
443
- /**
444
- * Checks the libp2p metrics to determine if any values have exceeded
445
- * the configured maximums.
446
- *
447
- * @private
448
- */
449
- async _checkMetrics () {
450
- const metrics = this.components.metrics
451
-
452
- if (metrics != null) {
453
- try {
454
- const movingAverages = metrics.getGlobal().getMovingAverages()
455
- const received = movingAverages.dataReceived[this.opts.movingAverageInterval].movingAverage
456
- await this._checkMaxLimit('maxReceivedData', received)
457
- const sent = movingAverages.dataSent[this.opts.movingAverageInterval].movingAverage
458
- await this._checkMaxLimit('maxSentData', sent)
459
- const total = received + sent
460
- await this._checkMaxLimit('maxData', total)
461
- log.trace('metrics update', total)
462
- } finally {
463
- this.timer = retimer(this._checkMetrics, this.opts.pollInterval)
464
- }
465
- }
466
- }
467
-
468
422
  onConnect (evt: CustomEvent<Connection>) {
469
423
  void this._onConnect(evt).catch(err => {
470
424
  log.error(err)
@@ -524,8 +478,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
524
478
  } else if (storedConn != null) {
525
479
  this.connections.delete(peerId)
526
480
  this.dispatchEvent(new CustomEvent<Connection>('peer:disconnect', { detail: connection }))
527
-
528
- this.components.metrics?.onPeerDisconnected(connection.remotePeer)
529
481
  }
530
482
  }
531
483
 
@@ -543,7 +495,18 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
543
495
  return conns
544
496
  }
545
497
 
546
- async openConnection (peerId: PeerId, options: AbortOptions = {}): Promise<Connection> {
498
+ async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr, options: AbortOptions = {}): Promise<Connection> {
499
+ let peerId: PeerId
500
+
501
+ if (isPeerId(peerIdOrMultiaddr)) {
502
+ peerId = peerIdOrMultiaddr
503
+ } else if (isMultiaddr(peerIdOrMultiaddr)) {
504
+ const info = getPeer(peerIdOrMultiaddr)
505
+ peerId = info.id
506
+ } else {
507
+ throw errCode(new TypeError('Can only open connections to PeerIds or Multiaddrs'), codes.ERR_INVALID_PARAMETERS)
508
+ }
509
+
547
510
  log('dial to %p', peerId)
548
511
  const existingConnections = this.getConnections(peerId)
549
512
 
@@ -566,7 +529,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
566
529
  }
567
530
 
568
531
  try {
569
- const connection = await this.components.dialer.dial(peerId, options)
532
+ const connection = await this.components.dialer.dial(peerIdOrMultiaddr, options)
570
533
  let peerConnections = this.connections.get(peerId.toString())
571
534
 
572
535
  if (peerConnections == null) {
@@ -14,6 +14,8 @@ import { pipe } from 'it-pipe'
14
14
  import first from 'it-first'
15
15
  import { TimeoutController } from 'timeout-abort-controller'
16
16
  import { setMaxListeners } from 'events'
17
+ import { fromString as uint8arrayFromString } from 'uint8arrays/from-string'
18
+ import { toString as uint8arrayToString } from 'uint8arrays/to-string'
17
19
  import type { ConnectionManager } from '@libp2p/interface-connection-manager'
18
20
 
19
21
  const log = logger('libp2p:fetch')
@@ -103,6 +105,7 @@ export class FetchService implements Startable {
103
105
 
104
106
  // create a timeout if no abort signal passed
105
107
  if (signal == null) {
108
+ log('using default timeout of %d ms', this.init.timeout)
106
109
  timeoutController = new TimeoutController(this.init.timeout)
107
110
  signal = timeoutController.signal
108
111
 
@@ -113,13 +116,15 @@ export class FetchService implements Startable {
113
116
  }
114
117
 
115
118
  try {
116
- stream = await connection.newStream([this.protocol], {
119
+ stream = await connection.newStream(this.protocol, {
117
120
  signal
118
121
  })
119
122
 
120
123
  // make stream abortable
121
124
  const source = abortableDuplex(stream, signal)
122
125
 
126
+ log('fetch %s', key)
127
+
123
128
  const result = await pipe(
124
129
  [FetchRequest.encode({ identifier: key })],
125
130
  lp.encode(),
@@ -136,16 +141,20 @@ export class FetchService implements Startable {
136
141
 
137
142
  switch (response.status) {
138
143
  case (FetchResponse.StatusCode.OK): {
144
+ log('received status for %s ok', key)
139
145
  return response.data
140
146
  }
141
147
  case (FetchResponse.StatusCode.NOT_FOUND): {
148
+ log('received status for %s not found', key)
142
149
  return null
143
150
  }
144
151
  case (FetchResponse.StatusCode.ERROR): {
145
- const errmsg = (new TextDecoder()).decode(response.data)
152
+ log('received status for %s error', key)
153
+ const errmsg = uint8arrayToString(response.data)
146
154
  throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)
147
155
  }
148
156
  default: {
157
+ log('received status for %s unknown', key)
149
158
  throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)
150
159
  }
151
160
  }
@@ -189,14 +198,18 @@ export class FetchService implements Startable {
189
198
  let response: FetchResponse
190
199
  const lookup = self._getLookupFunction(request.identifier)
191
200
  if (lookup != null) {
201
+ log('look up data with identifier %s', request.identifier)
192
202
  const data = await lookup(request.identifier)
193
203
  if (data != null) {
204
+ log('sending status for %s ok', request.identifier)
194
205
  response = { status: FetchResponse.StatusCode.OK, data }
195
206
  } else {
207
+ log('sending status for %s not found', request.identifier)
196
208
  response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }
197
209
  }
198
210
  } else {
199
- const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)
211
+ log('sending status for %s error', request.identifier)
212
+ const errmsg = uint8arrayFromString(`No lookup function registered for key: ${request.identifier}`)
200
213
  response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }
201
214
  }
202
215
 
package/src/get-peer.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { peerIdFromString } from '@libp2p/peer-id'
2
2
  import type { Multiaddr } from '@multiformats/multiaddr'
3
- import { multiaddr, isMultiaddr } from '@multiformats/multiaddr'
3
+ import { isMultiaddr } from '@multiformats/multiaddr'
4
4
  import errCode from 'err-code'
5
5
  import { codes } from './errors.js'
6
6
  import { isPeerId } from '@libp2p/interface-peer-id'
@@ -28,9 +28,9 @@ function peerIdFromMultiaddr (ma: Multiaddr) {
28
28
  }
29
29
 
30
30
  /**
31
- * Converts the given `peer` to a `Peer` object.
31
+ * Converts the given `peer` to a `PeerInfo` object.
32
32
  */
33
- export function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {
33
+ export function getPeer (peer: PeerId | Multiaddr): PeerInfo {
34
34
  if (isPeerId(peer)) {
35
35
  return {
36
36
  id: peer,
@@ -39,10 +39,6 @@ export function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {
39
39
  }
40
40
  }
41
41
 
42
- if (typeof peer === 'string') {
43
- peer = multiaddr(peer)
44
- }
45
-
46
42
  let addr
47
43
 
48
44
  if (isMultiaddr(peer)) {
package/src/index.ts CHANGED
@@ -20,7 +20,7 @@ import type { ContentRouting } from '@libp2p/interface-content-routing'
20
20
  import type { PubSub } from '@libp2p/interface-pubsub'
21
21
  import type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'
22
22
  import type { ConnectionManager } from '@libp2p/interface-connection-manager'
23
- import type { Metrics, MetricsInit } from '@libp2p/interface-metrics'
23
+ import type { Metrics } from '@libp2p/interface-metrics'
24
24
  import type { PeerInfo } from '@libp2p/interface-peer-info'
25
25
  import type { KeyChain } from './keychain/index.js'
26
26
  import type { ConnectionManagerInit } from './connection-manager/index.js'
@@ -104,7 +104,6 @@ export interface Libp2pInit {
104
104
  connectionGater: Partial<ConnectionGater>
105
105
  transportManager: TransportManagerConfig
106
106
  datastore: Datastore
107
- metrics: MetricsInit
108
107
  peerStore: PeerStoreInit
109
108
  peerRouting: PeerRoutingConfig
110
109
  keychain: KeychainConfig
@@ -121,6 +120,7 @@ export interface Libp2pInit {
121
120
  peerRouters?: Array<(components: Components) => PeerRouting>
122
121
  contentRouters?: Array<(components: Components) => ContentRouting>
123
122
  dht?: (components: Components) => DualDHT
123
+ metrics?: (components: Components) => Metrics
124
124
  pubsub?: (components: Components) => PubSub
125
125
  connectionProtector?: (components: Components) => ConnectionProtector
126
126
  }
@@ -178,7 +178,7 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
178
178
  /**
179
179
  * Disconnects all connections to the given `peer`
180
180
  */
181
- hangUp: (peer: PeerId | Multiaddr | string) => Promise<void>
181
+ hangUp: (peer: PeerId | Multiaddr) => Promise<void>
182
182
 
183
183
  /**
184
184
  * Registers the `handler` for each protocol
@@ -194,12 +194,12 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
194
194
  /**
195
195
  * Pings the given peer in order to obtain the operation latency
196
196
  */
197
- ping: (peer: Multiaddr | PeerId, options?: AbortOptions) => Promise<number>
197
+ ping: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise<number>
198
198
 
199
199
  /**
200
200
  * Sends a request to fetch the value associated with the given key from the given peer.
201
201
  */
202
- fetch: (peer: PeerId | Multiaddr | string, key: string, options?: AbortOptions) => Promise<Uint8Array | null>
202
+ fetch: (peer: PeerId | Multiaddr, key: string, options?: AbortOptions) => Promise<Uint8Array | null>
203
203
 
204
204
  /**
205
205
  * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA' type
@@ -208,12 +208,20 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
208
208
  getPublicKey: (peer: PeerId, options?: AbortOptions) => Promise<Uint8Array>
209
209
  }
210
210
 
211
- export type Libp2pOptions = RecursivePartial<Libp2pInit>
211
+ export type Libp2pOptions = RecursivePartial<Libp2pInit> & { start?: boolean }
212
212
 
213
213
  /**
214
214
  * Returns a new instance of the Libp2p interface, generating a new PeerId
215
215
  * if one is not passed as part of the options.
216
+ *
217
+ * The node will be started unless `start: false` is passed as an option.
216
218
  */
217
219
  export async function createLibp2p (options: Libp2pOptions): Promise<Libp2p> {
218
- return await createLibp2pNode(options)
220
+ const node = await createLibp2pNode(options)
221
+
222
+ if (options.start !== false) {
223
+ await node.start()
224
+ }
225
+
226
+ return node
219
227
  }
@@ -118,7 +118,7 @@ export interface KeyChainComponents {
118
118
  */
119
119
  export class KeyChain implements Startable {
120
120
  private readonly components: KeyChainComponents
121
- private init: KeyChainInit
121
+ private readonly init: KeyChainInit
122
122
  private started: boolean
123
123
 
124
124
  /**
package/src/libp2p.ts CHANGED
@@ -14,7 +14,6 @@ import { AutoDialler } from './connection-manager/auto-dialler.js'
14
14
  import { Circuit } from './circuit/transport.js'
15
15
  import { Relay } from './circuit/index.js'
16
16
  import { KeyChain } from './keychain/index.js'
17
- import { DefaultMetrics } from './metrics/index.js'
18
17
  import { DefaultTransportManager } from './transport-manager.js'
19
18
  import { DefaultUpgrader } from './upgrader.js'
20
19
  import { DefaultRegistrar } from './registrar.js'
@@ -103,8 +102,8 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
103
102
  ]
104
103
 
105
104
  // Create Metrics
106
- if (init.metrics.enabled) {
107
- this.metrics = this.components.metrics = new DefaultMetrics(init.metrics)
105
+ if (init.metrics != null) {
106
+ this.metrics = this.components.metrics = this.configureComponent(init.metrics(this.components))
108
107
  }
109
108
 
110
109
  this.peerStore = this.components.peerStore
@@ -374,7 +373,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
374
373
  return this.components.addressManager.getAddresses()
375
374
  }
376
375
 
377
- async hangUp (peer: PeerId | Multiaddr | string): Promise<void> {
376
+ async hangUp (peer: PeerId | Multiaddr): Promise<void> {
378
377
  const { id } = getPeer(peer)
379
378
 
380
379
  await this.components.connectionManager.closeConnections(id)
@@ -419,7 +418,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
419
418
  throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)
420
419
  }
421
420
 
422
- async fetch (peer: PeerId | Multiaddr | string, key: string, options: AbortOptions = {}): Promise<Uint8Array | null> {
421
+ async fetch (peer: PeerId | Multiaddr, key: string, options: AbortOptions = {}): Promise<Uint8Array | null> {
423
422
  const { id, multiaddrs } = getPeer(peer)
424
423
 
425
424
  if (multiaddrs != null) {
@@ -429,7 +428,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
429
428
  return await this.fetchService.fetch(id, key, options)
430
429
  }
431
430
 
432
- async ping (peer: PeerId | Multiaddr | string, options: AbortOptions = {}): Promise<number> {
431
+ async ping (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise<number> {
433
432
  const { id, multiaddrs } = getPeer(peer)
434
433
 
435
434
  if (multiaddrs.length > 0) {
package/src/registrar.ts CHANGED
@@ -35,8 +35,10 @@ export class DefaultRegistrar implements Registrar {
35
35
 
36
36
  this._onDisconnect = this._onDisconnect.bind(this)
37
37
  this._onProtocolChange = this._onProtocolChange.bind(this)
38
+ this._onConnect = this._onConnect.bind(this)
38
39
 
39
40
  this.components.connectionManager.addEventListener('peer:disconnect', this._onDisconnect)
41
+ this.components.connectionManager.addEventListener('peer:connect', this._onConnect)
40
42
 
41
43
  // happens after identify
42
44
  this.components.peerStore.addEventListener('change:protocols', this._onProtocolChange)
@@ -176,12 +178,38 @@ export class DefaultRegistrar implements Registrar {
176
178
  })
177
179
  }
178
180
 
181
+ /**
182
+ * On peer connected if we already have their protocols. Usually used for reconnects
183
+ * as change:protocols event won't be emitted due to identical protocols.
184
+ */
185
+ _onConnect (evt: CustomEvent<Connection>) {
186
+ const connection = evt.detail
187
+
188
+ void this.components.peerStore.protoBook.get(connection.remotePeer)
189
+ .then(peerProtocols => {
190
+ for (const protocol of peerProtocols) {
191
+ const topologies = this.topologies.get(protocol)
192
+
193
+ if (topologies == null) {
194
+ // no topologies are interested in this protocol
195
+ continue
196
+ }
197
+
198
+ for (const topology of topologies.values()) {
199
+ topology.onConnect(connection.remotePeer, connection)
200
+ }
201
+ }
202
+ })
203
+ .catch(err => {
204
+ log.error(err)
205
+ })
206
+ }
207
+
179
208
  /**
180
209
  * Check if a new peer support the multicodecs for this topology
181
210
  */
182
211
  _onProtocolChange (evt: CustomEvent<PeerProtocolsChangeData>) {
183
212
  const { peerId, protocols, oldProtocols } = evt.detail
184
-
185
213
  const removed = oldProtocols.filter(protocol => !protocols.includes(protocol))
186
214
  const added = protocols.filter(protocol => !oldProtocols.includes(protocol))
187
215
 
@@ -212,7 +240,6 @@ export class DefaultRegistrar implements Registrar {
212
240
  if (connection == null) {
213
241
  continue
214
242
  }
215
-
216
243
  topology.onConnect(peerId, connection)
217
244
  }
218
245
  }
@@ -38,8 +38,7 @@ export class DefaultTransportManager extends EventEmitter<TransportManagerEvents
38
38
  this.started = false
39
39
  this.transports = new Map<string, Transport>()
40
40
  this.listeners = trackedMap({
41
- component: 'transport-manager',
42
- metric: 'listeners',
41
+ name: 'libp2p_transport_manager_listeners',
43
42
  metrics: this.components.metrics
44
43
  })
45
44
  this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL