@@ -194,38 +194,9 @@ export class Connection extends EventEmitter {
194
194
/* ignore errors, listen to `close` instead */
195
195
} ) ;
196
196
197
- stream . on ( 'close' , ( ) => {
198
- if ( this . closed ) {
199
- return ;
200
- }
201
-
202
- this . closed = true ;
203
- this [ kQueue ] . forEach ( op =>
204
- op . cb ( new MongoNetworkError ( `connection ${ this . id } to ${ this . address } closed` ) )
205
- ) ;
206
- this [ kQueue ] . clear ( ) ;
207
-
208
- this . emit ( 'close' ) ;
209
- } ) ;
210
-
211
- stream . on ( 'timeout' , ( ) => {
212
- if ( this . closed ) {
213
- return ;
214
- }
215
-
216
- stream . destroy ( ) ;
217
- this . closed = true ;
218
- this [ kQueue ] . forEach ( op =>
219
- op . cb (
220
- new MongoNetworkTimeoutError ( `connection ${ this . id } to ${ this . address } timed out` , {
221
- beforeHandshake : this [ kIsMaster ] == null
222
- } )
223
- )
224
- ) ;
225
-
226
- this [ kQueue ] . clear ( ) ;
227
- this . emit ( 'close' ) ;
228
- } ) ;
197
+ this [ kMessageStream ] . on ( 'error' , error => this . handleIssue ( { destroy : error } ) ) ;
198
+ stream . on ( 'close' , ( ) => this . handleIssue ( { isClose : true } ) ) ;
199
+ stream . on ( 'timeout' , ( ) => this . handleIssue ( { isTimeout : true , destroy : true } ) ) ;
229
200
230
201
// hook the message stream up to the passed in stream
231
202
stream . pipe ( this [ kMessageStream ] ) ;
@@ -269,6 +240,35 @@ export class Connection extends EventEmitter {
269
240
this [ kLastUseTime ] = now ( ) ;
270
241
}
271
242
243
+ handleIssue ( issue : { isTimeout ?: boolean ; isClose ?: boolean ; destroy ?: boolean | Error } ) : void {
244
+ if ( this . closed ) {
245
+ return ;
246
+ }
247
+
248
+ if ( issue . destroy ) {
249
+ this [ kStream ] . destroy ( typeof issue . destroy === 'boolean' ? undefined : issue . destroy ) ;
250
+ }
251
+
252
+ this . closed = true ;
253
+
254
+ for ( const [ , op ] of this [ kQueue ] ) {
255
+ if ( issue . isTimeout ) {
256
+ op . cb (
257
+ new MongoNetworkTimeoutError ( `connection ${ this . id } to ${ this . address } timed out` , {
258
+ beforeHandshake : ! ! this [ kIsMaster ]
259
+ } )
260
+ ) ;
261
+ } else if ( issue . isClose ) {
262
+ op . cb ( new MongoNetworkError ( `connection ${ this . id } to ${ this . address } closed` ) ) ;
263
+ } else {
264
+ op . cb ( typeof issue . destroy === 'boolean' ? undefined : issue . destroy ) ;
265
+ }
266
+ }
267
+
268
+ this [ kQueue ] . clear ( ) ;
269
+ this . emit ( 'close' ) ;
270
+ }
271
+
272
272
destroy ( ) : void ;
273
273
destroy ( callback : Callback ) : void ;
274
274
destroy ( options : DestroyOptions ) : void ;
0 commit comments