@@ -362,29 +362,26 @@ function topologyTypeForServerType(serverType: ServerType): TopologyType {
362362 }
363363}
364364
365+ /**
366+ * Compare objectIds. `null` is always less
367+ * - `+1 = oid1 is greater than oid2`
368+ * - `-1 = oid1 is less than oid2`
369+ * - `+0 = oid1 is equal oid2`
370+ */
365371function compareObjectId ( oid1 ?: ObjectId , oid2 ?: ObjectId ) : 0 | 1 | - 1 {
366- if ( oid1 == null ) {
367- return oid2 == null ? 0 : - 1 ;
368- }
369-
370- if ( oid2 == null ) {
371- return 1 ;
372+ if ( oid1 == null && oid2 == null ) {
373+ return 0 ;
372374 }
373375
374- const res = oid1 . id . compare ( oid2 . id ) ;
375- return res === 0 ? 0 : res > 0 ? 1 : - 1 ;
376- }
377-
378- function compareNumber ( num1 ?: number , num2 ?: number ) : 0 | 1 | - 1 {
379- if ( num1 == null ) {
380- return num2 == null ? 0 : - 1 ;
376+ if ( oid1 == null ) {
377+ return - 1 ;
381378 }
382379
383- if ( num2 == null ) {
380+ if ( oid2 == null ) {
384381 return 1 ;
385382 }
386383
387- return num1 === num2 ? 0 : num1 > num2 ? 1 : - 1 ;
384+ return oid1 . id . compare ( oid2 . id ) ;
388385}
389386
390387function updateRsFromPrimary (
@@ -403,21 +400,17 @@ function updateRsFromPrimary(
403400 const electionIdComparison = compareObjectId ( maxElectionId , serverDescription . electionId ) ;
404401 const maxElectionIdIsEqual = electionIdComparison === 0 ;
405402 const maxElectionIdIsLess = electionIdComparison === - 1 ;
403+ const maxSetVersionIsLessOrEqual = ( maxSetVersion ?? - 1 ) <= ( serverDescription . setVersion ?? - 1 ) ;
406404
407- const setVersionComparison = compareNumber ( maxSetVersion , serverDescription . setVersion ) ;
408- const maxSetVersionIsLess = setVersionComparison === - 1 ;
409- const maxSetVersionIsEqual = setVersionComparison === 0 ;
410-
411- if (
412- maxElectionIdIsLess ||
413- ( maxElectionIdIsEqual && ( maxSetVersionIsLess || maxSetVersionIsEqual ) )
414- ) {
415- // We've seen a higher ElectionId! Update both!
416- // Or the electionId is the same but the setVersion increased
405+ if ( maxElectionIdIsLess || ( maxElectionIdIsEqual && maxSetVersionIsLessOrEqual ) ) {
406+ // The reported electionId was greater
407+ // or the electionId was equal and reported setVersion was greater
408+ // Always update both values, they are a tuple
417409 maxElectionId = serverDescription . electionId ;
418410 maxSetVersion = serverDescription . setVersion ;
419411 } else {
420- // this primary is stale, we must remove it
412+ // Stale primary
413+ // replace serverDescription with a default ServerDescription of type "Unknown"
421414 serverDescriptions . set (
422415 serverDescription . address ,
423416 new ServerDescription ( serverDescription . address )
0 commit comments