Skip to main content

reddb_wire/
topology.rs

1//! Canonical `Topology` payload — shared by both transports.
2//!
3//! ADR 0008 (`.red/adr/0008-topology-advertisement-security.md`)
4//! settled the security model and the schema-evolution rule:
5//!
6//!   * New optional fields land under a versioned envelope.
7//!   * Old parsers ignore unknown fields cleanly. Unknown version
8//!     tags are dropped (no panic), the consumer falls back to
9//!     URI-only routing.
10//!   * Schema-version bumps are reserved for changes a naive
11//!     optional field cannot express (a removed field, a renegotiated
12//!     meaning, a framing change). They are not the default move.
13//!
14//! Wire encoding (single shape across RedWire HelloAck + gRPC
15//! `Topology` RPC):
16//!
17//! ```text
18//! ┌────────────────────────────────────────────────────────────┐
19//! │ u8   version_tag        currently 0x01                     │
20//! │ u32  body_length (LE)   bytes that follow                  │
21//! │ ... body ...            version-specific payload encoding  │
22//! └────────────────────────────────────────────────────────────┘
23//! ```
24//!
25//! The header (tag + length) is fixed across versions so a parser
26//! that does not recognise the tag can still skip the entire blob
27//! cleanly.
28//!
29//! Body for `0x01`: a flat little-endian struct dump where every
30//! string is `u32 len` + utf-8 bytes:
31//!
32//! ```text
33//! u64  epoch
34//! str  primary.addr
35//! str  primary.region
36//! u32  replicas.len
37//! foreach replica:
38//!   str  addr
39//!   str  region
40//!   u8   healthy   (0 / 1)
41//!   u32  lag_ms
42//!   u64  last_applied_lsn
43//! ```
44//!
45//! No serde dependency: a hex dump stays readable, no extra crate
46//! pulled into `reddb-wire`, and the format matches the rest of the
47//! RedWire codec discipline.
48
49use reddb_types::encoding::base64_encode;
50
51/// Wire version tag for the initial schema.
52///
53/// Bumping this is reserved for genuinely breaking changes (removed
54/// field, renegotiated meaning, framing change). Additive evolution
55/// (new optional fields) keeps this byte stable — see ADR 0008 §4.
56pub const TOPOLOGY_WIRE_VERSION_V1: u8 = 0x01;
57
58/// Highest tag the current parser understands. A `Topology` blob
59/// stamped with anything else is ignored cleanly so an older client
60/// can keep its URI-only routing fallback.
61pub const MAX_KNOWN_TOPOLOGY_VERSION: u8 = TOPOLOGY_WIRE_VERSION_V1;
62
63/// Header size (version tag + u32 body length).
64pub const TOPOLOGY_HEADER_SIZE: usize = 1 + 4;
65
66/// Canonical topology payload — the same shape both transports
67/// carry. New optional fields go in here as `Option<…>` /
68/// `Vec<…>` and ride the existing version tag; only a genuinely
69/// breaking change earns a new tag.
70#[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    /// `true` while this replica is re-bootstrapping (loading a fresh
91    /// snapshot). Its `last_applied_lsn` describes data it is about to
92    /// discard, so a causal reader must treat it as ineligible for
93    /// bookmark reads even when the advertised frontier covers the
94    /// bookmark (issue #837). Non-causal reads are unaffected.
95    ///
96    /// Additive field (ADR 0008 §4): it rides the existing `0x01`
97    /// version tag as a trailing per-replica flag block appended after
98    /// the replica records. An old decoder stops after the records and
99    /// ignores the trailing bytes (defaulting every replica to
100    /// `false`); a new decoder reading old bytes finds no trailing
101    /// block and likewise defaults to `false`. No version bump.
102    pub rebootstrapping: bool,
103}
104
105/// Decode-side errors. Distinct from "unknown version tag", which
106/// is reported as `Ok(None)` on `decode_topology` so the consumer
107/// can fall back to URI-only routing without branching on an
108/// error variant.
109#[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
142/// Encode `topology` to the canonical version-tagged byte string.
143/// Same bytes consumed by both RedWire HelloAck (after base64
144/// embedding in the JSON envelope) and the gRPC `TopologyReply`
145/// (carried directly as a `bytes` field).
146pub 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    // Additive trailing block (ADR 0008 §4): one `rebootstrapping`
160    // byte per replica, in advertised order, appended after the
161    // records. Placed at the tail rather than interleaved into each
162    // record so an old decoder — which stops after `replicas.len`
163    // records — skips it cleanly instead of mis-framing every field.
164    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
175/// Decode a topology blob.
176///
177/// Returns:
178/// * `Ok(Some(Topology))` — recognised version tag, body parsed.
179/// * `Ok(None)` — unknown version tag. The consumer is expected to
180///   fall back to URI-only routing rather than treat this as an
181///   error (ADR 0008 §4: unknown fields are dropped, not rejected).
182/// * `Err(TopologyError)` — recognised tag, but the body was
183///   structurally malformed (truncated, invalid UTF-8, …).
184pub 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        // Forward-compat: unknown version tag, drop cleanly.
201        return Ok(None);
202    }
203
204    // version == 0x01
205    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    // Even an empty-address replica needs two string lengths, a healthy
211    // byte, lag, and LSN. Validate before allocating from a peer's count.
212    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            // Default until the trailing block is read below. A
232            // pre-#837 advertisement carries no trailing block, so
233            // every replica stays `false`.
234            rebootstrapping: false,
235        });
236    }
237    // Additive trailing block: a `rebootstrapping` byte per replica.
238    // Present only when the producer is post-#837. When the producer
239    // is older the cursor has no bytes left here and every flag keeps
240    // its `false` default. A partial/truncated block (fewer bytes than
241    // replicas) leaves the unread tail `false` rather than erroring —
242    // forward-compat posture per ADR 0008 §4.
243    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    // Trailing `rebootstrapping` flag block: one byte per replica.
266    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
335// ---------------------------------------------------------------
336// HelloAck embedding.
337//
338// The HelloAck payload is a JSON object. To carry the binary
339// topology blob inside it without breaking the existing JSON-only
340// parser (which deserialises the whole payload with `serde_json`),
341// the canonical bytes are base64-encoded under a new `topology`
342// key. Old parsers ignore unknown keys cleanly; new parsers extract
343// the field and run `decode_topology` on the decoded bytes.
344// ---------------------------------------------------------------
345
346/// Base64-encode the canonical topology bytes for embedding inside
347/// a HelloAck JSON payload as a string field.
348///
349/// The caller (server-side HelloAck builder) is expected to insert
350/// the resulting string under the JSON key `"topology"`; the client
351/// extracts that key, base64-decodes it, and runs `decode_topology`.
352pub fn encode_topology_for_hello_ack(topology: &Topology) -> String {
353    base64_encode(&encode_topology(topology))
354}
355
356/// Decode the base64 string carried in HelloAck JSON `topology`
357/// field back into a `Topology`.
358///
359/// Mirrors `decode_topology`'s three-state contract:
360/// * `Ok(Some(_))` — recognised version tag, body parsed.
361/// * `Ok(None)` — base64 decode failed *or* the version tag is
362///   unknown. Both cases collapse to "fall back to URI-only
363///   routing"; the consumer does not branch on which one it was.
364/// * `Err(_)` — recognised version tag with a malformed body.
365pub fn decode_topology_from_hello_ack(field: &str) -> Result<Option<Topology>, TopologyError> {
366    let Some(bytes) = base64_decode(field) else {
367        // Malformed base64 is treated as "unknown encoding, drop
368        // cleanly" so the client falls back to URI-only routing —
369        // same posture as an unknown version tag (ADR 0008 §4).
370        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        // Forward-compat invariant from ADR 0008 §4: an unknown
457        // version tag must be ignored, not rejected. The consumer
458        // falls back to URI-only routing.
459        let mut bytes = encode_topology(&fixture());
460        bytes[0] = 0xFE; // bumped past MAX_KNOWN_TOPOLOGY_VERSION
461        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        // Declared body length larger than buffer.
479        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        // Sentinel against an accidental schema bump. ADR 0008 §4
489        // reserves the bump for genuinely breaking changes; a PR
490        // adding an optional field must NOT touch this value.
491        assert_eq!(TOPOLOGY_WIRE_VERSION_V1, 0x01);
492    }
493
494    #[test]
495    fn rebootstrapping_flag_round_trips_per_replica() {
496        // The additive #837 flag survives a full encode/decode and is
497        // carried independently per replica.
498        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        // Backward-compat (ADR 0008 §4): a pre-#837 producer emits no
509        // trailing flag block. Synthesise that blob by encoding, then
510        // truncating the trailing per-replica flag bytes off the body
511        // and fixing the declared length. The decoder must still parse
512        // and default every replica to `false`.
513        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        // Every other field is preserved verbatim — only the new flag
525        // is absent.
526        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        // The HelloAck embedding shape: encode → base64-string →
533        // decode. Same canonical bytes both transports carry, just
534        // base64-wrapped so the JSON envelope stays valid.
535        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        // The acceptance criterion (#166 §4): same bytes consumed
546        // by both transports. Round-trip via the HelloAck base64
547        // wrapper and assert the decoded inner payload is byte-for-
548        // byte equivalent to the canonical encoding.
549        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        // A HelloAck whose topology field carries a future version
559        // tag must not panic — the client falls back to URI-only
560        // routing.
561        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        // A garbled base64 field is treated like an unknown version
571        // tag: drop, fall back to URI-only routing, never panic.
572        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        // Backwards-compat (#166 acceptance criterion §6): an
579        // old-style HelloAck JSON payload — no `topology` key —
580        // still parses cleanly into a Topology slot of `None` on
581        // the consumer side. We model that here by extracting the
582        // JSON value the way the client will (look for the key,
583        // run our decoder if present), and checking the absence
584        // path resolves to "no topology, fall back to URI-only".
585        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    /// Tiny JSON probe used only by the backwards-compat test.
599    /// `reddb-wire` has no JSON dep — keep this scoped to test
600    /// code so we do not pull serde into the production build.
601    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                        // Skip primitives (numbers, true/false/null,
664                        // arrays). The probe only cares about object
665                        // keys at the top level, so coarse skipping
666                        // is enough for our fixture.
667                        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); // '{'
698                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        // Pinning the layout: byte 0 is the tag, bytes 1..5 are the
752        // little-endian body length. A consumer that sees an unknown
753        // tag still knows how many bytes to skip — that is the only
754        // forward-compat invariant the header has to carry.
755        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}