1use reddb_types::encoding::base64_encode;
50
51pub const TOPOLOGY_WIRE_VERSION_V1: u8 = 0x01;
57
58pub const MAX_KNOWN_TOPOLOGY_VERSION: u8 = TOPOLOGY_WIRE_VERSION_V1;
62
63pub const TOPOLOGY_HEADER_SIZE: usize = 1 + 4;
65
66#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Topology {
72 pub epoch: u64,
73 pub primary: Endpoint,
74 pub replicas: Vec<ReplicaInfo>,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Endpoint {
79 pub addr: String,
80 pub region: String,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct ReplicaInfo {
85 pub addr: String,
86 pub region: String,
87 pub healthy: bool,
88 pub lag_ms: u32,
89 pub last_applied_lsn: u64,
90 pub rebootstrapping: bool,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum TopologyError {
111 Truncated,
112 BodyLengthMismatch { declared: u32, available: usize },
113 InvalidUtf8,
114 StringTooLong { declared: u32, remaining: usize },
115}
116
117impl std::fmt::Display for TopologyError {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 match self {
120 Self::Truncated => write!(f, "topology blob truncated (< 5-byte header)"),
121 Self::BodyLengthMismatch {
122 declared,
123 available,
124 } => write!(
125 f,
126 "topology body length mismatch: declared {declared}, available {available}"
127 ),
128 Self::InvalidUtf8 => write!(f, "topology string field is not valid UTF-8"),
129 Self::StringTooLong {
130 declared,
131 remaining,
132 } => write!(
133 f,
134 "topology string length {declared} exceeds remaining body bytes {remaining}"
135 ),
136 }
137 }
138}
139
140impl std::error::Error for TopologyError {}
141
142pub fn encode_topology(topology: &Topology) -> Vec<u8> {
147 let mut body = Vec::with_capacity(estimate_body_size(topology));
148 body.extend_from_slice(&topology.epoch.to_le_bytes());
149 write_str(&mut body, &topology.primary.addr);
150 write_str(&mut body, &topology.primary.region);
151 body.extend_from_slice(&(topology.replicas.len() as u32).to_le_bytes());
152 for r in &topology.replicas {
153 write_str(&mut body, &r.addr);
154 write_str(&mut body, &r.region);
155 body.push(if r.healthy { 1 } else { 0 });
156 body.extend_from_slice(&r.lag_ms.to_le_bytes());
157 body.extend_from_slice(&r.last_applied_lsn.to_le_bytes());
158 }
159 for r in &topology.replicas {
165 body.push(if r.rebootstrapping { 1 } else { 0 });
166 }
167
168 let mut out = Vec::with_capacity(TOPOLOGY_HEADER_SIZE + body.len());
169 out.push(TOPOLOGY_WIRE_VERSION_V1);
170 out.extend_from_slice(&(body.len() as u32).to_le_bytes());
171 out.extend_from_slice(&body);
172 out
173}
174
175pub fn decode_topology(bytes: &[u8]) -> Result<Option<Topology>, TopologyError> {
185 if bytes.len() < TOPOLOGY_HEADER_SIZE {
186 return Err(TopologyError::Truncated);
187 }
188 let version = bytes[0];
189 let declared_len = u32::from_le_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
190 let body = &bytes[TOPOLOGY_HEADER_SIZE..];
191 if (body.len() as u64) < declared_len as u64 {
192 return Err(TopologyError::BodyLengthMismatch {
193 declared: declared_len,
194 available: body.len(),
195 });
196 }
197 let body = &body[..declared_len as usize];
198
199 if version > MAX_KNOWN_TOPOLOGY_VERSION {
200 return Ok(None);
202 }
203
204 let mut cur = Cursor::new(body);
206 let epoch = cur.read_u64()?;
207 let primary_addr = cur.read_str()?;
208 let primary_region = cur.read_str()?;
209 let replica_count = cur.read_u32()? as usize;
210 let replica_bytes_min = replica_count
213 .checked_mul(21)
214 .ok_or(TopologyError::Truncated)?;
215 if replica_bytes_min > cur.remaining() {
216 return Err(TopologyError::Truncated);
217 }
218 let mut replicas = Vec::with_capacity(replica_count);
219 for _ in 0..replica_count {
220 let addr = cur.read_str()?;
221 let region = cur.read_str()?;
222 let healthy = cur.read_u8()? != 0;
223 let lag_ms = cur.read_u32()?;
224 let last_applied_lsn = cur.read_u64()?;
225 replicas.push(ReplicaInfo {
226 addr,
227 region,
228 healthy,
229 lag_ms,
230 last_applied_lsn,
231 rebootstrapping: false,
235 });
236 }
237 for r in replicas.iter_mut() {
244 if cur.remaining() == 0 {
245 break;
246 }
247 r.rebootstrapping = cur.read_u8()? != 0;
248 }
249 Ok(Some(Topology {
250 epoch,
251 primary: Endpoint {
252 addr: primary_addr,
253 region: primary_region,
254 },
255 replicas,
256 }))
257}
258
259fn estimate_body_size(t: &Topology) -> usize {
260 let endpoint = |e: &Endpoint| 4 + e.addr.len() + 4 + e.region.len();
261 let mut n = 8 + endpoint(&t.primary) + 4;
262 for r in &t.replicas {
263 n += 4 + r.addr.len() + 4 + r.region.len() + 1 + 4 + 8;
264 }
265 n += t.replicas.len();
267 n
268}
269
270fn write_str(buf: &mut Vec<u8>, s: &str) {
271 buf.extend_from_slice(&(s.len() as u32).to_le_bytes());
272 buf.extend_from_slice(s.as_bytes());
273}
274
275struct Cursor<'a> {
276 buf: &'a [u8],
277 pos: usize,
278}
279
280impl<'a> Cursor<'a> {
281 fn new(buf: &'a [u8]) -> Self {
282 Self { buf, pos: 0 }
283 }
284
285 fn remaining(&self) -> usize {
286 self.buf.len() - self.pos
287 }
288
289 fn read_u8(&mut self) -> Result<u8, TopologyError> {
290 if self.remaining() < 1 {
291 return Err(TopologyError::Truncated);
292 }
293 let v = self.buf[self.pos];
294 self.pos += 1;
295 Ok(v)
296 }
297
298 fn read_u32(&mut self) -> Result<u32, TopologyError> {
299 if self.remaining() < 4 {
300 return Err(TopologyError::Truncated);
301 }
302 let bytes = &self.buf[self.pos..self.pos + 4];
303 self.pos += 4;
304 Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
305 }
306
307 fn read_u64(&mut self) -> Result<u64, TopologyError> {
308 if self.remaining() < 8 {
309 return Err(TopologyError::Truncated);
310 }
311 let bytes = &self.buf[self.pos..self.pos + 8];
312 self.pos += 8;
313 Ok(u64::from_le_bytes([
314 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
315 ]))
316 }
317
318 fn read_str(&mut self) -> Result<String, TopologyError> {
319 let len = self.read_u32()?;
320 if (len as usize) > self.remaining() {
321 return Err(TopologyError::StringTooLong {
322 declared: len,
323 remaining: self.remaining(),
324 });
325 }
326 let bytes = &self.buf[self.pos..self.pos + len as usize];
327 self.pos += len as usize;
328 let s = std::str::from_utf8(bytes)
329 .map_err(|_| TopologyError::InvalidUtf8)?
330 .to_string();
331 Ok(s)
332 }
333}
334
335pub fn encode_topology_for_hello_ack(topology: &Topology) -> String {
353 base64_encode(&encode_topology(topology))
354}
355
356pub fn decode_topology_from_hello_ack(field: &str) -> Result<Option<Topology>, TopologyError> {
366 let Some(bytes) = base64_decode(field) else {
367 return Ok(None);
371 };
372 decode_topology(&bytes)
373}
374
375fn base64_decode(input: &str) -> Option<Vec<u8>> {
376 let trimmed = input.trim_end_matches('=');
377 let mut out = Vec::with_capacity(trimmed.len() * 3 / 4);
378 let mut buf = 0u32;
379 let mut bits = 0u8;
380 for ch in trimmed.bytes() {
381 let v: u32 = match ch {
382 b'A'..=b'Z' => (ch - b'A') as u32,
383 b'a'..=b'z' => (ch - b'a' + 26) as u32,
384 b'0'..=b'9' => (ch - b'0' + 52) as u32,
385 b'+' => 62,
386 b'/' => 63,
387 _ => return None,
388 };
389 buf = (buf << 6) | v;
390 bits += 6;
391 if bits >= 8 {
392 bits -= 8;
393 out.push(((buf >> bits) & 0xFF) as u8);
394 }
395 }
396 Some(out)
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 fn fixture() -> Topology {
404 Topology {
405 epoch: 0xDEAD_BEEF_CAFE_BABE,
406 primary: Endpoint {
407 addr: "primary.example.com:5050".into(),
408 region: "us-east-1".into(),
409 },
410 replicas: vec![
411 ReplicaInfo {
412 addr: "replica-a.example.com:5050".into(),
413 region: "us-east-1".into(),
414 healthy: true,
415 lag_ms: 12,
416 last_applied_lsn: 4242,
417 rebootstrapping: false,
418 },
419 ReplicaInfo {
420 addr: "replica-b.example.com:5050".into(),
421 region: "us-west-2".into(),
422 healthy: false,
423 lag_ms: 999,
424 last_applied_lsn: 4100,
425 rebootstrapping: true,
426 },
427 ],
428 }
429 }
430
431 #[test]
432 fn round_trip_v1() {
433 let t = fixture();
434 let bytes = encode_topology(&t);
435 let decoded = decode_topology(&bytes).expect("decode").expect("v1 known");
436 assert_eq!(decoded, t);
437 }
438
439 #[test]
440 fn empty_replicas_round_trip() {
441 let t = Topology {
442 epoch: 1,
443 primary: Endpoint {
444 addr: "p:5050".into(),
445 region: "r".into(),
446 },
447 replicas: vec![],
448 };
449 let bytes = encode_topology(&t);
450 let decoded = decode_topology(&bytes).expect("decode").expect("v1");
451 assert_eq!(decoded, t);
452 }
453
454 #[test]
455 fn unknown_version_tag_returns_none() {
456 let mut bytes = encode_topology(&fixture());
460 bytes[0] = 0xFE; let decoded = decode_topology(&bytes).expect("decode");
462 assert!(
463 decoded.is_none(),
464 "unknown version tag must drop cleanly, got {decoded:?}"
465 );
466 }
467
468 #[test]
469 fn truncated_header_errors() {
470 assert!(matches!(
471 decode_topology(&[0x01, 0x00]),
472 Err(TopologyError::Truncated)
473 ));
474 }
475
476 #[test]
477 fn body_length_mismatch_errors() {
478 let bytes = vec![0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0x00];
480 assert!(matches!(
481 decode_topology(&bytes),
482 Err(TopologyError::BodyLengthMismatch { .. })
483 ));
484 }
485
486 #[test]
487 fn version_tag_is_pinned_to_0x01() {
488 assert_eq!(TOPOLOGY_WIRE_VERSION_V1, 0x01);
492 }
493
494 #[test]
495 fn rebootstrapping_flag_round_trips_per_replica() {
496 let t = fixture();
499 let decoded = decode_topology(&encode_topology(&t))
500 .expect("decode")
501 .expect("v1 known");
502 assert!(!decoded.replicas[0].rebootstrapping);
503 assert!(decoded.replicas[1].rebootstrapping);
504 }
505
506 #[test]
507 fn legacy_blob_without_trailing_block_defaults_rebootstrapping_false() {
508 let t = fixture();
514 let full = encode_topology(&t);
515 let trailing = t.replicas.len();
516 let body_len = (full.len() - TOPOLOGY_HEADER_SIZE - trailing) as u32;
517 let mut legacy = Vec::new();
518 legacy.push(TOPOLOGY_WIRE_VERSION_V1);
519 legacy.extend_from_slice(&body_len.to_le_bytes());
520 legacy.extend_from_slice(&full[TOPOLOGY_HEADER_SIZE..full.len() - trailing]);
521 let decoded = decode_topology(&legacy).expect("decode").expect("v1 known");
522 assert_eq!(decoded.replicas.len(), 2);
523 assert!(decoded.replicas.iter().all(|r| !r.rebootstrapping));
524 assert_eq!(decoded.replicas[0].last_applied_lsn, 4242);
527 assert_eq!(decoded.replicas[1].lag_ms, 999);
528 }
529
530 #[test]
531 fn hello_ack_round_trip_via_base64() {
532 let t = fixture();
536 let field = encode_topology_for_hello_ack(&t);
537 let decoded = decode_topology_from_hello_ack(&field)
538 .expect("decode")
539 .expect("v1 known");
540 assert_eq!(decoded, t);
541 }
542
543 #[test]
544 fn hello_ack_inner_bytes_match_grpc_bytes() {
545 let t = fixture();
550 let canonical = encode_topology(&t);
551 let field = encode_topology_for_hello_ack(&t);
552 let recovered = base64_decode(&field).expect("base64");
553 assert_eq!(recovered, canonical);
554 }
555
556 #[test]
557 fn hello_ack_unknown_version_tag_drops_cleanly() {
558 let mut bytes = encode_topology(&fixture());
562 bytes[0] = 0x99;
563 let field = base64_encode(&bytes);
564 let decoded = decode_topology_from_hello_ack(&field).expect("decode");
565 assert!(decoded.is_none());
566 }
567
568 #[test]
569 fn hello_ack_malformed_base64_drops_cleanly() {
570 let decoded = decode_topology_from_hello_ack("@not base64@").expect("decode");
573 assert!(decoded.is_none());
574 }
575
576 #[test]
577 fn old_hello_ack_without_topology_field_is_backwards_compat() {
578 let json = br#"{"version":1,"auth":"bearer","features":3,"server":"reddb/0.2.9"}"#;
586 let v: serde_json_check::Value = serde_json_check::from_slice(json).expect("valid JSON");
587 let topo_field = v.find_string("topology");
588 let topology = match topo_field {
589 None => None,
590 Some(s) => decode_topology_from_hello_ack(&s).expect("decode"),
591 };
592 assert!(
593 topology.is_none(),
594 "an old HelloAck without `topology` must produce None"
595 );
596 }
597
598 mod serde_json_check {
602 pub enum Value {
603 Object(Vec<(String, Value)>),
604 String(String),
605 Other,
606 }
607
608 impl Value {
609 pub fn find_string(&self, key: &str) -> Option<String> {
610 match self {
611 Value::Object(map) => map.iter().find_map(|(k, v)| {
612 if k == key {
613 if let Value::String(s) = v {
614 Some(s.clone())
615 } else {
616 None
617 }
618 } else {
619 None
620 }
621 }),
622 _ => None,
623 }
624 }
625 }
626
627 pub fn from_slice(bytes: &[u8]) -> Result<Value, &'static str> {
628 let s = std::str::from_utf8(bytes).map_err(|_| "utf8")?;
629 let mut p = Parser { src: s, pos: 0 };
630 p.skip_ws();
631 let v = p.parse_value()?;
632 Ok(v)
633 }
634
635 struct Parser<'a> {
636 src: &'a str,
637 pos: usize,
638 }
639
640 impl<'a> Parser<'a> {
641 fn rest(&self) -> &'a str {
642 &self.src[self.pos..]
643 }
644 fn bump(&mut self, n: usize) {
645 self.pos += n;
646 }
647 fn skip_ws(&mut self) {
648 while let Some(c) = self.rest().chars().next() {
649 if c.is_whitespace() {
650 self.bump(c.len_utf8());
651 } else {
652 break;
653 }
654 }
655 }
656 fn parse_value(&mut self) -> Result<Value, &'static str> {
657 self.skip_ws();
658 let head = self.rest().chars().next().ok_or("eof")?;
659 match head {
660 '{' => self.parse_object(),
661 '"' => self.parse_string().map(Value::String),
662 _ => {
663 self.skip_until_top_level_comma_or_close();
668 Ok(Value::Other)
669 }
670 }
671 }
672 fn skip_until_top_level_comma_or_close(&mut self) {
673 let mut depth = 0i32;
674 while let Some(c) = self.rest().chars().next() {
675 match c {
676 '"' => {
677 let _ = self.parse_string();
678 continue;
679 }
680 '{' | '[' => {
681 depth += 1;
682 self.bump(1);
683 }
684 '}' | ']' => {
685 if depth == 0 {
686 return;
687 }
688 depth -= 1;
689 self.bump(1);
690 }
691 ',' if depth == 0 => return,
692 _ => self.bump(c.len_utf8()),
693 }
694 }
695 }
696 fn parse_object(&mut self) -> Result<Value, &'static str> {
697 self.bump(1); let mut map = Vec::new();
699 loop {
700 self.skip_ws();
701 if self.rest().starts_with('}') {
702 self.bump(1);
703 return Ok(Value::Object(map));
704 }
705 let key = self.parse_string()?;
706 self.skip_ws();
707 if !self.rest().starts_with(':') {
708 return Err("expected ':'");
709 }
710 self.bump(1);
711 let val = self.parse_value()?;
712 map.push((key, val));
713 self.skip_ws();
714 match self.rest().chars().next() {
715 Some(',') => {
716 self.bump(1);
717 continue;
718 }
719 Some('}') => {
720 self.bump(1);
721 return Ok(Value::Object(map));
722 }
723 _ => return Err("expected ',' or '}'"),
724 }
725 }
726 }
727 fn parse_string(&mut self) -> Result<String, &'static str> {
728 if !self.rest().starts_with('"') {
729 return Err("expected '\"'");
730 }
731 self.bump(1);
732 let start = self.pos;
733 while let Some(c) = self.rest().chars().next() {
734 if c == '"' {
735 let s = self.src[start..self.pos].to_string();
736 self.bump(1);
737 return Ok(s);
738 }
739 if c == '\\' {
740 self.bump(c.len_utf8());
741 }
742 self.bump(c.len_utf8());
743 }
744 Err("unterminated string")
745 }
746 }
747 }
748
749 #[test]
750 fn header_layout_first_byte_is_version_then_le_length() {
751 let t = fixture();
756 let bytes = encode_topology(&t);
757 assert_eq!(bytes[0], TOPOLOGY_WIRE_VERSION_V1);
758 let declared = u32::from_le_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
759 assert_eq!(declared as usize, bytes.len() - TOPOLOGY_HEADER_SIZE);
760 }
761}