Skip to main content

picodata_driver/
topology.rs

1use std::{
2    collections::{HashMap, hash_map::Entry},
3    sync::{
4        Arc,
5        atomic::{AtomicUsize, Ordering},
6    },
7};
8
9use serde::Deserialize;
10use uuid::Uuid;
11
12use crate::instance::{Instance, State};
13
14/// Global counter for assigning unique pool slot indices to instances.
15static NEXT_IDX: AtomicUsize = AtomicUsize::new(0);
16
17/// Name of a connection type in `_pico_peer_address`, such as `pgproto` or `iproto`.
18type ConnectionType = String;
19
20/// A single bucket range entry from `_pico_bucket()` response.
21#[derive(Clone, Debug, Deserialize)]
22pub(crate) struct BucketRangeEntry {
23    pub tier_name: String,
24    pub bucket_id_start: u64,
25    pub bucket_id_end: u64,
26    pub current_replicaset_uuid: Uuid,
27}
28
29/// The cluster topology as handed out by [`crate::Client::topology`].
30pub mod view {
31    use std::{collections::HashMap, ops::RangeInclusive};
32
33    use uuid::Uuid;
34
35    use super::ConnectionType;
36    use crate::error::{Error, IncompleteBucketMap};
37
38    /// Cluster topology: tiers with their replicasets and bucket ranges.
39    #[derive(Debug, Clone, PartialEq, Eq)]
40    pub struct Topology {
41        pub(super) tiers: Vec<Tier>,
42    }
43
44    /// A tier with its replicasets.
45    #[derive(Debug, Clone, PartialEq, Eq)]
46    pub struct Tier {
47        pub(super) name: String,
48        pub(super) bucket_count: u64,
49        pub(super) replicasets: Vec<Replicaset>,
50    }
51
52    /// A replicaset with its instances and the buckets it owns.
53    #[derive(Debug, Clone, PartialEq, Eq)]
54    pub struct Replicaset {
55        pub(super) uuid: Uuid,
56        pub(super) name: String,
57        pub(super) master: Option<Instance>,
58        pub(super) replicas: Vec<Instance>,
59        pub(super) ranges: Vec<RangeInclusive<u64>>,
60    }
61
62    /// An instance of a replicaset.
63    #[derive(Debug, Clone, PartialEq, Eq)]
64    pub struct Instance {
65        pub(super) name: String,
66        /// The address of each connection type the instance accepts.
67        pub(super) addresses: HashMap<ConnectionType, String>,
68        pub(super) online: bool,
69        pub(super) expelled: bool,
70        pub(super) is_master: bool,
71        pub(super) raft_id: u64,
72        pub(super) uuid: Uuid,
73    }
74
75    /// Bucket ranges of a tier by the UUID of the replicaset owning them.
76    pub type BucketMap<'a> = HashMap<Uuid, &'a [RangeInclusive<u64>]>;
77
78    impl Topology {
79        /// The cluster's tiers.
80        #[must_use]
81        pub fn tiers(&self) -> &[Tier] {
82            &self.tiers
83        }
84    }
85
86    impl Tier {
87        /// Tier name.
88        #[must_use]
89        pub fn name(&self) -> &str {
90            &self.name
91        }
92
93        /// The tier's replicasets.
94        #[must_use]
95        pub fn replicasets(&self) -> &[Replicaset] {
96            &self.replicasets
97        }
98
99        /// Number of buckets the tier is configured with.
100        #[must_use]
101        pub fn bucket_count(&self) -> u64 {
102            self.bucket_count
103        }
104
105        /// Bucket ranges by the UUID of the replicaset owning them.
106        ///
107        /// # Errors
108        ///
109        /// Returns [`Error::IncompleteBucketMap`] if the ranges leave some of the tier's
110        /// buckets uncovered.
111        pub fn bucket_map(&self) -> Result<BucketMap<'_>, Error> {
112            let mut ranges: Vec<_> = self.replicasets.iter().flat_map(|rs| &rs.ranges).collect();
113            ranges.sort_unstable_by_key(|r| *r.start());
114            // Buckets covered without a gap, counting from bucket 1.
115            let mut covered = 0;
116            for r in ranges {
117                if *r.start() != covered + 1 || r.is_empty() {
118                    break;
119                }
120                covered = *r.end();
121            }
122            if covered != self.bucket_count {
123                return Err(Error::IncompleteBucketMap(Box::new(IncompleteBucketMap {
124                    tier: self.name.clone(),
125                    covered,
126                    expected: self.bucket_count,
127                })));
128            }
129            Ok(self
130                .replicasets
131                .iter()
132                .map(|rs| (rs.uuid(), rs.ranges()))
133                .collect())
134        }
135    }
136
137    impl Replicaset {
138        /// UUID of the replicaset.
139        #[must_use]
140        pub fn uuid(&self) -> Uuid {
141            self.uuid
142        }
143
144        /// The current master, or `None` while the cluster has not named one.
145        #[must_use]
146        pub fn master(&self) -> Option<&Instance> {
147            self.master.as_ref()
148        }
149
150        /// The remaining instances.
151        #[must_use]
152        pub fn replicas(&self) -> &[Instance] {
153            &self.replicas
154        }
155
156        /// All the instances, the master first.
157        pub fn instances(&self) -> impl Iterator<Item = &Instance> {
158            self.master.iter().chain(&self.replicas)
159        }
160
161        /// Bucket ranges the replicaset owns, ordered by start.
162        #[must_use]
163        pub fn ranges(&self) -> &[RangeInclusive<u64>] {
164            &self.ranges
165        }
166
167        /// Name of the replicaset.
168        #[must_use]
169        pub fn name(&self) -> &str {
170            &self.name
171        }
172    }
173
174    impl Instance {
175        /// Instance name.
176        #[must_use]
177        pub fn name(&self) -> &str {
178            &self.name
179        }
180
181        /// The address the instance accepts `connection_type`, such as `iproto`, on;
182        /// `None` if it does not.
183        #[must_use]
184        pub fn address(&self, connection_type: impl AsRef<str>) -> Option<&str> {
185            self.addresses
186                .get(connection_type.as_ref())
187                .map(String::as_str)
188        }
189
190        /// Returns `true` if the instance is online.
191        #[must_use]
192        pub fn is_online(&self) -> bool {
193            self.online
194        }
195
196        /// Returns `true` if the instance is expelled from the cluster:
197        /// permanently removed, its address will not come back.
198        #[must_use]
199        pub fn is_expelled(&self) -> bool {
200            self.expelled
201        }
202
203        /// Returns `true` if the instance is the master of its replicaset.
204        #[must_use]
205        pub fn is_master(&self) -> bool {
206            self.is_master
207        }
208
209        /// Raft id of the instance.
210        #[must_use]
211        pub fn raft_id(&self) -> u64 {
212            self.raft_id
213        }
214
215        /// UUID of the instance.
216        #[must_use]
217        pub fn uuid(&self) -> Uuid {
218            self.uuid
219        }
220    }
221}
222
223/// Cluster topology: instances, tiers, replicasets, and bucket ranges.
224#[derive(Debug, Default)]
225pub(crate) struct Topology {
226    pub(crate) instances: HashMap<String, Arc<Instance>>,
227    pgproto_tiers: Vec<Tier>,
228    /// Tiers by every other connection type, such as `iproto`; never routed to.
229    other_tiers: HashMap<ConnectionType, Vec<Tier>>,
230}
231
232/// A single tier with its replicasets and bucket-to-replicaset mapping.
233#[derive(Debug, Clone)]
234struct Tier {
235    name: String,
236    bucket_count: u64,
237    replicasets: Vec<Replicaset>,
238    bucket_map: Vec<BucketSlot>,
239}
240
241/// Maps a contiguous bucket range [start, end] to a replicaset index.
242#[derive(Debug, Clone)]
243struct BucketSlot {
244    start: u64,
245    end: u64,
246    replicaset_idx: usize,
247}
248
249/// A replicaset with its master and replica instances.
250#[derive(Debug, Clone)]
251struct Replicaset {
252    uuid: Uuid,
253    master: Arc<Instance>,
254    replicas: Vec<Arc<Instance>>,
255}
256
257impl From<(Vec<pg::Row>, Vec<pg::Row>)> for Topology {
258    fn from((topology_rows, bucket_rows): (Vec<pg::Row>, Vec<pg::Row>)) -> Self {
259        // One row per advertised address: a topology per connection type, `pgproto` is routed to.
260        let mut by_type: HashMap<ConnectionType, Vec<pg::Row>> = HashMap::new();
261        let mut tiers = HashMap::new();
262        for row in topology_rows {
263            let name: String = row.get("tier");
264            let bucket_count = u64::try_from(row.get::<_, i64>("bucket_count"))
265                .expect("bucket_count is non-negative");
266            tiers.insert(name, bucket_count);
267            let Ok(connection_type) = row.try_get::<_, &str>("connection_type") else {
268                continue;
269            };
270            if let Some(rows) = by_type.get_mut(connection_type) {
271                rows.push(row);
272            } else {
273                by_type.insert(connection_type.to_string(), vec![row]);
274            }
275        }
276        // Parsed once: every connection type shares the same bucket ranges.
277        let mut buckets: Vec<BucketRangeEntry> = Vec::new();
278        for row in bucket_rows {
279            let entries = if let Ok(json) = row.try_get::<_, serde_json::Value>(0) {
280                serde_json::from_value::<Vec<BucketRangeEntry>>(json)
281            } else if let Ok(s) = row.try_get::<_, &str>(0) {
282                serde_json::from_str(s)
283            } else {
284                log::error!("failed to read bucket ranges column");
285                continue;
286            };
287            match entries {
288                Ok(v) => buckets.extend(v),
289                Err(e) => log::error!("failed to parse bucket ranges: {e}"),
290            }
291        }
292
293        let mut other_tiers: HashMap<ConnectionType, Vec<Tier>> = by_type
294            .into_iter()
295            .map(|(connection_type, rows)| (connection_type, build_tiers(rows, &buckets)))
296            .collect();
297        let mut pgproto_tiers = other_tiers.remove("pgproto").unwrap_or_default();
298        for (name, bucket_count) in tiers {
299            if !pgproto_tiers.iter().any(|tier| tier.name == name) {
300                pgproto_tiers.push(Tier {
301                    name,
302                    bucket_count,
303                    replicasets: Vec::new(),
304                    bucket_map: Vec::new(),
305                });
306            }
307        }
308        // A master placeholder that is not the master also sits in `replicas`.
309        let instances = pgproto_tiers
310            .iter()
311            .flat_map(|t| &t.replicasets)
312            .flat_map(|rs| {
313                rs.master
314                    .is_master
315                    .then_some(&rs.master)
316                    .into_iter()
317                    .chain(&rs.replicas)
318            })
319            .map(|inst| (inst.name.clone(), inst.clone()))
320            .collect();
321        Topology {
322            instances,
323            pgproto_tiers,
324            other_tiers,
325        }
326    }
327}
328
329/// Builds the tiers from the rows of one connection type.
330fn build_tiers(topology_rows: Vec<pg::Row>, buckets: &[BucketRangeEntry]) -> Vec<Tier> {
331    let mut tiers: Vec<Tier> = Vec::new();
332    for row in topology_rows {
333        let inst = match Instance::try_from(row) {
334            Ok(v) => v,
335            Err(e) => {
336                log::error!("failed to convert instance: {e}");
337                continue;
338            }
339        };
340
341        let inst = Arc::new(inst);
342
343        let tier = if let Some(t) = tiers.iter_mut().find(|t| t.name == inst.tier) {
344            t
345        } else {
346            tiers.push(Tier {
347                name: inst.tier.clone(),
348                bucket_count: inst.bucket_count,
349                replicasets: Vec::new(),
350                bucket_map: Vec::new(),
351            });
352            tiers.last_mut().expect("just pushed")
353        };
354
355        let rs = if let Some(r) = tier
356            .replicasets
357            .iter_mut()
358            .find(|r| r.uuid == inst.replicaset_uuid)
359        {
360            r
361        } else {
362            tier.replicasets.push(Replicaset {
363                uuid: inst.replicaset_uuid,
364                master: inst.clone(),
365                replicas: Vec::new(),
366            });
367            tier.replicasets.last_mut().expect("just pushed")
368        };
369
370        if inst.is_master {
371            rs.master = inst.clone();
372        } else {
373            rs.replicas.push(inst.clone());
374        }
375    }
376
377    for entry in buckets {
378        let Some(tier) = tiers.iter_mut().find(|t| t.name == entry.tier_name) else {
379            continue;
380        };
381        let Some(rs_idx) = tier
382            .replicasets
383            .iter()
384            .position(|r| r.uuid == entry.current_replicaset_uuid)
385        else {
386            continue;
387        };
388        tier.bucket_map.push(BucketSlot {
389            start: entry.bucket_id_start,
390            end: entry.bucket_id_end,
391            replicaset_idx: rs_idx,
392        });
393    }
394
395    for tier in &mut tiers {
396        tier.bucket_map.sort_unstable_by_key(|s| s.start);
397    }
398
399    tiers
400}
401
402impl Topology {
403    /// Creates an empty topology.
404    pub(crate) fn new() -> Self {
405        Self::default()
406    }
407
408    /// Merges incoming topology: updates existing instance states, adds new instances,
409    /// marks missing instances as offline, and replaces tier/bucket data.
410    pub(crate) fn merge(&mut self, incoming: Topology) {
411        for (name, existing) in &self.instances {
412            if !incoming.instances.contains_key(name) {
413                existing.set_state(State::Offline);
414            }
415        }
416
417        // The map keeps the same Arc the new tiers hold, so each instance is one object;
418        // only its pool slot index carries over from the previous refresh.
419        for (name, inc_inst) in incoming.instances {
420            match self.instances.entry(name) {
421                Entry::Occupied(mut e) => {
422                    inc_inst.set_idx(e.get().idx());
423                    e.insert(inc_inst);
424                }
425                Entry::Vacant(e) => {
426                    inc_inst.set_idx(NEXT_IDX.fetch_add(1, Ordering::Relaxed));
427                    e.insert(inc_inst);
428                }
429            }
430        }
431
432        self.pgproto_tiers = incoming.pgproto_tiers;
433        self.other_tiers = incoming.other_tiers;
434    }
435
436    /// Resolves the pool slot index for a given tier, `bucket_id`, and master preference.
437    /// Returns `None` if the bucket or replicaset cannot be found, or no instance is online.
438    pub(crate) fn resolve(&self, tier: &str, bucket_id: u64, on_master: bool) -> Option<usize> {
439        let t = self.pgproto_tiers.iter().find(|t| t.name == tier)?;
440        let rs = t.lookup(bucket_id)?;
441
442        if on_master || rs.replicas.is_empty() {
443            return if rs.master.is_online() {
444                Some(rs.master.idx())
445            } else {
446                None
447            };
448        }
449
450        let online: Vec<_> = rs.replicas.iter().filter(|r| r.is_online()).collect();
451        if online.is_empty() {
452            return if rs.master.is_online() {
453                Some(rs.master.idx())
454            } else {
455                None
456            };
457        }
458
459        let idx =
460            usize::try_from(bucket_id % online.len() as u64).expect("modulo result fits in usize");
461        Some(online[idx].idx())
462    }
463
464    /// Builds the topology handed out to the user: each instance once, with its address
465    /// of every connection type.
466    pub(crate) fn snapshot(&self) -> view::Topology {
467        let mut view_tiers = Vec::with_capacity(self.pgproto_tiers.len());
468        add_to_view(&mut view_tiers, "pgproto", &self.pgproto_tiers);
469        for (connection_type, tiers) in &self.other_tiers {
470            add_to_view(&mut view_tiers, connection_type, tiers);
471        }
472        view_tiers.sort_unstable_by(|a, b| a.name.cmp(&b.name));
473        for tier in &mut view_tiers {
474            sort(&mut tier.replicasets);
475        }
476        view::Topology { tiers: view_tiers }
477    }
478
479    /// Returns the total bucket count for a tier.
480    pub(crate) fn bucket_count(&self, tier: &str) -> Option<u64> {
481        self.pgproto_tiers
482            .iter()
483            .find(|t| t.name == tier)
484            .map(|t| t.bucket_count)
485    }
486}
487
488/// Adds the instances of `tiers` to `view_tiers` with their `connection_type` address,
489/// next to what the other connection types have added.
490fn add_to_view(view_tiers: &mut Vec<view::Tier>, connection_type: &str, tiers: &[Tier]) {
491    for tier in tiers {
492        let view_tier = if let Some(t) = view_tiers.iter_mut().find(|t| t.name == tier.name) {
493            t
494        } else {
495            view_tiers.push(view::Tier {
496                name: tier.name.clone(),
497                bucket_count: tier.bucket_count,
498                replicasets: Vec::new(),
499            });
500            view_tiers.last_mut().expect("just pushed")
501        };
502
503        for (idx, rs) in tier.replicasets.iter().enumerate() {
504            let view_rs =
505                if let Some(r) = view_tier.replicasets.iter_mut().find(|r| r.uuid == rs.uuid) {
506                    r
507                } else {
508                    view_tier.replicasets.push(view::Replicaset {
509                        uuid: rs.uuid,
510                        name: rs.master.replicaset_name.clone(),
511                        master: None,
512                        replicas: Vec::new(),
513                        ranges: tier
514                            .bucket_map
515                            .iter()
516                            .filter(|s| s.replicaset_idx == idx)
517                            .map(|s| s.start..=s.end)
518                            .collect(),
519                    });
520                    view_tier.replicasets.last_mut().expect("just pushed")
521                };
522
523            if rs.master.is_master {
524                match &mut view_rs.master {
525                    Some(m) => {
526                        m.addresses
527                            .insert(connection_type.to_string(), rs.master.addr.to_string());
528                    }
529                    None => view_rs.master = Some(instance(&rs.master, connection_type)),
530                }
531            }
532            for r in &rs.replicas {
533                if let Some(i) = view_rs.replicas.iter_mut().find(|i| i.name == r.name) {
534                    i.addresses
535                        .insert(connection_type.to_string(), r.addr.to_string());
536                } else {
537                    view_rs.replicas.push(instance(r, connection_type));
538                }
539            }
540        }
541    }
542}
543
544impl Tier {
545    /// Finds the replicaset owning `bucket_id` via binary search on the bucket map.
546    fn lookup(&self, bucket_id: u64) -> Option<&Replicaset> {
547        let i = self
548            .bucket_map
549            .partition_point(|s| s.start <= bucket_id)
550            .checked_sub(1)?;
551        let slot = &self.bucket_map[i];
552        if bucket_id <= slot.end {
553            self.replicasets.get(slot.replicaset_idx)
554        } else {
555            None
556        }
557    }
558}
559
560/// Orders replicasets by UUID and their replicas by name, so equal topologies compare equal.
561fn sort(replicasets: &mut [view::Replicaset]) {
562    replicasets.sort_unstable_by_key(|rs| rs.uuid);
563    for rs in replicasets {
564        rs.replicas.sort_unstable_by(|a, b| a.name.cmp(&b.name));
565    }
566}
567
568/// Builds the view of an instance with its `connection_type` address.
569fn instance(inst: &Instance, connection_type: &str) -> view::Instance {
570    view::Instance {
571        name: inst.name.clone(),
572        addresses: HashMap::from([(connection_type.to_string(), inst.addr.to_string())]),
573        online: inst.is_online(),
574        expelled: inst.is_expelled(),
575        is_master: inst.is_master,
576        raft_id: inst.raft_id,
577        uuid: inst.uuid,
578    }
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584    use crate::error::Error;
585
586    const RS1: Uuid = Uuid::from_u128(1);
587    const RS2: Uuid = Uuid::from_u128(2);
588
589    #[test]
590    fn empty_tier_gains_instances() {
591        let empty = || Topology {
592            pgproto_tiers: vec![Tier {
593                name: "default".to_owned(),
594                bucket_count: 3000,
595                replicasets: Vec::new(),
596                bucket_map: Vec::new(),
597            }],
598            ..Topology::default()
599        };
600        let mut topology = empty();
601        topology.merge(make_topology("i1", "default", RS1));
602        let snapshot = topology.snapshot();
603        assert_eq!(snapshot.tiers().len(), 1);
604        assert_eq!(snapshot.tiers()[0].bucket_count(), 3000);
605        assert_eq!(snapshot.tiers()[0].replicasets().len(), 1);
606        assert_eq!(
607            snapshot.tiers()[0].replicasets()[0]
608                .master()
609                .map(|master| master.name()),
610            Some("i1")
611        );
612        assert!(topology.resolve("default", 1, true).is_some());
613
614        topology.merge(empty());
615        let snapshot = topology.snapshot();
616        assert_eq!(snapshot.tiers().len(), 1);
617        assert_eq!(snapshot.tiers()[0].bucket_count(), 3000);
618        assert_eq!(snapshot.tiers()[0].replicasets(), []);
619        assert!(topology.resolve("default", 1, true).is_none());
620    }
621
622    /// Build a single-instance topology directly, bypassing `pg::Row` parsing.
623    fn make_topology(name: &str, tier: &str, rs_uuid: Uuid) -> Topology {
624        let inst = Arc::new(Instance::new_for_test(
625            name,
626            "127.0.0.1:3301",
627            tier,
628            rs_uuid,
629            true,
630            3000,
631        ));
632
633        let mut instances = HashMap::new();
634        instances.insert(inst.name.clone(), inst.clone());
635
636        let rs = Replicaset {
637            uuid: rs_uuid,
638            master: inst.clone(),
639            replicas: vec![],
640        };
641        let tier_obj = Tier {
642            name: tier.to_string(),
643            bucket_count: 3000,
644            replicasets: vec![rs],
645            bucket_map: vec![BucketSlot {
646                start: 1,
647                end: 3000,
648                replicaset_idx: 0,
649            }],
650        };
651
652        Topology {
653            instances,
654            pgproto_tiers: vec![tier_obj],
655            other_tiers: HashMap::new(),
656        }
657    }
658
659    /// An expelled instance must be distinguishable from an offline one.
660    #[test]
661    fn snapshot_tells_expelled_from_offline() {
662        let mut topo = Topology::new();
663        topo.merge(make_topology("i1", "default", RS1));
664        let view = || {
665            topo.snapshot().tiers()[0].replicasets()[0]
666                .instances()
667                .next()
668                .expect("one instance")
669                .clone()
670        };
671
672        topo.instances["i1"].set_state(State::Expelled);
673        let inst = view();
674        assert!(inst.is_expelled());
675        assert!(!inst.is_online());
676
677        topo.instances["i1"].set_state(State::Offline);
678        let inst = view();
679        assert!(!inst.is_expelled());
680        assert!(!inst.is_online());
681    }
682
683    /// A range of an unknown replicaset leaves a hole, which must be reported.
684    #[test]
685    fn bucket_map_rejects_an_incomplete_map() {
686        let mut topo = Topology::new();
687        let mut incoming = make_topology("i1", "default", RS1);
688        incoming.pgproto_tiers[0].bucket_map = vec![
689            BucketSlot {
690                start: 1,
691                end: 1500,
692                replicaset_idx: 0,
693            },
694            // Dangling: `replicasets` holds a single entry, so idx 7 is unknown.
695            BucketSlot {
696                start: 1501,
697                end: 3000,
698                replicaset_idx: 7,
699            },
700        ];
701        topo.merge(incoming);
702
703        match topo.snapshot().tiers()[0].bucket_map() {
704            Err(Error::IncompleteBucketMap(m)) => {
705                assert_eq!(m.tier, "default");
706                assert_eq!((m.covered, m.expected), (1500, 3000));
707            }
708            other => panic!("a half-covered tier must not be returned: {other:?}"),
709        }
710    }
711
712    /// A tier without ranges must be reported, not returned empty.
713    #[test]
714    fn bucket_map_rejects_a_tier_with_no_ranges() {
715        let mut topo = Topology::new();
716        let mut incoming = make_topology("i1", "default", RS1);
717        incoming.pgproto_tiers[0].bucket_map.clear();
718        topo.merge(incoming);
719
720        assert!(matches!(
721            topo.snapshot().tiers()[0].bucket_map(),
722            Err(Error::IncompleteBucketMap(ref m)) if m.covered == 0
723        ));
724    }
725
726    /// Every range a replicaset owns must route to that replicaset's master.
727    #[test]
728    fn snapshot_ranges_agree_with_resolve() {
729        let mut topo = Topology::new();
730        let mut incoming = make_topology("i1", "default", RS1);
731        let i2 = Arc::new(Instance::new_for_test(
732            "i2",
733            "127.0.0.1:3302",
734            "default",
735            RS2,
736            true,
737            3000,
738        ));
739        incoming.instances.insert(i2.name.clone(), i2.clone());
740        let tier = &mut incoming.pgproto_tiers[0];
741        tier.replicasets.push(Replicaset {
742            uuid: RS2,
743            master: i2,
744            replicas: vec![],
745        });
746        tier.bucket_map = vec![
747            BucketSlot {
748                start: 1,
749                end: 1000,
750                replicaset_idx: 0,
751            },
752            BucketSlot {
753                start: 1001,
754                end: 2000,
755                replicaset_idx: 1,
756            },
757            BucketSlot {
758                start: 2001,
759                end: 3000,
760                replicaset_idx: 0,
761            },
762        ];
763        topo.merge(incoming);
764
765        let snapshot = topo.snapshot();
766        let tier = &snapshot.tiers()[0];
767        assert_eq!(tier.name(), "default");
768        let owned: Vec<_> = tier
769            .replicasets()
770            .iter()
771            .map(|rs| {
772                (
773                    rs.uuid(),
774                    rs.master().map(view::Instance::name),
775                    rs.ranges().len(),
776                )
777            })
778            .collect();
779        assert_eq!(owned, [(RS1, Some("i1"), 2), (RS2, Some("i2"), 1)]);
780        let bucket_map = tier.bucket_map().expect("map covers the tier");
781        assert_eq!(bucket_map[&RS1], [1..=1000, 2001..=3000]);
782
783        for rs in tier.replicasets() {
784            let expected = topo.instances[rs.master().expect("named master").name()].idx();
785            for r in rs.ranges() {
786                for bucket in [*r.start(), *r.end()] {
787                    assert_eq!(topo.resolve("default", bucket, true), Some(expected));
788                }
789            }
790        }
791    }
792
793    /// Without a named master routing keeps the placeholder, but `master()` is `None`.
794    #[test]
795    fn snapshot_reports_no_master_until_one_is_named() {
796        // What `Topology::from` builds when no row carries is_master.
797        let inst = Arc::new(Instance::new_for_test(
798            "i1",
799            "127.0.0.1:3301",
800            "default",
801            RS1,
802            false,
803            3000,
804        ));
805        let mut incoming = make_topology("i1", "default", RS1);
806        incoming.instances.insert(inst.name.clone(), inst.clone());
807        let rs = &mut incoming.pgproto_tiers[0].replicasets[0];
808        rs.master = inst.clone();
809        rs.replicas = vec![inst];
810        let mut topo = Topology::new();
811        topo.merge(incoming);
812
813        assert_eq!(
814            topo.resolve("default", 1, true),
815            Some(topo.instances["i1"].idx())
816        );
817        let snapshot = topo.snapshot();
818        let rs = &snapshot.tiers()[0].replicasets()[0];
819        assert_eq!(rs.master(), None);
820        let replicas: Vec<_> = rs.replicas().iter().map(view::Instance::name).collect();
821        assert_eq!(replicas, ["i1"]);
822    }
823
824    /// `instances` yields the master first, then the replicas by name.
825    #[test]
826    fn replicaset_lists_the_master_first() {
827        let mut topo = make_topology("m", "default", RS1);
828        topo.pgproto_tiers[0].replicasets[0].replicas = ["b", "a"]
829            .map(|name| {
830                Arc::new(Instance::new_for_test(
831                    name,
832                    "127.0.0.1:3302",
833                    "default",
834                    RS1,
835                    false,
836                    3000,
837                ))
838            })
839            .into();
840
841        let snapshot = topo.snapshot();
842        let rs = &snapshot.tiers()[0].replicasets()[0];
843        let instances: Vec<_> = rs.instances().map(|i| (i.name(), i.is_master())).collect();
844        assert_eq!(instances, [("m", true), ("a", false), ("b", false)]);
845    }
846
847    /// Regression: without `inc_inst.set_idx(existing.idx())` in `merge`, the
848    /// second merge replaces `self.pgproto_tiers` with `incoming.pgproto_tiers` whose
849    /// `Arc<Instance>` objects still carry the default `idx == 0`.  Every
850    /// subsequent `resolve` call would then return `Some(0)` instead of the
851    /// pool slot that was assigned during the first merge.
852    #[test]
853    fn merge_preserves_pool_idx_in_tiers() {
854        // Bump the global counter so the assigned idx is unambiguously non-zero.
855        NEXT_IDX.fetch_add(1, Ordering::Relaxed);
856
857        let mut topo = Topology::new();
858
859        // First merge: "i1" is unknown, so it receives a fresh pool-slot index.
860        topo.merge(make_topology("i1", "default", RS1));
861        let expected_idx = topo.instances["i1"].idx();
862        assert!(expected_idx > 0, "precondition: idx must be non-zero");
863
864        // Second merge: same instance name, but a brand-new Arc<Instance> with
865        // idx == 0.  Before the fix, `self.pgproto_tiers = incoming.pgproto_tiers` made the
866        // tiers point at those fresh objects, so resolve returned Some(0).
867        topo.merge(make_topology("i1", "default", RS1));
868
869        assert_eq!(
870            topo.resolve("default", 1, true),
871            Some(expected_idx),
872            "resolve must return the stable pool slot, not the default 0 from the fresh Arc"
873        );
874    }
875
876    /// Regression: `merge` kept the first-seen Arc in `instances` while the tiers got the
877    /// fresh one, so the pools and routing saw two objects with diverging fields.
878    #[test]
879    fn merge_keeps_one_object_per_instance() {
880        let mut topo = Topology::new();
881        topo.merge(make_topology("i1", "default", RS1));
882        topo.merge(make_topology("i1", "default", RS1));
883
884        let master = &topo.pgproto_tiers[0].replicasets[0].master;
885        assert!(Arc::ptr_eq(&topo.instances["i1"], master));
886    }
887
888    /// Builds a topology holding only `tier`, filed under the `iproto` connection type.
889    fn with_tier(tier: Tier) -> Topology {
890        Topology {
891            instances: HashMap::new(),
892            pgproto_tiers: Vec::new(),
893            other_tiers: HashMap::from([("iproto".to_string(), vec![tier])]),
894        }
895    }
896
897    /// Builds a one-replicaset tier whose master listens on `addr`.
898    fn tier_at(addr: &str) -> Tier {
899        let inst = Arc::new(Instance::new_for_test(
900            "i1", addr, "default", RS1, true, 3000,
901        ));
902        Tier {
903            name: "default".to_string(),
904            bucket_count: 3000,
905            replicasets: vec![Replicaset {
906                uuid: RS1,
907                master: inst,
908                replicas: vec![],
909            }],
910            bucket_map: vec![BucketSlot {
911                start: 1,
912                end: 3000,
913                replicaset_idx: 0,
914            }],
915        }
916    }
917
918    /// An instance is listed once, with the address of each connection type it accepts.
919    #[test]
920    fn snapshot_merges_the_addresses_of_an_instance() {
921        let mut topo = with_tier(tier_at("127.0.0.1:3301"));
922        topo.pgproto_tiers = vec![tier_at("127.0.0.1:5432")];
923
924        let snapshot = topo.snapshot();
925        let rs = &snapshot.tiers()[0].replicasets()[0];
926        assert!(rs.replicas().is_empty());
927        let i1 = rs.master().expect("named master");
928        assert_eq!(i1.address("pgproto"), Some("127.0.0.1:5432"));
929        assert_eq!(i1.address("iproto"), Some("127.0.0.1:3301"));
930    }
931
932    /// An instance without pgproto is still listed, and the buckets it owns still count.
933    #[test]
934    fn snapshot_keeps_an_instance_without_pgproto() {
935        let topo = with_tier(tier_at("127.0.0.1:3301"));
936
937        let snapshot = topo.snapshot();
938        let tier = &snapshot.tiers()[0];
939        let i1 = tier.replicasets()[0].master().expect("named master");
940        assert_eq!(i1.address("pgproto"), None);
941        assert_eq!(i1.address("iproto"), Some("127.0.0.1:3301"));
942        assert!(tier.bucket_map().is_ok());
943    }
944
945    /// `merge` replaces the non-pgproto tiers wholesale.
946    #[test]
947    fn merge_replaces_other_tiers() {
948        let mut topo = with_tier(tier_at("127.0.0.1:3301"));
949        topo.merge(with_tier(tier_at("127.0.0.1:3302")));
950
951        let snapshot = topo.snapshot();
952        let i1 = snapshot.tiers()[0].replicasets()[0]
953            .master()
954            .expect("named master");
955        assert_eq!(i1.address("iproto"), Some("127.0.0.1:3302"));
956    }
957
958    /// Insertion order of replicasets and replicas does not affect the snapshot.
959    #[test]
960    fn snapshot_is_independent_of_insertion_order() {
961        let inst = |name: &str, rs: Uuid, master: bool| {
962            Arc::new(Instance::new_for_test(
963                name,
964                "127.0.0.1:3301",
965                "default",
966                rs,
967                master,
968                3000,
969            ))
970        };
971        let build = |reversed: bool| {
972            let mut sets = vec![
973                (RS1, 1, 1500, vec!["a", "b"]),
974                (RS2, 1501, 3000, vec!["c", "d"]),
975            ];
976            if reversed {
977                sets.reverse();
978            }
979            let mut tier = Tier {
980                name: "default".to_string(),
981                bucket_count: 3000,
982                replicasets: Vec::new(),
983                bucket_map: Vec::new(),
984            };
985            for (idx, (uuid, start, end, mut names)) in sets.into_iter().enumerate() {
986                if reversed {
987                    names.reverse();
988                }
989                tier.replicasets.push(Replicaset {
990                    uuid,
991                    master: inst(&format!("{uuid}-m"), uuid, true),
992                    replicas: names.into_iter().map(|n| inst(n, uuid, false)).collect(),
993                });
994                tier.bucket_map.push(BucketSlot {
995                    start,
996                    end,
997                    replicaset_idx: idx,
998                });
999            }
1000            tier.bucket_map.sort_unstable_by_key(|s| s.start);
1001            let mut topo = Topology::new();
1002            topo.pgproto_tiers = vec![tier];
1003            topo.snapshot()
1004        };
1005
1006        assert_eq!(build(false), build(true));
1007    }
1008}