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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//! Snapshot ship wire format — split out of [`crate::wire`]
//! to keep that file under the 500-LOC project ceiling.
//!
//! See `docs/snapshot.md` for the full spec. The primary sends:
//!
//! `+SNAPSHOT\r\n`
//! `$L1\r\n<L1 bytes>\r\n` (chunk 1)
//! `$L2\r\n<L2 bytes>\r\n` (chunk 2)
//! ...
//! `+SNAPSHOT_END <ack_offset>\r\n`
//!
//! Markers are RESP simple strings, chunks are RESP bulk strings —
//! any RESP-aware tool can peek a captured stream.
use crateFeedPosition;
use crate;
/// Per-chunk cap: a chunk's `$L\r\n` length must not exceed this.
/// Replica drops the link if a chunk header reports a larger size.
/// 64 KiB matches a typical TCP segment + keeps the per-chunk
/// allocation modest. The primary may pick any chunk size from
/// `1` up to this.
///
/// ```
/// use kevy_replicate::wire::{SNAPSHOT_CHUNK_MAX, WireError, decode_snapshot_chunk};
///
/// let dump = vec![0u8; 3 * SNAPSHOT_CHUNK_MAX / 2];
/// assert_eq!(dump.chunks(SNAPSHOT_CHUNK_MAX).count(), 2); // ship it in two chunks
/// // a header announcing a larger chunk is refused before any allocation
/// let oversize = format!("${}\r\n", SNAPSHOT_CHUNK_MAX + 1);
/// assert_eq!(decode_snapshot_chunk(oversize.as_bytes()), Err(WireError::BadEnvelope));
/// ```
pub const SNAPSHOT_CHUNK_MAX: usize = 64 * 1024;
/// Maximum length of a snapshot control line (`+SNAPSHOT_END N\r\n`).
/// 256 B is generous — the longest legal line is `+SNAPSHOT_END ` +
/// 20 digits + `\r\n` = 38 B.
///
/// ```
/// use kevy_replicate::wire::{SNAPSHOT_LINE_MAX, WireError, decode_snapshot_marker};
///
/// assert!(kevy_replicate::wire::encode_snapshot_end(u64::MAX).len() <= SNAPSHOT_LINE_MAX);
/// // a `+` line that runs on without a terminator is refused, not buffered forever
/// let runaway = [b"+".as_slice(), &[b'x'; SNAPSHOT_LINE_MAX + 1]].concat();
/// assert_eq!(decode_snapshot_marker(&runaway), Err(WireError::BadEnvelope));
/// ```
pub const SNAPSHOT_LINE_MAX: usize = 256;
/// Decoded snapshot marker, returned by [`decode_snapshot_marker`].
///
/// ```
/// use kevy_replicate::wire::{SnapshotMarker, decode_snapshot_marker, encode_snapshot_end};
///
/// let (marker, _) = decode_snapshot_marker(&encode_snapshot_end(12))?.expect("a marker line");
/// let next_live_offset = match marker {
/// SnapshotMarker::End(ack) => ack,
/// other => panic!("unexpected {other:?}"),
/// };
/// assert_eq!(next_live_offset, 12);
/// # Ok::<(), kevy_replicate::wire::WireError>(())
/// ```
/// Encode the snapshot-begin marker. Allocates the exact 11 bytes.
///
/// ```
/// assert_eq!(kevy_replicate::wire::encode_snapshot_begin(), b"+SNAPSHOT\r\n");
/// ```
/// Encode one snapshot chunk as a RESP bulk string. Caller is
/// responsible for chunking — typical strategy is fixed
/// [`SNAPSHOT_CHUNK_MAX`]-sized reads from a snapshot file or
/// in-memory serializer.
///
/// **Debug-asserts** `bytes.len() <= SNAPSHOT_CHUNK_MAX` so an
/// accidental oversize chunk trips during development; release
/// builds emit a frame the peer will reject with [`WireError::BadEnvelope`]
/// (replica's decoder caps incoming chunk lengths).
///
/// ```
/// use kevy_replicate::wire::{SNAPSHOT_CHUNK_MAX, decode_snapshot_chunk, encode_snapshot_chunk};
///
/// let dump = b"serialized keyspace";
/// let mut stream = Vec::new();
/// for part in dump.chunks(SNAPSHOT_CHUNK_MAX) {
/// stream.extend(encode_snapshot_chunk(part));
/// }
/// assert_eq!(stream, b"$19\r\nserialized keyspace\r\n");
/// assert_eq!(decode_snapshot_chunk(&stream)?.0, dump);
/// # Ok::<(), kevy_replicate::wire::WireError>(())
/// ```
/// Encode the in-stream heartbeat carrying the primary's tail:
/// `+PING <generation> <next_offset>\r\n`.
///
/// ```
/// use kevy_replicate::feed::FeedPosition;
///
/// assert_eq!(kevy_replicate::wire::encode_ping(FeedPosition::new(3, 9)), b"+PING 3 9\r\n");
/// ```
/// Encode the replica→primary acknowledgment line:
/// `REPLCONF ACK <offset>\r\n` — inline RESP, written back on the
/// SAME replication connection (the pump drains it non-blocking).
///
/// ```
/// use kevy_replicate::wire::{decode_replconf_ack, encode_replconf_ack};
///
/// let line = encode_replconf_ack(128);
/// assert_eq!(line, b"REPLCONF ACK 128\r\n");
/// assert_eq!(decode_replconf_ack(&line)?, Some((128, line.len())));
/// # Ok::<(), kevy_replicate::wire::WireError>(())
/// ```
/// Parse one `REPLCONF ACK <offset>\r\n` line at the front of `buf`.
/// `Ok(Some((offset, used)))` on a full line; `Ok(None)` if the buffer
/// doesn't start with `R` (not an ACK); `Err(Truncated)` if incomplete.
///
/// ```
/// use kevy_replicate::wire::{WireError, decode_replconf_ack};
///
/// assert_eq!(decode_replconf_ack(b"REPLCONF ACK 9\r\n")?, Some((9, 16)));
/// assert_eq!(decode_replconf_ack(b"PING\r\n")?, None); // not an ack
/// assert_eq!(decode_replconf_ack(b"REPLCONF AC"), Err(WireError::Truncated));
/// # Ok::<(), WireError>(())
/// ```
/// Encode the snapshot-end marker carrying the ack offset (the
/// next live frame's offset will equal this value).
///
/// ```
/// assert_eq!(kevy_replicate::wire::encode_snapshot_end(57), b"+SNAPSHOT_END 57\r\n");
/// ```
/// Peek the next line at the front of `buf` to detect a snapshot
/// marker. Returns:
/// - `Ok(Some((marker, used)))` — a full marker line was found;
/// `used` bytes may be dropped.
/// - `Ok(None)` — the buffer doesn't start with a `+` byte; caller
/// should treat the bytes as a regular `*2\r\n` frame and feed
/// the frame decoder instead.
/// - `Err(WireError::Truncated)` — buffer starts with `+` but the
/// `\r\n` terminator is not yet in the buffer.
/// - `Err(WireError::BadEnvelope)` — buffer starts with `+` but the
/// line is neither `+SNAPSHOT` nor `+SNAPSHOT_END <N>`, or the
/// line exceeds [`SNAPSHOT_LINE_MAX`].
///
/// ```
/// use kevy_replicate::wire::{SnapshotMarker, WireError, decode_snapshot_marker};
///
/// assert_eq!(decode_snapshot_marker(b"+SNAPSHOT\r\n$3")?, Some((SnapshotMarker::Begin, 11)));
/// assert_eq!(decode_snapshot_marker(b"*2\r\n")?, None); // a live frame: use decode_frame
/// assert_eq!(decode_snapshot_marker(b"+SNAPSH"), Err(WireError::Truncated));
/// assert_eq!(decode_snapshot_marker(b"+HELLO\r\n"), Err(WireError::BadEnvelope));
/// # Ok::<(), WireError>(())
/// ```
/// Decode the next snapshot chunk (`$L\r\n<L bytes>\r\n`) at the
/// front of `buf`. Returns:
/// - `Ok((chunk_bytes, used))` — `chunk_bytes` borrows from `buf`;
/// `used` bytes were consumed.
/// - `Err(WireError::Truncated)` — not enough bytes for a complete
/// chunk yet.
/// - `Err(WireError::BadEnvelope)` — header wasn't `$L\r\n`, `L`
/// exceeded [`SNAPSHOT_CHUNK_MAX`], `L` parsed as non-numeric, or
/// the trailing CRLF was missing.
///
/// ```
/// use kevy_replicate::wire::{WireError, decode_snapshot_chunk};
///
/// let (chunk, used) = decode_snapshot_chunk(b"$4\r\nabcd\r\n+SNAPSHOT_END 9\r\n")?;
/// assert_eq!((chunk, used), (&b"abcd"[..], 10)); // the end marker follows
/// assert_eq!(decode_snapshot_chunk(b"$4\r\nab"), Err(WireError::Truncated));
/// # Ok::<(), WireError>(())
/// ```