Diffinery

homeflare/celldpublic

celld/crates/ltx/src/bundle.rs
138 lines · 4.4 KBRaw History
1//! The bundle envelope: a container of verbatim L0 LTX files, never a
2//! format.
3//!
4//! celld-original, not a Litestream port. Layout: the concatenated raw L0
5//! bytes, a binary footer of rows, the footer length as a little-endian
6//! u32, and a four-byte magic. A row is `u16 cell_len | cell utf-8 |
7//! u64 cell_epoch | u64 txid | u64 offset | u64 len`, all little-endian.
8//! Un-bundling is arithmetic. The inner bytes are exactly what the
9//! per-cell writer produces, so byte-level compatibility stays checkable.
10//! At rest, the bucket is pure Litestream. A drained bundle leaves no trace
11//! that this module ever existed. Nothing else in this crate depends on bundles;
12//! deleting this file returns the crate to its upstream shape.
13
14use crate::error::{Error, Result};
15use crate::TXID;
16
17const MAGIC: &[u8; 4] = b"CLB1";
18
19fn malformed(what: &str) -> Error {
20 Error::Other(format!("bundle: {what}").into())
21}
22
23fn split_data_and_footer(bundle: &[u8]) -> Result<(&[u8], &[u8])> {
24 if bundle.len() < 8 {
25 return Err(malformed("shorter than its trailer"));
26 }
27 let (rest, magic) = bundle.split_at(bundle.len() - 4);
28 if magic != MAGIC {
29 return Err(malformed("bad magic"));
30 }
31 let (rest, len_bytes) = rest.split_at(rest.len() - 4);
32 let len = u32::from_le_bytes(len_bytes.try_into().unwrap()) as usize;
33 if rest.len() < len {
34 return Err(malformed("footer overruns the object"));
35 }
36 Ok(rest.split_at(rest.len() - len))
37}
38
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct BundleRow {
41 pub cell: String,
42 pub cell_epoch: u64,
43 pub txid: u64,
44 pub offset: u64,
45 pub len: u64,
46}
47
48impl BundleRow {
49 pub fn txid(&self) -> TXID {
50 TXID(self.txid)
51 }
52}
53
54/// One captured L0 segment headed for a bundle.
55pub struct BundleEntry {
56 pub cell: String,
57 pub cell_epoch: u64,
58 pub txid: u64,
59 pub bytes: Vec<u8>,
60}
61
62pub fn encode(entries: &[BundleEntry]) -> Result<Vec<u8>> {
63 let mut out = Vec::new();
64 let mut footer = Vec::new();
65 for entry in entries {
66 let cell = entry.cell.as_bytes();
67 let cell_len: u16 = cell
68 .len()
69 .try_into()
70 .map_err(|_| malformed("cell name too long"))?;
71 footer.extend_from_slice(&cell_len.to_le_bytes());
72 footer.extend_from_slice(cell);
73 for value in [
74 entry.cell_epoch,
75 entry.txid,
76 out.len() as u64,
77 entry.bytes.len() as u64,
78 ] {
79 footer.extend_from_slice(&value.to_le_bytes());
80 }
81 out.extend_from_slice(&entry.bytes);
82 }
83 let len: u32 = footer
84 .len()
85 .try_into()
86 .map_err(|_| malformed("footer too large"))?;
87 out.extend_from_slice(&footer);
88 out.extend_from_slice(&len.to_le_bytes());
89 out.extend_from_slice(MAGIC);
90 Ok(out)
91}
92
93/// The rows, from a complete bundle object.
94pub fn decode_rows(bundle: &[u8]) -> Result<Vec<BundleRow>> {
95 let (_, mut footer) = split_data_and_footer(bundle)?;
96 let mut rows = Vec::new();
97 while !footer.is_empty() {
98 if footer.len() < 2 {
99 return Err(malformed("truncated row"));
100 }
101 let cell_len = u16::from_le_bytes(footer[..2].try_into().unwrap()) as usize;
102 footer = &footer[2..];
103 if footer.len() < cell_len + 32 {
104 return Err(malformed("truncated row"));
105 }
106 let cell = std::str::from_utf8(&footer[..cell_len])
107 .map_err(|_| malformed("cell name not utf-8"))?
108 .to_string();
109 footer = &footer[cell_len..];
110 let mut values = [0_u64; 4];
111 for value in &mut values {
112 *value = u64::from_le_bytes(footer[..8].try_into().unwrap());
113 footer = &footer[8..];
114 }
115 rows.push(BundleRow {
116 cell,
117 cell_epoch: values[0],
118 txid: values[1],
119 offset: values[2],
120 len: values[3],
121 });
122 }
123 Ok(rows)
124}
125
126/// One row's verbatim L0 bytes out of a complete bundle object.
127pub fn slice<'a>(bundle: &'a [u8], row: &BundleRow) -> Result<&'a [u8]> {
128 let (data, _) = split_data_and_footer(bundle)?;
129 let start = usize::try_from(row.offset).map_err(|_| malformed("row overflows"))?;
130 let len = usize::try_from(row.len).map_err(|_| malformed("row overflows"))?;
131 let end = start
132 .checked_add(len)
133 .ok_or_else(|| malformed("row overflows"))?;
134 if end > data.len() {
135 return Err(malformed("row overruns the data section"));
136 }
137 Ok(&data[start..end])
138}