Skip to main content

simraft_core/
log.rs

1//! The replicated log: a contiguous entry vector behind a snapshot base.
2//!
3//! The entry at log index `i` lives at vector position
4//! `i - base_index - 1`. Index 0 is the sentinel with term 0.
5
6use crate::ids::{ClientId, LogIndex, Term};
7use crate::membership::ClusterConfig;
8
9/// What a log entry does when it applies.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum EntryKind {
12    /// No operation. Leaders append one on election so they hold a
13    /// current-term entry they may count toward commitment.
14    NoOp,
15    /// A client command. The payload is the canonical command encoding
16    /// produced by simraft-kv; the core treats it as opaque bytes and
17    /// carries the client identity alongside for deduplication.
18    Command {
19        /// The client that proposed the command.
20        client_id: ClientId,
21        /// The per-client sequence number of the proposal.
22        seq: u64,
23        /// The canonical command payload bytes.
24        payload: Vec<u8>,
25    },
26    /// A cluster configuration change.
27    Config {
28        /// The configuration this entry installs when it applies.
29        config: ClusterConfig,
30    },
31}
32
33/// One replicated log entry.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct LogEntry {
36    /// The term of the leader that created this entry.
37    pub term: Term,
38    /// The entry payload.
39    pub kind: EntryKind,
40}
41
42impl LogEntry {
43    /// An approximate encoded size of this entry, used to enforce the
44    /// `AppendEntries` byte budget.
45    #[must_use]
46    pub fn approx_len(&self) -> usize {
47        match &self.kind {
48            EntryKind::NoOp => 16,
49            EntryKind::Command { payload, .. } => 32 + payload.len(),
50            EntryKind::Config { config } => 32 + 8 * (config.voters.len() + config.learners.len()),
51        }
52    }
53}
54
55/// A node's log: the snapshot base plus every entry after it.
56#[derive(Debug, Clone, PartialEq, Eq, Default)]
57pub struct Log {
58    base_index: LogIndex,
59    base_term: Term,
60    entries: Vec<LogEntry>,
61}
62
63impl Log {
64    /// An empty log with only the sentinel base.
65    #[must_use]
66    pub fn new() -> Self {
67        Self::default()
68    }
69
70    /// The index of the snapshot base (0 before any snapshot is installed).
71    #[must_use]
72    pub const fn base_index(&self) -> LogIndex {
73        self.base_index
74    }
75
76    /// The index of the last entry, or the base index when empty.
77    #[must_use]
78    pub const fn last_index(&self) -> LogIndex {
79        LogIndex(self.base_index.0 + self.entries.len() as u64)
80    }
81
82    /// The term of the last entry, or the base term when empty.
83    #[must_use]
84    pub fn last_term(&self) -> Term {
85        self.entries.last().map_or(self.base_term, |e| e.term)
86    }
87
88    /// The term of the entry at `index`, the base term at the base index,
89    /// term 0 at the sentinel, and `None` outside the log.
90    #[must_use]
91    pub fn term_at(&self, index: LogIndex) -> Option<Term> {
92        if index == LogIndex::ZERO && self.base_index == LogIndex::ZERO {
93            return Some(Term::ZERO);
94        }
95        if index == self.base_index {
96            return Some(self.base_term);
97        }
98        if index < self.base_index || index > self.last_index() {
99            return None;
100        }
101        let pos = self.pos_of(index);
102        self.entries.get(pos).map(|e| e.term)
103    }
104
105    /// The entry at `index`, or `None` at or below the base and beyond
106    /// the tail.
107    #[must_use]
108    pub fn entry_at(&self, index: LogIndex) -> Option<&LogEntry> {
109        if index <= self.base_index || index > self.last_index() {
110            return None;
111        }
112        let pos = self.pos_of(index);
113        self.entries.get(pos)
114    }
115
116    /// The vector position of `index`. Callers have already bounds
117    /// checked `index` against the in-memory entry vector, so the
118    /// offset always fits in a `usize`.
119    fn pos_of(&self, index: LogIndex) -> usize {
120        usize::try_from(index.0 - self.base_index.0 - 1)
121            .expect("a bounds-checked log offset always fits in usize")
122    }
123
124    /// Append entries at the tail. Returns the index of the first
125    /// appended entry.
126    pub fn append(&mut self, new_entries: &[LogEntry]) -> LogIndex {
127        let first = self.last_index().next();
128        self.entries.extend_from_slice(new_entries);
129        first
130    }
131
132    /// The term of the snapshot base entry (term 0 at the sentinel).
133    #[must_use]
134    pub const fn base_term(&self) -> Term {
135        self.base_term
136    }
137
138    /// Advance the snapshot base to (`index`, `term`), discarding every
139    /// entry at or below `index`. The caller (snapshot install)
140    /// guarantees `term` is the term of the entry at `index` and that
141    /// `index` does not pass the node's commit boundary (invariant
142    /// N-05). Advancing to or below the current base is a no-op.
143    pub fn advance_base(&mut self, index: LogIndex, term: Term) {
144        if index <= self.base_index {
145            return;
146        }
147        let drop = usize::try_from(index.0 - self.base_index.0)
148            .unwrap_or(usize::MAX)
149            .min(self.entries.len());
150        self.entries.drain(..drop);
151        self.base_index = index;
152        self.base_term = term;
153    }
154
155    /// Discard the entire entry vector, keeping the snapshot base. Used
156    /// by snapshot install when the follower's log holds no entry
157    /// matching the snapshot's last included entry (invariant N-04).
158    pub fn clear_entries(&mut self) {
159        self.entries.clear();
160    }
161
162    /// Delete every entry at or after `index`. Deleting at or below the
163    /// base index is a no-op: compacted history is never resurrected.
164    pub fn truncate_from(&mut self, index: LogIndex) {
165        if index <= self.base_index {
166            return;
167        }
168        let keep = self.pos_of(index);
169        self.entries.truncate(keep);
170    }
171
172    /// The first index whose entry carries `term`, if any.
173    #[must_use]
174    pub fn first_index_of_term(&self, term: Term) -> Option<LogIndex> {
175        // Terms are non-decreasing along a Raft log, so the run of any
176        // term is one contiguous span found by binary search.
177        if term == self.base_term && self.base_index != LogIndex::ZERO {
178            return Some(self.base_index);
179        }
180        let start = self.entries.partition_point(|e| e.term < term);
181        match self.entries.get(start) {
182            Some(entry) if entry.term == term => {
183                Some(LogIndex(self.base_index.0 + start as u64 + 1))
184            }
185            _ => None,
186        }
187    }
188
189    /// The last index whose entry carries `term`, if any.
190    #[must_use]
191    pub fn last_index_of_term(&self, term: Term) -> Option<LogIndex> {
192        let end = self.entries.partition_point(|e| e.term <= term);
193        if end == 0 {
194            if term == self.base_term && self.base_index != LogIndex::ZERO {
195                return Some(self.base_index);
196            }
197            return None;
198        }
199        match self.entries.get(end - 1) {
200            Some(entry) if entry.term == term => Some(LogIndex(self.base_index.0 + end as u64)),
201            _ => None,
202        }
203    }
204
205    /// Up to `max_count` entries starting at `index`, bounded also by the
206    /// approximate byte budget `max_bytes`. Empty when `index` is past
207    /// the tail.
208    #[must_use]
209    pub fn entries_from(
210        &self,
211        index: LogIndex,
212        max_count: usize,
213        max_bytes: usize,
214    ) -> Vec<LogEntry> {
215        if index <= self.base_index || index > self.last_index() {
216            return Vec::new();
217        }
218        let start = self.pos_of(index);
219        let mut out = Vec::new();
220        let mut bytes = 0_usize;
221        for entry in self.entries.iter().skip(start) {
222            if out.len() >= max_count {
223                break;
224            }
225            bytes += entry.approx_len();
226            if !out.is_empty() && bytes > max_bytes {
227                break;
228            }
229            out.push(entry.clone());
230        }
231        out
232    }
233
234    /// Every entry in index order, for oracles and tests.
235    #[must_use]
236    pub fn entries(&self) -> &[LogEntry] {
237        &self.entries
238    }
239}