@@ -84,7 +84,7 @@ class RPCClient extends EventEmitter {
84
84
}
85
85
86
86
reconfigure ( options ) {
87
- const newOpts = Object . assign ( { } , this . _options , options ) ;
87
+ const newOpts = Object . assign ( this . _options , options ) ;
88
88
89
89
if ( ! newOpts . identity ) {
90
90
throw Error ( `'identity' is required` ) ;
@@ -119,7 +119,9 @@ class RPCClient extends EventEmitter {
119
119
this . _callQueue . setConcurrency ( newOpts . callConcurrency ) ;
120
120
this . _backoffStrategy = new ExponentialStrategy ( newOpts . backoff ) ;
121
121
122
- this . _options = newOpts ;
122
+ if ( 'pingIntervalMs' in options ) {
123
+ this . _keepAlive ( ) ;
124
+ }
123
125
}
124
126
125
127
/**
@@ -348,8 +350,7 @@ class RPCClient extends EventEmitter {
348
350
this . emit ( 'ping' , { rtt} ) ;
349
351
} ) ;
350
352
351
- this . _keepAliveAbortController = new AbortController ( ) ;
352
- this . _keepAlive ( this . _keepAliveAbortController . signal ) ;
353
+ this . _keepAlive ( ) ;
353
354
354
355
process . nextTick ( ( ) => {
355
356
if ( leadMsgBuffer ) {
@@ -494,26 +495,42 @@ class RPCClient extends EventEmitter {
494
495
return this . _connectPromise ;
495
496
}
496
497
497
- async _keepAlive ( signal ) {
498
+ async _keepAlive ( ) {
499
+ // abort any previously running keepAlive
500
+ this . _keepAliveAbortController ?. abort ( ) ;
501
+
498
502
try {
503
+ if ( this . _state !== OPEN ) {
504
+ // don't start pinging if connection not open
505
+ return ;
506
+ }
507
+
499
508
if ( ! this . _options . pingIntervalMs || this . _options . pingIntervalMs <= 0 || this . _options . pingIntervalMs > 2147483647 ) {
500
- // don't ping
509
+ // don't ping for unusuable intervals
501
510
return ;
502
511
}
512
+
513
+ // setup new abort controller
514
+ this . _keepAliveAbortController = new AbortController ( ) ;
503
515
504
- for await ( const _ of setInterval ( this . _options . pingIntervalMs , 1 , { signal} ) ) {
516
+ while ( true ) {
517
+ await setTimeout ( this . _options . pingIntervalMs , undefined , { signal : this . _keepAliveAbortController . signal } ) ;
518
+
505
519
if ( this . _state !== OPEN ) {
506
- throw Error ( "Cannot ping while connection not open" ) ;
520
+ // keepalive no longer required
521
+ break ;
507
522
}
523
+
508
524
if ( this . _pendingPingResponse ) {
509
525
// we didn't get a response to our last ping
510
- this . _ws . terminate ( ) ;
511
- return ;
526
+ throw Error ( "Ping timeout" ) ;
512
527
}
528
+
513
529
this . _lastPingTime = Date . now ( ) ;
514
530
this . _pendingPingResponse = true ;
515
531
this . _ws . ping ( ) ;
516
532
}
533
+
517
534
} catch ( err ) {
518
535
if ( err . name !== 'AbortError' ) {
519
536
// throws on ws.ping() error
0 commit comments