1use crate::action::{Action, ClientResult, ConfigResult};
16use crate::config::Config;
17use crate::error::{ConfigError, ProtocolError};
18use crate::event::{Event, PersistKind};
19use crate::ids::{ClientId, LogIndex, NodeId, Term, Tick};
20use crate::log::{EntryKind, Log, LogEntry};
21use crate::membership::{ClusterConfig, ConfigChange, ConfigState};
22use crate::message::Message;
23use crate::snapshot::{IncomingSnapshot, LoadedSnapshot, SnapshotMeta};
24use std::collections::{BTreeMap, BTreeSet};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Role {
30 Follower,
32 PreCandidate,
35 Candidate,
37 Leader,
39}
40
41#[derive(Debug, Clone, Copy, Default)]
43pub(crate) struct Progress {
44 pub next_index: LogIndex,
46 pub match_index: LogIndex,
49 pub snapshot: Option<(LogIndex, Term, u64)>,
54}
55
56#[derive(Debug, Clone)]
59pub(crate) struct PendingAction {
60 pub need_hard_gen: u64,
62 pub need_entries_up_to: LogIndex,
64 pub term: Term,
69 pub action: Action,
71}
72
73#[derive(Debug, Clone)]
78pub(crate) struct ReadBatch {
79 pub round: u64,
81 pub gate_index: LogIndex,
83 pub acks: BTreeSet<NodeId>,
85 pub requests: Vec<(u64, Vec<u8>)>,
87}
88
89#[derive(Debug)]
91pub struct Node {
92 pub(crate) id: NodeId,
93 pub(crate) config: Config,
94 pub(crate) config_state: ConfigState,
95 pub(crate) initial_config: ClusterConfig,
96 pub(crate) base_config: ClusterConfig,
97 pub(crate) pending_config: Option<(LogIndex, ConfigChange)>,
98 pub(crate) pending_install: Option<SnapshotMeta>,
99 pub(crate) seed: u64,
100 pub(crate) role: Role,
101 pub(crate) current_term: Term,
102 pub(crate) voted_for: Option<NodeId>,
103 pub(crate) log: Log,
104 pub(crate) commit_index: LogIndex,
105 pub(crate) last_applied: LogIndex,
106 pub(crate) leader_id: Option<NodeId>,
107 pub(crate) now: Tick,
108 pub(crate) election_deadline: Tick,
109 pub(crate) heartbeat_deadline: Tick,
110 pub(crate) election_epoch: u64,
111 pub(crate) last_leader_contact: Option<Tick>,
112 pub(crate) prevote_term: Term,
113 pub(crate) prevotes_received: BTreeSet<NodeId>,
114 pub(crate) votes_received: BTreeSet<NodeId>,
115 pub(crate) progress: BTreeMap<NodeId, Progress>,
116 pub(crate) pending: Vec<PendingAction>,
117 pub(crate) read_round_counter: u64,
118 pub(crate) pending_reads: Option<ReadBatch>,
119 pub(crate) last_read_round: u64,
120 pub(crate) inflight: BTreeMap<(ClientId, u64), LogIndex>,
121 pub(crate) attached: BTreeMap<LogIndex, u64>,
122 #[allow(
123 dead_code,
124 reason = "M3 Stage A contract state; the Stage B chunk handler consumes it"
125 )]
126 pub(crate) incoming_snapshot: Option<IncomingSnapshot>,
127 pub(crate) loaded_snapshot: Option<LoadedSnapshot>,
128 pub(crate) hard_gen_sent: u64,
129 pub(crate) hard_gen_acked: u64,
130 pub(crate) entries_durable_up_to: LogIndex,
131}
132
133impl Node {
134 pub fn new(
145 id: NodeId,
146 config: Config,
147 cluster: ClusterConfig,
148 seed: u64,
149 ) -> Result<Self, ConfigError> {
150 config.validate()?;
151 let mut node = Self {
152 id,
153 config,
154 config_state: ConfigState::new(cluster.clone()),
155 initial_config: cluster.clone(),
156 base_config: cluster,
157 pending_config: None,
158 pending_install: None,
159 seed,
160 role: Role::Follower,
161 current_term: Term::ZERO,
162 voted_for: None,
163 log: Log::new(),
164 commit_index: LogIndex::ZERO,
165 last_applied: LogIndex::ZERO,
166 leader_id: None,
167 now: 0,
168 election_deadline: 0,
169 heartbeat_deadline: 0,
170 election_epoch: 0,
171 last_leader_contact: None,
172 prevote_term: Term::ZERO,
173 prevotes_received: BTreeSet::new(),
174 votes_received: BTreeSet::new(),
175 progress: BTreeMap::new(),
176 pending: Vec::new(),
177 read_round_counter: 0,
178 pending_reads: None,
179 last_read_round: 0,
180 inflight: BTreeMap::new(),
181 attached: BTreeMap::new(),
182 incoming_snapshot: None,
183 loaded_snapshot: None,
184 hard_gen_sent: 0,
185 hard_gen_acked: 0,
186 entries_durable_up_to: LogIndex::ZERO,
187 };
188 node.reset_election_deadline();
189 Ok(node)
190 }
191
192 #[must_use]
194 pub const fn id(&self) -> NodeId {
195 self.id
196 }
197
198 #[must_use]
200 pub const fn role(&self) -> Role {
201 self.role
202 }
203
204 #[must_use]
206 pub const fn current_term(&self) -> Term {
207 self.current_term
208 }
209
210 #[must_use]
212 pub const fn voted_for(&self) -> Option<NodeId> {
213 self.voted_for
214 }
215
216 #[must_use]
218 pub const fn commit_index(&self) -> LogIndex {
219 self.commit_index
220 }
221
222 #[must_use]
224 pub const fn last_applied(&self) -> LogIndex {
225 self.last_applied
226 }
227
228 #[must_use]
230 pub const fn log(&self) -> &Log {
231 &self.log
232 }
233
234 #[must_use]
236 pub const fn cluster(&self) -> &ClusterConfig {
237 &self.config_state.latest
238 }
239
240 #[must_use]
245 pub const fn last_config_index(&self) -> LogIndex {
246 self.config_state.last_config_index
247 }
248
249 #[must_use]
251 pub const fn leader_id(&self) -> Option<NodeId> {
252 self.leader_id
253 }
254
255 #[must_use]
259 pub fn progress(&self, peer: NodeId) -> Option<(LogIndex, LogIndex)> {
260 self.progress
261 .get(&peer)
262 .map(|p| (p.next_index, p.match_index))
263 }
264
265 #[must_use]
270 pub const fn poll_timeout(&self) -> Option<Tick> {
271 match self.role {
272 Role::Leader => Some(self.heartbeat_deadline),
273 _ => Some(self.election_deadline),
274 }
275 }
276
277 pub fn step(&mut self, event: Event) -> Vec<Action> {
280 let mut out = Vec::new();
281 match event {
282 Event::Tick { now } => self.on_tick(now, &mut out),
283 Event::Propose {
284 client_id,
285 seq,
286 payload,
287 } => self.on_propose(client_id, seq, payload, &mut out),
288 Event::ReadIndex { request_id, key } => {
289 self.on_read_index(request_id, key, &mut out);
290 }
291 Event::ProposeConfig { change } => self.on_propose_config(change, &mut out),
292 Event::SnapshotLoaded { meta, data } => {
293 self.loaded_snapshot = Some(LoadedSnapshot { meta, data });
294 }
295 Event::SnapshotPersisted { meta } => self.on_snapshot_persisted(&meta),
296 Event::Message { from, msg } => self.on_message(from, msg, &mut out),
297 Event::Persisted { kind, up_to_index } => {
298 self.on_persisted(kind, up_to_index, &mut out);
299 }
300 Event::Restored {
301 hard_state,
302 entries,
303 snapshot,
304 } => self.on_restored(
305 hard_state.current_term,
306 hard_state.voted_for,
307 &entries,
308 snapshot.as_ref(),
309 ),
310 }
311 out
312 }
313
314 pub(crate) const fn timer_offset(&self) -> u64 {
319 let span = self
320 .config
321 .max_election_timeout
322 .saturating_sub(self.config.min_election_timeout);
323 if span == 0 {
324 return 0;
325 }
326 splitmix64(
327 self.seed
328 ^ self.id.0.wrapping_mul(0x9E37_79B9_7F4A_7C15)
329 ^ self.election_epoch.wrapping_mul(0xBF58_476D_1CE4_E5B9),
330 ) % span
331 }
332
333 pub(crate) const fn reset_election_deadline(&mut self) {
336 self.election_epoch += 1;
337 self.election_deadline = self
338 .now
339 .saturating_add(self.config.min_election_timeout)
340 .saturating_add(self.timer_offset());
341 }
342
343 fn emit_persist_hard(&mut self, out: &mut Vec<Action>) -> u64 {
348 self.hard_gen_sent += 1;
349 out.push(Action::PersistHardState {
350 current_term: self.current_term,
351 voted_for: self.voted_for,
352 });
353 self.hard_gen_sent
354 }
355
356 fn defer_or_emit(
359 &mut self,
360 out: &mut Vec<Action>,
361 action: Action,
362 need_hard_gen: u64,
363 need_entries_up_to: LogIndex,
364 ) {
365 if need_hard_gen <= self.hard_gen_acked && need_entries_up_to <= self.entries_durable_up_to
366 {
367 out.push(action);
368 } else {
369 self.pending.push(PendingAction {
370 need_hard_gen,
371 need_entries_up_to,
372 term: self.current_term,
373 action,
374 });
375 }
376 }
377
378 fn flush_pending(&mut self, out: &mut Vec<Action>) {
382 let pending = std::mem::take(&mut self.pending);
383 for held in pending {
384 let stale_send =
385 matches!(held.action, Action::Send { .. }) && held.term != self.current_term;
386 if stale_send {
387 continue;
388 }
389 if held.need_hard_gen <= self.hard_gen_acked
390 && held.need_entries_up_to <= self.entries_durable_up_to
391 {
392 out.push(held.action);
393 } else {
394 self.pending.push(held);
395 }
396 }
397 }
398
399 fn on_persisted(&mut self, kind: PersistKind, up_to_index: LogIndex, out: &mut Vec<Action>) {
400 match kind {
401 PersistKind::HardState => {
402 self.hard_gen_acked = self
403 .hard_gen_acked
404 .saturating_add(1)
405 .min(self.hard_gen_sent);
406 }
407 PersistKind::Entries => {
408 if up_to_index > self.entries_durable_up_to {
409 self.entries_durable_up_to = up_to_index;
410 }
411 }
412 }
413 self.flush_pending(out);
414 }
415
416 fn on_restored(
417 &mut self,
418 term: Term,
419 voted_for: Option<NodeId>,
420 entries: &[LogEntry],
421 snapshot: Option<&SnapshotMeta>,
422 ) {
423 self.current_term = term;
424 self.voted_for = voted_for;
425 self.log = Log::new();
426 if let Some(meta) = snapshot {
433 self.log
434 .advance_base(meta.last_included_index, meta.last_included_term);
435 }
436 self.log.append(entries);
437 self.role = Role::Follower;
438 self.commit_index = LogIndex::ZERO;
439 self.last_applied = LogIndex::ZERO;
440 self.leader_id = None;
441 self.last_leader_contact = None;
442 self.progress.clear();
443 self.pending.clear();
444 self.pending_reads = None;
445 self.last_read_round = 0;
446 self.inflight.clear();
447 self.attached.clear();
448 self.votes_received.clear();
449 self.prevotes_received.clear();
450 self.base_config = self.initial_config.clone();
451 self.pending_config = None;
452 self.pending_install = None;
453 self.incoming_snapshot = None;
454 self.loaded_snapshot = None;
455 self.recompute_config();
456 if let Some(meta) = snapshot {
464 self.install_snapshot(meta);
465 }
466 self.entries_durable_up_to = self.log.last_index();
467 self.hard_gen_sent += 1;
468 self.hard_gen_acked = self.hard_gen_sent;
469 self.reset_election_deadline();
470 }
471
472 fn set_term(&mut self, term: Term, out: &mut Vec<Action>) {
477 if self.role == Role::Leader {
478 out.push(Action::StepDown { term });
479 self.fail_pending_reads(out);
480 }
481 self.role = Role::Follower;
482 self.current_term = term;
483 self.voted_for = None;
484 self.leader_id = None;
485 self.progress.clear();
486 self.votes_received.clear();
487 self.prevotes_received.clear();
488 self.inflight.clear();
489 self.attached.clear();
490 self.pending_config = None;
491 self.last_read_round = 0;
492 }
493
494 fn recompute_config(&mut self) {
501 let mut latest = self.base_config.clone();
502 let mut committed = self.base_config.clone();
503 let mut last_config_index = if self.log.base_index() > LogIndex::ZERO {
504 self.log.base_index()
505 } else {
506 LogIndex::ZERO
507 };
508 let base = self.log.base_index().0;
509 for (offset, entry) in self.log.entries().iter().enumerate() {
510 if let EntryKind::Config { config } = &entry.kind {
511 let index = LogIndex(base + 1 + offset as u64);
512 latest = config.clone();
513 last_config_index = index;
514 if index <= self.commit_index {
515 committed = config.clone();
516 }
517 }
518 }
519 self.config_state = ConfigState {
520 latest,
521 committed,
522 last_config_index,
523 };
524 }
525
526 fn step_down_after_removal(&mut self, out: &mut Vec<Action>) {
530 out.push(Action::StepDown {
531 term: self.current_term,
532 });
533 self.fail_pending_reads(out);
534 self.role = Role::Follower;
535 self.leader_id = None;
536 self.progress.clear();
537 self.inflight.clear();
538 self.attached.clear();
539 }
540
541 fn on_config_applied(
545 &mut self,
546 index: LogIndex,
547 config: &ClusterConfig,
548 out: &mut Vec<Action>,
549 ) {
550 self.recompute_config();
551 if let Some((pending_index, change)) = self.pending_config.take() {
552 if pending_index == index {
553 self.defer_or_emit(
554 out,
555 Action::ConfigResponse {
556 change,
557 result: ConfigResult::Committed,
558 },
559 0,
560 index,
561 );
562 } else {
563 self.pending_config = Some((pending_index, change));
564 }
565 }
566 if self.role != Role::Leader {
567 return;
568 }
569 let next = self.log.last_index().next();
570 for member in config.members() {
571 if member != self.id && !self.progress.contains_key(&member) {
572 self.progress.insert(
573 member,
574 Progress {
575 next_index: next,
576 match_index: LogIndex::ZERO,
577 snapshot: None,
578 },
579 );
580 }
581 }
582 self.progress.retain(|peer, _| config.contains(*peer));
583 if !config.is_voter(self.id) {
584 self.step_down_after_removal(out);
585 }
586 }
587
588 fn fail_pending_reads(&mut self, out: &mut Vec<Action>) {
591 if let Some(batch) = self.pending_reads.take() {
592 for (request_id, _key) in batch.requests {
593 out.push(Action::ReadRejected {
594 request_id,
595 leader: None,
596 });
597 }
598 }
599 }
600
601 fn try_release_reads(&mut self, out: &mut Vec<Action>) {
606 let Some(batch) = &self.pending_reads else {
607 return;
608 };
609 if batch.acks.len() < self.config_state.latest.quorum()
610 || self.commit_index < batch.gate_index
611 {
612 return;
613 }
614 let read_index = self.commit_index;
615 let batch = self.pending_reads.take().expect("batch checked above");
616 for (request_id, key) in batch.requests {
617 out.push(Action::ReadReady {
618 request_id,
619 key,
620 read_index,
621 });
622 }
623 }
624
625 fn log_up_to_date(&self, last_term: Term, last_index: LogIndex) -> bool {
628 let my_term = self.log.last_term();
629 last_term > my_term || (last_term == my_term && last_index >= self.log.last_index())
630 }
631
632 fn start_prevote(&mut self, out: &mut Vec<Action>) {
633 self.role = Role::PreCandidate;
634 self.leader_id = None;
635 self.prevote_term = self.current_term.next();
636 self.prevotes_received = BTreeSet::from([self.id]);
637 self.reset_election_deadline();
638 if self.prevotes_received.len() >= self.config_state.latest.quorum() {
639 self.start_election(out);
640 return;
641 }
642 let msg = Message::RequestPreVote {
643 term: self.prevote_term,
644 last_log_index: self.log.last_index(),
645 last_log_term: self.log.last_term(),
646 };
647 for voter in self.config_state.latest.voters.iter().copied() {
648 if voter != self.id {
649 out.push(Action::Send {
650 to: voter,
651 msg: msg.clone(),
652 });
653 }
654 }
655 }
656
657 fn start_election(&mut self, out: &mut Vec<Action>) {
658 self.role = Role::Candidate;
659 self.current_term = self.prevote_term;
660 self.voted_for = Some(self.id);
661 self.votes_received = BTreeSet::from([self.id]);
662 self.reset_election_deadline();
663 let generation = self.emit_persist_hard(out);
664 if self.votes_received.len() >= self.config_state.latest.quorum() {
665 self.become_leader(out);
666 return;
667 }
668 let msg = Message::RequestVote {
669 term: self.current_term,
670 last_log_index: self.log.last_index(),
671 last_log_term: self.log.last_term(),
672 };
673 let voters: Vec<NodeId> = self.config_state.latest.voters.iter().copied().collect();
674 for voter in voters {
675 if voter != self.id {
676 self.defer_or_emit(
677 out,
678 Action::Send {
679 to: voter,
680 msg: msg.clone(),
681 },
682 generation,
683 LogIndex::ZERO,
684 );
685 }
686 }
687 }
688
689 fn become_leader(&mut self, out: &mut Vec<Action>) {
690 self.role = Role::Leader;
691 self.leader_id = Some(self.id);
692 self.last_leader_contact = Some(self.now);
693 self.heartbeat_deadline = self.now.saturating_add(self.config.heartbeat_interval);
694 let next = self.log.last_index().next();
695 self.progress = self
696 .config_state
697 .latest
698 .members()
699 .filter(|&m| m != self.id)
700 .map(|m| {
701 (
702 m,
703 Progress {
704 next_index: next,
705 match_index: LogIndex::ZERO,
706 snapshot: None,
707 },
708 )
709 })
710 .collect();
711 let entries = vec![LogEntry {
714 term: self.current_term,
715 kind: EntryKind::NoOp,
716 }];
717 let first = self.log.append(&entries);
718 out.push(Action::PersistEntries {
719 from_index: first,
720 entries,
721 });
722 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
723 for peer in peers {
724 self.send_append(peer, out);
725 }
726 }
727
728 fn on_tick(&mut self, now: Tick, out: &mut Vec<Action>) {
731 self.now = self.now.max(now);
732 match self.role {
733 Role::Leader => {
734 if self.now >= self.heartbeat_deadline {
735 self.heartbeat_deadline =
736 self.now.saturating_add(self.config.heartbeat_interval);
737 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
738 for peer in peers {
739 self.send_append(peer, out);
740 }
741 }
742 }
743 Role::Follower | Role::PreCandidate | Role::Candidate => {
744 if self.now >= self.election_deadline && self.config_state.latest.is_voter(self.id)
745 {
746 self.start_prevote(out);
747 }
748 }
749 }
750 }
751
752 fn on_read_index(&mut self, request_id: u64, key: Vec<u8>, out: &mut Vec<Action>) {
757 if self.role != Role::Leader {
758 out.push(Action::ReadRejected {
759 request_id,
760 leader: self.leader_id,
761 });
762 return;
763 }
764 if let Some(batch) = &mut self.pending_reads {
765 batch.requests.push((request_id, key));
766 return;
767 }
768 let Some(gate_index) = self.log.first_index_of_term(self.current_term) else {
769 out.push(Action::ReadRejected {
772 request_id,
773 leader: self.leader_id,
774 });
775 return;
776 };
777 self.read_round_counter += 1;
778 let mut acks = BTreeSet::new();
779 acks.insert(self.id);
780 self.pending_reads = Some(ReadBatch {
781 round: self.read_round_counter,
782 gate_index,
783 acks,
784 requests: vec![(request_id, key)],
785 });
786 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
787 for peer in peers {
788 self.send_append(peer, out);
789 }
790 self.try_release_reads(out);
791 }
792
793 fn on_propose(
794 &mut self,
795 client_id: ClientId,
796 seq: u64,
797 payload: Vec<u8>,
798 out: &mut Vec<Action>,
799 ) {
800 if self.role != Role::Leader {
801 out.push(Action::ClientResponse {
802 client_id,
803 seq,
804 result: ClientResult::NotLeader {
805 leader: self.leader_id,
806 },
807 });
808 return;
809 }
810 if let Some(&index) = self.inflight.get(&(client_id, seq)) {
814 if index > self.commit_index {
815 *self.attached.entry(index).or_insert(0) += 1;
816 return;
817 }
818 }
819 let entry = LogEntry {
820 term: self.current_term,
821 kind: EntryKind::Command {
822 client_id,
823 seq,
824 payload,
825 },
826 };
827 let entries = vec![entry];
828 let first = self.log.append(&entries);
829 self.inflight.insert((client_id, seq), first);
830 out.push(Action::PersistEntries {
831 from_index: first,
832 entries,
833 });
834 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
835 for peer in peers {
836 self.send_append(peer, out);
837 }
838 }
839
840 fn build_append(&self, peer: NodeId, read_round: u64) -> Message {
845 let next = self
846 .progress
847 .get(&peer)
848 .map_or_else(|| self.log.last_index().next(), |p| p.next_index);
849 let prev = LogIndex(next.0.saturating_sub(1));
850 let prev_term = self.log.term_at(prev).unwrap_or(Term::ZERO);
851 let entries = self.log.entries_from(
852 next,
853 self.config.max_entries_per_append,
854 self.config.max_append_bytes,
855 );
856 Message::AppendEntries {
857 term: self.current_term,
858 prev_log_index: prev,
859 prev_log_term: prev_term,
860 entries,
861 leader_commit: self.commit_index,
862 read_round,
863 }
864 }
865
866 fn send_append(&mut self, peer: NodeId, out: &mut Vec<Action>) {
869 let next = self
873 .progress
874 .get(&peer)
875 .map_or_else(|| self.log.last_index().next(), |prog| prog.next_index);
876 if self.log.base_index() > LogIndex::ZERO && next <= self.log.base_index() {
877 self.send_snapshot_chunk(peer, out);
878 return;
879 }
880 let round = self.pending_reads.as_ref().map_or(0, |batch| batch.round);
881 let msg = self.build_append(peer, round);
882 let mut need = LogIndex::ZERO;
883 if let Message::AppendEntries {
884 prev_log_index,
885 entries,
886 ..
887 } = &msg
888 {
889 if !entries.is_empty() {
890 need = LogIndex(prev_log_index.0 + entries.len() as u64);
891 }
892 }
893 self.defer_or_emit(out, Action::Send { to: peer, msg }, 0, need);
894 }
895
896 fn base_meta(&self) -> SnapshotMeta {
898 SnapshotMeta {
899 last_included_index: self.log.base_index(),
900 last_included_term: self.log.base_term(),
901 config: self.base_config.clone(),
902 }
903 }
904
905 fn send_snapshot_chunk(&mut self, peer: NodeId, out: &mut Vec<Action>) {
916 let meta = self.base_meta();
917 let Some(loaded) = &self.loaded_snapshot else {
918 out.push(Action::LoadSnapshot { meta });
919 return;
920 };
921 if loaded.meta != meta {
922 out.push(Action::LoadSnapshot { meta });
923 return;
924 }
925 let loaded = loaded.clone();
926 let chunk = self.config.snapshot_chunk_bytes;
927 let Some(prog) = self.progress.get_mut(&peer) else {
928 return;
929 };
930 let offset = match prog.snapshot {
931 Some((index, term, next_offset))
932 if index == meta.last_included_index
933 && term == meta.last_included_term
934 && next_offset > 0
935 && next_offset < loaded.data.len() as u64 =>
936 {
937 next_offset
938 }
939 _ => 0,
940 };
941 let start = usize::try_from(offset)
942 .unwrap_or(usize::MAX)
943 .min(loaded.data.len());
944 let end = start.saturating_add(chunk).min(loaded.data.len());
945 let done = end == loaded.data.len();
946 prog.snapshot = Some((
947 meta.last_included_index,
948 meta.last_included_term,
949 end as u64,
950 ));
951 out.push(Action::Send {
952 to: peer,
953 msg: Message::InstallSnapshot {
954 term: self.current_term,
955 last_included_index: meta.last_included_index,
956 last_included_term: meta.last_included_term,
957 config: meta.config,
958 offset,
959 data: loaded.data[start..end].to_vec(),
960 done,
961 },
962 });
963 }
964
965 #[allow(
971 clippy::too_many_arguments,
972 reason = "one argument per InstallSnapshot field keeps the handler aligned with the message layout"
973 )]
974 fn on_install_snapshot(
975 &mut self,
976 from: NodeId,
977 term: Term,
978 meta: SnapshotMeta,
979 offset: u64,
980 data: &[u8],
981 done: bool,
982 out: &mut Vec<Action>,
983 ) {
984 let respond = |out: &mut Vec<Action>, term: Term, match_index: LogIndex| {
985 out.push(Action::Send {
986 to: from,
987 msg: Message::InstallSnapshotResponse { term, match_index },
988 });
989 };
990 if term < self.current_term {
991 respond(out, self.current_term, self.log.base_index());
992 return;
993 }
994 if term > self.current_term {
995 self.set_term(term, out);
996 let _ = self.emit_persist_hard(out);
997 } else if self.role == Role::Leader {
998 out.push(Action::StepDown { term });
999 self.fail_pending_reads(out);
1000 self.role = Role::Follower;
1001 self.progress.clear();
1002 self.inflight.clear();
1003 self.attached.clear();
1004 self.pending_config = None;
1005 } else {
1006 self.role = Role::Follower;
1007 }
1008 self.leader_id = Some(from);
1009 self.last_leader_contact = Some(self.now);
1010 self.reset_election_deadline();
1011
1012 if meta.last_included_index <= self.log.base_index() {
1014 respond(out, self.current_term, self.log.base_index());
1015 return;
1016 }
1017 let fresh = self
1020 .incoming_snapshot
1021 .as_ref()
1022 .is_none_or(|incoming| incoming.meta != meta);
1023 if fresh {
1024 self.incoming_snapshot = Some(IncomingSnapshot::new(meta.clone()));
1025 }
1026 let expected = self
1027 .incoming_snapshot
1028 .as_ref()
1029 .map_or(0, IncomingSnapshot::expected_offset);
1030 if offset != expected {
1031 respond(out, self.current_term, self.log.base_index());
1037 return;
1038 }
1039 if let Some(incoming) = &mut self.incoming_snapshot {
1040 incoming.data.extend_from_slice(data);
1041 }
1042 if done {
1043 if let Some(incoming) = self.incoming_snapshot.take() {
1044 self.pending_install = Some(meta.clone());
1045 out.push(Action::PersistSnapshot {
1046 meta,
1047 data: incoming.data,
1048 });
1049 }
1050 }
1051 respond(out, self.current_term, self.log.base_index());
1052 }
1053
1054 fn on_snapshot_response(
1058 &mut self,
1059 from: NodeId,
1060 term: Term,
1061 match_index: LogIndex,
1062 out: &mut Vec<Action>,
1063 ) {
1064 if term > self.current_term {
1065 self.set_term(term, out);
1066 let _ = self.emit_persist_hard(out);
1067 return;
1068 }
1069 if self.role != Role::Leader || term < self.current_term {
1070 return;
1071 }
1072 let mut advance = false;
1073 if let Some(prog) = self.progress.get_mut(&from) {
1074 if match_index > prog.match_index {
1075 prog.match_index = match_index;
1076 advance = true;
1077 }
1078 if prog.next_index < prog.match_index.next() {
1079 prog.next_index = prog.match_index.next();
1080 }
1081 if match_index >= self.log.base_index() {
1082 prog.snapshot = None;
1083 }
1084 }
1085 if advance {
1086 self.advance_commit(out);
1087 }
1088 }
1089
1090 fn on_snapshot_persisted(&mut self, meta: &SnapshotMeta) {
1096 if self.pending_install.as_ref() == Some(meta) {
1097 self.pending_install = None;
1098 self.install_snapshot(meta);
1099 return;
1100 }
1101 if let Some(loaded) = &self.loaded_snapshot {
1102 if loaded.meta == *meta && meta.last_included_index <= self.commit_index {
1103 self.install_snapshot(meta);
1104 }
1105 }
1106 }
1107
1108 fn install_snapshot(&mut self, meta: &SnapshotMeta) {
1113 let index = meta.last_included_index;
1114 if index < self.log.base_index() {
1115 return;
1116 }
1117 if self.log.term_at(index) != Some(meta.last_included_term) {
1118 self.log.clear_entries();
1119 }
1120 self.log.advance_base(index, meta.last_included_term);
1121 if self.commit_index < index {
1122 self.commit_index = index;
1123 }
1124 if self.last_applied < index {
1125 self.last_applied = index;
1126 }
1127 self.base_config = meta.config.clone();
1128 self.inflight.retain(|_, entry_index| *entry_index > index);
1129 self.attached.retain(|entry_index, _| *entry_index > index);
1130 if let Some(incoming) = &self.incoming_snapshot {
1131 if incoming.meta.last_included_index <= index {
1132 self.incoming_snapshot = None;
1133 }
1134 }
1135 self.recompute_config();
1136 }
1137
1138 fn advance_commit(&mut self, out: &mut Vec<Action>) {
1142 let mut held: Vec<u64> = self
1143 .config_state
1144 .latest
1145 .voters
1146 .iter()
1147 .map(|&v| {
1148 if v == self.id {
1149 self.log.last_index().0
1150 } else {
1151 self.progress.get(&v).map_or(0, |p| p.match_index.0)
1152 }
1153 })
1154 .collect();
1155 held.sort_unstable();
1156 let quorum = self.config_state.latest.quorum();
1157 let candidate = LogIndex(held[held.len() - quorum]);
1158 if candidate > self.commit_index && self.log.term_at(candidate) == Some(self.current_term) {
1159 self.commit_index = candidate;
1160 self.emit_applies(out);
1161 self.try_release_reads(out);
1162 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
1163 for peer in peers {
1164 self.send_append(peer, out);
1165 }
1166 }
1167 }
1168
1169 fn emit_applies(&mut self, out: &mut Vec<Action>) {
1173 while self.last_applied < self.commit_index {
1174 self.last_applied = self.last_applied.next();
1175 let index = self.last_applied;
1176 let Some(entry) = self.log.entry_at(index).cloned() else {
1177 break;
1178 };
1179 self.defer_or_emit(
1180 out,
1181 Action::Apply {
1182 index,
1183 entry: entry.clone(),
1184 },
1185 0,
1186 index,
1187 );
1188 if let EntryKind::Config { config } = &entry.kind {
1189 let config = config.clone();
1190 self.on_config_applied(index, &config, out);
1191 }
1192 if let EntryKind::Command { client_id, seq, .. } = entry.kind {
1193 self.defer_or_emit(
1194 out,
1195 Action::ClientResponse {
1196 client_id,
1197 seq,
1198 result: ClientResult::Committed,
1199 },
1200 0,
1201 index,
1202 );
1203 self.inflight.remove(&(client_id, seq));
1208 if let Some(extra) = self.attached.remove(&index) {
1209 for _ in 0..extra {
1210 self.defer_or_emit(
1211 out,
1212 Action::ClientResponse {
1213 client_id,
1214 seq,
1215 result: ClientResult::Committed,
1216 },
1217 0,
1218 index,
1219 );
1220 }
1221 }
1222 }
1223 }
1224 }
1225
1226 fn on_message(&mut self, from: NodeId, msg: Message, out: &mut Vec<Action>) {
1229 match msg {
1230 Message::RequestVote {
1231 term,
1232 last_log_index,
1233 last_log_term,
1234 } => self.on_request_vote(from, term, last_log_index, last_log_term, out),
1235 Message::RequestVoteResponse { term, vote_granted } => {
1236 self.on_vote_response(from, term, vote_granted, out);
1237 }
1238 Message::RequestPreVote {
1239 term,
1240 last_log_index,
1241 last_log_term,
1242 } => self.on_request_prevote(from, term, last_log_index, last_log_term, out),
1243 Message::RequestPreVoteResponse { term, vote_granted } => {
1244 self.on_prevote_response(from, term, vote_granted, out);
1245 }
1246 Message::AppendEntries {
1247 term,
1248 prev_log_index,
1249 prev_log_term,
1250 entries,
1251 leader_commit,
1252 read_round,
1253 } => self.on_append_entries(
1254 from,
1255 term,
1256 prev_log_index,
1257 prev_log_term,
1258 &entries,
1259 leader_commit,
1260 read_round,
1261 out,
1262 ),
1263 Message::AppendEntriesResponse {
1264 term,
1265 success,
1266 match_index,
1267 conflict_index,
1268 conflict_term,
1269 read_round,
1270 } => self.on_append_response(
1271 from,
1272 term,
1273 success,
1274 match_index,
1275 conflict_index,
1276 conflict_term,
1277 read_round,
1278 out,
1279 ),
1280 Message::InstallSnapshot {
1281 term,
1282 last_included_index,
1283 last_included_term,
1284 config,
1285 offset,
1286 data,
1287 done,
1288 } => self.on_install_snapshot(
1289 from,
1290 term,
1291 SnapshotMeta {
1292 last_included_index,
1293 last_included_term,
1294 config,
1295 },
1296 offset,
1297 &data,
1298 done,
1299 out,
1300 ),
1301 Message::InstallSnapshotResponse { term, match_index } => {
1302 self.on_snapshot_response(from, term, match_index, out);
1303 }
1304 }
1305 }
1306
1307 fn on_propose_config(&mut self, change: ConfigChange, out: &mut Vec<Action>) {
1315 let reject = |out: &mut Vec<Action>, error: ProtocolError| {
1316 out.push(Action::ConfigResponse {
1317 change,
1318 result: ConfigResult::Rejected { error },
1319 });
1320 };
1321 if self.role != Role::Leader {
1322 out.push(Action::ConfigResponse {
1323 change,
1324 result: ConfigResult::NotLeader {
1325 leader: self.leader_id,
1326 },
1327 });
1328 return;
1329 }
1330 if let Some(noop_index) = self.log.first_index_of_term(self.current_term) {
1331 if self.commit_index < noop_index {
1332 reject(
1333 out,
1334 ProtocolError::LeaderNoopUncommitted {
1335 noop_index,
1336 commit_index: self.commit_index,
1337 },
1338 );
1339 return;
1340 }
1341 }
1342 if self.config_state.last_config_index > self.commit_index {
1343 reject(
1344 out,
1345 ProtocolError::ConfigChangePending {
1346 last_config_index: self.config_state.last_config_index,
1347 commit_index: self.commit_index,
1348 },
1349 );
1350 return;
1351 }
1352 let new_config = match self.config_state.latest.apply_change(change) {
1353 Ok(config) => config,
1354 Err(error) => {
1355 reject(out, error);
1356 return;
1357 }
1358 };
1359 if let ConfigChange::PromoteVoter { node } = change {
1360 let matched = self
1361 .progress
1362 .get(&node)
1363 .map_or(LogIndex::ZERO, |prog| prog.match_index);
1364 if matched < self.commit_index {
1365 reject(
1366 out,
1367 ProtocolError::LearnerNotCaughtUp {
1368 node,
1369 match_index: matched,
1370 required: self.commit_index,
1371 },
1372 );
1373 return;
1374 }
1375 }
1376 let entries = vec![LogEntry {
1377 term: self.current_term,
1378 kind: EntryKind::Config { config: new_config },
1379 }];
1380 let first = self.log.append(&entries);
1381 self.pending_config = Some((first, change));
1382 out.push(Action::PersistEntries {
1383 from_index: first,
1384 entries,
1385 });
1386 self.recompute_config();
1387 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
1388 for peer in peers {
1389 self.send_append(peer, out);
1390 }
1391 }
1392
1393 fn on_request_vote(
1394 &mut self,
1395 from: NodeId,
1396 term: Term,
1397 last_log_index: LogIndex,
1398 last_log_term: Term,
1399 out: &mut Vec<Action>,
1400 ) {
1401 if term < self.current_term {
1402 out.push(Action::Send {
1403 to: from,
1404 msg: Message::RequestVoteResponse {
1405 term: self.current_term,
1406 vote_granted: false,
1407 },
1408 });
1409 return;
1410 }
1411 let mut hard_changed = if term > self.current_term {
1412 self.set_term(term, out);
1413 true
1414 } else {
1415 false
1416 };
1417 if !self.config_state.latest.is_voter(self.id) {
1420 out.push(Action::Send {
1421 to: from,
1422 msg: Message::RequestVoteResponse {
1423 term: self.current_term,
1424 vote_granted: false,
1425 },
1426 });
1427 return;
1428 }
1429 let grant = (self.voted_for.is_none() || self.voted_for == Some(from))
1430 && self.log_up_to_date(last_log_term, last_log_index);
1431 if grant {
1432 if self.voted_for != Some(from) {
1433 self.voted_for = Some(from);
1434 hard_changed = true;
1435 }
1436 self.reset_election_deadline();
1437 }
1438 let response = Action::Send {
1439 to: from,
1440 msg: Message::RequestVoteResponse {
1441 term: self.current_term,
1442 vote_granted: grant,
1443 },
1444 };
1445 if hard_changed {
1446 let generation = self.emit_persist_hard(out);
1447 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1448 } else {
1449 out.push(response);
1450 }
1451 }
1452
1453 fn on_vote_response(
1454 &mut self,
1455 from: NodeId,
1456 term: Term,
1457 vote_granted: bool,
1458 out: &mut Vec<Action>,
1459 ) {
1460 if term > self.current_term {
1461 self.set_term(term, out);
1462 let _ = self.emit_persist_hard(out);
1463 return;
1464 }
1465 if self.role == Role::Candidate
1466 && term == self.current_term
1467 && vote_granted
1468 && self.config_state.latest.is_voter(from)
1469 {
1470 self.votes_received.insert(from);
1471 if self.votes_received.len() >= self.config_state.latest.quorum() {
1472 self.become_leader(out);
1473 }
1474 }
1475 }
1476
1477 fn on_request_prevote(
1478 &self,
1479 from: NodeId,
1480 term: Term,
1481 last_log_index: LogIndex,
1482 last_log_term: Term,
1483 out: &mut Vec<Action>,
1484 ) {
1485 let leader_recent = self.role == Role::Leader
1488 || (self.leader_id.is_some()
1489 && self.last_leader_contact.is_some_and(|t| {
1490 self.now.saturating_sub(t) < self.config.min_election_timeout
1491 }));
1492 let granted = term > self.current_term
1493 && self.log_up_to_date(last_log_term, last_log_index)
1494 && !leader_recent;
1495 out.push(Action::Send {
1496 to: from,
1497 msg: Message::RequestPreVoteResponse {
1498 term: self.current_term,
1499 vote_granted: granted,
1500 },
1501 });
1502 }
1503
1504 fn on_prevote_response(
1505 &mut self,
1506 from: NodeId,
1507 term: Term,
1508 vote_granted: bool,
1509 out: &mut Vec<Action>,
1510 ) {
1511 if term > self.current_term {
1512 self.set_term(term, out);
1513 let _ = self.emit_persist_hard(out);
1514 return;
1515 }
1516 if self.role == Role::PreCandidate
1517 && vote_granted
1518 && self.config_state.latest.is_voter(from)
1519 {
1520 self.prevotes_received.insert(from);
1521 if self.prevotes_received.len() >= self.config_state.latest.quorum() {
1522 self.start_election(out);
1523 }
1524 }
1525 }
1526
1527 fn on_append_below_base(
1532 &mut self,
1533 from: NodeId,
1534 leader_commit: LogIndex,
1535 read_round: u64,
1536 hard_changed: bool,
1537 out: &mut Vec<Action>,
1538 ) {
1539 let new_commit = leader_commit.min(self.log.last_index());
1540 if new_commit > self.commit_index {
1541 self.commit_index = new_commit;
1542 self.emit_applies(out);
1543 }
1544 if read_round > self.last_read_round {
1545 self.last_read_round = read_round;
1546 }
1547 let response = Action::Send {
1548 to: from,
1549 msg: Message::AppendEntriesResponse {
1550 term: self.current_term,
1551 success: true,
1552 match_index: self.log.base_index(),
1553 conflict_index: LogIndex::ZERO,
1554 conflict_term: Term::ZERO,
1555 read_round: self.last_read_round,
1556 },
1557 };
1558 if hard_changed {
1559 let generation = self.emit_persist_hard(out);
1560 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1561 } else {
1562 out.push(response);
1563 }
1564 }
1565
1566 #[allow(
1567 clippy::too_many_arguments,
1568 reason = "one argument per AppendEntries field keeps the handler aligned with the message layout"
1569 )]
1570 fn on_append_entries(
1571 &mut self,
1572 from: NodeId,
1573 term: Term,
1574 prev_log_index: LogIndex,
1575 prev_log_term: Term,
1576 entries: &[LogEntry],
1577 leader_commit: LogIndex,
1578 read_round: u64,
1579 out: &mut Vec<Action>,
1580 ) {
1581 if term < self.current_term {
1582 out.push(Action::Send {
1583 to: from,
1584 msg: Message::AppendEntriesResponse {
1585 term: self.current_term,
1586 success: false,
1587 match_index: LogIndex::ZERO,
1588 conflict_index: LogIndex::ZERO,
1589 conflict_term: Term::ZERO,
1590 read_round: 0,
1591 },
1592 });
1593 return;
1594 }
1595 let hard_changed = if term > self.current_term {
1596 self.set_term(term, out);
1597 true
1598 } else if self.role == Role::Leader {
1599 out.push(Action::StepDown { term });
1600 self.fail_pending_reads(out);
1601 self.role = Role::Follower;
1602 self.progress.clear();
1603 self.inflight.clear();
1604 self.attached.clear();
1605 false
1606 } else {
1607 self.role = Role::Follower;
1608 false
1609 };
1610 self.leader_id = Some(from);
1611 self.last_leader_contact = Some(self.now);
1612 self.reset_election_deadline();
1613
1614 if prev_log_index < self.log.base_index() {
1618 self.on_append_below_base(from, leader_commit, read_round, hard_changed, out);
1619 return;
1620 }
1621
1622 let rejection = if prev_log_index > self.log.last_index() {
1624 Some((self.log.last_index().next(), Term::ZERO))
1625 } else if self.log.term_at(prev_log_index) != Some(prev_log_term) {
1626 let conflict_term = self.log.term_at(prev_log_index).unwrap_or(Term::ZERO);
1627 let conflict_index = self
1628 .log
1629 .first_index_of_term(conflict_term)
1630 .unwrap_or(prev_log_index);
1631 Some((conflict_index, conflict_term))
1632 } else {
1633 None
1634 };
1635 if let Some((conflict_index, conflict_term)) = rejection {
1636 let response = Action::Send {
1637 to: from,
1638 msg: Message::AppendEntriesResponse {
1639 term: self.current_term,
1640 success: false,
1641 match_index: LogIndex::ZERO,
1642 conflict_index,
1643 conflict_term,
1644 read_round: 0,
1645 },
1646 };
1647 if hard_changed {
1648 let generation = self.emit_persist_hard(out);
1649 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1650 } else {
1651 out.push(response);
1652 }
1653 return;
1654 }
1655
1656 let need_entries = self.merge_and_commit(prev_log_index, entries, leader_commit, out);
1657 let verified_up_to = if entries.is_empty() {
1658 self.log.last_index()
1659 } else {
1660 LogIndex(prev_log_index.0 + entries.len() as u64)
1661 };
1662
1663 if read_round > self.last_read_round {
1667 self.last_read_round = read_round;
1668 }
1669 let matched = if entries.is_empty() {
1670 prev_log_index
1671 } else {
1672 verified_up_to
1673 };
1674 let response = Action::Send {
1675 to: from,
1676 msg: Message::AppendEntriesResponse {
1677 term: self.current_term,
1678 success: true,
1679 match_index: matched,
1680 conflict_index: LogIndex::ZERO,
1681 conflict_term: Term::ZERO,
1682 read_round: self.last_read_round,
1683 },
1684 };
1685 if hard_changed {
1686 let generation = self.emit_persist_hard(out);
1687 self.defer_or_emit(out, response, generation, need_entries);
1688 } else {
1689 self.defer_or_emit(out, response, 0, need_entries);
1690 }
1691 }
1692
1693 fn merge_and_commit(
1698 &mut self,
1699 prev_log_index: LogIndex,
1700 entries: &[LogEntry],
1701 leader_commit: LogIndex,
1702 out: &mut Vec<Action>,
1703 ) -> LogIndex {
1704 let mut changed_from: Option<LogIndex> = None;
1707 for (offset, entry) in entries.iter().enumerate() {
1708 let index = LogIndex(prev_log_index.0 + 1 + offset as u64);
1709 match self.log.entry_at(index) {
1710 Some(existing) if existing.term == entry.term => {}
1711 Some(_) => {
1712 self.log.truncate_from(index);
1713 self.log.append(&entries[offset..]);
1714 changed_from = Some(index);
1715 break;
1716 }
1717 None => {
1718 self.log.append(&entries[offset..]);
1719 changed_from = Some(index);
1720 break;
1721 }
1722 }
1723 }
1724 let mut need_entries = LogIndex::ZERO;
1725 if let Some(from_index) = changed_from {
1726 let suffix = self.log.entries_from(from_index, usize::MAX, usize::MAX);
1727 need_entries = self.log.last_index();
1728 out.push(Action::PersistEntries {
1729 from_index,
1730 entries: suffix,
1731 });
1732 }
1733 let verified_up_to = if entries.is_empty() {
1735 self.log.last_index()
1736 } else {
1737 LogIndex(prev_log_index.0 + entries.len() as u64)
1738 };
1739 let new_commit = leader_commit.min(verified_up_to);
1740 if new_commit > self.commit_index {
1741 self.commit_index = new_commit;
1742 self.emit_applies(out);
1743 }
1744 self.recompute_config();
1745 need_entries
1746 }
1747
1748 #[allow(
1749 clippy::too_many_arguments,
1750 reason = "one argument per AppendEntriesResponse field keeps the handler aligned with the message layout"
1751 )]
1752 fn on_append_response(
1753 &mut self,
1754 from: NodeId,
1755 term: Term,
1756 success: bool,
1757 match_index: LogIndex,
1758 conflict_index: LogIndex,
1759 conflict_term: Term,
1760 read_round: u64,
1761 out: &mut Vec<Action>,
1762 ) {
1763 if term > self.current_term {
1764 self.set_term(term, out);
1765 let _ = self.emit_persist_hard(out);
1766 return;
1767 }
1768 if self.role != Role::Leader || term < self.current_term {
1769 return;
1770 }
1771 if success {
1772 let mut advance = false;
1773 if let Some(prog) = self.progress.get_mut(&from) {
1774 if match_index > prog.match_index {
1775 prog.match_index = match_index;
1776 advance = true;
1777 }
1778 if prog.next_index < prog.match_index.next() {
1779 prog.next_index = prog.match_index.next();
1780 }
1781 let cap = self.log.last_index().next();
1782 if prog.next_index > cap {
1783 prog.next_index = cap;
1784 }
1785 }
1786 if advance {
1787 self.advance_commit(out);
1788 }
1789 if read_round != 0 {
1793 if let Some(batch) = &mut self.pending_reads {
1794 if batch.round == read_round && self.config_state.latest.is_voter(from) {
1795 batch.acks.insert(from);
1796 }
1797 }
1798 }
1799 self.try_release_reads(out);
1800 return;
1801 }
1802 if conflict_index == LogIndex::ZERO && conflict_term == Term::ZERO {
1806 return;
1807 }
1808 let candidate = if conflict_term > Term::ZERO {
1809 self.log
1810 .last_index_of_term(conflict_term)
1811 .map_or(conflict_index, LogIndex::next)
1812 } else {
1813 conflict_index
1814 };
1815 let mut retry = false;
1816 if let Some(prog) = self.progress.get_mut(&from) {
1817 let floor = prog.match_index.next();
1818 let cap = self.log.last_index().next();
1819 let new_next = candidate.max(floor).min(cap);
1820 if new_next < prog.next_index {
1821 prog.next_index = new_next;
1822 retry = true;
1823 }
1824 }
1825 if retry {
1826 self.send_append(from, out);
1827 }
1828 }
1829}
1830
1831pub(crate) const fn splitmix64(mut x: u64) -> u64 {
1835 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1836 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1837 x ^ (x >> 31)
1838}