kevy_replicate/source.rs
1//! Primary-side replication source — bounded backlog of recent
2//! mutations, indexed by monotonic offset.
3//!
4//! Behaviour at a glance:
5//! - [`ReplicationSource::push_mutation`] is called on every applied
6//! write. It assigns the next monotonic offset, encodes the frame
7//! with [`crate::wire::encode_frame`], and appends to the backlog.
8//! - The backlog is bounded by a byte budget (`max_bytes`, fed from
9//! `[replication]` `replication_buffer_size` in config). When a new
10//! frame would exceed the budget, the oldest frames are dropped to
11//! make room.
12//! - Replicas that disconnect and reconnect within the backlog window
13//! resume via [`ReplicationSource::frames_from`]. Replicas that fall
14//! off the back of the buffer get `Err(FromOffset::TooOld)` and the
15//! caller initiates a full snapshot ship.
16//!
17//! The source does **not** know about replicas — slot tracking lives
18//! in [`crate::slot::SlotTable`]. The source is a passive structure
19//! the streaming loop reads; mutation/serialisation lock policy is the
20//! wiring layer's concern.
21
22use crate::wire::encode_frame;
23#[cfg(test)]
24use kevy_resp::Argv;
25use kevy_resp::ArgvView;
26
27/// One encoded mutation frame parked in the backlog.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Frame {
30 /// Monotonic offset the source assigned at push time.
31 pub offset: u64,
32 /// Wire-encoded frame bytes (envelope + offset + RESP argv).
33 pub bytes: Vec<u8>,
34}
35
36/// Reason [`ReplicationSource::frames_from`] cannot serve a replica
37/// from the backlog.
38#[derive(Debug, PartialEq, Eq)]
39pub enum FromOffset {
40 /// The replica is asking for an offset we already evicted; the
41 /// streaming loop must initiate a snapshot ship.
42 TooOld,
43 /// The replica's requested offset is greater than the next offset
44 /// we would assign — peer is ahead of us (data-dir wipe, epoch
45 /// confusion, or bug). The caller should drop the link.
46 Future,
47}
48
49/// Bounded backlog of recent replicated mutations.
50pub struct ReplicationSource {
51 next_offset: u64,
52 bytes_in_buf: usize,
53 max_bytes: usize,
54 buf: std::collections::VecDeque<Frame>,
55}
56
57impl ReplicationSource {
58 /// Create a new source with the given byte budget. `max_bytes` must
59 /// be > 0; the source guarantees at most one over-budget frame at
60 /// a time (the most recently pushed) so a single huge command does
61 /// not silently disappear before its replicas even see it.
62 ///
63 /// # Panics
64 ///
65 /// Panics if `max_bytes == 0` — a zero budget could never hold
66 /// even one frame, so it is a caller bug, not a runtime state.
67 pub fn new(max_bytes: usize) -> Self {
68 assert!(max_bytes > 0, "ReplicationSource max_bytes must be > 0");
69 Self { next_offset: 0, bytes_in_buf: 0, max_bytes, buf: std::collections::VecDeque::new() }
70 }
71
72 /// Resume offset assignment at `next` (boot continuity from the
73 /// feed sidecar). Only meaningful on an empty, freshly created
74 /// source — asserts the backlog has no frames.
75 ///
76 /// # Panics
77 ///
78 /// Panics if the backlog already holds frames: renumbering live
79 /// frames would corrupt every replica's ack bookkeeping.
80 pub fn set_next_offset(&mut self, next: u64) {
81 assert!(self.buf.is_empty(), "set_next_offset on non-empty backlog");
82 self.next_offset = next;
83 }
84
85 /// The byte budget this source was created with.
86 pub fn max_bytes(&self) -> usize {
87 self.max_bytes
88 }
89
90 /// Next offset this source would assign. Equal to one past the
91 /// last assigned offset; equals `0` for a fresh source.
92 pub fn next_offset(&self) -> u64 {
93 self.next_offset
94 }
95
96 /// Lowest offset still in the backlog, or `None` if empty.
97 pub fn oldest_offset(&self) -> Option<u64> {
98 self.buf.front().map(|f| f.offset)
99 }
100
101 /// Highest offset still in the backlog, or `None` if empty.
102 pub fn newest_offset(&self) -> Option<u64> {
103 self.buf.back().map(|f| f.offset)
104 }
105
106 /// Total bytes occupied by frames currently in the backlog.
107 pub fn buffered_bytes(&self) -> usize {
108 self.bytes_in_buf
109 }
110
111 /// Number of frames currently in the backlog.
112 pub fn len(&self) -> usize {
113 self.buf.len()
114 }
115
116 /// Whether the backlog has no frames.
117 pub fn is_empty(&self) -> bool {
118 self.buf.is_empty()
119 }
120
121 /// Append one applied mutation. Returns the offset assigned to it.
122 /// Generic over [`ArgvView`] so the dispatcher's borrowed argv can
123 /// flow straight in — no `Argv` materialisation on the write path.
124 ///
125 /// May evict older frames if the new frame would exceed the byte
126 /// budget; the new frame is always retained (even if it is larger
127 /// than `max_bytes` on its own — losing the most recent applied
128 /// write before any replica has had a chance to ack it would be
129 /// a worse failure than briefly running over budget).
130 // missing_panics_doc: the eviction loop's expect pops a front the loop
131 // guard just observed — unreachable, not a caller-facing panic condition.
132 #[allow(clippy::missing_panics_doc)]
133 pub fn push_mutation<A: ArgvView + ?Sized>(&mut self, argv: &A) -> u64 {
134 let offset = self.next_offset;
135 let bytes = encode_frame(offset, argv);
136 let frame_len = bytes.len();
137
138 // Evict from the front until either the new frame fits or
139 // the buffer is empty.
140 while self.bytes_in_buf + frame_len > self.max_bytes && !self.buf.is_empty() {
141 let dropped = self.buf.pop_front().expect("non-empty checked");
142 self.bytes_in_buf -= dropped.bytes.len();
143 }
144
145 self.bytes_in_buf += frame_len;
146 self.buf.push_back(Frame { offset, bytes });
147 self.next_offset = self
148 .next_offset
149 .checked_add(1)
150 .expect("replication offset wrap — i64::MAX guard tripped");
151 offset
152 }
153
154 /// Drop every buffered frame whose offset is `< watermark` —
155 /// i.e. every replica has consumed past it. Used by the per-
156 /// shard tick to enforce a retention floor tighter
157 /// than the raw byte budget; lets the backlog reclaim space
158 /// for live frames once all consumers have advanced.
159 ///
160 /// No-op when `watermark <= oldest_offset()` (nothing to drop)
161 /// or when the buffer is empty. Updates the internal byte
162 /// accounting to stay consistent with the live buffer length.
163 // missing_panics_doc: same front-of-loop expect rationale as
164 // `push_mutation` — unreachable by the `while let` guard.
165 #[allow(clippy::missing_panics_doc)]
166 pub fn drop_up_to(&mut self, watermark: u64) {
167 while let Some(front) = self.buf.front() {
168 if front.offset >= watermark {
169 break;
170 }
171 let dropped = self.buf.pop_front().expect("front-of-loop");
172 self.bytes_in_buf -= dropped.bytes.len();
173 }
174 }
175
176 /// Borrow the slice of frames with offset ≥ `from`. Suitable for
177 /// the streaming loop to write each frame's `bytes` to a replica
178 /// socket. Returns:
179 /// - `Ok(iter)` — zero or more frames in offset order (empty iter
180 /// means the replica is caught up).
181 /// - `Err(FromOffset::TooOld)` — `from` is older than the oldest
182 /// buffered frame; the streaming loop must snapshot-ship.
183 /// - `Err(FromOffset::Future)` — `from > next_offset()`; peer is
184 /// ahead of us, drop the link.
185 pub fn frames_from(&self, from: u64) -> Result<FramesIter<'_>, FromOffset> {
186 if from > self.next_offset {
187 return Err(FromOffset::Future);
188 }
189 // from == next_offset → replica is exactly caught up; empty slice.
190 if from == self.next_offset {
191 return Ok(FramesIter { buf: &self.buf, cursor: self.buf.len() });
192 }
193 // from < next_offset: the requested frame either is still in
194 // the backlog or was evicted. Empty buf with from < next_offset
195 // means every frame ever pushed has been evicted — same TooOld
196 // outcome as `from < oldest`. (Without this branch the function
197 // returns an empty iterator and the streaming pump silently
198 // stalls — an embed-replica restart test caught this.)
199 match self.oldest_offset() {
200 Some(oldest) if from < oldest => return Err(FromOffset::TooOld),
201 None => return Err(FromOffset::TooOld),
202 _ => {}
203 }
204 // Offsets are monotonic, so the start index is a binary search. The
205 // comment here used to say exactly that — and then called
206 // `iter().position(...)`, an O(B) walk of the whole backlog, on a path
207 // that both FEED.READ and the replica stream take on every poll. A
208 // consumer resuming from an old cursor paid for the entire backlog
209 // before it saw its first frame.
210 //
211 // `VecDeque` is two contiguous runs, each individually sorted, so
212 // `partition_point` on each half gives the answer in O(log B).
213 let (a, b) = self.buf.as_slices();
214 let start = match a.partition_point(|f| f.offset < from) {
215 i if i < a.len() => i,
216 _ => a.len() + b.partition_point(|f| f.offset < from),
217 };
218 Ok(FramesIter { buf: &self.buf, cursor: start })
219 }
220}
221
222/// Iterator over backlog frames returned by [`ReplicationSource::frames_from`].
223pub struct FramesIter<'a> {
224 buf: &'a std::collections::VecDeque<Frame>,
225 cursor: usize,
226}
227
228impl<'a> Iterator for FramesIter<'a> {
229 type Item = &'a Frame;
230 fn next(&mut self) -> Option<&'a Frame> {
231 let item = self.buf.get(self.cursor)?;
232 self.cursor += 1;
233 Some(item)
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use crate::wire::decode_frame;
241
242 fn argv(args: &[&[u8]]) -> Argv {
243 let mut a = Argv::default();
244 for arg in args {
245 a.push(arg);
246 }
247 a
248 }
249
250 #[test]
251 fn fresh_source_is_empty() {
252 let s = ReplicationSource::new(1024);
253 assert!(s.is_empty());
254 assert_eq!(s.len(), 0);
255 assert_eq!(s.next_offset(), 0);
256 assert_eq!(s.oldest_offset(), None);
257 assert_eq!(s.newest_offset(), None);
258 assert_eq!(s.buffered_bytes(), 0);
259 }
260
261 #[test]
262 fn push_assigns_monotonic_offsets() {
263 let mut s = ReplicationSource::new(64 * 1024);
264 let o0 = s.push_mutation(&argv(&[b"SET", b"a", b"1"]));
265 let o1 = s.push_mutation(&argv(&[b"SET", b"b", b"2"]));
266 let o2 = s.push_mutation(&argv(&[b"DEL", b"a"]));
267 assert_eq!((o0, o1, o2), (0, 1, 2));
268 assert_eq!(s.oldest_offset(), Some(0));
269 assert_eq!(s.newest_offset(), Some(2));
270 assert_eq!(s.next_offset(), 3);
271 assert_eq!(s.len(), 3);
272 }
273
274 #[test]
275 fn pushed_frames_decode_back_to_the_pushed_argv() {
276 let mut s = ReplicationSource::new(1024);
277 let a = argv(&[b"HSET", b"h", b"f", b"v"]);
278 let off = s.push_mutation(&a);
279 let frame = s.buf.front().expect("one frame");
280 assert_eq!(frame.offset, off);
281 let (decoded_off, decoded_argv, used) = decode_frame(&frame.bytes).expect("decode");
282 assert_eq!(decoded_off, off);
283 assert_eq!(decoded_argv, a);
284 assert_eq!(used, frame.bytes.len());
285 }
286
287 #[test]
288 fn eviction_drops_oldest_when_budget_exceeded() {
289 // Each frame encodes to ~37 bytes (envelope + offset + 3-arg SET).
290 // Budget of 80 bytes holds 2 frames; pushing a 3rd evicts oldest.
291 let mut s = ReplicationSource::new(80);
292 let _ = s.push_mutation(&argv(&[b"SET", b"a", b"1"]));
293 let _ = s.push_mutation(&argv(&[b"SET", b"b", b"2"]));
294 assert_eq!(s.oldest_offset(), Some(0));
295 let _ = s.push_mutation(&argv(&[b"SET", b"c", b"3"]));
296 assert_eq!(s.oldest_offset(), Some(1));
297 assert_eq!(s.newest_offset(), Some(2));
298 assert!(s.buffered_bytes() <= 80);
299 // next_offset keeps climbing even when older frames are evicted.
300 assert_eq!(s.next_offset(), 3);
301 }
302
303 #[test]
304 fn oversized_single_frame_is_retained_against_budget() {
305 // Budget of 8 bytes — smaller than any real frame. The most
306 // recent push always survives so a freshly-applied write is
307 // never lost before any replica can see it.
308 let mut s = ReplicationSource::new(8);
309 let off = s.push_mutation(&argv(&[b"SET", b"k", b"v"]));
310 assert_eq!(s.len(), 1);
311 assert_eq!(s.oldest_offset(), Some(off));
312 assert!(s.buffered_bytes() > 8); // ran over budget; expected.
313 // Pushing again still keeps only the newest (older is evicted).
314 let off2 = s.push_mutation(&argv(&[b"DEL", b"k"]));
315 assert_eq!(s.len(), 1);
316 assert_eq!(s.oldest_offset(), Some(off2));
317 }
318
319 #[test]
320 fn frames_from_at_exact_offset_returns_that_frame_first() {
321 let mut s = ReplicationSource::new(1024);
322 for i in 0..5 {
323 let _ = s.push_mutation(&argv(&[b"SET", b"k", format!("{i}").as_bytes()]));
324 }
325 let mut it = s.frames_from(2).unwrap();
326 let f = it.next().expect("frame");
327 assert_eq!(f.offset, 2);
328 let remaining: Vec<u64> = it.map(|f| f.offset).collect();
329 assert_eq!(remaining, vec![3, 4]);
330 }
331
332 #[test]
333 fn frames_from_at_next_offset_is_empty_caught_up() {
334 let mut s = ReplicationSource::new(1024);
335 let _ = s.push_mutation(&argv(&[b"PING"]));
336 let _ = s.push_mutation(&argv(&[b"PING"]));
337 let it = s.frames_from(s.next_offset()).unwrap();
338 assert_eq!(it.count(), 0);
339 }
340
341 #[test]
342 fn frames_from_too_old_after_eviction() {
343 // Tight budget; push enough to evict offset 0.
344 let mut s = ReplicationSource::new(80);
345 for _ in 0..5 {
346 let _ = s.push_mutation(&argv(&[b"SET", b"k", b"v"]));
347 }
348 // Offset 0 was evicted.
349 assert!(s.oldest_offset().unwrap() > 0);
350 assert!(matches!(s.frames_from(0), Err(FromOffset::TooOld)));
351 }
352
353 #[test]
354 fn frames_from_future_offset_rejected() {
355 let mut s = ReplicationSource::new(1024);
356 let _ = s.push_mutation(&argv(&[b"PING"]));
357 // next_offset is 1; asking for 2 is a future-offset peer.
358 assert!(matches!(s.frames_from(2), Err(FromOffset::Future)));
359 }
360
361 #[test]
362 fn frames_from_empty_source_at_zero_is_caught_up_not_too_old() {
363 // A fresh source has nothing buffered but is at offset 0; a
364 // replica asking from 0 is up-to-date (the source has nothing
365 // to send yet), not too-old.
366 let s = ReplicationSource::new(1024);
367 assert_eq!(s.frames_from(0).unwrap().count(), 0);
368 // Asking for offset 1 (one past empty next_offset 0) = Future.
369 assert!(matches!(s.frames_from(1), Err(FromOffset::Future)));
370 }
371
372 #[test]
373 fn push_mutation_accepts_argv_borrowed_from_dispatcher_hot_path() {
374 // The reactor's local fast path holds the parsed argv as an
375 // `ArgvBorrowed` over the connection read buffer (zero-copy);
376 // `push_mutation` must accept that view directly, not force
377 // a materialised `Argv`. Parse one with the public parser and
378 // push it; the decoded round-trip must match a hand-built Argv
379 // of the same command.
380 let resp = b"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n";
381 let (borrowed, consumed) =
382 kevy_resp::parse_command_borrowed(resp).expect("parse ok").expect("complete frame");
383 assert_eq!(consumed, resp.len());
384
385 let mut s = ReplicationSource::new(1024);
386 let off = s.push_mutation(&borrowed);
387 assert_eq!(off, 0);
388
389 let frame = s.buf.front().expect("one frame");
390 let (decoded_off, decoded_argv, _) =
391 crate::wire::decode_frame(&frame.bytes).expect("decode");
392 assert_eq!(decoded_off, 0);
393 assert_eq!(decoded_argv, argv(&[b"SET", b"foo", b"bar"]));
394 }
395
396 #[test]
397 fn buffered_bytes_tracks_actual_frame_total() {
398 let mut s = ReplicationSource::new(1024);
399 let _ = s.push_mutation(&argv(&[b"SET", b"k", b"v"]));
400 let _ = s.push_mutation(&argv(&[b"DEL", b"k"]));
401 let actual: usize = s.buf.iter().map(|f| f.bytes.len()).sum();
402 assert_eq!(s.buffered_bytes(), actual);
403 }
404
405 #[test]
406 fn drop_up_to_evicts_below_watermark() {
407 // drop_up_to(w) evicts every frame with offset < w.
408 let mut s = ReplicationSource::new(64 * 1024);
409 for i in 0..5 {
410 let v = format!("v{i}");
411 let _ = s.push_mutation(&argv(&[b"SET", b"k", v.as_bytes()]));
412 }
413 assert_eq!(s.len(), 5);
414 let bytes_before = s.buffered_bytes();
415 // Watermark = 3 → drop offsets 0, 1, 2; keep 3, 4.
416 s.drop_up_to(3);
417 assert_eq!(s.len(), 2);
418 assert_eq!(s.oldest_offset(), Some(3));
419 assert_eq!(s.newest_offset(), Some(4));
420 // bytes accounting must shrink.
421 assert!(s.buffered_bytes() < bytes_before);
422 // Frames-from at the watermark works without TooOld.
423 let kept: Vec<_> = s.frames_from(3).unwrap().collect();
424 assert_eq!(kept.len(), 2);
425 }
426
427 #[test]
428 fn drop_up_to_below_oldest_is_noop() {
429 let mut s = ReplicationSource::new(64 * 1024);
430 let _ = s.push_mutation(&argv(&[b"SET", b"k", b"v"]));
431 let _ = s.push_mutation(&argv(&[b"SET", b"k", b"v"]));
432 assert_eq!(s.oldest_offset(), Some(0));
433 s.drop_up_to(0); // already-at-or-past-oldest
434 assert_eq!(s.len(), 2);
435 }
436
437 #[test]
438 fn drop_up_to_at_or_past_newest_drops_everything() {
439 let mut s = ReplicationSource::new(64 * 1024);
440 for _ in 0..3 {
441 let _ = s.push_mutation(&argv(&[b"SET", b"k", b"v"]));
442 }
443 s.drop_up_to(99);
444 assert!(s.is_empty());
445 assert_eq!(s.buffered_bytes(), 0);
446 }
447}