peat-btle 0.4.0

Bluetooth Low Energy mesh transport for Peat Protocol
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright (c) 2025-2026 Defense Unicorns, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Universal Document frame helpers for cross-transport sync.
//!
//! peat-btle carries `peat_lite::MessageType::Document` envelopes
//! over BLE alongside its existing typed-translator (0xB6) frames and
//! delta-document (0xB2) frames. The envelope itself owns the wire
//! format (16-byte peat-lite header + Document payload, see
//! [`peat_lite::protocol::document`]); this module provides the
//! peat-btle-side helpers for:
//!
//! - **Frame discrimination on receive**: a fully-reassembled buffer
//!   starts with peat-lite's MAGIC bytes (`b"PEAT"`, `[0x50, 0x45,
//!   0x41, 0x54]`); [`is_peat_lite_frame`] is the cheap prefix check
//!   the dispatcher uses to route into [`decode_peat_lite_document`].
//!   No new single-byte marker burns a code in the existing 0xAB-0xBF
//!   range — peat-lite's 4-byte magic is the discriminator.
//! - **Frame construction on transmit**: [`encode_peat_lite_document`]
//!   wraps a Document envelope payload with the 16-byte peat-lite
//!   header and returns wire-ready bytes. Callers feed the returned
//!   `Vec<u8>` to the existing chunked transport
//!   ([`crate::sync::protocol::chunk_data`] +
//!   [`crate::sync::protocol::ChunkReassembler`]) which transparently
//!   fragments envelopes that exceed BLE MTU.
//!
//! ## Layering
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  peat-mesh::transport::document_codec                            │
//! │   (host side)  encode_document(..) → payload bytes               │
//! └────────────────────────┬────────────────────────────────────────┘
//!//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  this module: encode_peat_lite_document(payload) →              │
//! │    [16-byte peat-lite header (MessageType::Document)] + payload │
//! └────────────────────────┬────────────────────────────────────────┘
//!//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  crate::sync::protocol::chunk_data(bytes, mtu, message_id)      │
//! │   → Vec<SyncChunk>                                               │
//! └────────────────────────┬────────────────────────────────────────┘
//!//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  GATT writes (BLE transport)                                     │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! The transport layer (chunk_data + ChunkReassembler) stays opaque
//! to the envelope contents — that's what makes the same codec usable
//! over LoRa or any future radio without re-spec'ing.
//!
//! ## Inbound dispatcher integration
//!
//! [`try_handle_peat_lite_frame`] is the entry point the
//! receive-path callers in `peat_mesh.rs` invoke. It's wired into
//! all three dispatch sites (`process_*_data` family, around lines
//! 2620 / 2890 / 3080) **before** the existing 0xB6 translator
//! handler, so peat-lite frames don't fall through to translator
//! decode (which would mis-decode the magic byte 0x50 as a 0xB6
//! collection code on the wire). Decoded frames surface via
//! [`crate::peat_mesh::DataReceivedResult::peat_lite_document`] —
//! the polled-consumer field hosts read on each receive.
//!
//! ## Outbound API
//!
//! [`crate::peat_mesh::PeatMesh::publish_peat_lite_document`] is the
//! caller-facing surface. It wraps the envelope payload with the
//! 16-byte peat-lite header (sender's node id + seq num) and then
//! encrypts via the same `encrypt_document` path translator-frame
//! and platform-advertisement publishers use, so wire-level
//! encryption stays uniform across frame types.

use peat_lite::protocol::constants::{HEADER_SIZE, MAGIC};
use peat_lite::protocol::document as pl_doc;
use peat_lite::protocol::error::MessageError;
use peat_lite::protocol::header::{decode_header, encode_header, Header};
use peat_lite::protocol::message_type::MessageType;

// `PeatLiteDocumentFrame` is defined unconditionally in
// `crate::peat_mesh` so the UniFFI binding shape stays stable across
// feature combos (mirrors the existing `DecodedTranslatorFrame`
// pattern). This module owns the codec that *populates* it.
pub use crate::peat_mesh::PeatLiteDocumentFrame;

/// Per-call outcome of the peat-lite frame dispatcher. Mirrors the
/// [`crate::peat_mesh::TranslatorMarkerOutcome`] pattern: each call
/// returns its own value so concurrent receives on different threads
/// can't race on a shared slot.
#[derive(Debug, Clone)]
pub enum PeatLiteFrameOutcome {
    /// Buffer didn't carry peat-lite's MAGIC prefix; caller continues
    /// the dispatch chain (translator-marker, then delta-document,
    /// then legacy peripheral merge).
    NotPeatLiteFrame,
    /// Buffer was a peat-lite frame but malformed, an unsupported
    /// message type, or otherwise undeliverable. Caller stops the
    /// dispatch chain — falling through would mis-route or duplicate-
    /// log.
    Handled,
    /// Frame decoded into a [`PeatLiteDocumentFrame`]. Caller hoists
    /// the payload into `DataReceivedResult.peat_lite_document` and
    /// returns to the host.
    Decoded(PeatLiteDocumentFrame),
}

/// Dispatcher entry point. Combines the magic-prefix check with full
/// envelope decode, surfaces an [`PeatLiteFrameOutcome`] the receive-
/// path callers can match on alongside the existing translator-marker
/// handling.
///
/// Logs (at `warn` for malformed input, `debug` for "not a peat-lite
/// frame, fall through") so dispatcher-routing bugs surface in
/// production telemetry without needing to thread errors through the
/// caller. Telemetry shape mirrors `try_handle_translator_marker`'s
/// existing log calls.
pub fn try_handle_peat_lite_frame(buf: &[u8]) -> PeatLiteFrameOutcome {
    if !is_peat_lite_frame(buf) {
        return PeatLiteFrameOutcome::NotPeatLiteFrame;
    }

    let (header, view) = match decode_peat_lite_document(buf) {
        Ok(pair) => pair,
        Err(FrameError::NotPeatLiteFrame) => {
            // Magic check passed but decode disagreed — should be
            // impossible given the prefix check above, but log so a
            // peat-lite version skew or codec drift surfaces.
            log::warn!(
                "ble: peat-lite magic-prefix matched but decode reported NotPeatLiteFrame; \
                 codec drift?"
            );
            return PeatLiteFrameOutcome::Handled;
        }
        Err(FrameError::UnsupportedMessageType) => {
            // peat-lite Heartbeat / Announce / OTA frames don't
            // belong on the BLE wire (they travel via UDP transport
            // in peat-mesh's lite-bridge). Silent-drop the frame so
            // a misconfigured peer's chatter doesn't pollute logs;
            // bump to warn if this turns into an attack vector.
            log::debug!("ble: dropping peat-lite frame with non-Document MessageType");
            return PeatLiteFrameOutcome::Handled;
        }
        Err(FrameError::Envelope(e)) => {
            log::warn!(
                "ble: dropping malformed peat-lite Document frame (envelope error: {:?})",
                e
            );
            return PeatLiteFrameOutcome::Handled;
        }
    };

    PeatLiteFrameOutcome::Decoded(PeatLiteDocumentFrame {
        source_node_id: header.node_id,
        seq_num: header.seq_num,
        flags: view.flags,
        collection: view.collection.to_string(),
        doc_id: view.doc_id.to_string(),
        timestamp_ms: view.timestamp_ms,
        body: view.body.to_vec(),
    })
}

/// Errors specific to peat-btle's wrapping/unwrapping of peat-lite
/// frames. Distinct from [`MessageError`] so callers can route
/// envelope-level failures vs. peat-btle-specific framing failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameError {
    /// peat-lite codec rejected the bytes (header malformed, body
    /// envelope invalid, etc.). See the wrapped [`MessageError`].
    Envelope(MessageError),
    /// The buffer didn't start with peat-lite's MAGIC bytes — the
    /// dispatcher should not have routed it here. Surfaced as a
    /// distinct variant rather than masquerading as `Envelope` so
    /// dispatcher-routing bugs are obvious in logs.
    NotPeatLiteFrame,
    /// The header decoded but `MessageType` wasn't
    /// [`MessageType::Document`]. peat-lite carries other message
    /// types (Announce, Heartbeat, OTA, …) which are handled by
    /// peat-mesh's `transport::lite` UDP path, not this BLE wrapper.
    UnsupportedMessageType,
}

impl From<MessageError> for FrameError {
    fn from(e: MessageError) -> Self {
        Self::Envelope(e)
    }
}

/// Quick prefix check: does this buffer look like a peat-lite frame?
///
/// Used by the dispatcher to decide whether to route a reassembled
/// buffer into [`decode_peat_lite_document`] vs. peat-btle's typed-
/// translator path or delta-document path. The 4-byte magic is
/// distinctive enough to make this check effectively unambiguous —
/// no peat-btle-native frame starts with `[0x50, 0x45, 0x41, 0x54]`
/// (peat-btle's markers occupy the 0xAB-0xBF range; ASCII 'P' = 0x50).
///
/// Returns `false` for any input shorter than the 4-byte magic, so
/// callers don't need to length-check first.
pub fn is_peat_lite_frame(buf: &[u8]) -> bool {
    buf.len() >= MAGIC.len() && buf[..MAGIC.len()] == MAGIC
}

/// Wrap a Document envelope payload with the 16-byte peat-lite header
/// (`MessageType::Document`, given node_id + seq_num) and return the
/// wire-ready bytes ready for [`crate::sync::protocol::chunk_data`].
///
/// `payload` is the bytes produced by
/// `peat_mesh::transport::document_codec::encode_document` — the
/// envelope post-header. This function adds the header.
///
/// Errors if `payload` is so large that the encoded total would
/// exceed [`peat_lite::MAX_PACKET_SIZE`]. For BLE specifically the
/// chunked-transport handles oversized totals, but the limit comes
/// from peat-lite's wire-format constants and is the right ceiling
/// for cross-transport portability — LoRa-class consumers honor the
/// same.
pub fn encode_peat_lite_document(
    node_id: u32,
    seq_num: u32,
    payload: &[u8],
) -> Result<Vec<u8>, FrameError> {
    let header = Header {
        msg_type: MessageType::Document,
        flags: 0,
        node_id,
        seq_num,
    };

    let total = HEADER_SIZE + payload.len();
    let mut buf = vec![0u8; total];
    encode_header(&header, &mut buf[..HEADER_SIZE])?;
    buf[HEADER_SIZE..].copy_from_slice(payload);
    Ok(buf)
}

/// Decode a peat-lite Document frame from a fully-reassembled buffer.
///
/// Returns the decoded `Header` (carrying source node_id + seq_num
/// for the dispatcher's loop-prevention / dedup tracking) plus a
/// borrowing [`pl_doc::DocumentRef`] into the envelope body.
///
/// **Caller MUST verify `is_peat_lite_frame(buf)` first.** This
/// function returns `FrameError::NotPeatLiteFrame` on a magic
/// mismatch, but the dispatcher will already have done that check
/// for routing; the explicit error variant exists so a misrouted
/// frame surfaces an obvious diagnostic rather than a generic
/// envelope error.
pub fn decode_peat_lite_document(
    buf: &[u8],
) -> Result<(Header, pl_doc::DocumentRef<'_>), FrameError> {
    if !is_peat_lite_frame(buf) {
        return Err(FrameError::NotPeatLiteFrame);
    }
    let (header, payload) = decode_header(buf)?;
    if !matches!(header.msg_type, MessageType::Document) {
        return Err(FrameError::UnsupportedMessageType);
    }
    let view = pl_doc::decode(payload)?;
    Ok((header, view))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Round-trip: build a peat-lite Document envelope payload, wrap
    /// with header via `encode_peat_lite_document`, decode the wrapper
    /// via `decode_peat_lite_document`, verify header + envelope
    /// fields preserved.
    #[test]
    fn roundtrip_document_frame() {
        // Build a Document envelope payload (mirrors what
        // peat-mesh::transport::document_codec::encode_document
        // produces).
        let mut env = vec![0u8; 256];
        let env_n = pl_doc::encode(
            0, // flags
            "markers",
            "uuid-abc",
            1_700_000_000_000,
            b"opaque-body",
            &mut env,
        )
        .expect("envelope encode");
        env.truncate(env_n);

        // Wrap with peat-lite header.
        let frame = encode_peat_lite_document(0xCAFE_BABE, 42, &env).expect("frame encode");
        assert!(
            is_peat_lite_frame(&frame),
            "wrapped frame must start with MAGIC"
        );

        // Decode and verify.
        let (header, view) = decode_peat_lite_document(&frame).expect("frame decode");
        assert_eq!(header.msg_type, MessageType::Document);
        assert_eq!(header.node_id, 0xCAFE_BABE);
        assert_eq!(header.seq_num, 42);
        assert_eq!(view.collection, "markers");
        assert_eq!(view.doc_id, "uuid-abc");
        assert_eq!(view.timestamp_ms, 1_700_000_000_000);
        assert_eq!(view.body, b"opaque-body");
    }

    /// The magic-prefix check is the dispatcher's routing gate. Any
    /// buffer not starting with `b"PEAT"` MUST surface as
    /// `NotPeatLiteFrame` to aid debugging when the dispatcher
    /// mis-routes.
    #[test]
    fn non_magic_buffer_is_rejected() {
        // A peat-btle 0xB6 translator-frame-shaped prefix would be
        // misrouted if magic isn't checked.
        let translator_frame = [0xB6_u8, 0x01, 0x00, 0x00];
        assert!(!is_peat_lite_frame(&translator_frame));
        assert_eq!(
            decode_peat_lite_document(&translator_frame),
            Err(FrameError::NotPeatLiteFrame),
        );

        // Empty buffer: also rejected, no panic.
        assert!(!is_peat_lite_frame(&[]));
        assert_eq!(
            decode_peat_lite_document(&[]),
            Err(FrameError::NotPeatLiteFrame),
        );
    }

    /// peat-lite frames carrying `MessageType::Heartbeat` (or any
    /// non-Document type) must surface as `UnsupportedMessageType`.
    /// peat-btle's BLE wrapping is for Documents only — other
    /// peat-lite message types travel via peat-mesh's UDP transport
    /// (`transport::lite`), not this BLE path.
    #[test]
    fn non_document_message_type_is_rejected() {
        // Hand-build a peat-lite header with MessageType::Heartbeat,
        // attach a minimum-shape Document envelope-ish payload.
        let mut buf = [0u8; 32];
        let header = Header {
            msg_type: MessageType::Heartbeat,
            flags: 0,
            node_id: 1,
            seq_num: 1,
        };
        encode_header(&header, &mut buf[..HEADER_SIZE]).expect("header");
        // No payload required — UnsupportedMessageType fires before
        // body parsing.
        assert_eq!(
            decode_peat_lite_document(&buf[..HEADER_SIZE]),
            Err(FrameError::UnsupportedMessageType),
        );
    }

    /// Magic-match but corrupt header bytes (wrong protocol version,
    /// invalid message type byte, etc.) surface as
    /// `Envelope(MessageError::*)`, distinguishing wire-corruption
    /// from misrouting.
    #[test]
    fn corrupt_header_surfaces_envelope_error() {
        let mut buf = [0u8; HEADER_SIZE];
        buf[0..4].copy_from_slice(&MAGIC);
        buf[4] = 99; // bogus protocol version
        buf[5] = MessageType::Document as u8;
        match decode_peat_lite_document(&buf) {
            Err(FrameError::Envelope(MessageError::UnsupportedVersion)) => {}
            other => panic!("expected Envelope(UnsupportedVersion), got {:?}", other),
        }
    }

    /// `encode_peat_lite_document` writes exactly `HEADER_SIZE +
    /// payload.len()` bytes — no trailing padding, no implicit
    /// length-prefix overhead beyond what the envelope carries
    /// internally.
    #[test]
    fn encode_size_is_exact() {
        let mut env = vec![0u8; 64];
        let env_n =
            pl_doc::encode(0, "tracks", "id", 0, b"body", &mut env).expect("envelope encode");
        env.truncate(env_n);

        let frame = encode_peat_lite_document(0, 0, &env).expect("frame encode");
        assert_eq!(
            frame.len(),
            HEADER_SIZE + env.len(),
            "frame should be exactly header + payload bytes",
        );
    }

    // -------------------------------------------------------------
    // Dispatcher (try_handle_peat_lite_frame) tests
    // -------------------------------------------------------------

    /// A well-formed peat-lite Document frame surfaces as
    /// `Decoded(PeatLiteDocumentFrame)` with every field populated.
    /// This is the happy path the dispatcher hands to the
    /// host-facing `DataReceivedResult`.
    #[test]
    fn dispatcher_decodes_well_formed_frame() {
        let mut env = vec![0u8; 256];
        let env_n = pl_doc::encode(
            pl_doc::DOC_FLAG_TOMBSTONE,
            "platforms",
            "ANDROID-abc",
            1_700_000_000_000,
            &[],
            &mut env,
        )
        .expect("envelope");
        env.truncate(env_n);

        let frame = encode_peat_lite_document(0xCAFE_BABE, 7, &env).expect("frame");

        match try_handle_peat_lite_frame(&frame) {
            PeatLiteFrameOutcome::Decoded(doc) => {
                assert_eq!(doc.source_node_id, 0xCAFE_BABE);
                assert_eq!(doc.seq_num, 7);
                assert_eq!(doc.collection, "platforms");
                assert_eq!(doc.doc_id, "ANDROID-abc");
                assert_eq!(doc.timestamp_ms, 1_700_000_000_000);
                assert!(doc.is_tombstone());
                assert!(doc.body.is_empty());
            }
            other => panic!("expected Decoded, got {:?}", other),
        }
    }

    /// A buffer whose first byte is in peat-btle's translator-frame
    /// range (0xB6) must surface `NotPeatLiteFrame` so the
    /// dispatcher falls through to the existing translator handler
    /// without attempting peat-lite decode. **Crucial routing
    /// invariant** — getting this wrong would either misroute
    /// translator frames to peat-lite (corrupting the BLE 0xB6 path)
    /// or peat-lite frames to the translator (unparseable).
    #[test]
    fn dispatcher_falls_through_for_translator_frames() {
        // Plausible 0xB6 translator frame shape: [0xB6, 0x02 (PLATFORMS),
        // postcard payload bytes...]
        let translator_frame = vec![0xB6, 0x02, 0xDE, 0xAD, 0xBE, 0xEF];
        match try_handle_peat_lite_frame(&translator_frame) {
            PeatLiteFrameOutcome::NotPeatLiteFrame => {} // expected
            other => panic!(
                "translator-frame buffer must NOT be claimed by peat-lite dispatcher, got {:?}",
                other
            ),
        }
    }

    /// Empty buffer falls through cleanly — no panic on slice
    /// indexing, no false claim of being a peat-lite frame. This is
    /// the malformed-input safety contract.
    #[test]
    fn dispatcher_falls_through_for_empty_input() {
        match try_handle_peat_lite_frame(&[]) {
            PeatLiteFrameOutcome::NotPeatLiteFrame => {} // expected
            other => panic!("expected NotPeatLiteFrame, got {:?}", other),
        }
    }

    /// A peat-lite header carrying a non-Document MessageType (e.g.
    /// Heartbeat) surfaces `Handled` — caller does NOT fall through
    /// to translator (which would mis-decode the magic-prefix bytes
    /// as a 0xB6 translator-frame collection code).
    #[test]
    fn dispatcher_handles_unsupported_message_type_without_fallthrough() {
        let mut buf = [0u8; HEADER_SIZE];
        let header = Header {
            msg_type: MessageType::Heartbeat,
            flags: 0,
            node_id: 1,
            seq_num: 1,
        };
        encode_header(&header, &mut buf[..HEADER_SIZE]).expect("header");

        match try_handle_peat_lite_frame(&buf) {
            PeatLiteFrameOutcome::Handled => {}
            other => panic!("expected Handled (silent drop), got {:?}", other),
        }
    }

    /// Magic match + corrupt protocol-version byte surfaces
    /// `Handled`. Caller stops the dispatch chain — falling through
    /// to the translator handler would treat the version byte as a
    /// collection code and silently mis-decode.
    #[test]
    fn dispatcher_handles_corrupt_header_without_fallthrough() {
        let mut buf = [0u8; HEADER_SIZE];
        buf[0..4].copy_from_slice(&MAGIC);
        buf[4] = 99; // bogus protocol version
        buf[5] = MessageType::Document as u8;

        match try_handle_peat_lite_frame(&buf) {
            PeatLiteFrameOutcome::Handled => {}
            other => panic!("expected Handled (silent drop), got {:?}", other),
        }
    }

    /// **End-to-end wire round-trip**: encode a Document via the
    /// outbound API, hand the bytes through the dispatcher (as a
    /// reassembled buffer would arrive on inbound), verify every
    /// field survives. This is the contract the marker-bridge demo
    /// will rely on.
    #[test]
    fn end_to_end_outbound_then_dispatcher_roundtrip() {
        // Outbound: peat-mesh would produce this envelope payload.
        let mut env = vec![0u8; 512];
        let body = b"{\"lat\":33.71576,\"lon\":-84.41152}";
        let env_n = pl_doc::encode(
            0,
            "markers",
            "marker-uuid-001",
            1_700_000_000_000,
            body,
            &mut env,
        )
        .expect("envelope encode");
        env.truncate(env_n);

        // peat-btle wraps with header.
        let wire_bytes = encode_peat_lite_document(0xBEEFCAFE, 99, &env).expect("frame encode");

        // Dispatcher (post-reassembly) decodes.
        match try_handle_peat_lite_frame(&wire_bytes) {
            PeatLiteFrameOutcome::Decoded(doc) => {
                assert_eq!(doc.source_node_id, 0xBEEFCAFE);
                assert_eq!(doc.seq_num, 99);
                assert_eq!(doc.collection, "markers");
                assert_eq!(doc.doc_id, "marker-uuid-001");
                assert_eq!(doc.timestamp_ms, 1_700_000_000_000);
                assert!(!doc.is_tombstone());
                assert_eq!(doc.body.as_slice(), body);
            }
            other => panic!("end-to-end roundtrip failed: {:?}", other),
        }
    }
}