Skip to main content

kevy_replicate/
replica.rs

1//! Replica-side client — connect to a primary's replication listener,
2//! perform the handshake, then yield decoded mutation frames in order.
3//!
4//! The client is **synchronous + blocking** by design: it slots into a
5//! dedicated thread on the replica node alongside (but separate from)
6//! the regular kevy reactor.
7//!
8//! Hot loop usage:
9//!
10//! ```no_run
11//! use kevy_replicate::replica::ReplicaClient;
12//!
13//! let mut client = ReplicaClient::connect("127.0.0.1:16004", "replica-a", 0)
14//!     .expect("connect ok");
15//! while let Some(result) = client.next() {
16//!     let frame = result.expect("decode ok");
17//!     // apply frame.argv at frame.offset — caller's responsibility
18//!     drop(frame);
19//! }
20//! ```
21//!
22//! Errors map to actionable next steps for the caller:
23//! - [`ReplicaError::HandshakeRejected`] / [`ReplicaError::AckMalformed`]
24//!   — primary refused or replied with garbage; drop the link, log,
25//!   maybe back off and retry.
26//! - [`ReplicaError::Truncated`] — peer EOF mid-frame; treat as a
27//!   disconnect, reconnect later.
28//! - [`ReplicaError::OffsetGap { expected, got }`] — frames arrived
29//!   out of order or with a skip; the caller should trigger a full
30//!   snapshot resync.
31//! - [`ReplicaError::Frame`] — wire-level decode error; same
32//!   action as Truncated (drop + reconnect).
33
34pub use crate::replica_error::ReplicaError;
35use kevy_resp::Argv;
36use std::io::{self, Read, Write};
37use std::net::{TcpStream, ToSocketAddrs};
38use std::time::Duration;
39
40/// A decoded mutation frame the replica should apply to its local
41/// store. Ownership of the [`Argv`] passes to the caller.
42#[derive(Debug)]
43pub struct DecodedFrame {
44    /// Monotonic offset the primary assigned at apply-time.
45    pub offset: u64,
46    /// Wire-decoded argv — feed to the dispatcher the same way AOF
47    /// replay does (cmd name + arg bytes).
48    pub argv: Argv,
49}
50
51/// Event yielded by [`ReplicaClient::next_event`]. A driver loop
52/// pattern-matches and applies each:
53/// - [`Self::Frame`] → run through the local dispatcher.
54/// - [`Self::SnapshotBegin`] → caller should reset / prepare the
55///   local store for a fresh-from-snapshot fill.
56/// - [`Self::SnapshotChunk`] → append the bytes to the caller's
57///   accumulating snapshot buffer.
58/// - [`Self::SnapshotEnd`] → caller hands the accumulated buffer to
59///   `kevy_persist::load_snapshot`; [`ReplicaClient`] has already
60///   advanced `expected_offset` to `ack_offset`, so the next
61///   [`Self::Frame`] arrives at `ack_offset` with no gap.
62#[derive(Debug)]
63pub enum ReplicaEvent {
64    /// A live mutation frame.
65    Frame(DecodedFrame),
66    /// In-stream heartbeat: the primary's `next_offset` at send
67    /// time. Lets the replica compute lag (applied vs primary) and
68    /// judge link liveness. Occupies no offset space.
69    Ping {
70        /// Primary's feed generation at send time (the
71        /// REPL.TOKEN / REPL.WAIT gen truth). `0` = the primary spoke
72        /// the legacy one-number heartbeat ("unknown").
73        generation: u64,
74        /// Primary's `next_offset` when the heartbeat was emitted.
75        primary_offset: u64,
76    },
77    /// Snapshot ship begin marker (`+SNAPSHOT\r\n`).
78    SnapshotBegin,
79    /// One snapshot chunk's payload bytes (RESP bulk string body).
80    SnapshotChunk(Vec<u8>),
81    /// Snapshot ship end marker carrying the offset the next live
82    /// frame will have.
83    SnapshotEnd {
84        /// The offset the primary's `next_offset` was at when the
85        /// snapshot started. After this event, [`ReplicaClient::expected_offset`]
86        /// equals this value.
87        ack_offset: u64,
88    },
89}
90
91/// One blocking TCP connection to a primary's per-shard replication
92/// listener. After [`Self::connect`] completes the handshake, the
93/// client behaves as an `Iterator<Item = Result<DecodedFrame, ReplicaError>>`
94/// yielding frames in offset order until the peer disconnects or a
95/// hard error surfaces.
96pub struct ReplicaClient {
97    pub(crate) sock: TcpStream,
98    /// Bytes pulled off the socket waiting to parse the next frame.
99    pub(crate) buf: Vec<u8>,
100    /// Position into `buf` where the next decode attempt starts. We
101    /// drain `buf` only when this passes a high-water mark, so per-
102    /// frame work avoids repeated `Vec::drain` shifts.
103    pub(crate) cursor: usize,
104    /// Offset the primary advertised at handshake (`+ACK <gen> <N>`
105    /// second value). Informational; useful for gap-detection
106    /// decisions (re-handshake vs full sync).
107    pub(crate) primary_offset_at_handshake: u64,
108    /// Feed generation the primary advertised at handshake
109    /// (`+ACK <gen> <N>` first value). Whatever this session delivers
110    /// (frames or snapshot) belongs to this generation — the caller
111    /// records it as its data's generation once the delivery lands,
112    /// and presents it on the next reconnect.
113    pub(crate) primary_gen_at_handshake: u64,
114    /// The next offset we expect from the stream. Initially the
115    /// `from_offset` we requested; advances by 1 on each accepted frame.
116    pub(crate) expected_offset: u64,
117    /// `true` while we're between `+SNAPSHOT` and `+SNAPSHOT_END`.
118    /// In this state, only chunk + end-marker bytes are valid; a
119    /// `*2\r\n` (live frame envelope) returns
120    /// [`ReplicaError::UnexpectedInSnapshot`] — interleaving live
121    /// frames inside a snapshot is forbidden (`docs/snapshot.md`).
122    pub(crate) in_snapshot: bool,
123}
124
125impl ReplicaClient {
126    /// Connect to `addr` with no continuity claim (generation 0),
127    /// send `REPLICATE FROM 0 <from_offset> ID <replica_id>`, read
128    /// the `+ACK <gen> <offset>` reply, and return a ready-to-iterate
129    /// client. Blocks until the handshake completes or the connect
130    /// times out. Callers resuming with data from a prior session
131    /// must use [`Self::connect_at`] and present that data's
132    /// generation — a gen-0 claim with a nonzero offset makes the
133    /// primary ship a snapshot rather than risk offset aliasing.
134    pub fn connect<A: ToSocketAddrs>(
135        addr: A,
136        replica_id: &str,
137        from_offset: u64,
138    ) -> Result<Self, ReplicaError> {
139        Self::connect_at(addr, replica_id, 0, from_offset, Duration::from_secs(5))
140    }
141
142    /// [`Self::connect`] with an explicit connect timeout. Useful for
143    /// tests that don't want to wait the default 5 s when a port is
144    /// closed.
145    pub fn connect_with_timeout<A: ToSocketAddrs>(
146        addr: A,
147        replica_id: &str,
148        from_offset: u64,
149        connect_timeout: Duration,
150    ) -> Result<Self, ReplicaError> {
151        Self::connect_at(addr, replica_id, 0, from_offset, connect_timeout)
152    }
153
154    /// Full-form connect: present `generation` (the feed generation
155    /// this replica's data reflects; `0` = unknown / fresh) alongside
156    /// `from_offset`. The generation is what makes a resume claim
157    /// safe — the primary only serves `from_offset` continuity when
158    /// the generations match; otherwise it ships a snapshot.
159    pub fn connect_at<A: ToSocketAddrs>(
160        addr: A,
161        replica_id: &str,
162        generation: u64,
163        from_offset: u64,
164        connect_timeout: Duration,
165    ) -> Result<Self, ReplicaError> {
166        let mut sock = connect_stream(addr, connect_timeout)?;
167
168        // Send the handshake. `encode_replicate_from` is a private
169        // helper so the on-the-wire shape is one place to change.
170        let req = encode_replicate_from(generation, from_offset, replica_id);
171        sock.write_all(&req)?;
172
173        // Read the `+ACK <gen> <offset>\r\n` reply. Use a small read
174        // timeout so a primary that opens the socket but never
175        // replies doesn't hang the replica forever.
176        sock.set_read_timeout(Some(connect_timeout))?;
177        let (primary_gen, primary_offset) = read_ack(&mut sock)?;
178        // Clear the read timeout for normal streaming (replica may sit
179        // for minutes with no frames if the primary is idle).
180        sock.set_read_timeout(None)?;
181        sock.set_nonblocking(false)?; // explicit: blocking reads after handshake.
182
183        Ok(ReplicaClient {
184            sock,
185            buf: Vec::with_capacity(8 * 1024),
186            cursor: 0,
187            primary_offset_at_handshake: primary_offset,
188            primary_gen_at_handshake: primary_gen,
189            expected_offset: from_offset,
190            in_snapshot: false,
191        })
192    }
193
194    /// Offset the primary reported at handshake (`+ACK <gen> <N>`
195    /// second value). Informational — exposed so callers can log, and
196    /// so snapshot-ship logic can compare against the local applied
197    /// offset to decide resume vs full-sync.
198    pub fn primary_offset_at_handshake(&self) -> u64 {
199        self.primary_offset_at_handshake
200    }
201
202    /// Feed generation the primary reported at handshake
203    /// (`+ACK <gen> <N>` first value). Everything this session
204    /// delivers belongs to this generation; a heartbeat carrying a
205    /// DIFFERENT generation mid-session means the primary broke
206    /// continuity under us (FLUSHALL / promotion) — the caller should
207    /// drop the link and re-handshake so the fence decides afresh.
208    pub fn primary_gen_at_handshake(&self) -> u64 {
209        self.primary_gen_at_handshake
210    }
211
212    /// Return a `try_clone`'d handle on the underlying socket. The
213    /// clone shares the same kernel file description, so calling
214    /// `shutdown(Shutdown::Both)` on it unblocks any in-flight
215    /// blocking read on the original (and vice versa). The server uses
216    /// this to interrupt a runner thread parked in `next_event` when
217    /// `REPLICAOF` retargets or `REPLICAOF NO ONE` demotes — without
218    /// this handle, the runner stays blocked until the upstream peer
219    /// closes the connection.
220    pub fn socket_handle(&self) -> io::Result<TcpStream> {
221        self.sock.try_clone()
222    }
223
224    /// Write `REPLCONF ACK <offset>` back on the replication
225    /// connection. The primary's pump drains these non-blocking and
226    /// advances the replica's slot; call every ~100ms with the highest
227    /// received frame offset + 1 (i.e. the next offset you expect).
228    pub fn send_ack(&mut self, offset: u64) -> std::io::Result<()> {
229        use std::io::Write as _;
230        self.sock.write_all(&crate::wire::encode_replconf_ack(offset))
231    }
232
233    /// The offset the next frame should carry. Advances on every
234    /// successful `next()`.
235    pub fn expected_offset(&self) -> u64 {
236        self.expected_offset
237    }
238
239    /// Pull the next frame from the stream. Frame-only convenience —
240    /// returns [`ReplicaError::SnapshotInProgress`] if the primary is
241    /// sending a snapshot. Callers that need the snapshot-aware
242    /// surface must use [`Self::next_event`] instead.
243    /// Returns `None` on clean peer EOF (no buffered bytes left).
244    pub fn next_frame(&mut self) -> Option<Result<DecodedFrame, ReplicaError>> {
245        loop {
246            match self.next_event()? {
247                Ok(ReplicaEvent::Frame(f)) => return Some(Ok(f)),
248                // Heartbeats are out-of-band — invisible to a
249                // frame-only consumer.
250                Ok(ReplicaEvent::Ping { .. }) => {}
251                Ok(_) => return Some(Err(ReplicaError::SnapshotInProgress)),
252                Err(e) => return Some(Err(e)),
253            }
254        }
255    }
256
257    /// Drop already-consumed prefix when the cursor has walked past
258    /// 4 KiB of buffer (amortises per-frame work without doing a full
259    /// `drain` on every frame). Used by the event-decoding helpers
260    /// in [`crate::replica_decode`].
261    pub(crate) fn maybe_compact_buf(&mut self) {
262        if self.cursor >= 4 * 1024 {
263            self.buf.drain(..self.cursor);
264            self.cursor = 0;
265        }
266    }
267}
268
269impl Iterator for ReplicaClient {
270    type Item = Result<DecodedFrame, ReplicaError>;
271    /// Frame-only iterator. Use [`ReplicaClient::next_event`] for the
272    /// snapshot-aware surface.
273    fn next(&mut self) -> Option<Self::Item> {
274        self.next_frame()
275    }
276}
277
278/// Resolve + connect with timeout. `ToSocketAddrs` returns an
279/// iterator; try each address until one succeeds.
280fn connect_stream<A: ToSocketAddrs>(
281    addr: A,
282    connect_timeout: Duration,
283) -> Result<TcpStream, ReplicaError> {
284    let mut last_err: Option<io::Error> = None;
285    for sa in addr.to_socket_addrs().map_err(ReplicaError::Io)? {
286        match TcpStream::connect_timeout(&sa, connect_timeout) {
287            Ok(s) => return Ok(s),
288            Err(e) => last_err = Some(e),
289        }
290    }
291    Err(ReplicaError::Io(last_err.unwrap_or_else(|| {
292        io::Error::new(io::ErrorKind::InvalidInput, "no socket address resolved")
293    })))
294}
295
296/// Compose a `REPLICATE FROM <gen> <offset> ID <id>` RESP2
297/// multi-bulk request — symmetric to
298/// `handshake::parse_replicate_from` on the primary side.
299fn encode_replicate_from(generation: u64, from_offset: u64, replica_id: &str) -> Vec<u8> {
300    let mut v = Vec::with_capacity(80 + replica_id.len());
301    v.extend_from_slice(b"*6\r\n");
302    let gen_str = generation.to_string();
303    let offset_str = from_offset.to_string();
304    for arg in [
305        b"REPLICATE".as_slice(),
306        b"FROM",
307        gen_str.as_bytes(),
308        offset_str.as_bytes(),
309        b"ID",
310        replica_id.as_bytes(),
311    ] {
312        let header = format!("${}\r\n", arg.len());
313        v.extend_from_slice(header.as_bytes());
314        v.extend_from_slice(arg);
315        v.extend_from_slice(b"\r\n");
316    }
317    v
318}
319
320/// Read `+ACK <gen> <offset>\r\n` from `sock`, return the parsed
321/// `(generation, offset)` pair.
322/// Pulls one byte at a time — the reply is < 50 bytes, so the per-
323/// byte syscall cost is negligible and avoids a buffering surface
324/// we'd have to thread into the client struct just for the handshake.
325fn read_ack(sock: &mut TcpStream) -> Result<(u64, u64), ReplicaError> {
326    let mut line = Vec::with_capacity(32);
327    let mut b = [0u8; 1];
328    loop {
329        match sock.read(&mut b) {
330            Ok(0) => return Err(ReplicaError::HandshakeRejected),
331            Ok(_) => {
332                line.push(b[0]);
333                if line.len() >= 2 && line.ends_with(b"\r\n") {
334                    break;
335                }
336                if line.len() > 256 {
337                    return Err(ReplicaError::AckMalformed);
338                }
339            }
340            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
341            Err(e) => return Err(ReplicaError::Io(e)),
342        }
343    }
344    parse_ack_line(&line)
345}
346
347fn parse_ack_line(line: &[u8]) -> Result<(u64, u64), ReplicaError> {
348    let body = line.strip_suffix(b"\r\n").ok_or(ReplicaError::AckMalformed)?;
349    let body = body.strip_prefix(b"+ACK ").ok_or(ReplicaError::AckMalformed)?;
350    let s = std::str::from_utf8(body).map_err(|_| ReplicaError::AckMalformed)?;
351    // Exactly two space-separated decimals: `<gen> <offset>`. A
352    // one-number (pre-4.0) ACK is malformed — clean wire break.
353    let (gen_s, off_s) = s.split_once(' ').ok_or(ReplicaError::AckMalformed)?;
354    let generation = gen_s.parse::<u64>().map_err(|_| ReplicaError::AckMalformed)?;
355    let offset = off_s.parse::<u64>().map_err(|_| ReplicaError::AckMalformed)?;
356    Ok((generation, offset))
357}
358
359#[cfg(test)]
360impl ReplicaClient {
361    /// Test-only constructor that wraps an already-connected socket
362    /// without doing the handshake. Lets unit tests drive the event
363    /// loop against canned bytes from the other end of a TcpStream pair.
364    pub(crate) fn from_socket_for_test(sock: TcpStream, expected_offset: u64) -> Self {
365        Self {
366            sock,
367            buf: Vec::with_capacity(8 * 1024),
368            cursor: 0,
369            primary_offset_at_handshake: expected_offset,
370            primary_gen_at_handshake: 1,
371            expected_offset,
372            in_snapshot: false,
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn encoded_replicate_from_matches_what_primary_parses() {
383        // Round-trip: encode here, parse via the primary-side parser.
384        let bytes = encode_replicate_from(3, 42, "replica-a");
385        let mut argv = Argv::default();
386        let consumed =
387            kevy_resp::parse_command_into(&bytes, &mut argv).expect("parse ok").expect("complete");
388        assert_eq!(consumed, bytes.len());
389        let req = crate::handshake::parse_replicate_from(&argv).expect("handshake ok");
390        assert_eq!(req.generation, 3);
391        assert_eq!(req.from_offset, 42);
392        assert_eq!(req.replica_id, "replica-a");
393    }
394
395    #[test]
396    fn ack_line_parses_gen_and_offset() {
397        assert_eq!(parse_ack_line(b"+ACK 1 0\r\n").unwrap(), (1, 0));
398        assert_eq!(parse_ack_line(b"+ACK 7 42\r\n").unwrap(), (7, 42));
399        assert_eq!(parse_ack_line(b"+ACK 2 12345678\r\n").unwrap(), (2, 12_345_678));
400    }
401
402    #[test]
403    fn ack_line_rejects_malformed() {
404        assert!(matches!(parse_ack_line(b"+PONG\r\n"), Err(ReplicaError::AckMalformed)));
405        assert!(matches!(parse_ack_line(b"+ACK abc 1\r\n"), Err(ReplicaError::AckMalformed)));
406        assert!(matches!(parse_ack_line(b"-ERR nope\r\n"), Err(ReplicaError::AckMalformed)));
407        // The legacy one-number (pre-4.0) ACK — clean wire break.
408        assert!(matches!(parse_ack_line(b"+ACK 42\r\n"), Err(ReplicaError::AckMalformed)));
409        // Missing CRLF.
410        assert!(matches!(parse_ack_line(b"+ACK 1 1"), Err(ReplicaError::AckMalformed)));
411    }
412
413    #[test]
414    fn ack_line_rejects_offset_overflow() {
415        // 21+ digits — beyond u64::MAX. parse::<u64>() returns Err →
416        // AckMalformed.
417        assert!(matches!(
418            parse_ack_line(b"+ACK 1 99999999999999999999999\r\n"),
419            Err(ReplicaError::AckMalformed)
420        ));
421    }
422}