1use serde_json::Value as JsonValue;
2
3use super::util::{
4 get_bool_default, get_opt_string, get_opt_u64, get_string, get_u64, hex_decode, hex_encode,
5 object_from_slice, ReplicationPayloadError, Result,
6};
7use super::{catchup::CatchupModeReply, DEFAULT_REPLICATION_TERM};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct WalStreamOpen {
11 pub since_lsn: u64,
12 pub max_count: usize,
13 pub replica_id: Option<String>,
14 pub term: u64,
15 pub await_data: bool,
16 pub await_timeout_ms: u64,
17}
18
19impl WalStreamOpen {
20 pub fn encode_json(&self) -> Vec<u8> {
21 self.encode_json_with_endpoints(None)
22 }
23
24 pub fn encode_json_with_endpoints(
25 &self,
26 endpoints: Option<&crate::routing::RoutingEndpoints>,
27 ) -> Vec<u8> {
28 let mut obj = serde_json::Map::new();
29 obj.insert(
30 "since_lsn".to_string(),
31 JsonValue::Number(self.since_lsn.into()),
32 );
33 obj.insert(
34 "max_count".to_string(),
35 JsonValue::Number((self.max_count as u64).into()),
36 );
37 if let Some(replica_id) = &self.replica_id {
38 obj.insert(
39 "replica_id".to_string(),
40 JsonValue::String(replica_id.clone()),
41 );
42 }
43 obj.insert("term".to_string(), JsonValue::Number(self.term.into()));
44 obj.insert("await_data".to_string(), JsonValue::Bool(self.await_data));
45 obj.insert(
46 "await_timeout_ms".to_string(),
47 JsonValue::Number(self.await_timeout_ms.into()),
48 );
49 if let Some(endpoints) = endpoints {
50 obj.insert("endpoints".to_string(), serde_json::json!(endpoints));
51 }
52 serde_json::to_vec(&JsonValue::Object(obj)).unwrap_or_default()
53 }
54
55 pub fn decode_json(bytes: &[u8]) -> Result<Self> {
56 Self::decode_json_with_endpoints(bytes).map(|(open, _)| open)
57 }
58
59 pub fn decode_json_with_endpoints(
60 bytes: &[u8],
61 ) -> Result<(Self, Option<crate::routing::RoutingEndpoints>)> {
62 let obj = object_from_slice(bytes)?;
63 let endpoints = obj.get("endpoints").map(crate::routing::routing_endpoints);
64 let max_count = get_opt_u64(&obj, "max_count").unwrap_or(1000);
65 let open = Self {
66 since_lsn: get_opt_u64(&obj, "since_lsn").unwrap_or(0),
67 max_count: usize::try_from(max_count)
68 .map_err(|_| ReplicationPayloadError::InvalidField("max_count"))?,
69 replica_id: get_opt_string(&obj, "replica_id"),
70 term: get_opt_u64(&obj, "term").unwrap_or(DEFAULT_REPLICATION_TERM),
71 await_data: get_bool_default(&obj, "await_data", false),
72 await_timeout_ms: get_opt_u64(&obj, "await_timeout_ms").unwrap_or(30_000),
73 };
74 Ok((open, endpoints))
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct WalStreamRecord {
80 pub lsn: u64,
81 pub data: Vec<u8>,
82}
83
84impl WalStreamRecord {
85 fn to_json(&self) -> JsonValue {
86 let mut obj = serde_json::Map::new();
87 obj.insert("lsn".to_string(), JsonValue::Number(self.lsn.into()));
88 obj.insert(
89 "data".to_string(),
90 JsonValue::String(hex_encode(&self.data)),
91 );
92 JsonValue::Object(obj)
93 }
94
95 fn from_json(value: &JsonValue) -> Result<Self> {
96 let obj = value
97 .as_object()
98 .ok_or(ReplicationPayloadError::InvalidField("records"))?;
99 let data_hex = get_string(obj, "data")?;
100 Ok(Self {
101 lsn: get_u64(obj, "lsn")?,
102 data: hex_decode("data", &data_hex)?,
103 })
104 }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct WalStreamChunk {
109 pub records: Vec<WalStreamRecord>,
110 pub current_lsn: u64,
111 pub oldest_available_lsn: Option<u64>,
112 pub partial_resync: bool,
113 pub partial_resync_count: u64,
114 pub needs_rebootstrap: bool,
115 pub invalidation_reason: Option<String>,
116 pub catchup: Option<CatchupModeReply>,
117}
118
119impl WalStreamChunk {
120 pub fn encode_json(&self) -> Vec<u8> {
121 self.encode_json_with_endpoints(None)
122 }
123
124 pub fn encode_json_with_endpoints(
125 &self,
126 endpoints: Option<&crate::routing::RoutingEndpoints>,
127 ) -> Vec<u8> {
128 let mut obj = serde_json::Map::new();
129 obj.insert(
130 "records".to_string(),
131 JsonValue::Array(self.records.iter().map(WalStreamRecord::to_json).collect()),
132 );
133 obj.insert(
134 "current_lsn".to_string(),
135 JsonValue::Number(self.current_lsn.into()),
136 );
137 if let Some(lsn) = self.oldest_available_lsn {
138 obj.insert(
139 "oldest_available_lsn".to_string(),
140 JsonValue::Number(lsn.into()),
141 );
142 }
143 obj.insert(
144 "partial_resync".to_string(),
145 JsonValue::Bool(self.partial_resync),
146 );
147 obj.insert(
148 "partial_resync_count".to_string(),
149 JsonValue::Number(self.partial_resync_count.into()),
150 );
151 obj.insert(
152 "needs_rebootstrap".to_string(),
153 JsonValue::Bool(self.needs_rebootstrap),
154 );
155 if let Some(reason) = &self.invalidation_reason {
156 obj.insert(
157 "invalidation_reason".to_string(),
158 JsonValue::String(reason.clone()),
159 );
160 }
161 if let Some(catchup) = &self.catchup {
162 let catchup_obj = object_from_slice(&catchup.encode_json())
163 .expect("CatchupModeReply emits a JSON object");
164 for (key, value) in catchup_obj {
165 obj.insert(key, value);
166 }
167 }
168 if let Some(endpoints) = endpoints {
169 obj.insert(
170 "primary_endpoints".to_string(),
171 serde_json::json!(endpoints),
172 );
173 }
174 serde_json::to_vec(&JsonValue::Object(obj)).unwrap_or_default()
175 }
176
177 pub fn decode_json(bytes: &[u8]) -> Result<Self> {
178 Self::decode_json_with_endpoints(bytes).map(|(chunk, _)| chunk)
179 }
180
181 pub fn decode_json_with_endpoints(
182 bytes: &[u8],
183 ) -> Result<(Self, Option<crate::routing::RoutingEndpoints>)> {
184 let obj = object_from_slice(bytes)?;
185 let endpoints = obj
186 .get("primary_endpoints")
187 .map(crate::routing::routing_endpoints);
188 let records = match obj.get("records") {
189 Some(JsonValue::Array(values)) => values
190 .iter()
191 .map(WalStreamRecord::from_json)
192 .collect::<Result<Vec<_>>>()?,
193 Some(_) => return Err(ReplicationPayloadError::InvalidField("records")),
194 None => Vec::new(),
195 };
196 let chunk = Self {
197 records,
198 current_lsn: get_u64(&obj, "current_lsn")?,
199 oldest_available_lsn: get_opt_u64(&obj, "oldest_available_lsn"),
200 partial_resync: get_bool_default(&obj, "partial_resync", false),
201 partial_resync_count: get_opt_u64(&obj, "partial_resync_count").unwrap_or(0),
202 needs_rebootstrap: get_bool_default(&obj, "needs_rebootstrap", false),
203 invalidation_reason: get_opt_string(&obj, "invalidation_reason"),
204 catchup: CatchupModeReply::from_wal_rebootstrap_object(&obj)?,
205 };
206 Ok((chunk, endpoints))
207 }
208}
209
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct WalStreamAck {
212 pub replica_id: String,
213 pub applied_lsn: u64,
214 pub durable_lsn: u64,
215 pub apply_errors_total: u64,
216 pub divergence_total: u64,
217}
218
219impl WalStreamAck {
220 pub fn encode_json(&self) -> Vec<u8> {
221 let mut obj = serde_json::Map::new();
222 obj.insert(
223 "replica_id".to_string(),
224 JsonValue::String(self.replica_id.clone()),
225 );
226 obj.insert(
227 "applied_lsn".to_string(),
228 JsonValue::Number(self.applied_lsn.into()),
229 );
230 obj.insert(
231 "durable_lsn".to_string(),
232 JsonValue::Number(self.durable_lsn.into()),
233 );
234 obj.insert(
235 "apply_errors_total".to_string(),
236 JsonValue::Number(self.apply_errors_total.into()),
237 );
238 obj.insert(
239 "divergence_total".to_string(),
240 JsonValue::Number(self.divergence_total.into()),
241 );
242 serde_json::to_vec(&JsonValue::Object(obj)).unwrap_or_default()
243 }
244
245 pub fn decode_json(bytes: &[u8]) -> Result<Self> {
246 let obj = object_from_slice(bytes)?;
247 let applied_lsn = get_u64(&obj, "applied_lsn")?;
248 Ok(Self {
249 replica_id: get_string(&obj, "replica_id")?,
250 applied_lsn,
251 durable_lsn: get_opt_u64(&obj, "durable_lsn").unwrap_or(applied_lsn),
252 apply_errors_total: get_opt_u64(&obj, "apply_errors_total").unwrap_or(0),
253 divergence_total: get_opt_u64(&obj, "divergence_total").unwrap_or(0),
254 })
255 }
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct WalStreamAckReply {
260 pub ok: bool,
261 pub replica_id: String,
262 pub applied_lsn: u64,
263 pub durable_lsn: u64,
264 pub apply_errors_total: u64,
265 pub divergence_total: u64,
266}
267
268impl WalStreamAckReply {
269 pub fn from_ack(ack: &WalStreamAck) -> Self {
270 Self {
271 ok: true,
272 replica_id: ack.replica_id.clone(),
273 applied_lsn: ack.applied_lsn,
274 durable_lsn: ack.durable_lsn,
275 apply_errors_total: ack.apply_errors_total,
276 divergence_total: ack.divergence_total,
277 }
278 }
279
280 pub fn encode_json(&self) -> Vec<u8> {
281 let mut obj = serde_json::Map::new();
282 obj.insert("ok".to_string(), JsonValue::Bool(self.ok));
283 obj.insert(
284 "replica_id".to_string(),
285 JsonValue::String(self.replica_id.clone()),
286 );
287 obj.insert(
288 "applied_lsn".to_string(),
289 JsonValue::Number(self.applied_lsn.into()),
290 );
291 obj.insert(
292 "durable_lsn".to_string(),
293 JsonValue::Number(self.durable_lsn.into()),
294 );
295 obj.insert(
296 "apply_errors_total".to_string(),
297 JsonValue::Number(self.apply_errors_total.into()),
298 );
299 obj.insert(
300 "divergence_total".to_string(),
301 JsonValue::Number(self.divergence_total.into()),
302 );
303 serde_json::to_vec(&JsonValue::Object(obj)).unwrap_or_default()
304 }
305
306 pub fn decode_json(bytes: &[u8]) -> Result<Self> {
307 let obj = object_from_slice(bytes)?;
308 Ok(Self {
309 ok: get_bool_default(&obj, "ok", false),
310 replica_id: get_string(&obj, "replica_id")?,
311 applied_lsn: get_u64(&obj, "applied_lsn")?,
312 durable_lsn: get_u64(&obj, "durable_lsn")?,
313 apply_errors_total: get_opt_u64(&obj, "apply_errors_total").unwrap_or(0),
314 divergence_total: get_opt_u64(&obj, "divergence_total").unwrap_or(0),
315 })
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use crate::replication::CatchupMode;
323
324 #[test]
325 fn wal_stream_open_round_trips() {
326 let open = WalStreamOpen {
327 since_lsn: 10,
328 max_count: 128,
329 replica_id: Some("replica-a".to_string()),
330 term: 7,
331 await_data: true,
332 await_timeout_ms: 5000,
333 };
334 assert_eq!(
335 WalStreamOpen::decode_json(&open.encode_json()).unwrap(),
336 open
337 );
338 let endpoints = crate::routing::RoutingEndpoints::from([(
339 "https".to_string(),
340 "https://replica:8443".to_string(),
341 )]);
342 let advertised = open.encode_json_with_endpoints(Some(&endpoints));
343 assert_eq!(
344 WalStreamOpen::decode_json(&advertised).expect("legacy fields"),
345 open
346 );
347 assert_eq!(
348 WalStreamOpen::decode_json_with_endpoints(&advertised).expect("endpoint metadata"),
349 (open.clone(), Some(endpoints))
350 );
351 assert_eq!(
352 WalStreamOpen::decode_json_with_endpoints(&open.encode_json())
353 .expect("old peer")
354 .1,
355 None
356 );
357 }
358
359 #[test]
360 fn wal_stream_open_defaults_missing_term_to_legacy_term() {
361 let open = WalStreamOpen::decode_json(
362 br#"{"since_lsn":10,"max_count":128,"replica_id":"replica-a"}"#,
363 )
364 .unwrap();
365 assert_eq!(open.term, DEFAULT_REPLICATION_TERM);
366 }
367
368 #[test]
369 fn wal_stream_chunk_round_trips_records_and_rebootstrap_hint() {
370 let chunk = WalStreamChunk {
371 records: vec![WalStreamRecord {
372 lsn: 11,
373 data: b"record".to_vec(),
374 }],
375 current_lsn: 12,
376 oldest_available_lsn: Some(9),
377 partial_resync: true,
378 partial_resync_count: 3,
379 needs_rebootstrap: true,
380 invalidation_reason: Some("retention".to_string()),
381 catchup: Some(CatchupModeReply {
382 mode: CatchupMode::BaseBackupThenWal,
383 available_from_lsn: Some(9),
384 replica_lsn: None,
385 reason: Some("retention".to_string()),
386 }),
387 };
388 assert_eq!(
389 WalStreamChunk::decode_json(&chunk.encode_json()).unwrap(),
390 chunk
391 );
392 let endpoints = crate::routing::RoutingEndpoints::from([(
393 "grpc".to_string(),
394 "grpc://primary:55055".to_string(),
395 )]);
396 let advertised = chunk.encode_json_with_endpoints(Some(&endpoints));
397 assert_eq!(
398 WalStreamChunk::decode_json(&advertised).expect("legacy fields"),
399 chunk
400 );
401 assert_eq!(
402 WalStreamChunk::decode_json_with_endpoints(&advertised).expect("endpoint metadata"),
403 (chunk.clone(), Some(endpoints))
404 );
405 assert_eq!(
406 WalStreamChunk::decode_json_with_endpoints(&chunk.encode_json())
407 .expect("old peer")
408 .1,
409 None
410 );
411 }
412
413 #[test]
414 fn wal_ack_defaults_durable_to_applied() {
415 let ack = WalStreamAck::decode_json(br#"{"replica_id":"r","applied_lsn":7}"#).unwrap();
416 assert_eq!(ack.durable_lsn, 7);
417 assert_eq!(ack.apply_errors_total, 0);
418 }
419
420 #[test]
421 fn wal_ack_reply_round_trips() {
422 let ack = WalStreamAck {
423 replica_id: "replica-a".to_string(),
424 applied_lsn: 11,
425 durable_lsn: 10,
426 apply_errors_total: 2,
427 divergence_total: 1,
428 };
429 let reply = WalStreamAckReply::from_ack(&ack);
430
431 assert_eq!(
432 WalStreamAckReply::decode_json(&reply.encode_json()).unwrap(),
433 reply
434 );
435 }
436}