1
1
import { randomBytes } from '@libp2p/crypto'
2
- import { serviceCapabilities } from '@libp2p/interface'
2
+ import { serviceCapabilities , setMaxListeners } from '@libp2p/interface'
3
3
import { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout'
4
4
import { byteStream } from 'it-byte-stream'
5
5
import type { ComponentLogger , Logger , Metrics , Startable } from '@libp2p/interface'
@@ -11,6 +11,7 @@ const PROTOCOL_VERSION = '1.0.0'
11
11
const PROTOCOL_NAME = 'ping'
12
12
const PROTOCOL_PREFIX = 'ipfs'
13
13
const PING_LENGTH = 32
14
+ const DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE = true
14
15
15
16
export interface ConnectionMonitorInit {
16
17
/**
@@ -65,14 +66,15 @@ export class ConnectionMonitor implements Startable {
65
66
private readonly pingIntervalMs : number
66
67
private abortController ?: AbortController
67
68
private readonly timeout : AdaptiveTimeout
69
+ private readonly abortConnectionOnPingFailure : boolean
68
70
69
71
constructor ( components : ConnectionMonitorComponents , init : ConnectionMonitorInit = { } ) {
70
72
this . components = components
71
73
this . protocol = `/${ init . protocolPrefix ?? PROTOCOL_PREFIX } /${ PROTOCOL_NAME } /${ PROTOCOL_VERSION } `
72
74
73
75
this . log = components . logger . forComponent ( 'libp2p:connection-monitor' )
74
76
this . pingIntervalMs = init . pingInterval ?? DEFAULT_PING_INTERVAL_MS
75
-
77
+ this . abortConnectionOnPingFailure = init . abortConnectionOnPingFailure ?? DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE
76
78
this . timeout = new AdaptiveTimeout ( {
77
79
...( init . pingTimeout ?? { } ) ,
78
80
metrics : components . metrics ,
@@ -88,6 +90,7 @@ export class ConnectionMonitor implements Startable {
88
90
89
91
start ( ) : void {
90
92
this . abortController = new AbortController ( )
93
+ setMaxListeners ( Infinity , this . abortController . signal )
91
94
92
95
this . heartbeatInterval = setInterval ( ( ) => {
93
96
this . components . connectionManager . getConnections ( ) . forEach ( conn => {
@@ -131,8 +134,14 @@ export class ConnectionMonitor implements Startable {
131
134
}
132
135
} )
133
136
. 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
+ }
136
145
} )
137
146
} )
138
147
} , this . pingIntervalMs )
0 commit comments