11import { randomBytes } from '@libp2p/crypto'
2- import { serviceCapabilities } from '@libp2p/interface'
2+ import { serviceCapabilities , setMaxListeners } from '@libp2p/interface'
33import { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout'
44import { byteStream } from 'it-byte-stream'
55import type { ComponentLogger , Logger , Metrics , Startable } from '@libp2p/interface'
@@ -11,6 +11,7 @@ const PROTOCOL_VERSION = '1.0.0'
1111const PROTOCOL_NAME = 'ping'
1212const PROTOCOL_PREFIX = 'ipfs'
1313const PING_LENGTH = 32
14+ const DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE = true
1415
1516export interface ConnectionMonitorInit {
1617 /**
@@ -65,14 +66,15 @@ export class ConnectionMonitor implements Startable {
6566 private readonly pingIntervalMs : number
6667 private abortController ?: AbortController
6768 private readonly timeout : AdaptiveTimeout
69+ private readonly abortConnectionOnPingFailure : boolean
6870
6971 constructor ( components : ConnectionMonitorComponents , init : ConnectionMonitorInit = { } ) {
7072 this . components = components
7173 this . protocol = `/${ init . protocolPrefix ?? PROTOCOL_PREFIX } /${ PROTOCOL_NAME } /${ PROTOCOL_VERSION } `
7274
7375 this . log = components . logger . forComponent ( 'libp2p:connection-monitor' )
7476 this . pingIntervalMs = init . pingInterval ?? DEFAULT_PING_INTERVAL_MS
75-
77+ this . abortConnectionOnPingFailure = init . abortConnectionOnPingFailure ?? DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE
7678 this . timeout = new AdaptiveTimeout ( {
7779 ...( init . pingTimeout ?? { } ) ,
7880 metrics : components . metrics ,
@@ -88,6 +90,7 @@ export class ConnectionMonitor implements Startable {
8890
8991 start ( ) : void {
9092 this . abortController = new AbortController ( )
93+ setMaxListeners ( Infinity , this . abortController . signal )
9194
9295 this . heartbeatInterval = setInterval ( ( ) => {
9396 this . components . connectionManager . getConnections ( ) . forEach ( conn => {
@@ -131,8 +134,14 @@ export class ConnectionMonitor implements Startable {
131134 }
132135 } )
133136 . catch ( err => {
134- this . log . error ( 'error during heartbeat, aborting connection' , err )
135- conn . abort ( err )
137+ this . log . error ( 'error during heartbeat' , err )
138+
139+ if ( this . abortConnectionOnPingFailure ) {
140+ this . log . error ( 'aborting connection due to ping failure' )
141+ conn . abort ( err )
142+ } else {
143+ this . log ( 'connection ping failed, but not aborting due to abortConnectionOnPingFailure flag' )
144+ }
136145 } )
137146 } )
138147 } , this . pingIntervalMs )
0 commit comments