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