@@ -452,7 +452,8 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
452
452
selector : string | ReadPreference | ServerSelector ,
453
453
options : SelectServerOptions
454
454
) : Promise < Server > {
455
- if ( ! this . isConnected ( ) ) {
455
+ const shouldInitialize = ! this . isConnected ( ) ;
456
+ if ( shouldInitialize ) {
456
457
this . stateTransition ( STATE_CONNECTING ) ;
457
458
// emit SDAM monitoring events
458
459
this . emitAndLog ( Topology . TOPOLOGY_OPENING , new TopologyOpeningEvent ( this . s . id ) ) ;
@@ -544,6 +545,11 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
544
545
) ;
545
546
}
546
547
if ( options . timeoutContext ?. clearServerSelectionTimeout ) timeout ?. clear ( ) ;
548
+ if ( shouldInitialize ) {
549
+ this . stateTransition ( STATE_CONNECTED ) ;
550
+ this . emit ( Topology . OPEN , this ) ;
551
+ this . emit ( Topology . CONNECT , this ) ;
552
+ }
547
553
return transaction . server ;
548
554
}
549
555
@@ -571,6 +577,11 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
571
577
if ( options . timeoutContext ?. csotEnabled ( ) && server . description . minRoundTripTime !== 0 ) {
572
578
options . timeoutContext . minRoundTripTime = server . description . minRoundTripTime ;
573
579
}
580
+ if ( shouldInitialize ) {
581
+ this . stateTransition ( STATE_CONNECTED ) ;
582
+ this . emit ( Topology . OPEN , this ) ;
583
+ this . emit ( Topology . CONNECT , this ) ;
584
+ }
574
585
return server ;
575
586
} catch ( error ) {
576
587
if ( TimeoutError . is ( error ) ) {
@@ -604,6 +615,10 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
604
615
}
605
616
throw timeoutError ;
606
617
}
618
+
619
+ if ( shouldInitialize ) {
620
+ this . close ( ) ;
621
+ }
607
622
// Other server selection error
608
623
throw error ;
609
624
} finally {
0 commit comments