1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
pub(crate) mod server_selection;
#[cfg(test)]
pub(crate) mod test;

use std::{
    collections::{HashMap, HashSet},
    time::Duration,
};

use serde::Deserialize;

use crate::{
    bson::oid::ObjectId,
    client::ClusterTime,
    cmap::Command,
    options::{ClientOptions, ServerAddress},
    sdam::description::server::{ServerDescription, ServerType},
    selection_criteria::{ReadPreference, SelectionCriteria},
};

const DEFAULT_HEARTBEAT_FREQUENCY: Duration = Duration::from_secs(10);

/// The possible types for a topology.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize)]
#[non_exhaustive]
pub enum TopologyType {
    /// A single mongod server.
    Single,

    /// A replica set with no primary.
    ReplicaSetNoPrimary,

    /// A replica set with a primary.
    ReplicaSetWithPrimary,

    /// A sharded topology.
    Sharded,

    /// A load balanced topology.
    LoadBalanced,

    /// A topology whose type is not known.
    Unknown,
}

#[cfg(test)]
impl TopologyType {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Single => "Single",
            Self::ReplicaSetNoPrimary => "ReplicaSetNoPrimary",
            Self::ReplicaSetWithPrimary => "ReplicaSetWithPrimary",
            Self::Sharded => "Sharded",
            Self::LoadBalanced => "LoadBalanced",
            Self::Unknown => "Unknown",
        }
    }
}

impl Default for TopologyType {
    fn default() -> Self {
        TopologyType::Unknown
    }
}

/// A description of the most up-to-date information known about a topology.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub(crate) struct TopologyDescription {
    /// Whether or not the topology was initialized with a single seed.
    pub(crate) single_seed: bool,

    /// The current type of the topology.
    pub(crate) topology_type: TopologyType,

    /// The replica set name of the topology.
    pub(crate) set_name: Option<String>,

    /// The highest replica set version the driver has seen by a member of the topology.
    pub(crate) max_set_version: Option<i32>,

    /// The highest replica set election id the driver has seen by a member of the topology.
    pub(crate) max_election_id: Option<ObjectId>,

    /// Describes the compatibility issue between the driver and server with regards to the
    /// respective supported wire versions.
    pub(crate) compatibility_error: Option<String>,

    /// Whether or not this topology supports sessions, and if so, what the logicalSessionTimeout
    /// is for them.
    pub(crate) session_support_status: SessionSupportStatus,

    /// Whether or not this topology supports transactions.
    pub(crate) transaction_support_status: TransactionSupportStatus,

    /// The highest reported cluster time by any server in this topology.
    pub(crate) cluster_time: Option<ClusterTime>,

    /// The amount of latency beyond that of the suitable server with the minimum latency that is
    /// acceptable for a read operation.
    pub(crate) local_threshold: Option<Duration>,

    /// The maximum amount of time to wait before checking a given server by sending an isMaster.
    pub(crate) heartbeat_freq: Option<Duration>,

    /// The server descriptions of each member of the topology.
    pub(crate) servers: HashMap<ServerAddress, ServerDescription>,
}

impl PartialEq for TopologyDescription {
    fn eq(&self, other: &Self) -> bool {
        // Since we only use TopologyDescription equality to determine whether to wake up server
        // selection operations to try to select again, the only fields we care about are the ones
        // checked by the server selection algorithm.
        self.compatibility_error == other.compatibility_error
            && self.servers == other.servers
            && self.topology_type == other.topology_type
    }
}

impl TopologyDescription {
    pub(crate) fn new(options: ClientOptions) -> crate::error::Result<Self> {
        verify_max_staleness(
            options
                .selection_criteria
                .as_ref()
                .and_then(|criteria| criteria.max_staleness()),
        )?;

        let topology_type = if let Some(true) = options.direct_connection {
            TopologyType::Single
        } else if options.repl_set_name.is_some() {
            TopologyType::ReplicaSetNoPrimary
        } else if options.load_balanced.unwrap_or(false) {
            TopologyType::LoadBalanced
        } else {
            TopologyType::Unknown
        };

        let servers: HashMap<_, _> = options
            .hosts
            .into_iter()
            .map(|address| (address.clone(), ServerDescription::new(address, None)))
            .collect();

        let session_support_status = if topology_type == TopologyType::LoadBalanced {
            SessionSupportStatus::Supported {
                logical_session_timeout: None,
            }
        } else {
            SessionSupportStatus::Undetermined
        };
        let transaction_support_status = if topology_type == TopologyType::LoadBalanced {
            TransactionSupportStatus::Supported
        } else {
            TransactionSupportStatus::Undetermined
        };

        Ok(Self {
            single_seed: servers.len() == 1,
            topology_type,
            set_name: options.repl_set_name,
            max_set_version: None,
            max_election_id: None,
            compatibility_error: None,
            session_support_status,
            transaction_support_status,
            cluster_time: None,
            local_threshold: options.local_threshold,
            heartbeat_freq: options.heartbeat_freq,
            servers,
        })
    }

    pub(crate) fn new_empty() -> Self {
        Self {
            single_seed: false,
            topology_type: TopologyType::Unknown,
            set_name: None,
            max_set_version: None,
            max_election_id: None,
            compatibility_error: None,
            session_support_status: SessionSupportStatus::Undetermined,
            transaction_support_status: TransactionSupportStatus::Undetermined,
            cluster_time: None,
            local_threshold: None,
            heartbeat_freq: None,
            servers: HashMap::new(),
        }
    }

    /// Gets the topology type of the cluster.
    pub(crate) fn topology_type(&self) -> TopologyType {
        self.topology_type
    }

    pub(crate) fn server_addresses(&self) -> impl Iterator<Item = &ServerAddress> {
        self.servers.keys()
    }

    pub(crate) fn cluster_time(&self) -> Option<&ClusterTime> {
        self.cluster_time.as_ref()
    }

    pub(crate) fn get_server_description(
        &self,
        address: &ServerAddress,
    ) -> Option<&ServerDescription> {
        self.servers.get(address)
    }

    pub(crate) fn update_command_with_read_pref<T>(
        &self,
        server_type: ServerType,
        command: &mut Command<T>,
        criteria: Option<&SelectionCriteria>,
    ) {
        match (self.topology_type, server_type) {
            (TopologyType::Sharded, ServerType::Mongos)
            | (TopologyType::Single, ServerType::Mongos)
            | (TopologyType::LoadBalanced, _) => {
                self.update_command_read_pref_for_mongos(command, criteria)
            }
            (TopologyType::Single, ServerType::Standalone) => {}
            (TopologyType::Single, _) => {
                let specified_read_pref = criteria
                    .and_then(SelectionCriteria::as_read_pref)
                    .map(Clone::clone);

                let resolved_read_pref = match specified_read_pref {
                    Some(ReadPreference::Primary) | None => ReadPreference::PrimaryPreferred {
                        options: Default::default(),
                    },
                    Some(other) => other,
                };

                command.set_read_preference(resolved_read_pref)
            }
            _ => {
                let read_pref = match criteria {
                    Some(SelectionCriteria::ReadPreference(rp)) => rp.clone(),
                    Some(SelectionCriteria::Predicate(_)) => ReadPreference::PrimaryPreferred {
                        options: Default::default(),
                    },
                    None => ReadPreference::Primary,
                };
                command.set_read_preference(read_pref)
            }
        }
    }

    fn update_command_read_pref_for_mongos<T>(
        &self,
        command: &mut Command<T>,
        criteria: Option<&SelectionCriteria>,
    ) {
        let read_preference = match criteria {
            Some(SelectionCriteria::ReadPreference(rp)) => rp,
            _ => return,
        };
        match read_preference {
            ReadPreference::Secondary { .. }
            | ReadPreference::PrimaryPreferred { .. }
            | ReadPreference::Nearest { .. }
            | ReadPreference::SecondaryPreferred { .. } => {
                command.set_read_preference(read_preference.clone())
            }
            _ => {}
        }
    }

    /// Gets the heartbeat frequency.
    fn heartbeat_frequency(&self) -> Duration {
        self.heartbeat_freq.unwrap_or(DEFAULT_HEARTBEAT_FREQUENCY)
    }

    /// Check the cluster for a compatibility error, and record the error message if one is found.
    fn check_compatibility(&mut self) {
        self.compatibility_error = None;

        for server in self.servers.values() {
            let error_message = server.compatibility_error_message();

            if error_message.is_some() {
                self.compatibility_error = error_message;
                return;
            }
        }
    }

    pub(crate) fn compatibility_error(&self) -> Option<&String> {
        self.compatibility_error.as_ref()
    }

    /// Update the ServerDescription's round trip time based on the rolling average.
    fn update_round_trip_time(&self, server_description: &mut ServerDescription) {
        if let Some(old_rtt) = self
            .servers
            .get(&server_description.address)
            .and_then(|server_desc| server_desc.average_round_trip_time)
        {
            if let Some(new_rtt) = server_description.average_round_trip_time {
                server_description.average_round_trip_time =
                    Some((new_rtt / 5) + (old_rtt * 4 / 5));
            }
        }
    }

    /// Updates the topology's logical session timeout value based on the server's value for it.
    fn update_session_support_status(&mut self, server_description: &ServerDescription) {
        if !server_description.server_type.is_data_bearing() {
            if let TopologyType::Single = self.topology_type {
                self.session_support_status = SessionSupportStatus::Unsupported {
                    logical_session_timeout: None,
                };
            }
            return;
        }

        match server_description.logical_session_timeout().ok().flatten() {
            Some(timeout) => match self.session_support_status {
                SessionSupportStatus::Supported {
                    logical_session_timeout: topology_timeout,
                } => {
                    self.session_support_status = SessionSupportStatus::Supported {
                        logical_session_timeout: std::cmp::min(Some(timeout), topology_timeout),
                    };
                }
                SessionSupportStatus::Undetermined => {
                    self.session_support_status = SessionSupportStatus::Supported {
                        logical_session_timeout: Some(timeout),
                    }
                }
                SessionSupportStatus::Unsupported { .. } => {
                    // Check if the timeout is now reported on all servers, and, if so, assign the
                    // topology's timeout to the minimum.
                    let min_timeout = self
                        .servers
                        .values()
                        .filter(|s| s.server_type.is_data_bearing())
                        .map(|s| s.logical_session_timeout().ok().flatten())
                        .min()
                        .flatten();

                    match min_timeout {
                        Some(timeout) => {
                            self.session_support_status = SessionSupportStatus::Supported {
                                logical_session_timeout: Some(timeout),
                            }
                        }
                        None => {
                            self.session_support_status = SessionSupportStatus::Unsupported {
                                logical_session_timeout: None,
                            }
                        }
                    }
                }
            },
            None if server_description.server_type.is_data_bearing()
                || self.topology_type == TopologyType::Single =>
            {
                self.session_support_status = SessionSupportStatus::Unsupported {
                    logical_session_timeout: None,
                }
            }
            None => {}
        }
    }

    /// Updates the topology's transaction support status based on its session support status and
    /// the server description's max wire version.
    fn update_transaction_support_status(&mut self, server_description: &ServerDescription) {
        if !matches!(
            self.session_support_status,
            SessionSupportStatus::Supported { .. }
        ) {
            self.transaction_support_status = TransactionSupportStatus::Unsupported;
        }
        if let Ok(Some(max_wire_version)) = server_description.max_wire_version() {
            self.transaction_support_status = if max_wire_version < 7
                || (max_wire_version < 8 && self.topology_type == TopologyType::Sharded)
            {
                TransactionSupportStatus::Unsupported
            } else {
                TransactionSupportStatus::Supported
            }
        }
    }

    /// Sets the topology's cluster time to the provided one if it is higher than the currently
    /// recorded one.
    pub(crate) fn advance_cluster_time(&mut self, cluster_time: &ClusterTime) {
        if self.cluster_time.as_ref() >= Some(cluster_time) {
            return;
        }
        self.cluster_time = Some(cluster_time.clone());
    }

    /// Returns the diff between this topology description and the provided one, or `None` if
    /// they are equal.
    ///
    /// The returned `TopologyDescriptionDiff` refers to the changes reflected in the provided
    /// description. For example, if the provided description has a server in it that this
    /// description does not, it will be returned in the `added_addresses` field.
    pub(crate) fn diff<'a>(
        &'a self,
        other: &'a TopologyDescription,
    ) -> Option<TopologyDescriptionDiff> {
        if self == other {
            return None;
        }

        let addresses: HashSet<&ServerAddress> = self.server_addresses().collect();
        let other_addresses: HashSet<&ServerAddress> = other.server_addresses().collect();

        let changed_servers = self
            .servers
            .iter()
            .filter_map(|(address, description)| match other.servers.get(address) {
                Some(other_description) if description != other_description => {
                    Some((address, (description, other_description)))
                }
                _ => None,
            });

        Some(TopologyDescriptionDiff {
            removed_addresses: addresses.difference(&other_addresses).cloned().collect(),
            added_addresses: other_addresses.difference(&addresses).cloned().collect(),
            changed_servers: changed_servers.collect(),
        })
    }

    /// Syncs the set of servers in the description to those in `hosts`. Servers in the set not
    /// already present in the cluster will be added, and servers in the cluster not present in the
    /// set will be removed.
    pub(crate) fn sync_hosts(&mut self, hosts: &HashSet<ServerAddress>) {
        self.add_new_servers_from_addresses(hosts.iter());
        self.servers.retain(|host, _| hosts.contains(host));
    }

    pub(crate) fn session_support_status(&self) -> SessionSupportStatus {
        self.session_support_status
    }

    pub(crate) fn transaction_support_status(&self) -> TransactionSupportStatus {
        self.transaction_support_status
    }

    /// Update the topology based on the new information about the topology contained by the
    /// ServerDescription.
    pub(crate) fn update(
        &mut self,
        mut server_description: ServerDescription,
    ) -> Result<(), String> {
        // Ignore updates from servers not currently in the cluster.
        if !self.servers.contains_key(&server_description.address) {
            return Ok(());
        }

        // Update the round trip time on the server description to the weighted average as described
        // by the spec.
        self.update_round_trip_time(&mut server_description);

        // Replace the old info about the server with the new info.
        self.servers.insert(
            server_description.address.clone(),
            server_description.clone(),
        );

        if let TopologyType::LoadBalanced = self.topology_type {
            // Load-balanced topologies don't have real server updates; attempting to update based
            // on the synthesized one causes incorrect behavior.
            return Ok(());
        }

        // Update the topology's min logicalSessionTimeout.
        self.update_session_support_status(&server_description);

        // Update the topology's transaction support status.
        self.update_transaction_support_status(&server_description);

        // Update the topology's max reported $clusterTime.
        if let Some(ref cluster_time) = server_description.cluster_time().ok().flatten() {
            self.advance_cluster_time(cluster_time);
        }

        // Update the topology description based on the current topology type.
        match self.topology_type {
            TopologyType::Single | TopologyType::LoadBalanced => {}
            TopologyType::Unknown => self.update_unknown_topology(server_description)?,
            TopologyType::Sharded => self.update_sharded_topology(server_description),
            TopologyType::ReplicaSetNoPrimary => {
                self.update_replica_set_no_primary_topology(server_description)?
            }
            TopologyType::ReplicaSetWithPrimary => {
                self.update_replica_set_with_primary_topology(server_description)?;
            }
        }

        // Record any compatibility error.
        self.check_compatibility();

        Ok(())
    }

    /// Update the Unknown topology description based on the server description.
    fn update_unknown_topology(
        &mut self,
        server_description: ServerDescription,
    ) -> Result<(), String> {
        match server_description.server_type {
            ServerType::Unknown | ServerType::RsGhost => {}
            ServerType::Standalone => {
                self.update_unknown_with_standalone_server(server_description)
            }
            ServerType::Mongos => self.topology_type = TopologyType::Sharded,
            ServerType::RsPrimary => {
                self.topology_type = TopologyType::ReplicaSetWithPrimary;
                self.update_rs_from_primary_server(server_description)?;
            }
            ServerType::RsSecondary | ServerType::RsArbiter | ServerType::RsOther => {
                self.topology_type = TopologyType::ReplicaSetNoPrimary;
                self.update_rs_without_primary_server(server_description)?;
            }
            ServerType::LoadBalancer => {
                return Err("cannot transition to a load balancer".to_string())
            }
        }

        Ok(())
    }

    /// Update the Sharded topology description based on the server description.
    fn update_sharded_topology(&mut self, server_description: ServerDescription) {
        match server_description.server_type {
            ServerType::Unknown | ServerType::Mongos => {}
            _ => {
                self.servers.remove(&server_description.address);
            }
        }
    }

    /// Update the ReplicaSetNoPrimary topology description based on the server description.
    fn update_replica_set_no_primary_topology(
        &mut self,
        server_description: ServerDescription,
    ) -> Result<(), String> {
        match server_description.server_type {
            ServerType::Unknown | ServerType::RsGhost => {}
            ServerType::Standalone | ServerType::Mongos => {
                self.servers.remove(&server_description.address);
            }
            ServerType::RsPrimary => {
                self.topology_type = TopologyType::ReplicaSetWithPrimary;
                self.update_rs_from_primary_server(server_description)?
            }
            ServerType::RsSecondary | ServerType::RsArbiter | ServerType::RsOther => {
                self.update_rs_without_primary_server(server_description)?;
            }
            ServerType::LoadBalancer => {
                return Err("cannot transition to a load balancer".to_string())
            }
        }

        Ok(())
    }

    /// Update the ReplicaSetWithPrimary topology description based on the server description.
    fn update_replica_set_with_primary_topology(
        &mut self,
        server_description: ServerDescription,
    ) -> Result<(), String> {
        match server_description.server_type {
            ServerType::Unknown | ServerType::RsGhost => {
                self.record_primary_state();
            }
            ServerType::Standalone | ServerType::Mongos => {
                self.servers.remove(&server_description.address);
                self.record_primary_state();
            }
            ServerType::RsPrimary => self.update_rs_from_primary_server(server_description)?,
            ServerType::RsSecondary | ServerType::RsArbiter | ServerType::RsOther => {
                self.update_rs_with_primary_from_member(server_description)?;
            }
            ServerType::LoadBalancer => {
                return Err("cannot transition to a load balancer".to_string())
            }
        }

        Ok(())
    }

    /// Update the Unknown topology description based on the Standalone server description.
    fn update_unknown_with_standalone_server(&mut self, server_description: ServerDescription) {
        if self.single_seed {
            self.topology_type = TopologyType::Single;
        } else {
            self.servers.remove(&server_description.address);
        }
    }

    /// Update the ReplicaSetNoPrimary topology description based on the non-primary server
    /// description.
    fn update_rs_without_primary_server(
        &mut self,
        server_description: ServerDescription,
    ) -> Result<(), String> {
        if self.set_name.is_none() {
            self.set_name = server_description.set_name()?;
        } else if self.set_name != server_description.set_name()? {
            self.servers.remove(&server_description.address);

            return Ok(());
        }

        self.add_new_servers(server_description.known_hosts()?)?;

        if server_description.invalid_me()? {
            self.servers.remove(&server_description.address);
        }

        Ok(())
    }

    /// Update the ReplicaSetWithPrimary topology description based on the non-primary server
    /// description.
    fn update_rs_with_primary_from_member(
        &mut self,
        server_description: ServerDescription,
    ) -> Result<(), String> {
        if self.set_name != server_description.set_name()? {
            self.servers.remove(&server_description.address);
            self.record_primary_state();

            return Ok(());
        }

        if server_description.invalid_me()? {
            self.servers.remove(&server_description.address);
            self.record_primary_state();

            return Ok(());
        }

        Ok(())
    }

    /// Update the replica set topology description based on the RSPrimary server description.
    fn update_rs_from_primary_server(
        &mut self,
        server_description: ServerDescription,
    ) -> Result<(), String> {
        if self.set_name.is_none() {
            self.set_name = server_description.set_name()?;
        } else if self.set_name != server_description.set_name()? {
            self.servers.remove(&server_description.address);
            self.record_primary_state();

            return Ok(());
        }

        if let Some(server_set_version) = server_description.set_version()? {
            if let Some(server_election_id) = server_description.election_id()? {
                if let Some(topology_max_set_version) = self.max_set_version {
                    if let Some(ref topology_max_election_id) = self.max_election_id {
                        if topology_max_set_version > server_set_version
                            || (topology_max_set_version == server_set_version
                                && *topology_max_election_id > server_election_id)
                        {
                            self.servers.insert(
                                server_description.address.clone(),
                                ServerDescription::new(server_description.address, None),
                            );
                            self.record_primary_state();
                            return Ok(());
                        }
                    }
                }

                self.max_election_id = Some(server_election_id);
            }
        }

        if let Some(server_set_version) = server_description.set_version()? {
            if self
                .max_set_version
                .as_ref()
                .map(|topology_max_set_version| server_set_version > *topology_max_set_version)
                .unwrap_or(true)
            {
                self.max_set_version = Some(server_set_version);
            }
        }

        let addresses: Vec<_> = self.servers.keys().cloned().collect();

        // If any other servers are RSPrimary, replace them with an unknown server decscription,
        // which will cause them to be updated by a new isMaster.
        for address in addresses.clone() {
            if address == server_description.address {
                continue;
            }

            if let ServerType::RsPrimary = self.servers.get(&address).unwrap().server_type {
                self.servers
                    .insert(address.clone(), ServerDescription::new(address, None));
            }
        }

        self.add_new_servers(server_description.known_hosts()?)?;
        let known_hosts: HashSet<_> = server_description.known_hosts()?.collect();

        for address in addresses {
            if !known_hosts.contains(&address.to_string()) {
                self.servers.remove(&address);
            }
        }

        self.record_primary_state();

        Ok(())
    }

    /// Inspect the topology for a primary server, and update the topology type to
    /// ReplicaSetNoPrimary if none is found.
    ///
    /// This should only be called on a replica set topology.
    fn record_primary_state(&mut self) {
        self.topology_type = if self
            .servers
            .values()
            .any(|server| server.server_type == ServerType::RsPrimary)
        {
            TopologyType::ReplicaSetWithPrimary
        } else {
            TopologyType::ReplicaSetNoPrimary
        };
    }

    /// Create a new ServerDescription for each address and add it to the topology.
    fn add_new_servers<'a>(
        &mut self,
        servers: impl Iterator<Item = &'a String>,
    ) -> Result<(), String> {
        let servers: Result<Vec<_>, String> = servers
            .map(|server| ServerAddress::parse(server).map_err(|e| e.to_string()))
            .collect();

        self.add_new_servers_from_addresses(servers?.iter());
        Ok(())
    }

    /// Create a new ServerDescription for each address and add it to the topology.
    fn add_new_servers_from_addresses<'a>(
        &mut self,
        servers: impl Iterator<Item = &'a ServerAddress>,
    ) {
        for server in servers {
            if !self.servers.contains_key(server) {
                self.servers
                    .insert(server.clone(), ServerDescription::new(server.clone(), None));
            }
        }
    }
}

/// Enum representing whether sessions are supported by the topology.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum SessionSupportStatus {
    /// It is not known yet whether the topology supports sessions. This is possible if no
    /// data-bearing servers have updated the `TopologyDescription` yet.
    Undetermined,

    /// Sessions are not supported by this topology. This is possible if there is a data-bearing
    /// server in the deployment that does not support sessions.
    ///
    /// While standalones do not support sessions, they still do report a logical session timeout,
    /// so it is stored here if necessary.
    Unsupported {
        logical_session_timeout: Option<Duration>,
    },

    /// Sessions are supported by this topology. This is the minimum timeout of all data-bearing
    /// servers in the deployment.
    Supported {
        logical_session_timeout: Option<Duration>,
    },
}

impl Default for SessionSupportStatus {
    fn default() -> Self {
        Self::Undetermined
    }
}

impl SessionSupportStatus {
    #[cfg(test)]
    fn logical_session_timeout(&self) -> Option<Duration> {
        match self {
            Self::Undetermined => None,
            Self::Unsupported {
                logical_session_timeout,
            } => *logical_session_timeout,
            Self::Supported {
                logical_session_timeout,
            } => *logical_session_timeout,
        }
    }
}

/// Enum representing whether transactions are supported by the topology.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum TransactionSupportStatus {
    /// It is not known yet whether the topology supports transactions. This is possible if no
    /// data-bearing servers have updated the `TopologyDescription` yet.
    Undetermined,

    /// Transactions are not supported by this topology.
    Unsupported,

    /// Transactions are supported by this topology. A topology supports transactions if it
    /// supports sessions and its maxWireVersion >= 7. If the topology is sharded, maxWireVersion
    /// must be >= 8 for transactions to be supported.
    ///
    /// Note that meeting these conditions does not guarantee that a deployment
    /// supports transactions; any other missing qualification will be reported by the server.
    Supported,
}

impl Default for TransactionSupportStatus {
    fn default() -> Self {
        Self::Undetermined
    }
}

/// A struct representing the diff between two `TopologyDescription`s.
/// Returned from `TopologyDescription::diff`.
#[derive(Debug)]
pub(crate) struct TopologyDescriptionDiff<'a> {
    pub(crate) removed_addresses: HashSet<&'a ServerAddress>,
    pub(crate) added_addresses: HashSet<&'a ServerAddress>,
    pub(crate) changed_servers:
        HashMap<&'a ServerAddress, (&'a ServerDescription, &'a ServerDescription)>,
}

fn verify_max_staleness(max_staleness: Option<Duration>) -> crate::error::Result<()> {
    verify_max_staleness_inner(max_staleness)
        .map_err(|s| crate::error::ErrorKind::InvalidArgument { message: s }.into())
}

fn verify_max_staleness_inner(max_staleness: Option<Duration>) -> std::result::Result<(), String> {
    if max_staleness
        .map(|staleness| staleness > Duration::from_secs(0) && staleness < Duration::from_secs(90))
        .unwrap_or(false)
    {
        return Err("max staleness cannot be both positive and below 90 seconds".into());
    }

    Ok(())
}