@@ -338,17 +338,7 @@ export class StateMachine {
338338 const message = request . message ;
339339 const buffer = new BufferPool ( ) ;
340340
341- const netSocket : net . Socket = new net . Socket ( ) ;
342- let socket : tls . TLSSocket ;
343-
344- function destroySockets ( ) {
345- for ( const sock of [ socket , netSocket ] ) {
346- if ( sock ) {
347- sock . removeAllListeners ( ) ;
348- sock . destroy ( ) ;
349- }
350- }
351- }
341+ const socket = new net . Socket ( ) ;
352342
353343 function onerror ( cause : Error ) {
354344 return new MongoCryptError ( 'KMS request failed' , { cause } ) ;
@@ -380,7 +370,8 @@ export class StateMachine {
380370 reject : rejectOnNetSocketError ,
381371 resolve : resolveOnNetSocketConnect
382372 } = promiseWithResolvers < void > ( ) ;
383- netSocket
373+
374+ socket
384375 . once ( 'error' , err => rejectOnNetSocketError ( onerror ( err ) ) )
385376 . once ( 'close' , ( ) => rejectOnNetSocketError ( onclose ( ) ) )
386377 . once ( 'connect' , ( ) => resolveOnNetSocketConnect ( ) ) ;
@@ -394,14 +385,14 @@ export class StateMachine {
394385 host : this . options . proxyOptions . proxyHost ,
395386 port : this . options . proxyOptions . proxyPort || 1080
396387 } ;
397- netSocket . connect ( netSocketOptions ) ;
388+ socketOptions . socket = socket . connect ( netSocketOptions ) ;
398389 await willConnect ;
399390
400391 try {
401392 socks ??= loadSocks ( ) ;
402393 socketOptions . socket = (
403394 await socks . SocksClient . createConnection ( {
404- existing_socket : netSocket ,
395+ existing_socket : socket ,
405396 command : 'connect' ,
406397 destination : { host : socketOptions . host , port : socketOptions . port } ,
407398 proxy : {
@@ -419,7 +410,7 @@ export class StateMachine {
419410 }
420411 }
421412
422- socket = tls . connect ( socketOptions , ( ) => {
413+ tls . connect ( socketOptions , ( ) => {
423414 socket . write ( message ) ;
424415 } ) ;
425416
@@ -430,7 +421,7 @@ export class StateMachine {
430421 } = promiseWithResolvers < void > ( ) ;
431422
432423 abortListener = addAbortListener ( options ?. signal , function ( ) {
433- destroySockets ( ) ;
424+ socket . destroy ( ) ;
434425 rejectOnTlsSocketError ( this . reason ) ;
435426 } ) ;
436427
@@ -455,12 +446,13 @@ export class StateMachine {
455446 ] )
456447 : willResolveKmsRequest ) ;
457448 } catch ( error ) {
458- if ( error instanceof TimeoutError )
449+ if ( TimeoutError . is ( error ) ) {
459450 throw new MongoOperationTimeoutError ( 'KMS request timed out' ) ;
451+ }
460452 throw error ;
461453 } finally {
462454 // There's no need for any more activity on this socket at this point.
463- destroySockets ( ) ;
455+ socket . destroy ( ) ;
464456 abortListener ?. [ kDispose ] ( ) ;
465457 }
466458 }
0 commit comments