libp2p 2.8.14 → 2.9.0-ce6b542a8

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/src/upgrader.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { InvalidMultiaddrError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, InvalidPeerIdError } from '@libp2p/interface'
1
+ import { InvalidMultiaddrError, InvalidPeerIdError } from '@libp2p/interface'
2
2
  import * as mss from '@libp2p/multistream-select'
3
3
  import { peerIdFromString } from '@libp2p/peer-id'
4
4
  import { trackedMap } from '@libp2p/utils/tracked-map'
@@ -6,15 +6,15 @@ import { anySignal } from 'any-signal'
6
6
  import { setMaxListeners } from 'main-event'
7
7
  import { CustomProgressEvent } from 'progress-events'
8
8
  import { raceSignal } from 'race-signal'
9
- import { createConnection } from './connection/index.js'
10
9
  import { PROTOCOL_NEGOTIATION_TIMEOUT, INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js'
10
+ import { createConnection } from './connection.js'
11
11
  import { ConnectionDeniedError, ConnectionInterceptedError, EncryptionFailedError, MuxerUnavailableError } from './errors.js'
12
- import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'
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'
12
+ import type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, ConnectionProtector, ConnectionEncrypter, SecuredConnection, ConnectionGater, Metrics, PeerId, PeerStore, StreamMuxerFactory, Upgrader as UpgraderInterface, UpgraderOptions, ConnectionLimits, SecureConnectionOptions, CounterGroup, ClearableSignal } from '@libp2p/interface'
14
13
  import type { ConnectionManager, Registrar } from '@libp2p/interface-internal'
15
14
  import type { TypedEventTarget } from 'main-event'
16
15
 
17
16
  interface CreateConnectionOptions {
17
+ id: string
18
18
  cryptoProtocol: string
19
19
  direction: 'inbound' | 'outbound'
20
20
  maConn: MultiaddrConnection
@@ -24,12 +24,6 @@ interface CreateConnectionOptions {
24
24
  limits?: ConnectionLimits
25
25
  }
26
26
 
27
- interface OnStreamOptions {
28
- connection: Connection
29
- stream: Stream
30
- protocol: string
31
- }
32
-
33
27
  export interface CryptoResult extends SecuredConnection<MultiaddrConnection> {
34
28
  protocol: string
35
29
  }
@@ -62,48 +56,6 @@ export interface UpgraderInit {
62
56
  outboundStreamProtocolNegotiationTimeout?: number
63
57
  }
64
58
 
65
- function findIncomingStreamLimit (protocol: string, registrar: Registrar): number | undefined {
66
- try {
67
- const { options } = registrar.getHandler(protocol)
68
-
69
- return options.maxInboundStreams
70
- } catch (err: any) {
71
- if (err.name !== 'UnhandledProtocolError') {
72
- throw err
73
- }
74
- }
75
-
76
- return DEFAULT_MAX_INBOUND_STREAMS
77
- }
78
-
79
- function findOutgoingStreamLimit (protocol: string, registrar: Registrar, options: NewStreamOptions = {}): number {
80
- try {
81
- const { options } = registrar.getHandler(protocol)
82
-
83
- if (options.maxOutboundStreams != null) {
84
- return options.maxOutboundStreams
85
- }
86
- } catch (err: any) {
87
- if (err.name !== 'UnhandledProtocolError') {
88
- throw err
89
- }
90
- }
91
-
92
- return options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS
93
- }
94
-
95
- function countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection): number {
96
- let streamCount = 0
97
-
98
- connection.streams.forEach(stream => {
99
- if (stream.direction === direction && stream.protocol === protocol) {
100
- streamCount++
101
- }
102
- })
103
-
104
- return streamCount
105
- }
106
-
107
59
  export interface UpgraderComponents {
108
60
  peerId: PeerId
109
61
  metrics?: Metrics
@@ -281,6 +233,9 @@ export class Upgrader implements UpgraderInterface {
281
233
  let muxerFactory: StreamMuxerFactory | undefined
282
234
  let cryptoProtocol
283
235
 
236
+ const id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`
237
+ maConn.log = maConn.log.newScope(`${direction}:${id}`)
238
+
284
239
  this.components.metrics?.trackMultiaddrConnection(maConn)
285
240
 
286
241
  maConn.log.trace('starting the %s connection upgrade', direction)
@@ -366,9 +321,8 @@ export class Upgrader implements UpgraderInterface {
366
321
 
367
322
  await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundUpgradedConnection' : 'denyOutboundUpgradedConnection', remotePeer, maConn)
368
323
 
369
- maConn.log('successfully upgraded %s connection', direction)
370
-
371
- return this._createConnection({
324
+ const conn = this._createConnection({
325
+ id,
372
326
  cryptoProtocol,
373
327
  direction,
374
328
  maConn,
@@ -377,6 +331,10 @@ export class Upgrader implements UpgraderInterface {
377
331
  remotePeer,
378
332
  limits: opts?.limits
379
333
  })
334
+
335
+ conn.log('successfully upgraded %s connection', direction)
336
+
337
+ return conn
380
338
  }
381
339
 
382
340
  /**
@@ -384,6 +342,7 @@ export class Upgrader implements UpgraderInterface {
384
342
  */
385
343
  _createConnection (opts: CreateConnectionOptions): Connection {
386
344
  const {
345
+ id,
387
346
  cryptoProtocol,
388
347
  direction,
389
348
  maConn,
@@ -393,190 +352,8 @@ export class Upgrader implements UpgraderInterface {
393
352
  limits
394
353
  } = opts
395
354
 
396
- let muxer: StreamMuxer | undefined
397
- let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise<Stream>) | undefined
398
355
  let connection: Connection // eslint-disable-line prefer-const
399
356
 
400
- if (muxerFactory != null) {
401
- // Create the muxer
402
- muxer = muxerFactory.createStreamMuxer({
403
- direction,
404
- // Run anytime a remote stream is created
405
- onIncomingStream: muxedStream => {
406
- if (connection == null) {
407
- return
408
- }
409
-
410
- const signal = AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout)
411
- setMaxListeners(Infinity, signal)
412
-
413
- void Promise.resolve()
414
- .then(async () => {
415
- const protocols = this.components.registrar.getProtocols()
416
-
417
- const { stream, protocol } = await mss.handle(muxedStream, protocols, {
418
- signal,
419
- log: muxedStream.log,
420
- yieldBytes: false
421
- })
422
-
423
- if (connection == null) {
424
- return
425
- }
426
-
427
- connection.log('incoming stream opened on %s', protocol)
428
-
429
- const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)
430
- const streamCount = countStreams(protocol, 'inbound', connection)
431
-
432
- if (streamCount === incomingLimit) {
433
- const err = new TooManyInboundProtocolStreamsError(`Too many inbound protocol streams for protocol "${protocol}" - limit ${incomingLimit}`)
434
- muxedStream.abort(err)
435
-
436
- throw err
437
- }
438
-
439
- // after the handshake the returned stream can have early data so override
440
- // the source/sink
441
- muxedStream.source = stream.source
442
- muxedStream.sink = stream.sink
443
- muxedStream.protocol = protocol
444
-
445
- // allow closing the write end of a not-yet-negotiated stream
446
- if (stream.closeWrite != null) {
447
- muxedStream.closeWrite = stream.closeWrite
448
- }
449
-
450
- // allow closing the read end of a not-yet-negotiated stream
451
- if (stream.closeRead != null) {
452
- muxedStream.closeRead = stream.closeRead
453
- }
454
-
455
- // make sure we don't try to negotiate a stream we are closing
456
- if (stream.close != null) {
457
- muxedStream.close = stream.close
458
- }
459
-
460
- // If a protocol stream has been successfully negotiated and is to be passed to the application,
461
- // the peer store should ensure that the peer is registered with that protocol
462
- await this.components.peerStore.merge(remotePeer, {
463
- protocols: [protocol]
464
- }, {
465
- signal
466
- })
467
-
468
- this.components.metrics?.trackProtocolStream(muxedStream, connection)
469
-
470
- this._onStream({ connection, stream: muxedStream, protocol })
471
- })
472
- .catch(async err => {
473
- connection.log.error('error handling incoming stream id %s - %e', muxedStream.id, err)
474
-
475
- if (muxedStream.timeline.close == null) {
476
- await muxedStream.close({
477
- signal
478
- })
479
- .catch(err => muxedStream.abort(err))
480
- }
481
- })
482
- }
483
- })
484
-
485
- newStream = async (protocols: string[], options: NewStreamOptions = {}): Promise<Stream> => {
486
- if (muxer == null) {
487
- throw new MuxerUnavailableError('Connection is not multiplexed')
488
- }
489
-
490
- connection.log.trace('starting new stream for protocols %s', protocols)
491
- const muxedStream = await muxer.newStream()
492
- connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols)
493
-
494
- try {
495
- if (options.signal == null) {
496
- muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)
497
-
498
- const signal = AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout)
499
- setMaxListeners(Infinity, signal)
500
-
501
- options = {
502
- ...options,
503
- signal
504
- }
505
- }
506
-
507
- muxedStream.log.trace('selecting protocol from protocols %s', protocols)
508
-
509
- const {
510
- stream,
511
- protocol
512
- } = await mss.select(muxedStream, protocols, {
513
- ...options,
514
- log: muxedStream.log,
515
- yieldBytes: true
516
- })
517
-
518
- muxedStream.log.trace('selected protocol %s', protocol)
519
-
520
- const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options)
521
- const streamCount = countStreams(protocol, 'outbound', connection)
522
-
523
- if (streamCount >= outgoingLimit) {
524
- const err = new TooManyOutboundProtocolStreamsError(`Too many outbound protocol streams for protocol "${protocol}" - ${streamCount}/${outgoingLimit}`)
525
- muxedStream.abort(err)
526
-
527
- throw err
528
- }
529
-
530
- // If a protocol stream has been successfully negotiated and is to be passed to the application,
531
- // the peer store should ensure that the peer is registered with that protocol
532
- await this.components.peerStore.merge(remotePeer, {
533
- protocols: [protocol]
534
- })
535
-
536
- // after the handshake the returned stream can have early data so override
537
- // the source/sink
538
- muxedStream.source = stream.source
539
- muxedStream.sink = stream.sink
540
- muxedStream.protocol = protocol
541
-
542
- // allow closing the write end of a not-yet-negotiated stream
543
- if (stream.closeWrite != null) {
544
- muxedStream.closeWrite = stream.closeWrite
545
- }
546
-
547
- // allow closing the read end of a not-yet-negotiated stream
548
- if (stream.closeRead != null) {
549
- muxedStream.closeRead = stream.closeRead
550
- }
551
-
552
- // make sure we don't try to negotiate a stream we are closing
553
- if (stream.close != null) {
554
- muxedStream.close = stream.close
555
- }
556
-
557
- this.components.metrics?.trackProtocolStream(muxedStream, connection)
558
-
559
- return muxedStream
560
- } catch (err: any) {
561
- connection.log.error('could not create new outbound stream on connection %s %a for protocols %s - %e', direction === 'inbound' ? 'from' : 'to', opts.maConn.remoteAddr, protocols, err)
562
-
563
- if (muxedStream.timeline.close == null) {
564
- muxedStream.abort(err)
565
- }
566
-
567
- throw err
568
- }
569
- }
570
-
571
- // Pipe all data through the muxer
572
- void Promise.all([
573
- muxer.sink(upgradedConn.source),
574
- upgradedConn.sink(muxer.source)
575
- ]).catch(err => {
576
- connection.log.error('error piping data through muxer - %e', err)
577
- })
578
- }
579
-
580
357
  const _timeline = maConn.timeline
581
358
  maConn.timeline = new Proxy(_timeline, {
582
359
  set: (...args) => {
@@ -604,64 +381,26 @@ export class Upgrader implements UpgraderInterface {
604
381
  })
605
382
  maConn.timeline.upgraded = Date.now()
606
383
 
607
- const errConnectionNotMultiplexed = (): any => {
608
- throw new MuxerUnavailableError('Connection is not multiplexed')
609
- }
610
-
611
384
  // Create the connection
612
- connection = createConnection({
613
- remoteAddr: maConn.remoteAddr,
385
+ connection = createConnection(this.components, {
386
+ id,
387
+ maConn: upgradedConn,
614
388
  remotePeer,
615
- status: 'open',
616
389
  direction,
617
- timeline: maConn.timeline,
618
- multiplexer: muxer?.protocol,
390
+ muxerFactory,
619
391
  encryption: cryptoProtocol,
620
392
  limits,
621
- logger: this.components.logger,
622
- newStream: newStream ?? errConnectionNotMultiplexed,
623
- getStreams: () => {
624
- return muxer?.streams ?? []
625
- },
626
- close: async (options?: AbortOptions) => {
627
- // ensure remaining streams are closed gracefully
628
- await muxer?.close(options)
629
-
630
- // close the underlying transport
631
- await maConn.close(options)
632
- },
633
- abort: (err) => {
634
- maConn.abort(err)
635
-
636
- // ensure remaining streams are aborted
637
- muxer?.abort(err)
638
- }
393
+ outboundStreamProtocolNegotiationTimeout: this.outboundStreamProtocolNegotiationTimeout,
394
+ inboundStreamProtocolNegotiationTimeout: this.inboundStreamProtocolNegotiationTimeout
639
395
  })
640
396
 
641
397
  this.events.safeDispatchEvent('connection:open', {
642
398
  detail: connection
643
399
  })
644
400
 
645
- // @ts-expect-error nah
646
- connection.__maConnTimeline = _timeline
647
-
648
401
  return connection
649
402
  }
650
403
 
651
- /**
652
- * Routes incoming streams to the correct handler
653
- */
654
- _onStream (opts: OnStreamOptions): void {
655
- const { connection, stream, protocol } = opts
656
- const { handler, options } = this.components.registrar.getHandler(protocol)
657
-
658
- if (connection.limits != null && options.runOnLimitedConnection !== true) {
659
- throw new LimitedConnectionError('Cannot open protocol stream on limited connection')
660
- }
661
-
662
- handler({ connection, stream })
663
- }
664
-
665
404
  /**
666
405
  * Attempts to encrypt the incoming `connection` with the provided `cryptos`
667
406
  */
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.8.14'
1
+ export const version = '2.9.0-ce6b542a8'
2
2
  export const name = 'js-libp2p'
@@ -1,84 +0,0 @@
1
- import { connectionSymbol } from '@libp2p/interface';
2
- import type { AbortOptions, Logger, ComponentLogger, Direction, Connection, Stream, ConnectionTimeline, ConnectionStatus, NewStreamOptions, PeerId, ConnectionLimits } from '@libp2p/interface';
3
- import type { Multiaddr } from '@multiformats/multiaddr';
4
- interface ConnectionInit {
5
- remoteAddr: Multiaddr;
6
- remotePeer: PeerId;
7
- newStream(protocols: string[], options?: AbortOptions): Promise<Stream>;
8
- close(options?: AbortOptions): Promise<void>;
9
- abort(err: Error): void;
10
- getStreams(): Stream[];
11
- status: ConnectionStatus;
12
- direction: Direction;
13
- timeline: ConnectionTimeline;
14
- multiplexer?: string;
15
- encryption?: string;
16
- limits?: ConnectionLimits;
17
- logger: ComponentLogger;
18
- }
19
- /**
20
- * An implementation of the js-libp2p connection.
21
- * Any libp2p transport should use an upgrader to return this connection.
22
- */
23
- export declare class ConnectionImpl implements Connection {
24
- /**
25
- * Connection identifier.
26
- */
27
- readonly id: string;
28
- /**
29
- * Observed multiaddr of the remote peer
30
- */
31
- readonly remoteAddr: Multiaddr;
32
- /**
33
- * Remote peer id
34
- */
35
- readonly remotePeer: PeerId;
36
- direction: Direction;
37
- timeline: ConnectionTimeline;
38
- multiplexer?: string;
39
- encryption?: string;
40
- status: ConnectionStatus;
41
- limits?: ConnectionLimits;
42
- readonly log: Logger;
43
- /**
44
- * User provided tags
45
- *
46
- */
47
- tags: string[];
48
- /**
49
- * Reference to the new stream function of the multiplexer
50
- */
51
- private readonly _newStream;
52
- /**
53
- * Reference to the close function of the raw connection
54
- */
55
- private readonly _close;
56
- private readonly _abort;
57
- /**
58
- * Reference to the getStreams function of the muxer
59
- */
60
- private readonly _getStreams;
61
- /**
62
- * An implementation of the js-libp2p connection.
63
- * Any libp2p transport should use an upgrader to return this connection.
64
- */
65
- constructor(init: ConnectionInit);
66
- readonly [Symbol.toStringTag] = "Connection";
67
- readonly [connectionSymbol] = true;
68
- /**
69
- * Get all the streams of the muxer
70
- */
71
- get streams(): Stream[];
72
- /**
73
- * Create a new stream from this connection
74
- */
75
- newStream(protocols: string | string[], options?: NewStreamOptions): Promise<Stream>;
76
- /**
77
- * Close the connection
78
- */
79
- close(options?: AbortOptions): Promise<void>;
80
- abort(err: Error): void;
81
- }
82
- export declare function createConnection(init: ConnectionInit): Connection;
83
- export {};
84
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/connection/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAyE,MAAM,mBAAmB,CAAA;AAE3H,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,eAAe,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAC/L,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM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O,CAAC,QAAQ,CAAC,MAAM,CAAsB;IAE7C;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAgB;IAE5C;;;OAGG;gBACU,IAAI,EAAE,cAAc;IAyBjC,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,gBAAe;IAE5C,QAAQ,CAAC,CAAC,gBAAgB,CAAC,QAAO;IAElC;;OAEG;IACH,IAAI,OAAO,IAAK,MAAM,EAAE,CAEvB;IAED;;OAEG;IACG,SAAS,CAAE,SAAS,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAwB3F;;OAEG;IACG,KAAK,CAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAmCvD,KAAK,CAAE,GAAG,EAAE,KAAK,GAAG,IAAI;CAezB;AAED,wBAAgB,gBAAgB,CAAE,IAAI,EAAE,cAAc,GAAG,UAAU,CAElE"}
@@ -1,144 +0,0 @@
1
- import { connectionSymbol, LimitedConnectionError, ConnectionClosedError, ConnectionClosingError } from '@libp2p/interface';
2
- import { setMaxListeners } from 'main-event';
3
- const CLOSE_TIMEOUT = 500;
4
- /**
5
- * An implementation of the js-libp2p connection.
6
- * Any libp2p transport should use an upgrader to return this connection.
7
- */
8
- export class ConnectionImpl {
9
- /**
10
- * Connection identifier.
11
- */
12
- id;
13
- /**
14
- * Observed multiaddr of the remote peer
15
- */
16
- remoteAddr;
17
- /**
18
- * Remote peer id
19
- */
20
- remotePeer;
21
- direction;
22
- timeline;
23
- multiplexer;
24
- encryption;
25
- status;
26
- limits;
27
- log;
28
- /**
29
- * User provided tags
30
- *
31
- */
32
- tags;
33
- /**
34
- * Reference to the new stream function of the multiplexer
35
- */
36
- _newStream;
37
- /**
38
- * Reference to the close function of the raw connection
39
- */
40
- _close;
41
- _abort;
42
- /**
43
- * Reference to the getStreams function of the muxer
44
- */
45
- _getStreams;
46
- /**
47
- * An implementation of the js-libp2p connection.
48
- * Any libp2p transport should use an upgrader to return this connection.
49
- */
50
- constructor(init) {
51
- const { remoteAddr, remotePeer, newStream, close, abort, getStreams } = init;
52
- this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`;
53
- this.remoteAddr = remoteAddr;
54
- this.remotePeer = remotePeer;
55
- this.direction = init.direction;
56
- this.status = 'open';
57
- this.timeline = init.timeline;
58
- this.multiplexer = init.multiplexer;
59
- this.encryption = init.encryption;
60
- this.limits = init.limits;
61
- this.log = init.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`);
62
- if (this.remoteAddr.getPeerId() == null) {
63
- this.remoteAddr = this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`);
64
- }
65
- this._newStream = newStream;
66
- this._close = close;
67
- this._abort = abort;
68
- this._getStreams = getStreams;
69
- this.tags = [];
70
- }
71
- [Symbol.toStringTag] = 'Connection';
72
- [connectionSymbol] = true;
73
- /**
74
- * Get all the streams of the muxer
75
- */
76
- get streams() {
77
- return this._getStreams();
78
- }
79
- /**
80
- * Create a new stream from this connection
81
- */
82
- async newStream(protocols, options) {
83
- if (this.status === 'closing') {
84
- throw new ConnectionClosingError('the connection is being closed');
85
- }
86
- if (this.status === 'closed') {
87
- throw new ConnectionClosedError('the connection is closed');
88
- }
89
- if (!Array.isArray(protocols)) {
90
- protocols = [protocols];
91
- }
92
- if (this.limits != null && options?.runOnLimitedConnection !== true) {
93
- throw new LimitedConnectionError('Cannot open protocol stream on limited connection');
94
- }
95
- const stream = await this._newStream(protocols, options);
96
- stream.direction = 'outbound';
97
- return stream;
98
- }
99
- /**
100
- * Close the connection
101
- */
102
- async close(options = {}) {
103
- if (this.status === 'closed' || this.status === 'closing') {
104
- return;
105
- }
106
- this.log('closing connection to %a', this.remoteAddr);
107
- this.status = 'closing';
108
- if (options.signal == null) {
109
- const signal = AbortSignal.timeout(CLOSE_TIMEOUT);
110
- setMaxListeners(Infinity, signal);
111
- options = {
112
- ...options,
113
- signal
114
- };
115
- }
116
- try {
117
- this.log.trace('closing underlying transport');
118
- // close raw connection
119
- await this._close(options);
120
- this.log.trace('updating timeline with close time');
121
- this.status = 'closed';
122
- this.timeline.close = Date.now();
123
- }
124
- catch (err) {
125
- this.log.error('error encountered during graceful close of connection to %a', this.remoteAddr, err);
126
- this.abort(err);
127
- }
128
- }
129
- abort(err) {
130
- if (this.status === 'closed') {
131
- return;
132
- }
133
- this.log.error('aborting connection to %a due to error', this.remoteAddr, err);
134
- this.status = 'closing';
135
- // Abort raw connection
136
- this._abort(err);
137
- this.status = 'closed';
138
- this.timeline.close = Date.now();
139
- }
140
- }
141
- export function createConnection(init) {
142
- return new ConnectionImpl(init);
143
- }
144
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/connection/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAC3H,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAI5C,MAAM,aAAa,GAAG,GAAG,CAAA;AAkBzB;;;GAGG;AACH,MAAM,OAAO,cAAc;IACzB;;OAEG;IACa,EAAE,CAAQ;IAE1B;;OAEG;IACa,UAAU,CAAW;IAErC;;OAEG;IACa,UAAU,CAAQ;IAE3B,SAAS,CAAW;IACpB,QAAQ,CAAoB;IAC5B,WAAW,CAAS;IACpB,UAAU,CAAS;IACnB,MAAM,CAAkB;IACxB,MAAM,CAAmB;IAChB,GAAG,CAAQ;IAE3B;;;OAGG;IACI,IAAI,CAAU;IAErB;;OAEG;IACc,UAAU,CAAsE;IAEjG;;OAEG;IACc,MAAM,CAA2C;IAEjD,MAAM,CAAsB;IAE7C;;OAEG;IACc,WAAW,CAAgB;IAE5C;;;OAGG;IACH,YAAa,IAAoB;QAC/B,MAAM,EAAE,UAAU,EAAE,UAAU,EAA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B;IACpD,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,CAAA;AACjC,CAAC"}
@@ -1,22 +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
- "dnsaddrResolver": "https://libp2p.github.io/js-libp2p/variables/libp2p.index.dnsaddrResolver.html",
14
- "createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
15
- ".:createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
16
- "userAgent": "https://libp2p.github.io/js-libp2p/functions/libp2p.user-agent.userAgent.html",
17
- "./user-agent:userAgent": "https://libp2p.github.io/js-libp2p/functions/libp2p.user-agent.userAgent.html",
18
- "name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
19
- "./version:name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
20
- "version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html",
21
- "./version:version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html"
22
- }