@@ -47,8 +47,8 @@ module.exports = class Connection extends EventEmitter {
4747 options = this . options ;
4848
4949 this . auto_reconnect = options . auto_reconnect || false ;
50- this . auto_reconnect_wait = options . auto_reconnect_wait || 4000 ;
5150 this . auto_reconnect_max_retries = options . auto_reconnect_max_retries || 3 ;
51+ this . auto_reconnect_max_wait = options . auto_reconnect_max_wait || 300000 ;
5252
5353 if ( this . transport ) {
5454 this . clearTimers ( ) ;
@@ -131,27 +131,32 @@ module.exports = class Connection extends EventEmitter {
131131 }
132132
133133 if ( should_reconnect ) {
134+ const reconnect_wait = that . calculateExponentialBackoff ( ) ;
135+
134136 that . reconnect_attempts ++ ;
135137 that . emit ( 'reconnecting' , {
136138 attempt : that . reconnect_attempts ,
137139 max_retries : that . auto_reconnect_max_retries ,
138- wait : that . auto_reconnect_wait
140+ wait : reconnect_wait
139141 } ) ;
142+
143+ that . debugOut ( 'Scheduling reconnect. Attempt: ' + that . reconnect_attempts + '/' + that . auto_reconnect_max_retries + ' Wait: ' + reconnect_wait + 'ms' ) ;
144+ that . setTimeout ( ( ) => that . connect ( ) , reconnect_wait ) ;
140145 } else {
141146 that . transport . removeAllListeners ( ) ;
142147 that . emit ( 'close' , ! ! err ) ;
143148 that . reconnect_attempts = 0 ;
144149 }
145-
146- if ( should_reconnect ) {
147- that . debugOut ( 'Scheduling reconnect' ) ;
148- that . setTimeout ( function ( ) {
149- that . connect ( ) ;
150- } , that . auto_reconnect_wait ) ;
151- }
152150 }
153151 }
154152
153+ calculateExponentialBackoff ( ) {
154+ const jitter = 1000 + Math . floor ( Math . random ( ) * 5000 ) ;
155+ const attempts = Math . min ( this . reconnect_attempts , 30 ) ;
156+ const time = 1000 * Math . pow ( 2 , attempts ) ;
157+ return Math . min ( time , this . auto_reconnect_max_wait ) + jitter ;
158+ }
159+
155160 addReadBuffer ( line ) {
156161 this . read_buffer . push ( line ) ;
157162 this . processReadBuffer ( ) ;
0 commit comments