Skip to main content

simraft_core/
membership.rs

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