@@ -45,6 +45,7 @@ export class StreamProcessor {
4545 private readyState : number ;
4646 private log : ConsoleLog ;
4747 private retryAttempt = 0 ;
48+ private retryTimeout : NodeJS . Timeout | undefined ;
4849
4950 constructor (
5051 api : ClientApi ,
@@ -111,16 +112,19 @@ export class StreamProcessor {
111112 } ;
112113
113114 const onFailed = ( msg : string ) => {
114- if ( this . readyState !== StreamProcessor . CLOSED ) {
115+ if ( this . readyState !== StreamProcessor . CLOSED && ! this . retryTimeout ) {
115116 this . retryAttempt += 1 ;
116117
117118 const delayMs = this . getRandomRetryDelayMs ( ) ;
118119 warnStreamDisconnectedWithRetry ( msg , delayMs , this . log ) ;
119120 this . readyState = StreamProcessor . RETRYING ;
120121 this . eventBus . emit ( StreamEvent . RETRYING ) ;
121122
122- setTimeout ( ( ) => {
123- this . connect ( url , options , onConnected , onFailed ) ;
123+ this . retryTimeout = setTimeout ( ( ) => {
124+ this . retryTimeout = undefined ;
125+ if ( this . readyState !== StreamProcessor . CLOSED ) {
126+ this . connect ( url , options , onConnected , onFailed ) ;
127+ }
124128 } , delayMs ) ;
125129 }
126130 } ;
@@ -135,6 +139,14 @@ export class StreamProcessor {
135139 return Math . min ( delayMs , 60000 ) ;
136140 }
137141
142+ private cleanupConnection ( ) : void {
143+ if ( this . request ) {
144+ this . request . removeAllListeners ( ) ;
145+ this . request . destroy ( ) ;
146+ this . request = undefined ;
147+ }
148+ }
149+
138150 private connect (
139151 url : string ,
140152 options : RequestOptions ,
@@ -146,6 +158,8 @@ export class StreamProcessor {
146158 return ;
147159 }
148160
161+ this . cleanupConnection ( ) ;
162+
149163 const isSecure = url . startsWith ( 'https:' ) ;
150164 this . log . debug ( 'SSE HTTP start request' , url ) ;
151165
@@ -174,8 +188,8 @@ export class StreamProcessor {
174188 . on ( 'timeout' , ( ) => {
175189 onFailed (
176190 'SSE request timed out after ' +
177- StreamProcessor . SSE_TIMEOUT_MS +
178- 'ms' ,
191+ StreamProcessor . SSE_TIMEOUT_MS +
192+ 'ms' ,
179193 ) ;
180194 } )
181195 . setTimeout ( StreamProcessor . SSE_TIMEOUT_MS ) ;
@@ -256,6 +270,8 @@ export class StreamProcessor {
256270 return ;
257271 }
258272
273+ clearTimeout ( this . retryTimeout ) ;
274+
259275 this . readyState = StreamProcessor . CLOSED ;
260276 this . log . info ( 'Closing StreamProcessor' ) ;
261277
0 commit comments