libp2p 0.40.0 → 0.41.0-1147550
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.
- package/README.md +26 -6
- package/dist/index.min.js +58 -0
- package/dist/src/address-manager/index.d.ts +8 -0
- package/dist/src/address-manager/index.d.ts.map +1 -1
- package/dist/src/address-manager/index.js +1 -1
- package/dist/src/address-manager/index.js.map +1 -1
- package/dist/src/circuit/index.d.ts +11 -1
- package/dist/src/circuit/index.d.ts.map +1 -1
- package/dist/src/circuit/index.js.map +1 -1
- package/dist/src/circuit/transport.d.ts +1 -1
- package/dist/src/circuit/transport.d.ts.map +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +1 -12
- package/dist/src/config.js.map +1 -1
- package/dist/src/connection/index.d.ts +83 -0
- package/dist/src/connection/index.d.ts.map +1 -0
- package/dist/src/connection/index.js +96 -0
- package/dist/src/connection/index.js.map +1 -0
- package/dist/src/connection-manager/dialer/index.d.ts +13 -14
- package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
- package/dist/src/connection-manager/dialer/index.js +82 -62
- package/dist/src/connection-manager/dialer/index.js.map +1 -1
- package/dist/src/connection-manager/index.d.ts +11 -38
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js +35 -65
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/fetch/index.d.ts +14 -0
- package/dist/src/fetch/index.d.ts.map +1 -1
- package/dist/src/fetch/index.js +29 -3
- package/dist/src/fetch/index.js.map +1 -1
- package/dist/src/get-peer.d.ts +2 -2
- package/dist/src/get-peer.d.ts.map +1 -1
- package/dist/src/get-peer.js +2 -5
- package/dist/src/get-peer.js.map +1 -1
- package/dist/src/index.d.ts +129 -139
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +41 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/insecure/index.d.ts +23 -0
- package/dist/src/insecure/index.d.ts.map +1 -1
- package/dist/src/insecure/index.js +23 -0
- package/dist/src/insecure/index.js.map +1 -1
- package/dist/src/keychain/index.d.ts +3 -3
- package/dist/src/keychain/index.d.ts.map +1 -1
- package/dist/src/libp2p.d.ts +4 -3
- package/dist/src/libp2p.d.ts.map +1 -1
- package/dist/src/libp2p.js +12 -3
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/nat-manager.d.ts.map +1 -1
- package/dist/src/nat-manager.js +5 -1
- package/dist/src/nat-manager.js.map +1 -1
- package/dist/src/peer-routing.d.ts +1 -1
- package/dist/src/peer-routing.d.ts.map +1 -1
- package/dist/src/peer-routing.js +1 -1
- package/dist/src/peer-routing.js.map +1 -1
- package/dist/src/pnet/index.d.ts +23 -0
- package/dist/src/pnet/index.d.ts.map +1 -1
- package/dist/src/pnet/index.js +23 -0
- package/dist/src/pnet/index.js.map +1 -1
- package/dist/src/pnet/key-generator.d.ts +3 -2
- package/dist/src/pnet/key-generator.d.ts.map +1 -1
- package/dist/src/pnet/key-generator.js +7 -10
- package/dist/src/pnet/key-generator.js.map +1 -1
- package/dist/src/registrar.d.ts +5 -0
- package/dist/src/registrar.d.ts.map +1 -1
- package/dist/src/registrar.js +25 -0
- package/dist/src/registrar.js.map +1 -1
- package/dist/src/transport-manager.d.ts +1 -13
- package/dist/src/transport-manager.d.ts.map +1 -1
- package/dist/src/transport-manager.js +2 -16
- package/dist/src/transport-manager.js.map +1 -1
- package/dist/src/upgrader.d.ts +1 -1
- package/dist/src/upgrader.d.ts.map +1 -1
- package/dist/src/upgrader.js +46 -59
- package/dist/src/upgrader.js.map +1 -1
- package/package.json +16 -19
- package/src/address-manager/index.ts +11 -2
- package/src/circuit/README.md +6 -6
- package/src/circuit/index.ts +13 -1
- package/src/circuit/transport.ts +1 -1
- package/src/config.ts +1 -12
- package/src/connection/index.ts +171 -0
- package/src/connection-manager/dialer/index.ts +100 -75
- package/src/connection-manager/index.ts +58 -114
- package/src/fetch/README.md +7 -2
- package/src/fetch/index.ts +30 -3
- package/src/get-peer.ts +3 -7
- package/src/index.ts +141 -152
- package/src/insecure/index.ts +24 -0
- package/src/keychain/index.ts +3 -3
- package/src/libp2p.ts +17 -6
- package/src/nat-manager.ts +6 -1
- package/src/peer-routing.ts +2 -2
- package/src/pnet/README.md +31 -29
- package/src/pnet/index.ts +24 -0
- package/src/pnet/key-generator.ts +7 -12
- package/src/registrar.ts +29 -2
- package/src/transport-manager.ts +2 -17
- package/src/upgrader.ts +51 -64
- package/src/version.ts +1 -1
- package/dist/src/metrics/index.d.ts +0 -93
- package/dist/src/metrics/index.d.ts.map +0 -1
- package/dist/src/metrics/index.js +0 -234
- package/dist/src/metrics/index.js.map +0 -1
- package/dist/src/metrics/moving-average.d.ts +0 -14
- package/dist/src/metrics/moving-average.d.ts.map +0 -1
- package/dist/src/metrics/moving-average.js +0 -40
- package/dist/src/metrics/moving-average.js.map +0 -1
- package/dist/src/metrics/stats.d.ts +0 -87
- package/dist/src/metrics/stats.d.ts.map +0 -1
- package/dist/src/metrics/stats.js +0 -183
- package/dist/src/metrics/stats.js.map +0 -1
- package/src/metrics/index.ts +0 -311
- package/src/metrics/moving-average.ts +0 -53
- 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'
|
|
@@ -11,78 +9,41 @@ import { codes } from '../errors.js'
|
|
|
11
9
|
import { isPeerId, PeerId } from '@libp2p/interface-peer-id'
|
|
12
10
|
import { setMaxListeners } from 'events'
|
|
13
11
|
import type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'
|
|
14
|
-
import type { ConnectionManager, Dialer } from '@libp2p/interface-connection-manager'
|
|
12
|
+
import type { ConnectionManager, ConnectionManagerEvents, 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
|
|
|
27
|
-
|
|
28
|
-
maxConnections: Infinity,
|
|
29
|
-
minConnections: 0,
|
|
30
|
-
maxData: Infinity,
|
|
31
|
-
maxSentData: Infinity,
|
|
32
|
-
maxReceivedData: Infinity,
|
|
33
|
-
maxEventLoopDelay: Infinity,
|
|
34
|
-
pollInterval: 2000,
|
|
35
|
-
autoDialInterval: 10000,
|
|
36
|
-
movingAverageInterval: 60000,
|
|
37
|
-
inboundConnectionThreshold: 5,
|
|
38
|
-
maxIncomingPendingConnections: 10
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const METRICS_SYSTEM = 'libp2p'
|
|
42
|
-
const METRICS_COMPONENT = 'connection-manager'
|
|
43
|
-
const STARTUP_RECONNECT_TIMEOUT = 60000
|
|
44
|
-
|
|
45
|
-
export interface ConnectionManagerInit {
|
|
26
|
+
export interface ConnectionManagerConfig {
|
|
46
27
|
/**
|
|
47
|
-
* The maximum number of connections to
|
|
28
|
+
* The maximum number of connections libp2p is willing to have before it starts disconnecting. Defaults to `Infinity`
|
|
48
29
|
*/
|
|
49
30
|
maxConnections: number
|
|
50
31
|
|
|
51
32
|
/**
|
|
52
|
-
* The minimum number of connections to
|
|
33
|
+
* The minimum number of connections below which libp2p not activate preemptive disconnections. Defaults to `0`.
|
|
53
34
|
*/
|
|
54
35
|
minConnections: number
|
|
55
36
|
|
|
56
37
|
/**
|
|
57
|
-
*
|
|
58
|
-
*/
|
|
59
|
-
maxData?: number
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* The max outgoing data, per average interval to allow
|
|
63
|
-
*/
|
|
64
|
-
maxSentData?: number
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* The max incoming data, per average interval to allow
|
|
68
|
-
*/
|
|
69
|
-
maxReceivedData?: number
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* The upper limit the event loop can take to run
|
|
38
|
+
* Sets the maximum event loop delay (measured in milliseconds) this node is willing to endure before it starts disconnecting peers. Defaults to `Infinity`.
|
|
73
39
|
*/
|
|
74
40
|
maxEventLoopDelay?: number
|
|
75
41
|
|
|
76
42
|
/**
|
|
77
|
-
*
|
|
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).
|
|
78
44
|
*/
|
|
79
45
|
pollInterval?: number
|
|
80
46
|
|
|
81
|
-
/**
|
|
82
|
-
* How often, in milliseconds, to compute averages
|
|
83
|
-
*/
|
|
84
|
-
movingAverageInterval?: number
|
|
85
|
-
|
|
86
47
|
/**
|
|
87
48
|
* If true, try to connect to all discovered peers up to the connection manager limit
|
|
88
49
|
*/
|
|
@@ -162,11 +123,18 @@ export interface ConnectionManagerInit {
|
|
|
162
123
|
maxIncomingPendingConnections?: number
|
|
163
124
|
}
|
|
164
125
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
126
|
+
const defaultOptions: Partial<ConnectionManagerConfig> = {
|
|
127
|
+
maxConnections: Infinity,
|
|
128
|
+
minConnections: 0,
|
|
129
|
+
maxEventLoopDelay: Infinity,
|
|
130
|
+
pollInterval: 2000,
|
|
131
|
+
autoDialInterval: 10000,
|
|
132
|
+
inboundConnectionThreshold: 5,
|
|
133
|
+
maxIncomingPendingConnections: 10
|
|
168
134
|
}
|
|
169
135
|
|
|
136
|
+
const STARTUP_RECONNECT_TIMEOUT = 60000
|
|
137
|
+
|
|
170
138
|
export interface DefaultConnectionManagerComponents {
|
|
171
139
|
peerId: PeerId
|
|
172
140
|
metrics?: Metrics
|
|
@@ -175,16 +143,17 @@ export interface DefaultConnectionManagerComponents {
|
|
|
175
143
|
dialer: Dialer
|
|
176
144
|
}
|
|
177
145
|
|
|
146
|
+
export type ConnectionManagerInit = ConnectionManagerConfig
|
|
147
|
+
|
|
178
148
|
/**
|
|
179
149
|
* Responsible for managing known connections.
|
|
180
150
|
*/
|
|
181
151
|
export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEvents> implements ConnectionManager, Startable {
|
|
182
152
|
private readonly components: DefaultConnectionManagerComponents
|
|
183
|
-
private readonly opts:
|
|
153
|
+
private readonly opts: ConnectionManagerInit
|
|
184
154
|
private readonly connections: Map<string, Connection[]>
|
|
185
155
|
private started: boolean
|
|
186
|
-
private
|
|
187
|
-
private readonly latencyMonitor: LatencyMonitor
|
|
156
|
+
private readonly latencyMonitor?: LatencyMonitor
|
|
188
157
|
private readonly startupReconnectTimeout: number
|
|
189
158
|
private connectOnStartupController?: TimeoutController
|
|
190
159
|
private readonly dialTimeout: number
|
|
@@ -193,7 +162,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
193
162
|
private readonly inboundConnectionRateLimiter: RateLimiterMemory
|
|
194
163
|
private incomingPendingConnections: number
|
|
195
164
|
|
|
196
|
-
constructor (components: DefaultConnectionManagerComponents, init:
|
|
165
|
+
constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerConfig) {
|
|
197
166
|
super()
|
|
198
167
|
|
|
199
168
|
this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)
|
|
@@ -212,12 +181,13 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
212
181
|
this.connections = new Map()
|
|
213
182
|
|
|
214
183
|
this.started = false
|
|
215
|
-
this._checkMetrics = this._checkMetrics.bind(this)
|
|
216
184
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
185
|
+
if (init.maxEventLoopDelay != null && init.maxEventLoopDelay > 0 && init.maxEventLoopDelay !== Infinity) {
|
|
186
|
+
this.latencyMonitor = new LatencyMonitor({
|
|
187
|
+
latencyCheckIntervalMs: init.pollInterval,
|
|
188
|
+
dataEmitIntervalMs: init.pollInterval
|
|
189
|
+
})
|
|
190
|
+
}
|
|
221
191
|
|
|
222
192
|
try {
|
|
223
193
|
// This emitter gets listened to a lot
|
|
@@ -250,17 +220,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
250
220
|
* only event loop and connection limits will be monitored.
|
|
251
221
|
*/
|
|
252
222
|
async start () {
|
|
253
|
-
if (this.components.metrics != null) {
|
|
254
|
-
this.timer = this.timer ?? retimer(this._checkMetrics, this.opts.pollInterval)
|
|
255
|
-
}
|
|
256
|
-
|
|
257
223
|
// track inbound/outbound connections
|
|
258
|
-
this.components.metrics?.
|
|
259
|
-
|
|
260
|
-
component: METRICS_COMPONENT,
|
|
261
|
-
metric: 'connections',
|
|
262
|
-
label: 'direction',
|
|
263
|
-
value: () => {
|
|
224
|
+
this.components.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {
|
|
225
|
+
calculate: () => {
|
|
264
226
|
const metric = {
|
|
265
227
|
inbound: 0,
|
|
266
228
|
outbound: 0
|
|
@@ -281,12 +243,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
281
243
|
})
|
|
282
244
|
|
|
283
245
|
// track total number of streams per protocol
|
|
284
|
-
this.components.metrics?.
|
|
285
|
-
system: METRICS_SYSTEM,
|
|
286
|
-
component: METRICS_COMPONENT,
|
|
287
|
-
metric: 'protocol-streams-total',
|
|
246
|
+
this.components.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {
|
|
288
247
|
label: 'protocol',
|
|
289
|
-
|
|
248
|
+
calculate: () => {
|
|
290
249
|
const metric: Record<string, number> = {}
|
|
291
250
|
|
|
292
251
|
for (const conns of this.connections.values()) {
|
|
@@ -304,12 +263,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
304
263
|
})
|
|
305
264
|
|
|
306
265
|
// track 90th percentile of streams per protocol
|
|
307
|
-
this.components.metrics?.
|
|
308
|
-
system: METRICS_SYSTEM,
|
|
309
|
-
component: METRICS_COMPONENT,
|
|
310
|
-
metric: 'protocol-streams-per-connection-90th-percentile',
|
|
266
|
+
this.components.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {
|
|
311
267
|
label: 'protocol',
|
|
312
|
-
|
|
268
|
+
calculate: () => {
|
|
313
269
|
const allStreams: Record<string, number[]> = {}
|
|
314
270
|
|
|
315
271
|
for (const conns of this.connections.values()) {
|
|
@@ -343,9 +299,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
343
299
|
})
|
|
344
300
|
|
|
345
301
|
// latency monitor
|
|
346
|
-
this.latencyMonitor
|
|
302
|
+
this.latencyMonitor?.start()
|
|
347
303
|
this._onLatencyMeasure = this._onLatencyMeasure.bind(this)
|
|
348
|
-
this.latencyMonitor
|
|
304
|
+
this.latencyMonitor?.addEventListener('data', this._onLatencyMeasure)
|
|
349
305
|
|
|
350
306
|
this.started = true
|
|
351
307
|
log('started')
|
|
@@ -407,10 +363,8 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
407
363
|
* Stops the Connection Manager
|
|
408
364
|
*/
|
|
409
365
|
async stop () {
|
|
410
|
-
this.
|
|
411
|
-
|
|
412
|
-
this.latencyMonitor.removeEventListener('data', this._onLatencyMeasure)
|
|
413
|
-
this.latencyMonitor.stop()
|
|
366
|
+
this.latencyMonitor?.removeEventListener('data', this._onLatencyMeasure)
|
|
367
|
+
this.latencyMonitor?.stop()
|
|
414
368
|
|
|
415
369
|
this.started = false
|
|
416
370
|
await this._close()
|
|
@@ -440,31 +394,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
440
394
|
this.connections.clear()
|
|
441
395
|
}
|
|
442
396
|
|
|
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
397
|
onConnect (evt: CustomEvent<Connection>) {
|
|
469
398
|
void this._onConnect(evt).catch(err => {
|
|
470
399
|
log.error(err)
|
|
@@ -524,8 +453,6 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
524
453
|
} else if (storedConn != null) {
|
|
525
454
|
this.connections.delete(peerId)
|
|
526
455
|
this.dispatchEvent(new CustomEvent<Connection>('peer:disconnect', { detail: connection }))
|
|
527
|
-
|
|
528
|
-
this.components.metrics?.onPeerDisconnected(connection.remotePeer)
|
|
529
456
|
}
|
|
530
457
|
}
|
|
531
458
|
|
|
@@ -543,7 +470,18 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
543
470
|
return conns
|
|
544
471
|
}
|
|
545
472
|
|
|
546
|
-
async openConnection (
|
|
473
|
+
async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr, options: AbortOptions = {}): Promise<Connection> {
|
|
474
|
+
let peerId: PeerId
|
|
475
|
+
|
|
476
|
+
if (isPeerId(peerIdOrMultiaddr)) {
|
|
477
|
+
peerId = peerIdOrMultiaddr
|
|
478
|
+
} else if (isMultiaddr(peerIdOrMultiaddr)) {
|
|
479
|
+
const info = getPeer(peerIdOrMultiaddr)
|
|
480
|
+
peerId = info.id
|
|
481
|
+
} else {
|
|
482
|
+
throw errCode(new TypeError('Can only open connections to PeerIds or Multiaddrs'), codes.ERR_INVALID_PARAMETERS)
|
|
483
|
+
}
|
|
484
|
+
|
|
547
485
|
log('dial to %p', peerId)
|
|
548
486
|
const existingConnections = this.getConnections(peerId)
|
|
549
487
|
|
|
@@ -566,7 +504,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
566
504
|
}
|
|
567
505
|
|
|
568
506
|
try {
|
|
569
|
-
const connection = await this.components.dialer.dial(
|
|
507
|
+
const connection = await this.components.dialer.dial(peerIdOrMultiaddr, options)
|
|
570
508
|
let peerConnections = this.connections.get(peerId.toString())
|
|
571
509
|
|
|
572
510
|
if (peerConnections == null) {
|
|
@@ -643,6 +581,12 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
|
|
|
643
581
|
*/
|
|
644
582
|
async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {
|
|
645
583
|
const limit = this.opts[name]
|
|
584
|
+
|
|
585
|
+
if (limit == null) {
|
|
586
|
+
log.trace('limit %s was not set so it cannot be applied', name)
|
|
587
|
+
return
|
|
588
|
+
}
|
|
589
|
+
|
|
646
590
|
log.trace('checking limit of %s. current value: %d of %d', name, value, limit)
|
|
647
591
|
if (value > limit) {
|
|
648
592
|
log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.peerId, name, value, limit, toPrune)
|
package/src/fetch/README.md
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
libp2p-fetch JavaScript Implementation
|
|
1
|
+
libp2p-fetch JavaScript Implementation <!-- omit in toc -->
|
|
2
2
|
=====================================
|
|
3
3
|
|
|
4
4
|
> Libp2p fetch protocol JavaScript implementation
|
|
5
5
|
|
|
6
|
+
## Table of contents <!-- omit in toc -->
|
|
7
|
+
|
|
8
|
+
- [Overview](#overview)
|
|
9
|
+
- [Usage](#usage)
|
|
10
|
+
|
|
6
11
|
## Overview
|
|
7
12
|
|
|
8
13
|
An implementation of the Fetch protocol as described here: https://github.com/libp2p/specs/tree/master/fetch
|
|
@@ -27,7 +32,7 @@ async function my_subsystem_key_lookup(key) {
|
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
// Enable this peer to respond to fetch requests for keys that begin with '/my_subsystem_key_prefix/'
|
|
30
|
-
const libp2p =
|
|
35
|
+
const libp2p = createLibp2p()
|
|
31
36
|
libp2p.fetchService.registerLookupFunction('/my_subsystem_key_prefix/', my_subsystem_key_lookup)
|
|
32
37
|
|
|
33
38
|
const key = '/my_subsystem_key_prefix/{...}'
|
package/src/fetch/index.ts
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -222,6 +235,13 @@ export class FetchService implements Startable {
|
|
|
222
235
|
/**
|
|
223
236
|
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
224
237
|
* share the same prefix
|
|
238
|
+
*
|
|
239
|
+
* @example
|
|
240
|
+
*
|
|
241
|
+
* ```js
|
|
242
|
+
* // ...
|
|
243
|
+
* libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
|
|
244
|
+
* ```
|
|
225
245
|
*/
|
|
226
246
|
registerLookupFunction (prefix: string, lookup: LookupFunction) {
|
|
227
247
|
if (this.lookupFunctions.has(prefix)) {
|
|
@@ -234,6 +254,13 @@ export class FetchService implements Startable {
|
|
|
234
254
|
/**
|
|
235
255
|
* Registers a new lookup callback that can map keys to values, for a given set of keys that
|
|
236
256
|
* share the same prefix.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
*
|
|
260
|
+
* ```js
|
|
261
|
+
* // ...
|
|
262
|
+
* libp2p.fetchService.unregisterLookupFunction('/prefix')
|
|
263
|
+
* ```
|
|
237
264
|
*/
|
|
238
265
|
unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {
|
|
239
266
|
if (lookup != null) {
|
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 {
|
|
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 `
|
|
31
|
+
* Converts the given `peer` to a `PeerInfo` object.
|
|
32
32
|
*/
|
|
33
|
-
export function getPeer (peer: PeerId | Multiaddr
|
|
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)) {
|