@@ -33,12 +33,21 @@ const reportJsonError = (
33
33
) ;
34
34
} ;
35
35
36
+ function reportEventClosed ( eventName : string , logger ?: LDLogger ) {
37
+ logger ?. debug ( `Received ${ eventName } event after processor was closed. Skipping processing.` ) ;
38
+ }
39
+
40
+ function reportPingClosed ( logger ?: LDLogger ) {
41
+ logger ?. debug ( 'Ping completed after processor was closed. Skipping processing.' ) ;
42
+ }
43
+
36
44
class StreamingProcessor implements subsystem . LDStreamProcessor {
37
45
private readonly _headers : { [ key : string ] : string | string [ ] } ;
38
46
private readonly _streamUri : string ;
39
47
40
48
private _eventSource ?: EventSource ;
41
49
private _connectionAttemptStartTime ?: number ;
50
+ private _stopped = false ;
42
51
43
52
constructor (
44
53
private readonly _plainContextString : string ,
@@ -157,6 +166,13 @@ class StreamingProcessor implements subsystem.LDStreamProcessor {
157
166
158
167
this . _listeners . forEach ( ( { deserializeData, processJson } , eventName ) => {
159
168
eventSource . addEventListener ( eventName , ( event ) => {
169
+ // If an event comes in after the processor has been stopped, we skip processing it.
170
+ // This event could be for a context which is no longer active.
171
+ if ( this . _stopped ) {
172
+ reportEventClosed ( eventName , this . _logger ) ;
173
+ return ;
174
+ }
175
+
160
176
this . _logger ?. debug ( `Received ${ eventName } event` ) ;
161
177
162
178
if ( event ?. data ) {
@@ -186,6 +202,12 @@ class StreamingProcessor implements subsystem.LDStreamProcessor {
186
202
try {
187
203
const res = await this . _pollingRequestor . requestPayload ( ) ;
188
204
try {
205
+ // If the ping completes after the processor has been stopped, then we discard it.
206
+ // This event could be for a context which is no longer active.
207
+ if ( this . _stopped ) {
208
+ reportPingClosed ( this . _logger ) ;
209
+ return ;
210
+ }
189
211
const payload = JSON . parse ( res ) ;
190
212
try {
191
213
// forward the payload on to the PUT listener
@@ -204,6 +226,12 @@ class StreamingProcessor implements subsystem.LDStreamProcessor {
204
226
) ;
205
227
}
206
228
} catch ( err ) {
229
+ if ( this . _stopped ) {
230
+ // If the ping errors after the processor has been stopped, then we discard it.
231
+ // The original caller would consider this connection no longer active.
232
+ reportPingClosed ( this . _logger ) ;
233
+ return ;
234
+ }
207
235
const requestError = err as LDRequestError ;
208
236
this . _errorHandler ?.(
209
237
new LDPollingError (
@@ -219,6 +247,7 @@ class StreamingProcessor implements subsystem.LDStreamProcessor {
219
247
stop ( ) {
220
248
this . _eventSource ?. close ( ) ;
221
249
this . _eventSource = undefined ;
250
+ this . _stopped = true ;
222
251
}
223
252
224
253
close ( ) {
0 commit comments