libp2p 2.8.8 → 2.8.9-6c42ea64a

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 (91) hide show
  1. package/dist/index.min.js +16 -16
  2. package/dist/index.min.js.map +4 -4
  3. package/dist/src/address-manager/dns-mappings.d.ts.map +1 -1
  4. package/dist/src/address-manager/dns-mappings.js +5 -1
  5. package/dist/src/address-manager/dns-mappings.js.map +1 -1
  6. package/dist/src/address-manager/index.d.ts +3 -1
  7. package/dist/src/address-manager/index.d.ts.map +1 -1
  8. package/dist/src/address-manager/index.js +2 -5
  9. package/dist/src/address-manager/index.js.map +1 -1
  10. package/dist/src/address-manager/ip-mappings.d.ts.map +1 -1
  11. package/dist/src/address-manager/ip-mappings.js +5 -1
  12. package/dist/src/address-manager/ip-mappings.js.map +1 -1
  13. package/dist/src/address-manager/observed-addresses.d.ts.map +1 -1
  14. package/dist/src/address-manager/observed-addresses.js +5 -1
  15. package/dist/src/address-manager/observed-addresses.js.map +1 -1
  16. package/dist/src/address-manager/transport-addresses.d.ts.map +1 -1
  17. package/dist/src/address-manager/transport-addresses.js +5 -1
  18. package/dist/src/address-manager/transport-addresses.js.map +1 -1
  19. package/dist/src/components.d.ts +2 -1
  20. package/dist/src/components.d.ts.map +1 -1
  21. package/dist/src/components.js.map +1 -1
  22. package/dist/src/connection/index.d.ts.map +1 -1
  23. package/dist/src/connection/index.js +2 -1
  24. package/dist/src/connection/index.js.map +1 -1
  25. package/dist/src/connection-manager/connection-pruner.d.ts +2 -3
  26. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
  27. package/dist/src/connection-manager/connection-pruner.js +4 -10
  28. package/dist/src/connection-manager/connection-pruner.js.map +1 -1
  29. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  30. package/dist/src/connection-manager/dial-queue.js +4 -7
  31. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  32. package/dist/src/connection-manager/index.d.ts +4 -2
  33. package/dist/src/connection-manager/index.d.ts.map +1 -1
  34. package/dist/src/connection-manager/index.js +13 -1
  35. package/dist/src/connection-manager/index.js.map +1 -1
  36. package/dist/src/connection-manager/reconnect-queue.d.ts +2 -1
  37. package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -1
  38. package/dist/src/connection-manager/reconnect-queue.js.map +1 -1
  39. package/dist/src/connection-monitor.d.ts.map +1 -1
  40. package/dist/src/connection-monitor.js +2 -1
  41. package/dist/src/connection-monitor.js.map +1 -1
  42. package/dist/src/content-routing.js +1 -1
  43. package/dist/src/content-routing.js.map +1 -1
  44. package/dist/src/libp2p.d.ts +3 -3
  45. package/dist/src/libp2p.d.ts.map +1 -1
  46. package/dist/src/libp2p.js +12 -11
  47. package/dist/src/libp2p.js.map +1 -1
  48. package/dist/src/peer-routing.js +2 -2
  49. package/dist/src/peer-routing.js.map +1 -1
  50. package/dist/src/random-walk.d.ts +1 -1
  51. package/dist/src/random-walk.d.ts.map +1 -1
  52. package/dist/src/random-walk.js +1 -1
  53. package/dist/src/random-walk.js.map +1 -1
  54. package/dist/src/registrar.d.ts +4 -2
  55. package/dist/src/registrar.d.ts.map +1 -1
  56. package/dist/src/registrar.js +22 -6
  57. package/dist/src/registrar.js.map +1 -1
  58. package/dist/src/transport-manager.d.ts +2 -1
  59. package/dist/src/transport-manager.d.ts.map +1 -1
  60. package/dist/src/transport-manager.js +4 -1
  61. package/dist/src/transport-manager.js.map +1 -1
  62. package/dist/src/upgrader.d.ts +2 -1
  63. package/dist/src/upgrader.d.ts.map +1 -1
  64. package/dist/src/upgrader.js +32 -10
  65. package/dist/src/upgrader.js.map +1 -1
  66. package/dist/src/version.d.ts +1 -1
  67. package/dist/src/version.d.ts.map +1 -1
  68. package/dist/src/version.js +1 -1
  69. package/dist/src/version.js.map +1 -1
  70. package/package.json +14 -13
  71. package/src/address-manager/dns-mappings.ts +5 -1
  72. package/src/address-manager/index.ts +5 -7
  73. package/src/address-manager/ip-mappings.ts +5 -1
  74. package/src/address-manager/observed-addresses.ts +5 -1
  75. package/src/address-manager/transport-addresses.ts +5 -1
  76. package/src/components.ts +2 -1
  77. package/src/connection/index.ts +2 -1
  78. package/src/connection-manager/connection-pruner.ts +6 -13
  79. package/src/connection-manager/dial-queue.ts +4 -8
  80. package/src/connection-manager/index.ts +21 -3
  81. package/src/connection-manager/reconnect-queue.ts +2 -1
  82. package/src/connection-monitor.ts +2 -1
  83. package/src/content-routing.ts +1 -1
  84. package/src/libp2p.ts +13 -12
  85. package/src/peer-routing.ts +2 -2
  86. package/src/random-walk.ts +1 -1
  87. package/src/registrar.ts +27 -7
  88. package/src/transport-manager.ts +6 -2
  89. package/src/upgrader.ts +39 -13
  90. package/src/version.ts +1 -1
  91. package/dist/typedoc-urls.json +0 -21
@@ -1,5 +1,6 @@
1
1
  import { isLinkLocal } from '@libp2p/utils/multiaddr/is-link-local'
2
2
  import { isPrivate } from '@libp2p/utils/multiaddr/is-private'
3
+ import { trackedMap } from '@libp2p/utils/tracked-map'
3
4
  import { multiaddr } from '@multiformats/multiaddr'
4
5
  import type { AddressManagerComponents, AddressManagerInit } from './index.js'
5
6
  import type { Logger } from '@libp2p/interface'
@@ -23,7 +24,10 @@ export class ObservedAddresses {
23
24
 
24
25
  constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {
25
26
  this.log = components.logger.forComponent('libp2p:address-manager:observed-addresses')
26
- this.addresses = new Map()
27
+ this.addresses = trackedMap({
28
+ name: 'libp2p_address_manager_observed_addresses',
29
+ metrics: components.metrics
30
+ })
27
31
  this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses
28
32
  }
29
33
 
@@ -1,5 +1,6 @@
1
1
  import { isNetworkAddress } from '@libp2p/utils/multiaddr/is-network-address'
2
2
  import { isPrivate } from '@libp2p/utils/multiaddr/is-private'
3
+ import { trackedMap } from '@libp2p/utils/tracked-map'
3
4
  import type { AddressManagerComponents, AddressManagerInit } from './index.js'
4
5
  import type { Logger } from '@libp2p/interface'
5
6
  import type { NodeAddress } from '@libp2p/interface-internal'
@@ -22,7 +23,10 @@ export class TransportAddresses {
22
23
 
23
24
  constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {
24
25
  this.log = components.logger.forComponent('libp2p:address-manager:observed-addresses')
25
- this.addresses = new Map()
26
+ this.addresses = trackedMap({
27
+ name: 'libp2p_address_manager_transport_addresses',
28
+ metrics: components.metrics
29
+ })
26
30
  this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses
27
31
  }
28
32
 
package/src/components.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { serviceCapabilities, serviceDependencies, isStartable } from '@libp2p/interface'
2
2
  import { defaultLogger } from '@libp2p/logger'
3
3
  import { MissingServiceError, UnmetServiceDependenciesError } from './errors.js'
4
- import type { Startable, Libp2pEvents, ComponentLogger, NodeInfo, ConnectionProtector, ConnectionGater, ContentRouting, TypedEventTarget, Metrics, PeerId, PeerRouting, PeerStore, PrivateKey, Upgrader } from '@libp2p/interface'
4
+ import type { Startable, Libp2pEvents, ComponentLogger, NodeInfo, ConnectionProtector, ConnectionGater, ContentRouting, Metrics, PeerId, PeerRouting, PeerStore, PrivateKey, Upgrader } from '@libp2p/interface'
5
5
  import type { AddressManager, ConnectionManager, RandomWalk, Registrar, TransportManager } from '@libp2p/interface-internal'
6
6
  import type { DNS } from '@multiformats/dns'
7
7
  import type { Datastore } from 'interface-datastore'
8
+ import type { TypedEventTarget } from 'main-event'
8
9
 
9
10
  export interface Components extends Record<string, any>, Startable {
10
11
  peerId: PeerId
@@ -1,4 +1,5 @@
1
- import { connectionSymbol, setMaxListeners, LimitedConnectionError, ConnectionClosedError, ConnectionClosingError } from '@libp2p/interface'
1
+ import { connectionSymbol, LimitedConnectionError, ConnectionClosedError, ConnectionClosingError } from '@libp2p/interface'
2
+ import { setMaxListeners } from 'main-event'
2
3
  import type { AbortOptions, Logger, ComponentLogger, Direction, Connection, Stream, ConnectionTimeline, ConnectionStatus, NewStreamOptions, PeerId, ConnectionLimits } from '@libp2p/interface'
3
4
  import type { Multiaddr } from '@multiformats/multiaddr'
4
5
 
@@ -1,14 +1,13 @@
1
1
  import { PeerMap } from '@libp2p/peer-collections'
2
2
  import { safelyCloseConnectionIfUnused } from '@libp2p/utils/close'
3
- import { MAX_CONNECTIONS } from './constants.js'
4
3
  import { multiaddrToIpNet } from './utils.js'
5
4
  import type { IpNet } from '@chainsafe/netmask'
6
- import type { Libp2pEvents, Logger, ComponentLogger, TypedEventTarget, PeerStore, Connection } from '@libp2p/interface'
5
+ import type { Libp2pEvents, Logger, ComponentLogger, PeerStore, Connection } from '@libp2p/interface'
7
6
  import type { ConnectionManager } from '@libp2p/interface-internal'
8
7
  import type { Multiaddr } from '@multiformats/multiaddr'
8
+ import type { TypedEventTarget } from 'main-event'
9
9
 
10
10
  interface ConnectionPrunerInit {
11
- maxConnections?: number
12
11
  allow?: Multiaddr[]
13
12
  }
14
13
 
@@ -19,16 +18,10 @@ interface ConnectionPrunerComponents {
19
18
  logger: ComponentLogger
20
19
  }
21
20
 
22
- const defaultOptions = {
23
- maxConnections: MAX_CONNECTIONS,
24
- allow: []
25
- }
26
-
27
21
  /**
28
22
  * If we go over the max connections limit, choose some connections to close
29
23
  */
30
24
  export class ConnectionPruner {
31
- private readonly maxConnections: number
32
25
  private readonly connectionManager: ConnectionManager
33
26
  private readonly peerStore: PeerStore
34
27
  private readonly allow: IpNet[]
@@ -36,7 +29,6 @@ export class ConnectionPruner {
36
29
  private readonly log: Logger
37
30
 
38
31
  constructor (components: ConnectionPrunerComponents, init: ConnectionPrunerInit = {}) {
39
- this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections
40
32
  this.allow = (init.allow ?? []).map(ma => multiaddrToIpNet(ma))
41
33
  this.connectionManager = components.connectionManager
42
34
  this.peerStore = components.peerStore
@@ -67,10 +59,11 @@ export class ConnectionPruner {
67
59
  private async _maybePruneConnections (): Promise<void> {
68
60
  const connections = this.connectionManager.getConnections()
69
61
  const numConnections = connections.length
62
+ const maxConnections = this.connectionManager.getMaxConnections()
70
63
 
71
- this.log('checking max connections limit %d/%d', numConnections, this.maxConnections)
64
+ this.log('checking max connections limit %d/%d', numConnections, maxConnections)
72
65
 
73
- if (numConnections <= this.maxConnections) {
66
+ if (numConnections <= maxConnections) {
74
67
  return
75
68
  }
76
69
 
@@ -103,7 +96,7 @@ export class ConnectionPruner {
103
96
  const sortedConnections = this.sortConnections(connections, peerValues)
104
97
 
105
98
  // close some connections
106
- const toPrune = Math.max(numConnections - this.maxConnections, 0)
99
+ const toPrune = Math.max(numConnections - maxConnections, 0)
107
100
  const toClose = []
108
101
 
109
102
  for (const connection of sortedConnections) {
@@ -1,11 +1,12 @@
1
1
  /* eslint-disable max-depth */
2
- import { TimeoutError, DialError, setMaxListeners, AbortError } from '@libp2p/interface'
2
+ import { TimeoutError, DialError, AbortError } from '@libp2p/interface'
3
3
  import { PeerMap } from '@libp2p/peer-collections'
4
4
  import { PriorityQueue } from '@libp2p/utils/priority-queue'
5
5
  import { resolvers, multiaddr } from '@multiformats/multiaddr'
6
6
  import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
7
7
  import { Circuit } from '@multiformats/multiaddr-matcher'
8
8
  import { anySignal } from 'any-signal'
9
+ import { setMaxListeners } from 'main-event'
9
10
  import { CustomProgressEvent } from 'progress-events'
10
11
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
11
12
  import { DialDeniedError, NoValidAddressesError } from '../errors.js'
@@ -436,15 +437,10 @@ export class DialQueue {
436
437
  if (peerId != null) {
437
438
  const peerIdMultiaddr = `/p2p/${peerId.toString()}`
438
439
  resolvedAddresses = resolvedAddresses.map(addr => {
439
- const lastProto = addr.multiaddr.protos().pop()
440
-
441
- // do not append peer id to path multiaddrs
442
- if (lastProto?.path === true) {
443
- return addr
444
- }
440
+ const lastComponent = addr.multiaddr.getComponents().pop()
445
441
 
446
442
  // append peer id to multiaddr if it is not already present
447
- if (addr.multiaddr.getPeerId() == null) {
443
+ if (lastComponent?.name !== 'p2p') {
448
444
  return {
449
445
  multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),
450
446
  isCertified: addr.isCertified
@@ -11,10 +11,11 @@ import { DialQueue } from './dial-queue.js'
11
11
  import { ReconnectQueue } from './reconnect-queue.js'
12
12
  import { multiaddrToIpNet } from './utils.js'
13
13
  import type { IpNet } from '@chainsafe/netmask'
14
- import type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions } from '@libp2p/interface'
14
+ import type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, Metrics, PeerId, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions } from '@libp2p/interface'
15
15
  import type { ConnectionManager, OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'
16
16
  import type { JobStatus } from '@libp2p/utils/queue'
17
17
  import type { Multiaddr, Resolver } from '@multiformats/multiaddr'
18
+ import type { TypedEventTarget } from 'main-event'
18
19
 
19
20
  export const DEFAULT_DIAL_PRIORITY = 50
20
21
 
@@ -205,7 +206,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
205
206
  private readonly maxIncomingPendingConnections: number
206
207
  private incomingPendingConnections: number
207
208
  private outboundPendingConnections: number
208
- private readonly maxConnections: number
209
+ private maxConnections: number
209
210
 
210
211
  public readonly dialQueue: DialQueue
211
212
  public readonly reconnectQueue: ReconnectQueue
@@ -260,7 +261,6 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
260
261
  events: components.events,
261
262
  logger: components.logger
262
263
  }, {
263
- maxConnections: this.maxConnections,
264
264
  allow: init.allow?.map(a => multiaddr(a))
265
265
  })
266
266
 
@@ -423,6 +423,24 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
423
423
  return this.maxConnections
424
424
  }
425
425
 
426
+ setMaxConnections (maxConnections: number): void {
427
+ if (this.maxConnections < 1) {
428
+ throw new InvalidParametersError('Connection Manager maxConnections must be greater than 0')
429
+ }
430
+
431
+ let needsPrune = false
432
+
433
+ if (maxConnections < this.maxConnections) {
434
+ needsPrune = true
435
+ }
436
+
437
+ this.maxConnections = maxConnections
438
+
439
+ if (needsPrune) {
440
+ this.connectionPruner.maybePruneConnections()
441
+ }
442
+ }
443
+
426
444
  onConnect (evt: CustomEvent<Connection>): void {
427
445
  void this._onConnect(evt).catch(err => {
428
446
  this.log.error(err)
@@ -2,8 +2,9 @@ import { KEEP_ALIVE } from '@libp2p/interface'
2
2
  import { PeerQueue } from '@libp2p/utils/peer-queue'
3
3
  import pRetry from 'p-retry'
4
4
  import { MAX_PARALLEL_RECONNECTS } from './constants.js'
5
- import type { ComponentLogger, Libp2pEvents, Logger, Metrics, Peer, PeerId, PeerStore, Startable, TypedEventTarget } from '@libp2p/interface'
5
+ import type { ComponentLogger, Libp2pEvents, Logger, Metrics, Peer, PeerId, PeerStore, Startable } from '@libp2p/interface'
6
6
  import type { ConnectionManager } from '@libp2p/interface-internal'
7
+ import type { TypedEventTarget } from 'main-event'
7
8
 
8
9
  export interface ReconnectQueueComponents {
9
10
  connectionManager: ConnectionManager
@@ -1,7 +1,8 @@
1
1
  import { randomBytes } from '@libp2p/crypto'
2
- import { serviceCapabilities, setMaxListeners } from '@libp2p/interface'
2
+ import { serviceCapabilities } from '@libp2p/interface'
3
3
  import { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout'
4
4
  import { byteStream } from 'it-byte-stream'
5
+ import { setMaxListeners } from 'main-event'
5
6
  import type { ComponentLogger, Logger, Metrics, Startable } from '@libp2p/interface'
6
7
  import type { ConnectionManager } from '@libp2p/interface-internal'
7
8
  import type { AdaptiveTimeoutInit } from '@libp2p/utils/adaptive-timeout'
@@ -118,7 +118,7 @@ export class CompoundContentRouting implements ContentRouting, Startable {
118
118
  if (peer.multiaddrs.length > 0) {
119
119
  await this.components.peerStore.merge(peer.id, {
120
120
  multiaddrs: peer.multiaddrs
121
- })
121
+ }, options)
122
122
  }
123
123
 
124
124
  // deduplicate peers
package/src/libp2p.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'
2
- import { contentRoutingSymbol, TypedEventEmitter, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol, InvalidParametersError } from '@libp2p/interface'
2
+ import { contentRoutingSymbol, peerDiscoverySymbol, peerRoutingSymbol, InvalidParametersError } from '@libp2p/interface'
3
3
  import { defaultLogger } from '@libp2p/logger'
4
4
  import { PeerSet } from '@libp2p/peer-collections'
5
5
  import { peerIdFromString } from '@libp2p/peer-id'
6
6
  import { persistentPeerStore } from '@libp2p/peer-store'
7
7
  import { isMultiaddr } from '@multiformats/multiaddr'
8
8
  import { MemoryDatastore } from 'datastore-core/memory'
9
+ import { TypedEventEmitter, setMaxListeners } from 'main-event'
9
10
  import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
10
11
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
11
12
  import { AddressManager } from './address-manager/index.js'
@@ -86,16 +87,16 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
86
87
  dns: init.dns
87
88
  })
88
89
 
89
- this.peerStore = this.configureComponent('peerStore', persistentPeerStore(components, {
90
- addressFilter: this.components.connectionGater.filterMultiaddrForPeer,
91
- ...init.peerStore
92
- }))
93
-
94
90
  // Create Metrics
95
91
  if (init.metrics != null) {
96
92
  this.metrics = this.configureComponent('metrics', init.metrics(this.components))
97
93
  }
98
94
 
95
+ this.peerStore = this.configureComponent('peerStore', persistentPeerStore(components, {
96
+ addressFilter: this.components.connectionGater.filterMultiaddrForPeer,
97
+ ...init.peerStore
98
+ }))
99
+
99
100
  components.events.addEventListener('peer:update', evt => {
100
101
  // if there was no peer previously in the peer store this is a new peer
101
102
  if (evt.detail.previous == null) {
@@ -340,7 +341,7 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
340
341
  }
341
342
 
342
343
  try {
343
- const peerInfo = await this.peerStore.get(peer)
344
+ const peerInfo = await this.peerStore.get(peer, options)
344
345
 
345
346
  if (peerInfo.id.publicKey != null) {
346
347
  return peerInfo.id.publicKey
@@ -364,7 +365,7 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
364
365
 
365
366
  await this.peerStore.patch(peer, {
366
367
  publicKey
367
- })
368
+ }, options)
368
369
 
369
370
  return publicKey
370
371
  }
@@ -381,20 +382,20 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
381
382
  )
382
383
  }
383
384
 
384
- async unhandle (protocols: string[] | string): Promise<void> {
385
+ async unhandle (protocols: string[] | string, options?: AbortOptions): Promise<void> {
385
386
  if (!Array.isArray(protocols)) {
386
387
  protocols = [protocols]
387
388
  }
388
389
 
389
390
  await Promise.all(
390
391
  protocols.map(async protocol => {
391
- await this.components.registrar.unhandle(protocol)
392
+ await this.components.registrar.unhandle(protocol, options)
392
393
  })
393
394
  )
394
395
  }
395
396
 
396
- async register (protocol: string, topology: Topology): Promise<string> {
397
- return this.components.registrar.register(protocol, topology)
397
+ async register (protocol: string, topology: Topology, options?: AbortOptions): Promise<string> {
398
+ return this.components.registrar.register(protocol, topology, options)
398
399
  }
399
400
 
400
401
  unregister (id: string): void {
@@ -92,7 +92,7 @@ export class DefaultPeerRouting implements PeerRouting {
92
92
  if (peer.multiaddrs.length > 0) {
93
93
  await this.peerStore.merge(peer.id, {
94
94
  multiaddrs: peer.multiaddrs
95
- })
95
+ }, options)
96
96
  }
97
97
 
98
98
  return peer
@@ -148,7 +148,7 @@ export class DefaultPeerRouting implements PeerRouting {
148
148
  if (peer.multiaddrs.length > 0) {
149
149
  await this.peerStore.merge(peer.id, {
150
150
  multiaddrs: peer.multiaddrs
151
- })
151
+ }, options)
152
152
  }
153
153
 
154
154
  // deduplicate peers
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from '@libp2p/crypto'
2
- import { TypedEventEmitter, setMaxListeners } from '@libp2p/interface'
3
2
  import { anySignal } from 'any-signal'
3
+ import { TypedEventEmitter, setMaxListeners } from 'main-event'
4
4
  import pDefer from 'p-defer'
5
5
  import { raceEvent } from 'race-event'
6
6
  import { raceSignal } from 'race-signal'
package/src/registrar.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { InvalidParametersError } from '@libp2p/interface'
2
2
  import { mergeOptions } from '@libp2p/utils/merge-options'
3
+ import { trackedMap } from '@libp2p/utils/tracked-map'
3
4
  import * as errorsJs from './errors.js'
4
- import type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, TypedEventTarget, PeerId, PeerStore, Topology, StreamHandler, StreamHandlerRecord, StreamHandlerOptions } from '@libp2p/interface'
5
+ import type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, PeerId, PeerStore, Topology, StreamHandler, StreamHandlerRecord, StreamHandlerOptions, AbortOptions, Metrics } from '@libp2p/interface'
5
6
  import type { Registrar as RegistrarInterface } from '@libp2p/interface-internal'
6
7
  import type { ComponentLogger } from '@libp2p/logger'
8
+ import type { TypedEventTarget } from 'main-event'
7
9
 
8
10
  export const DEFAULT_MAX_INBOUND_STREAMS = 32
9
11
  export const DEFAULT_MAX_OUTBOUND_STREAMS = 64
@@ -13,6 +15,7 @@ export interface RegistrarComponents {
13
15
  peerStore: PeerStore
14
16
  events: TypedEventTarget<Libp2pEvents>
15
17
  logger: ComponentLogger
18
+ metrics?: Metrics
16
19
  }
17
20
 
18
21
  /**
@@ -25,10 +28,24 @@ export class Registrar implements RegistrarInterface {
25
28
  private readonly components: RegistrarComponents
26
29
 
27
30
  constructor (components: RegistrarComponents) {
31
+ this.components = components
28
32
  this.log = components.logger.forComponent('libp2p:registrar')
29
33
  this.topologies = new Map()
30
- this.handlers = new Map()
31
- this.components = components
34
+ components.metrics?.registerMetricGroup('libp2p_registrar_topologies', {
35
+ calculate: () => {
36
+ const output: Record<string, number> = {}
37
+
38
+ for (const [key, value] of this.topologies) {
39
+ output[key] = value.size
40
+ }
41
+
42
+ return output
43
+ }
44
+ })
45
+ this.handlers = trackedMap({
46
+ name: 'libp2p_registrar_protocol_handlers',
47
+ metrics: components.metrics
48
+ })
32
49
 
33
50
  this._onDisconnect = this._onDisconnect.bind(this)
34
51
  this._onPeerUpdate = this._onPeerUpdate.bind(this)
@@ -90,14 +107,14 @@ export class Registrar implements RegistrarInterface {
90
107
  // Add new protocol to self protocols in the peer store
91
108
  await this.components.peerStore.merge(this.components.peerId, {
92
109
  protocols: [protocol]
93
- })
110
+ }, opts)
94
111
  }
95
112
 
96
113
  /**
97
114
  * Removes the handler for each protocol. The protocol
98
115
  * will no longer be supported on streams.
99
116
  */
100
- async unhandle (protocols: string | string[]): Promise<void> {
117
+ async unhandle (protocols: string | string[], options?: AbortOptions): Promise<void> {
101
118
  const protocolList = Array.isArray(protocols) ? protocols : [protocols]
102
119
 
103
120
  protocolList.forEach(protocol => {
@@ -107,7 +124,7 @@ export class Registrar implements RegistrarInterface {
107
124
  // Update self protocols in the peer store
108
125
  await this.components.peerStore.patch(this.components.peerId, {
109
126
  protocols: this.getProtocols()
110
- })
127
+ }, options)
111
128
  }
112
129
 
113
130
  /**
@@ -153,8 +170,11 @@ export class Registrar implements RegistrarInterface {
153
170
  */
154
171
  _onDisconnect (evt: CustomEvent<PeerId>): void {
155
172
  const remotePeer = evt.detail
173
+ const options = {
174
+ signal: AbortSignal.timeout(5_000)
175
+ }
156
176
 
157
- void this.components.peerStore.get(remotePeer)
177
+ void this.components.peerStore.get(remotePeer, options)
158
178
  .then(peer => {
159
179
  for (const protocol of peer.protocols) {
160
180
  const topologies = this.topologies.get(protocol)
@@ -3,9 +3,10 @@ import { trackedMap } from '@libp2p/utils/tracked-map'
3
3
  import { IP4, IP6 } from '@multiformats/multiaddr-matcher'
4
4
  import { CustomProgressEvent } from 'progress-events'
5
5
  import { TransportUnavailableError, UnsupportedListenAddressError, UnsupportedListenAddressesError } from './errors.js'
6
- import type { Libp2pEvents, ComponentLogger, Logger, Connection, TypedEventTarget, Metrics, Startable, Listener, Transport, Upgrader } from '@libp2p/interface'
6
+ import type { Libp2pEvents, ComponentLogger, Logger, Connection, Metrics, Startable, Listener, Transport, Upgrader } from '@libp2p/interface'
7
7
  import type { AddressManager, TransportManager, TransportManagerDialOptions } from '@libp2p/interface-internal'
8
8
  import type { Multiaddr } from '@multiformats/multiaddr'
9
+ import type { TypedEventTarget } from 'main-event'
9
10
 
10
11
  export interface TransportManagerInit {
11
12
  faultTolerance?: FaultTolerance
@@ -42,7 +43,10 @@ export class DefaultTransportManager implements TransportManager, Startable {
42
43
  this.log = components.logger.forComponent('libp2p:transports')
43
44
  this.components = components
44
45
  this.started = false
45
- this.transports = new Map<string, Transport>()
46
+ this.transports = trackedMap({
47
+ name: 'libp2p_transport_manager_transports',
48
+ metrics: this.components.metrics
49
+ })
46
50
  this.listeners = trackedMap({
47
51
  name: 'libp2p_transport_manager_listeners',
48
52
  metrics: this.components.metrics
package/src/upgrader.ts CHANGED
@@ -1,14 +1,18 @@
1
- import { InvalidMultiaddrError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, setMaxListeners, InvalidPeerIdError } from '@libp2p/interface'
1
+ import { InvalidMultiaddrError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, InvalidPeerIdError } from '@libp2p/interface'
2
2
  import * as mss from '@libp2p/multistream-select'
3
3
  import { peerIdFromString } from '@libp2p/peer-id'
4
+ import { trackedMap } from '@libp2p/utils/tracked-map'
4
5
  import { anySignal } from 'any-signal'
6
+ import { setMaxListeners } from 'main-event'
5
7
  import { CustomProgressEvent } from 'progress-events'
8
+ import { raceSignal } from 'race-signal'
6
9
  import { createConnection } from './connection/index.js'
7
10
  import { PROTOCOL_NEGOTIATION_TIMEOUT, INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js'
8
11
  import { ConnectionDeniedError, ConnectionInterceptedError, EncryptionFailedError, MuxerUnavailableError } from './errors.js'
9
12
  import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'
10
- import type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, Stream, ConnectionProtector, NewStreamOptions, ConnectionEncrypter, SecuredConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, StreamMuxer, StreamMuxerFactory, Upgrader as UpgraderInterface, UpgraderOptions, ConnectionLimits, SecureConnectionOptions, CounterGroup, ClearableSignal } from '@libp2p/interface'
13
+ import type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, Stream, ConnectionProtector, NewStreamOptions, ConnectionEncrypter, SecuredConnection, ConnectionGater, Metrics, PeerId, PeerStore, StreamMuxer, StreamMuxerFactory, Upgrader as UpgraderInterface, UpgraderOptions, ConnectionLimits, SecureConnectionOptions, CounterGroup, ClearableSignal } from '@libp2p/interface'
11
14
  import type { ConnectionManager, Registrar } from '@libp2p/interface-internal'
15
+ import type { TypedEventTarget } from 'main-event'
12
16
 
13
17
  interface CreateConnectionOptions {
14
18
  cryptoProtocol: string
@@ -125,17 +129,25 @@ export class Upgrader implements UpgraderInterface {
125
129
  private readonly metrics: {
126
130
  dials?: CounterGroup<'inbound' | 'outbound'>
127
131
  errors?: CounterGroup<'inbound' | 'outbound'>
132
+ inboundErrors?: CounterGroup
133
+ outboundErrors?: CounterGroup
128
134
  }
129
135
 
130
136
  constructor (components: UpgraderComponents, init: UpgraderInit) {
131
137
  this.components = components
132
- this.connectionEncrypters = new Map()
138
+ this.connectionEncrypters = trackedMap({
139
+ name: 'libp2p_upgrader_connection_encrypters',
140
+ metrics: this.components.metrics
141
+ })
133
142
 
134
143
  init.connectionEncrypters.forEach(encrypter => {
135
144
  this.connectionEncrypters.set(encrypter.protocol, encrypter)
136
145
  })
137
146
 
138
- this.streamMuxers = new Map()
147
+ this.streamMuxers = trackedMap({
148
+ name: 'libp2p_upgrader_stream_multiplexers',
149
+ metrics: this.components.metrics
150
+ })
139
151
 
140
152
  init.streamMuxers.forEach(muxer => {
141
153
  this.streamMuxers.set(muxer.protocol, muxer)
@@ -147,7 +159,9 @@ export class Upgrader implements UpgraderInterface {
147
159
  this.events = components.events
148
160
  this.metrics = {
149
161
  dials: components.metrics?.registerCounterGroup('libp2p_connection_manager_dials_total'),
150
- errors: components.metrics?.registerCounterGroup('libp2p_connection_manager_dial_errors_total')
162
+ errors: components.metrics?.registerCounterGroup('libp2p_connection_manager_dial_errors_total'),
163
+ inboundErrors: components.metrics?.registerCounterGroup('libp2p_connection_manager_dials_inbound_errors_total'),
164
+ outboundErrors: components.metrics?.registerCounterGroup('libp2p_connection_manager_dials_outbound_errors_total')
151
165
  }
152
166
  }
153
167
 
@@ -193,22 +207,25 @@ export class Upgrader implements UpgraderInterface {
193
207
  inbound: true
194
208
  })
195
209
 
196
- accepted = await this.components.connectionManager.acceptIncomingConnection(maConn)
210
+ accepted = await raceSignal(this.components.connectionManager.acceptIncomingConnection(maConn), signal)
197
211
 
198
212
  if (!accepted) {
199
213
  throw new ConnectionDeniedError('Connection denied')
200
214
  }
201
215
 
202
- await this.shouldBlockConnection('denyInboundConnection', maConn)
216
+ await raceSignal(this.shouldBlockConnection('denyInboundConnection', maConn), signal)
203
217
 
204
218
  await this._performUpgrade(maConn, 'inbound', {
205
219
  ...opts,
206
220
  signal
207
221
  })
208
- } catch (err) {
222
+ } catch (err: any) {
209
223
  this.metrics.errors?.increment({
210
224
  inbound: true
211
225
  })
226
+ this.metrics.inboundErrors?.increment({
227
+ [err.name ?? 'Error']: true
228
+ })
212
229
 
213
230
  throw err
214
231
  } finally {
@@ -234,7 +251,7 @@ export class Upgrader implements UpgraderInterface {
234
251
 
235
252
  if (idStr != null) {
236
253
  remotePeerId = peerIdFromString(idStr)
237
- await this.shouldBlockConnection('denyOutboundConnection', remotePeerId, maConn)
254
+ await raceSignal(this.shouldBlockConnection('denyOutboundConnection', remotePeerId, maConn), opts.signal)
238
255
  }
239
256
 
240
257
  let direction: 'inbound' | 'outbound' = 'outbound'
@@ -245,10 +262,13 @@ export class Upgrader implements UpgraderInterface {
245
262
  }
246
263
 
247
264
  return await this._performUpgrade(maConn, direction, opts)
248
- } catch (err) {
265
+ } catch (err: any) {
249
266
  this.metrics.errors?.increment({
250
267
  outbound: true
251
268
  })
269
+ this.metrics.outboundErrors?.increment({
270
+ [err.name ?? 'Error']: true
271
+ })
252
272
 
253
273
  throw err
254
274
  }
@@ -387,11 +407,12 @@ export class Upgrader implements UpgraderInterface {
387
407
  return
388
408
  }
389
409
 
410
+ const signal = AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout)
411
+ setMaxListeners(Infinity, signal)
412
+
390
413
  void Promise.resolve()
391
414
  .then(async () => {
392
415
  const protocols = this.components.registrar.getProtocols()
393
- const signal = AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout)
394
- setMaxListeners(Infinity, signal)
395
416
 
396
417
  const { stream, protocol } = await mss.handle(muxedStream, protocols, {
397
418
  signal,
@@ -440,6 +461,8 @@ export class Upgrader implements UpgraderInterface {
440
461
  // the peer store should ensure that the peer is registered with that protocol
441
462
  await this.components.peerStore.merge(remotePeer, {
442
463
  protocols: [protocol]
464
+ }, {
465
+ signal
443
466
  })
444
467
 
445
468
  this.components.metrics?.trackProtocolStream(muxedStream, connection)
@@ -450,7 +473,10 @@ export class Upgrader implements UpgraderInterface {
450
473
  connection.log.error('error handling incoming stream id %s - %e', muxedStream.id, err)
451
474
 
452
475
  if (muxedStream.timeline.close == null) {
453
- await muxedStream.close()
476
+ await muxedStream.close({
477
+ signal
478
+ })
479
+ .catch(err => muxedStream.abort(err))
454
480
  }
455
481
  })
456
482
  }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.8.8'
1
+ export const version = '2.8.9-6c42ea64a'
2
2
  export const name = 'js-libp2p'
@@ -1,21 +0,0 @@
1
- {
2
- "AddressFilter": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.AddressFilter.html",
3
- "AddressManagerInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.AddressManagerInit.html",
4
- "ConnectionManagerInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.ConnectionManagerInit.html",
5
- "ConnectionMonitorInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.ConnectionMonitorInit.html",
6
- "Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
7
- ".:Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
8
- "TransportManagerInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.TransportManagerInit.html",
9
- "Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
10
- ".:Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
11
- "ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
12
- ".:ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
13
- "createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
14
- ".:createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
15
- "userAgent": "https://libp2p.github.io/js-libp2p/functions/libp2p.user-agent.userAgent.html",
16
- "./user-agent:userAgent": "https://libp2p.github.io/js-libp2p/functions/libp2p.user-agent.userAgent.html",
17
- "name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
18
- "./version:name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
19
- "version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html",
20
- "./version:version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html"
21
- }