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