libp2p 0.40.0 → 0.41.0-19e96cc

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 (101) hide show
  1. package/README.md +26 -6
  2. package/dist/index.min.js +50 -0
  3. package/dist/src/address-manager/index.d.ts.map +1 -1
  4. package/dist/src/address-manager/index.js +1 -1
  5. package/dist/src/address-manager/index.js.map +1 -1
  6. package/dist/src/config.d.ts.map +1 -1
  7. package/dist/src/config.js +0 -11
  8. package/dist/src/config.js.map +1 -1
  9. package/dist/src/connection/index.d.ts +83 -0
  10. package/dist/src/connection/index.d.ts.map +1 -0
  11. package/dist/src/connection/index.js +96 -0
  12. package/dist/src/connection/index.js.map +1 -0
  13. package/dist/src/connection-manager/dialer/index.d.ts +13 -14
  14. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  15. package/dist/src/connection-manager/dialer/index.js +82 -62
  16. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  17. package/dist/src/connection-manager/index.d.ts +7 -115
  18. package/dist/src/connection-manager/index.d.ts.map +1 -1
  19. package/dist/src/connection-manager/index.js +21 -57
  20. package/dist/src/connection-manager/index.js.map +1 -1
  21. package/dist/src/fetch/index.d.ts +14 -0
  22. package/dist/src/fetch/index.d.ts.map +1 -1
  23. package/dist/src/fetch/index.js +29 -3
  24. package/dist/src/fetch/index.js.map +1 -1
  25. package/dist/src/get-peer.d.ts +2 -2
  26. package/dist/src/get-peer.d.ts.map +1 -1
  27. package/dist/src/get-peer.js +2 -5
  28. package/dist/src/get-peer.js.map +1 -1
  29. package/dist/src/index.d.ts +192 -77
  30. package/dist/src/index.d.ts.map +1 -1
  31. package/dist/src/index.js +41 -1
  32. package/dist/src/index.js.map +1 -1
  33. package/dist/src/insecure/index.d.ts +23 -0
  34. package/dist/src/insecure/index.d.ts.map +1 -1
  35. package/dist/src/insecure/index.js +23 -0
  36. package/dist/src/insecure/index.js.map +1 -1
  37. package/dist/src/keychain/index.d.ts +1 -1
  38. package/dist/src/keychain/index.d.ts.map +1 -1
  39. package/dist/src/libp2p.d.ts +3 -3
  40. package/dist/src/libp2p.d.ts.map +1 -1
  41. package/dist/src/libp2p.js +2 -3
  42. package/dist/src/libp2p.js.map +1 -1
  43. package/dist/src/nat-manager.d.ts.map +1 -1
  44. package/dist/src/nat-manager.js +5 -1
  45. package/dist/src/nat-manager.js.map +1 -1
  46. package/dist/src/pnet/index.d.ts +23 -0
  47. package/dist/src/pnet/index.d.ts.map +1 -1
  48. package/dist/src/pnet/index.js +23 -0
  49. package/dist/src/pnet/index.js.map +1 -1
  50. package/dist/src/pnet/key-generator.d.ts +3 -2
  51. package/dist/src/pnet/key-generator.d.ts.map +1 -1
  52. package/dist/src/pnet/key-generator.js +7 -10
  53. package/dist/src/pnet/key-generator.js.map +1 -1
  54. package/dist/src/registrar.d.ts +5 -0
  55. package/dist/src/registrar.d.ts.map +1 -1
  56. package/dist/src/registrar.js +25 -0
  57. package/dist/src/registrar.js.map +1 -1
  58. package/dist/src/transport-manager.d.ts.map +1 -1
  59. package/dist/src/transport-manager.js +1 -2
  60. package/dist/src/transport-manager.js.map +1 -1
  61. package/dist/src/upgrader.d.ts +1 -1
  62. package/dist/src/upgrader.d.ts.map +1 -1
  63. package/dist/src/upgrader.js +46 -59
  64. package/dist/src/upgrader.js.map +1 -1
  65. package/package.json +15 -14
  66. package/src/address-manager/index.ts +3 -2
  67. package/src/circuit/README.md +6 -6
  68. package/src/config.ts +0 -11
  69. package/src/connection/index.ts +171 -0
  70. package/src/connection-manager/dialer/index.ts +100 -75
  71. package/src/connection-manager/index.ts +29 -192
  72. package/src/fetch/README.md +7 -2
  73. package/src/fetch/index.ts +30 -3
  74. package/src/get-peer.ts +3 -7
  75. package/src/index.ts +224 -83
  76. package/src/insecure/index.ts +24 -0
  77. package/src/keychain/index.ts +1 -1
  78. package/src/libp2p.ts +5 -6
  79. package/src/nat-manager.ts +6 -1
  80. package/src/pnet/README.md +31 -29
  81. package/src/pnet/index.ts +24 -0
  82. package/src/pnet/key-generator.ts +7 -12
  83. package/src/registrar.ts +29 -2
  84. package/src/transport-manager.ts +1 -2
  85. package/src/upgrader.ts +51 -64
  86. package/src/version.ts +1 -1
  87. package/dist/src/metrics/index.d.ts +0 -93
  88. package/dist/src/metrics/index.d.ts.map +0 -1
  89. package/dist/src/metrics/index.js +0 -234
  90. package/dist/src/metrics/index.js.map +0 -1
  91. package/dist/src/metrics/moving-average.d.ts +0 -14
  92. package/dist/src/metrics/moving-average.d.ts.map +0 -1
  93. package/dist/src/metrics/moving-average.js +0 -40
  94. package/dist/src/metrics/moving-average.js.map +0 -1
  95. package/dist/src/metrics/stats.d.ts +0 -87
  96. package/dist/src/metrics/stats.d.ts.map +0 -1
  97. package/dist/src/metrics/stats.js +0 -183
  98. package/dist/src/metrics/stats.js.map +0 -1
  99. package/src/metrics/index.ts +0 -311
  100. package/src/metrics/moving-average.ts +0 -53
  101. package/src/metrics/stats.ts +0 -238
@@ -1,34 +1,41 @@
1
- js-libp2p-pnet
1
+ js-libp2p-pnet <!-- omit in toc -->
2
2
  ==================
3
3
 
4
4
  > Connection protection management for libp2p leveraging PSK encryption via XSalsa20.
5
5
 
6
6
  **Note**: git history prior to merging into js-libp2p can be found in the original repository, https://github.com/libp2p/js-libp2p-pnet.
7
7
 
8
- ## Table of Contents
8
+ ## Table of Contents <!-- omit in toc -->
9
9
 
10
- - [js-libp2p-pnet](#js-libp2p-pnet)
11
- - [Table of Contents](#table-of-contents)
12
- - [Usage](#usage)
13
- - [Examples](#examples)
14
- - [Private Shared Keys](#private-shared-keys)
15
- - [PSK Generation](#psk-generation)
16
- - [From libp2p-pnet](#from-libp2p-pnet)
17
- - [From a module using libp2p](#from-a-module-using-libp2p)
18
- - [Programmatically](#programmatically)
10
+ - [Usage](#usage)
11
+ - [Examples](#examples)
12
+ - [Private Shared Keys](#private-shared-keys)
13
+ - [PSK Generation](#psk-generation)
14
+ - [From a module using libp2p](#from-a-module-using-libp2p)
15
+ - [Programmatically](#programmatically)
19
16
 
20
17
  ## Usage
21
18
 
22
19
  ```js
23
- const Protector from 'libp2p-pnet')
24
- const protector = new Protector(swarmKeyBuffer)
25
- const privateConnection = protector.protect(myPublicConnection, (err) => { })
20
+ import { createLibp2p } from 'libp2p'
21
+ import { preSharedKey, generateKey } from 'libp2p/pnet'
22
+
23
+ // Create a Uint8Array and write the swarm key to it
24
+ const swarmKey = new Uint8Array(95)
25
+ generateKey(swarmKey)
26
+
27
+ const node = await createLibp2p({
28
+ // ...other options
29
+ connectionProtector: preSharedKey({
30
+ psk: swarmKey
31
+ })
32
+ })
26
33
  ```
27
34
 
28
- ### Examples
35
+ ## Examples
29
36
  [Private Networks with IPFS](../../examples/pnet-ipfs)
30
37
 
31
- ### Private Shared Keys
38
+ ## Private Shared Keys
32
39
 
33
40
  Private Shared Keys are expected to be in the following format:
34
41
 
@@ -38,33 +45,28 @@ Private Shared Keys are expected to be in the following format:
38
45
  dffb7e3135399a8b1612b2aaca1c36a3a8ac2cd0cca51ceeb2ced87d308cac6d
39
46
  ```
40
47
 
41
- ### PSK Generation
48
+ ## PSK Generation
42
49
 
43
50
  A utility method has been created to generate a key for your private network. You can
44
51
  use one of the methods below to generate your key.
45
52
 
46
- #### From libp2p-pnet
47
-
48
- If you have libp2p locally, you can run the following from the projects root.
49
-
50
- ```sh
51
- node ./src/pnet/key-generator.js > swarm.key
52
- ```
53
-
54
53
  #### From a module using libp2p
55
54
 
56
55
  If you have a module locally that depends on libp2p, you can run the following from
57
56
  that project, assuming the node_modules are installed.
58
57
 
59
- ```sh
60
- node -e "require('libp2p/src/pnet').generate(process.stdout)" > swarm.key
58
+ ```console
59
+ node -e "import('libp2p/pnet').then(({ generateKey }) => generateKey(process.stdout))" > swarm.key
61
60
  ```
62
61
 
63
62
  #### Programmatically
64
63
 
65
64
  ```js
66
- const writeKey from 'libp2p/src/pnet').generate
65
+ import fs from 'fs'
66
+ import { generateKey } from 'libp2p/pnet'
67
+
67
68
  const swarmKey = new Uint8Array(95)
68
- writeKey(swarmKey)
69
+ generateKey(swarmKey)
70
+
69
71
  fs.writeFileSync('swarm.key', swarmKey)
70
72
  ```
package/src/pnet/index.ts CHANGED
@@ -1,3 +1,27 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Connection protection management for libp2p leveraging PSK encryption via XSalsa20.
5
+ *
6
+ * @example
7
+ *
8
+ * ```typescript
9
+ * import { createLibp2p } from 'libp2p'
10
+ * import { preSharedKey, generateKey } from 'libp2p/pnet'
11
+ *
12
+ * // Create a Uint8Array and write the swarm key to it
13
+ * const swarmKey = new Uint8Array(95)
14
+ * generateKey(swarmKey)
15
+ *
16
+ * const node = await createLibp2p({
17
+ * // ...other options
18
+ * connectionProtector: preSharedKey({
19
+ * psk: swarmKey
20
+ * })
21
+ * })
22
+ * ```
23
+ */
24
+
1
25
  import { logger } from '@libp2p/logger'
2
26
  import { pipe } from 'it-pipe'
3
27
  import errCode from 'err-code'
@@ -5,24 +5,19 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
5
5
  /**
6
6
  * Generates a PSK that can be used in a libp2p-pnet private network
7
7
  *
8
- * @param {Uint8Array} bytes - An object to write the psk into
8
+ * @param {Uint8Array | NodeJS.WriteStream} bytes - An object to write the psk into
9
9
  * @returns {void}
10
10
  */
11
- export function generateKey (bytes: Uint8Array) {
11
+ export function generateKey (bytes: Uint8Array | NodeJS.WriteStream) {
12
12
  const psk = uint8ArrayToString(randomBytes(KEY_LENGTH), 'base16')
13
13
  const key = uint8ArrayFromString('/key/swarm/psk/1.0.0/\n/base16/\n' + psk)
14
14
 
15
- bytes.set(key)
15
+ if (bytes instanceof Uint8Array) {
16
+ bytes.set(key)
17
+ } else {
18
+ bytes.write(key)
19
+ }
16
20
  }
17
21
 
18
22
  export const NONCE_LENGTH = 24
19
23
  export const KEY_LENGTH = 32
20
-
21
- try {
22
- if (require.main === module) {
23
- // @ts-expect-error
24
- generate(process.stdout)
25
- }
26
- } catch (error: any) {
27
-
28
- }
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
package/src/upgrader.ts CHANGED
@@ -1,11 +1,8 @@
1
1
  import { logger } from '@libp2p/logger'
2
2
  import errCode from 'err-code'
3
3
  import * as mss from '@libp2p/multistream-select'
4
- import { pipe } from 'it-pipe'
5
- // @ts-expect-error mutable-proxy does not export types
6
- import mutableProxy from 'mutable-proxy'
7
4
  import { codes } from './errors.js'
8
- import { createConnection } from '@libp2p/connection'
5
+ import { createConnection } from './connection/index.js'
9
6
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
10
7
  import { peerIdFromString } from '@libp2p/peer-id'
11
8
  import type { MultiaddrConnection, Connection, Stream, ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'
@@ -134,7 +131,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
134
131
  /**
135
132
  * Upgrades an inbound connection
136
133
  */
137
- async upgradeInbound (maConn: MultiaddrConnection): Promise<Connection> {
134
+ async upgradeInbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise<Connection> {
138
135
  const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)
139
136
 
140
137
  if (!accept) {
@@ -146,9 +143,6 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
146
143
  let upgradedConn: Duplex<Uint8Array>
147
144
  let muxerFactory: StreamMuxerFactory | undefined
148
145
  let cryptoProtocol
149
- let setPeer
150
- let proxyPeer
151
- const metrics = this.components.metrics
152
146
 
153
147
  const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)
154
148
 
@@ -166,49 +160,62 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
166
160
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)
167
161
  }
168
162
 
169
- if (metrics != null) {
170
- ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
171
- const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`
172
- setPeer({ toString: () => idString })
173
- metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
174
- }
163
+ this.components.metrics?.trackMultiaddrConnection(maConn)
175
164
 
176
165
  log('starting the inbound connection upgrade')
177
166
 
178
167
  // Protect
179
168
  let protectedConn = maConn
180
- const protector = this.components.connectionProtector
181
169
 
182
- if (protector != null) {
183
- log('protecting the inbound connection')
184
- protectedConn = await protector.protect(maConn)
170
+ if (opts?.skipProtection !== true) {
171
+ const protector = this.components.connectionProtector
172
+
173
+ if (protector != null) {
174
+ log('protecting the inbound connection')
175
+ protectedConn = await protector.protect(maConn)
176
+ }
185
177
  }
186
178
 
187
179
  try {
188
180
  // Encrypt the connection
189
- ({
190
- conn: encryptedConn,
191
- remotePeer,
192
- protocol: cryptoProtocol
193
- } = await this._encryptInbound(protectedConn))
181
+ encryptedConn = protectedConn
182
+ if (opts?.skipEncryption !== true) {
183
+ ({
184
+ conn: encryptedConn,
185
+ remotePeer,
186
+ protocol: cryptoProtocol
187
+ } = await this._encryptInbound(protectedConn))
188
+
189
+ if (await this.components.connectionGater.denyInboundEncryptedConnection(remotePeer, {
190
+ ...protectedConn,
191
+ ...encryptedConn
192
+ })) {
193
+ throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
194
+ }
195
+ } else {
196
+ const idStr = maConn.remoteAddr.getPeerId()
194
197
 
195
- if (await this.components.connectionGater.denyInboundEncryptedConnection(remotePeer, {
196
- ...protectedConn,
197
- ...encryptedConn
198
- })) {
199
- throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
198
+ if (idStr == null) {
199
+ throw errCode(new Error('inbound connection that skipped encryption must have a peer id'), codes.ERR_INVALID_MULTIADDR)
200
+ }
201
+
202
+ const remotePeerId = peerIdFromString(idStr)
203
+
204
+ cryptoProtocol = 'native'
205
+ remotePeer = remotePeerId
200
206
  }
201
207
 
202
- // Multiplex the connection
203
- if (this.muxers.size > 0) {
208
+ upgradedConn = encryptedConn
209
+ if (opts?.muxerFactory != null) {
210
+ muxerFactory = opts.muxerFactory
211
+ } else if (this.muxers.size > 0) {
212
+ // Multiplex the connection
204
213
  const multiplexed = await this._multiplexInbound({
205
214
  ...protectedConn,
206
215
  ...encryptedConn
207
216
  }, this.muxers)
208
217
  muxerFactory = multiplexed.muxerFactory
209
218
  upgradedConn = multiplexed.stream
210
- } else {
211
- upgradedConn = encryptedConn
212
219
  }
213
220
  } catch (err: any) {
214
221
  log.error('Failed to upgrade inbound connection', err)
@@ -222,11 +229,6 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
222
229
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
223
230
  }
224
231
 
225
- if (metrics != null) {
226
- metrics.updatePlaceholder(proxyPeer, remotePeer)
227
- setPeer(remotePeer)
228
- }
229
-
230
232
  log('Successfully upgraded inbound connection')
231
233
 
232
234
  return this._createConnection({
@@ -263,16 +265,8 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
263
265
  let upgradedConn
264
266
  let cryptoProtocol
265
267
  let muxerFactory
266
- let setPeer
267
- let proxyPeer
268
- const metrics = this.components.metrics
269
-
270
- if (metrics != null) {
271
- ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
272
- const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`
273
- setPeer({ toB58String: () => idString })
274
- metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
275
- }
268
+
269
+ this.components.metrics?.trackMultiaddrConnection(maConn)
276
270
 
277
271
  log('Starting the outbound connection upgrade')
278
272
 
@@ -335,11 +329,6 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
335
329
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
336
330
  }
337
331
 
338
- if (metrics != null) {
339
- metrics.updatePlaceholder(proxyPeer, remotePeer)
340
- setPeer(remotePeer)
341
- }
342
-
343
332
  log('Successfully upgraded outbound connection')
344
333
 
345
334
  return this._createConnection({
@@ -385,12 +374,6 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
385
374
  const { stream, protocol } = await mss.handle(muxedStream, protocols)
386
375
  log('%s: incoming stream opened on %s', direction, protocol)
387
376
 
388
- const metrics = this.components.metrics
389
-
390
- if (metrics != null) {
391
- metrics.trackStream({ stream, remotePeer, protocol })
392
- }
393
-
394
377
  if (connection == null) {
395
378
  return
396
379
  }
@@ -415,6 +398,8 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
415
398
  this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
416
399
 
417
400
  connection.addStream(muxedStream)
401
+ this.components.metrics?.trackProtocolStream(muxedStream, connection)
402
+
418
403
  this._onStream({ connection, stream: muxedStream, protocol })
419
404
  })
420
405
  .catch(err => {
@@ -438,7 +423,6 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
438
423
 
439
424
  log('%s: starting new stream on %s', direction, protocols)
440
425
  const muxedStream = await muxer.newStream()
441
- const metrics = this.components.metrics
442
426
  let controller: TimeoutController | undefined
443
427
 
444
428
  try {
@@ -456,10 +440,6 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
456
440
 
457
441
  const { stream, protocol } = await mss.select(muxedStream, protocols, options)
458
442
 
459
- if (metrics != null) {
460
- metrics.trackStream({ stream, remotePeer, protocol })
461
- }
462
-
463
443
  const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar)
464
444
  const streamCount = countStreams(protocol, 'outbound', connection)
465
445
 
@@ -480,6 +460,8 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
480
460
  muxedStream.sink = stream.sink
481
461
  muxedStream.stat.protocol = protocol
482
462
 
463
+ this.components.metrics?.trackProtocolStream(muxedStream, connection)
464
+
483
465
  return muxedStream
484
466
  } catch (err: any) {
485
467
  log.error('could not create new stream', err)
@@ -501,7 +483,12 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
501
483
  }
502
484
 
503
485
  // Pipe all data through the muxer
504
- pipe(upgradedConn, muxer, upgradedConn).catch(log.error)
486
+ void Promise.all([
487
+ muxer.sink(upgradedConn.source),
488
+ upgradedConn.sink(muxer.source)
489
+ ]).catch(err => {
490
+ log.error(err)
491
+ })
505
492
  }
506
493
 
507
494
  const _timeline = maConn.timeline
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '0.40.0'
1
+ export const version = '0.41.0-19e96cc'
2
2
  export const name = 'libp2p'
@@ -1,93 +0,0 @@
1
- import { DefaultStats } from './stats.js';
2
- import type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics';
3
- import type { PeerId } from '@libp2p/interface-peer-id';
4
- import type { Startable } from '@libp2p/interfaces/startable';
5
- export interface OnMessageOptions {
6
- remotePeer: PeerId;
7
- protocol?: string;
8
- direction: 'in' | 'out';
9
- dataLength: number;
10
- }
11
- export interface MetricsInit {
12
- enabled: boolean;
13
- computeThrottleMaxQueueSize: number;
14
- computeThrottleTimeout: number;
15
- movingAverageIntervals: number[];
16
- maxOldPeersRetention: number;
17
- }
18
- export declare class DefaultMetrics implements Metrics, Startable {
19
- globalStats: DefaultStats;
20
- private readonly enabled;
21
- private readonly peerStats;
22
- private readonly protocolStats;
23
- private readonly oldPeers;
24
- private running;
25
- private readonly systems;
26
- private readonly statsInit;
27
- constructor(init: MetricsInit);
28
- isStarted(): boolean;
29
- /**
30
- * Must be called for stats to saved. Any data pushed for tracking
31
- * will be ignored.
32
- */
33
- start(): Promise<void>;
34
- /**
35
- * Stops all averages timers and prevents new data from being tracked.
36
- * Once `stop` is called, `start` must be called to resume stats tracking.
37
- */
38
- stop(): Promise<void>;
39
- /**
40
- * Gets the global `Stats` object
41
- */
42
- getGlobal(): DefaultStats;
43
- /**
44
- * Returns a list of `PeerId` strings currently being tracked
45
- */
46
- getPeers(): string[];
47
- getComponentMetrics(): Map<string, Map<string, Map<string, TrackedMetric>>>;
48
- updateComponentMetric(update: ComponentMetricsUpdate): void;
49
- /**
50
- * Returns the `Stats` object for the given `PeerId` whether it
51
- * is a live peer, or in the disconnected peer LRU cache.
52
- */
53
- forPeer(peerId: PeerId): Stats | undefined;
54
- /**
55
- * Returns a list of all protocol strings currently being tracked
56
- */
57
- getProtocols(): string[];
58
- /**
59
- * Returns the `Stats` object for the given `protocol`
60
- */
61
- forProtocol(protocol: string): Stats | undefined;
62
- /**
63
- * Should be called when all connections to a given peer
64
- * have closed. The `Stats` collection for the peer will
65
- * be stopped and moved to an LRU for temporary retention.
66
- */
67
- onPeerDisconnected(peerId: PeerId): void;
68
- /**
69
- * Takes the metadata for a message and tracks it in the
70
- * appropriate categories. If the protocol is present, protocol
71
- * stats will also be tracked.
72
- */
73
- _onMessage(opts: OnMessageOptions): void;
74
- /**
75
- * Replaces the `PeerId` string with the given `peerId`.
76
- * If stats are already being tracked for the given `peerId`, the
77
- * placeholder stats will be merged with the existing stats.
78
- *
79
- * @param {PeerId} placeholder - A peerId string
80
- * @param {PeerId} peerId
81
- * @returns {void}
82
- */
83
- updatePlaceholder(placeholder: PeerId, peerId: PeerId): void;
84
- /**
85
- * Tracks data running through a given Duplex Iterable `stream`. If
86
- * the `peerId` is not provided, a placeholder string will be created and
87
- * returned. This allows lazy tracking of a peer when the peer is not yet known.
88
- * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called
89
- * with the placeholder string returned from here, and the known `PeerId`.
90
- */
91
- trackStream(opts: TrackStreamOptions): void;
92
- }
93
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/metrics/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAa,MAAM,YAAY,CAAA;AACpD,OAAO,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAC1H,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAA;AAY7D,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,IAAI,GAAG,KAAK,CAAA;IACvB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAA;IAChB,2BAA2B,EAAE,MAAM,CAAA;IACnC,sBAAsB,EAAE,MAAM,CAAA;IAC9B,sBAAsB,EAAE,MAAM,EAAE,CAAA;IAChC,oBAAoB,EAAE,MAAM,CAAA;CAC7B;AAED,qBAAa,cAAe,YAAW,OAAO,EAAE,SAAS;IAChD,WAAW,EAAE,YAAY,CAAA;IAEhC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2B;IACrD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA2B;IACzD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAwB;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsD;IAC9E,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;gBAExB,IAAI,EAAE,WAAW;IAe9B,SAAS;IAIT;;;OAGG;IACG,KAAK;IAQX;;;OAGG;IACG,IAAI;IAiBV;;OAEG;IACH,SAAS;IAIT;;OAEG;IACH,QAAQ;IAIR,mBAAmB;IAInB,qBAAqB,CAAE,MAAM,EAAE,sBAAsB;IA8BrD;;;OAGG;IACH,OAAO,CAAE,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;IAK3C;;OAEG;IACH,YAAY,IAAK,MAAM,EAAE;IAIzB;;OAEG;IACH,WAAW,CAAE,QAAQ,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;IAIjD;;;;OAIG;IACH,kBAAkB,CAAE,MAAM,EAAE,MAAM;IAYlC;;;;OAIG;IACH,UAAU,CAAE,IAAI,EAAE,gBAAgB;IAkClC;;;;;;;;OAQG;IACH,iBAAiB,CAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAwBtD;;;;;;OAMG;IACH,WAAW,CAAE,IAAI,EAAE,kBAAkB,GAAG,IAAI;CA+B7C"}