Skip to main content

simraft_core/
membership.rs

1//! Cluster configuration representation and single-server membership
2//! change rules (`AddLearner`, `PromoteVoter`, `RemoveVoter`).
3//!
4//! Every quorum decision is computed against exactly one
5//! `ClusterConfig` (invariant M-05).
6
7use crate::error::{ConfigError, ProtocolError};
8use crate::ids::LogIndex;
9use crate::ids::NodeId;
10use std::collections::BTreeSet;
11
12/// The membership of the cluster: disjoint voter and learner sets.
13///
14/// A node appears in at most one set. Learners receive replication but
15/// never vote, never start elections, and never count toward any quorum.
16#[derive(Debug, Clone, PartialEq, Eq, Default)]
17pub struct ClusterConfig {
18    /// Nodes that vote and count toward quorums.
19    pub voters: BTreeSet<NodeId>,
20    /// Nodes that replicate without voting.
21    pub learners: BTreeSet<NodeId>,
22}
23
24impl ClusterConfig {
25    /// Build a configuration from voter and learner id lists.
26    ///
27    /// # Errors
28    ///
29    /// Returns `ConfigError::EmptyVoters` when the voter list is empty
30    /// (a cluster may shrink to one voter, never to none) and
31    /// `ConfigError::OverlappingMember` when a node appears in both
32    /// `voters` and `learners`.
33    pub fn new(
34        voters: impl IntoIterator<Item = NodeId>,
35        learners: impl IntoIterator<Item = NodeId>,
36    ) -> Result<Self, ConfigError> {
37        let cfg = Self {
38            voters: voters.into_iter().collect(),
39            learners: learners.into_iter().collect(),
40        };
41        if cfg.voters.is_empty() {
42            return Err(ConfigError::EmptyVoters);
43        }
44        if let Some(&node) = cfg.voters.intersection(&cfg.learners).next() {
45            return Err(ConfigError::OverlappingMember { node });
46        }
47        Ok(cfg)
48    }
49
50    /// The number of voters that makes a quorum of this configuration.
51    #[must_use]
52    pub fn quorum(&self) -> usize {
53        self.voters.len() / 2 + 1
54    }
55
56    /// Whether `id` may vote in this configuration.
57    #[must_use]
58    pub fn is_voter(&self, id: NodeId) -> bool {
59        self.voters.contains(&id)
60    }
61
62    /// Whether `id` is a member in either role.
63    #[must_use]
64    pub fn contains(&self, id: NodeId) -> bool {
65        self.voters.contains(&id) || self.learners.contains(&id)
66    }
67
68    /// Every member, voters and learners, in ascending id order.
69    pub fn members(&self) -> impl Iterator<Item = NodeId> + '_ {
70        self.voters.union(&self.learners).copied()
71    }
72}
73
74/// One single-server membership change (docs/ARCHITECTURE.md section
75/// 9). Each change is carried by exactly one config log entry; at most
76/// one change is ever uncommitted (invariant M-01).
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum ConfigChange {
79    /// The node joins as a learner: it receives replication and
80    /// snapshots but never votes and never counts toward a quorum.
81    AddLearner {
82        /// The node joining as a learner.
83        node: NodeId,
84    },
85    /// A caught-up learner becomes a voter.
86    PromoteVoter {
87        /// The learner being promoted.
88        node: NodeId,
89    },
90    /// A voter or learner leaves the cluster.
91    RemoveVoter {
92        /// The member being removed.
93        node: NodeId,
94    },
95}
96
97impl ClusterConfig {
98    /// The configuration produced by applying `change` to this one.
99    ///
100    /// This checks the set-level rules only (who may be added,
101    /// promoted, or removed). The leader-side rules that need log
102    /// state (one uncommitted change, the `NoOp` gate, promotion
103    /// catch-up) are enforced by `Node` before it appends the entry.
104    ///
105    /// # Errors
106    ///
107    /// Returns the `ProtocolError` naming the rule the change breaks.
108    pub fn apply_change(&self, change: ConfigChange) -> Result<Self, ProtocolError> {
109        let mut next = self.clone();
110        match change {
111            ConfigChange::AddLearner { node } => {
112                if self.voters.contains(&node) {
113                    return Err(ProtocolError::AlreadyVoter { node });
114                }
115                next.learners.insert(node);
116            }
117            ConfigChange::PromoteVoter { node } => {
118                if self.voters.contains(&node) {
119                    return Err(ProtocolError::AlreadyVoter { node });
120                }
121                if !self.learners.contains(&node) {
122                    return Err(ProtocolError::NotLearner { node });
123                }
124                next.learners.remove(&node);
125                next.voters.insert(node);
126            }
127            ConfigChange::RemoveVoter { node } => {
128                if self.voters.contains(&node) {
129                    if self.voters.len() == 1 {
130                        return Err(ProtocolError::LastVoterRemoval { node });
131                    }
132                    next.voters.remove(&node);
133                } else if self.learners.contains(&node) {
134                    next.learners.remove(&node);
135                } else {
136                    return Err(ProtocolError::NotMember { node });
137                }
138            }
139        }
140        Ok(next)
141    }
142}
143
144/// The node's view of cluster membership (section 5.3).
145///
146/// Holds the newest configuration whose entry exists in the log, the
147/// newest committed configuration, and the index of the newest
148/// config entry. Every quorum decision uses exactly one of these
149/// configurations, never a blend (invariant M-05).
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct ConfigState {
152    /// The newest configuration from the log, committed or not.
153    pub latest: ClusterConfig,
154    /// The newest committed configuration.
155    pub committed: ClusterConfig,
156    /// The log index of the newest config entry, or 0 when the log
157    /// holds no config entry (the construction configuration rules).
158    pub last_config_index: LogIndex,
159}
160
161impl ConfigState {
162    /// A state where the construction configuration is both the
163    /// latest and the committed configuration.
164    #[must_use]
165    pub fn new(initial: ClusterConfig) -> Self {
166        Self {
167            committed: initial.clone(),
168            latest: initial,
169            last_config_index: LogIndex::ZERO,
170        }
171    }
172}