Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 18.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Object records, the contents of segment files (format spec, section 7).
5//!
6//! ```text
7//! u32 sync = 0xB7A1D5E9 | u8 kind | u8 codec | u16 flags = 0
8//! u32 stored_len | u64 raw_len | [32] id
9//! codecs 2 and 3 only: [32] dictionary or base id
10//! payload: stored_len bytes
11//! u32 crc32c of everything from the sync word to the end of the payload
12//! zero padding to a multiple of 8 bytes
13//! ```
14//!
15//! Integers are little-endian. Records start at multiples of 8 bytes, so a
16//! reader that meets the remains of a write cut short can find the next
17//! record by looking for the sync word 8 bytes at a time.
18//!
19//! The codec says how the payload is stored:
20//!
21//! - 0, raw: as it is. Payloads of up to 64 bytes are always raw.
22//! - 1, zstd: one zstd frame at level 3, used when it is smaller than raw.
23//! - 2, reserved for zstd with a dictionary: its header is parsed, so a scan
24//! can step over it, but nothing writes or decodes it.
25//! - 3, delta: one zstd frame compressed with the raw payload of the base
26//! object as a reference prefix (see [`crate::delta`]). The base is stored
27//! whole, with codec 0 or 1.
28//! - 4, chunked, for blobs only: the payload is the list of the chunks the
29//! blob is cut into (see [`crate::chunks`]).
30//!
31//! Decoding codecs 0 and 1 needs the record alone, and is done here. Codecs 3
32//! and 4 need other objects, so the segments resolve them.
33
34use std::borrow::Cow;
35use std::io::Read;
36
37use braid_format::{Kind, ObjectId};
38
39/// The first four bytes of every record.
40pub(crate) const SYNC: u32 = 0xB7A1_D5E9;
41
42/// Bytes from the sync word to the payload, for codecs without a reference.
43pub(crate) const HEADER_LEN: usize = 52;
44
45/// Bytes of the dictionary or base id that codecs 2 and 3 add to the header.
46pub(crate) const REFERENCE_LEN: usize = 32;
47
48/// Records start at multiples of this.
49pub(crate) const ALIGN: u64 = 8;
50
51/// Payloads up to this size are always stored raw.
52pub(crate) const RAW_MAX: usize = 64;
53
54/// The zstd level for compressed payloads and deltas.
55pub(crate) const ZSTD_LEVEL: i32 = 3;
56
57/// The payload is stored as it is.
58pub(crate) const CODEC_RAW: u8 = 0;
59/// The payload is one zstd frame.
60pub(crate) const CODEC_ZSTD: u8 = 1;
61/// Reserved: one zstd frame compressed with a dictionary.
62pub(crate) const CODEC_DICTIONARY: u8 = 2;
63/// The payload is one zstd frame compressed against a base object.
64pub(crate) const CODEC_DELTA: u8 = 3;
65/// The payload is the chunk list of a blob stored in chunks.
66pub(crate) const CODEC_CHUNKED: u8 = 4;
67/// The highest codec number the format defines.
68pub(crate) const CODEC_MAX: u8 = CODEC_CHUNKED;
69
70/// Bytes the CRC adds after the payload.
71const CRC_LEN: usize = 4;
72
73/// Whether a record of this codec holds its object's payload by itself, so
74/// that it can be a delta's base.
75pub(crate) fn is_whole(codec: u8) -> bool {
76 codec == CODEC_RAW || codec == CODEC_ZSTD
77}
78
79/// The storage version a store must have to hold a record of this codec:
80/// 1 for records stored whole, 2 for the others.
81pub(crate) fn storage_version(codec: u8) -> u32 {
82 if is_whole(codec) { 1 } else { 2 }
83}
84
85/// How readers rank copies of one object, best first: whole records, then
86/// deltas, then chunked blobs, then what this version cannot decode. When a
87/// handle knows several copies of an object it uses the best ranked one, so
88/// that a delta's base resolves to a whole copy whenever one is known.
89pub(crate) fn rank(codec: u8) -> u8 {
90 match codec {
91 CODEC_RAW | CODEC_ZSTD => 0,
92 CODEC_DELTA => 1,
93 CODEC_CHUNKED => 2,
94 _ => 3,
95 }
96}
97
98/// The fixed fields of a record.
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub(crate) struct Header {
101 /// What the object is.
102 pub kind: Kind,
103 /// How the payload is stored.
104 pub codec: u8,
105 /// Bytes of payload in the record.
106 pub stored_len: u32,
107 /// Bytes of the object once decoded.
108 pub raw_len: u64,
109 /// The object's id.
110 pub id: ObjectId,
111}
112
113impl Header {
114 /// Bytes from the sync word to the start of the payload.
115 pub fn header_len(&self) -> u64 {
116 header_len(self.codec) as u64
117 }
118
119 /// Bytes the CRC covers: the header and the payload.
120 pub fn checked_len(&self) -> u64 {
121 self.header_len() + u64::from(self.stored_len)
122 }
123
124 /// Bytes to read to check the record: the header, the payload and the CRC.
125 pub fn unpadded_len(&self) -> u64 {
126 self.checked_len() + CRC_LEN as u64
127 }
128
129 /// Bytes the record takes in its segment, padding included.
130 pub fn record_len(&self) -> u64 {
131 align(self.unpadded_len())
132 }
133}
134
135/// Bytes from the sync word to the payload for a codec.
136pub(crate) fn header_len(codec: u8) -> usize {
137 if has_reference(codec) {
138 HEADER_LEN + REFERENCE_LEN
139 } else {
140 HEADER_LEN
141 }
142}
143
144/// Whether records of this codec name another object in their header.
145fn has_reference(codec: u8) -> bool {
146 codec == CODEC_DICTIONARY || codec == CODEC_DELTA
147}
148
149/// Rounds up to the next record boundary.
150pub(crate) fn align(offset: u64) -> u64 {
151 offset.next_multiple_of(ALIGN)
152}
153
154/// A record ready to append.
155#[derive(Debug)]
156pub(crate) struct Encoded {
157 /// Its fixed fields.
158 pub header: Header,
159 /// Its CRC.
160 pub crc: u32,
161 /// All of its bytes, padding included.
162 pub bytes: Vec<u8>,
163}
164
165/// The stored form of a payload on its own: raw when it is small or does
166/// not compress, else one zstd frame.
167pub(crate) fn standalone(payload: &[u8]) -> (u8, Cow<'_, [u8]>) {
168 if payload.len() > RAW_MAX
169 && let Ok(compressed) = zstd::bulk::compress(payload, ZSTD_LEVEL)
170 && compressed.len() < payload.len()
171 {
172 return (CODEC_ZSTD, Cow::Owned(compressed));
173 }
174 (CODEC_RAW, Cow::Borrowed(payload))
175}
176
177/// Encodes the object `id`, which must be the hash of `payload` as `kind`,
178/// on its own: raw or compressed, whichever is smaller. Fails with the
179/// payload size if the stored form does not fit in a record.
180pub(crate) fn encode(kind: Kind, id: ObjectId, payload: &[u8]) -> Result<Encoded, u64> {
181 let (codec, stored) = standalone(payload);
182 assemble(kind, id, codec, payload.len() as u64, None, &stored)
183}
184
185/// Encodes the object `id` raw, without trying to compress it.
186pub(crate) fn encode_raw(kind: Kind, id: ObjectId, payload: &[u8]) -> Result<Encoded, u64> {
187 assemble(kind, id, CODEC_RAW, payload.len() as u64, None, payload)
188}
189
190/// Builds a record from its fields: `stored` is the payload as stored, and
191/// `reference` the base or dictionary id of codecs 2 and 3. Fails with
192/// `raw_len` if the stored form does not fit in a record.
193pub(crate) fn assemble(
194 kind: Kind,
195 id: ObjectId,
196 codec: u8,
197 raw_len: u64,
198 reference: Option<&ObjectId>,
199 stored: &[u8],
200) -> Result<Encoded, u64> {
201 debug_assert_eq!(reference.is_some(), has_reference(codec));
202 let stored_len = u32::try_from(stored.len()).map_err(|_| raw_len)?;
203 let header = Header {
204 kind,
205 codec,
206 stored_len,
207 raw_len,
208 id,
209 };
210 let record_len = usize::try_from(header.record_len()).map_err(|_| raw_len)?;
211 let mut bytes = Vec::with_capacity(record_len);
212 bytes.extend_from_slice(&SYNC.to_le_bytes());
213 bytes.push(kind.code());
214 bytes.push(codec);
215 bytes.extend_from_slice(&0u16.to_le_bytes());
216 bytes.extend_from_slice(&stored_len.to_le_bytes());
217 bytes.extend_from_slice(&raw_len.to_le_bytes());
218 bytes.extend_from_slice(id.as_bytes());
219 if let Some(reference) = reference {
220 bytes.extend_from_slice(reference.as_bytes());
221 }
222 bytes.extend_from_slice(stored);
223 let crc = crc32c::crc32c(&bytes);
224 bytes.extend_from_slice(&crc.to_le_bytes());
225 bytes.resize(record_len, 0);
226 Ok(Encoded { header, crc, bytes })
227}
228
229/// Parses the fixed fields at the start of `bytes`, rejecting anything a
230/// writer would never produce.
231pub(crate) fn parse_header(bytes: &[u8]) -> Result<Header, &'static str> {
232 if bytes.len() < HEADER_LEN {
233 return Err("record header cut short");
234 }
235 if u32::from_le_bytes(array(&bytes[0..4])) != SYNC {
236 return Err("no sync word");
237 }
238 let kind = Kind::from_code(bytes[4]).ok_or("unknown object kind")?;
239 let codec = bytes[5];
240 if codec > CODEC_MAX {
241 return Err("unknown codec");
242 }
243 if u16::from_le_bytes(array(&bytes[6..8])) != 0 {
244 return Err("unknown flags");
245 }
246 let stored_len = u32::from_le_bytes(array(&bytes[8..12]));
247 let raw_len = u64::from_le_bytes(array(&bytes[12..20]));
248 if codec == CODEC_RAW && raw_len != u64::from(stored_len) {
249 return Err("raw payload with two different lengths");
250 }
251 if codec == CODEC_CHUNKED && kind != Kind::Blob {
252 return Err("only blobs are stored in chunks");
253 }
254 let id = ObjectId::from_bytes(array(&bytes[20..52]));
255 Ok(Header {
256 kind,
257 codec,
258 stored_len,
259 raw_len,
260 id,
261 })
262}
263
264/// A record whose checksum is valid, read from the bytes that hold it.
265#[derive(Clone, Copy, Debug)]
266pub(crate) struct Checked<'a> {
267 /// Its fixed fields.
268 pub header: Header,
269 /// Its CRC.
270 pub crc: u32,
271 /// The base (codec 3) or dictionary (codec 2) it names.
272 pub reference: Option<ObjectId>,
273 /// The payload as stored.
274 pub stored: &'a [u8],
275}
276
277/// Checks the record at the start of `bytes`, which must hold at least its
278/// unpadded length: the header and the CRC.
279pub(crate) fn check(bytes: &[u8]) -> Result<Checked<'_>, &'static str> {
280 let header = parse_header(bytes)?;
281 let checked = usize::try_from(header.checked_len()).map_err(|_| "record too large")?;
282 if bytes.len() < checked + CRC_LEN {
283 return Err("record cut short");
284 }
285 let crc = u32::from_le_bytes(array(&bytes[checked..checked + CRC_LEN]));
286 if crc32c::crc32c(&bytes[..checked]) != crc {
287 return Err("checksum mismatch");
288 }
289 let reference = has_reference(header.codec)
290 .then(|| ObjectId::from_bytes(array(&bytes[HEADER_LEN..HEADER_LEN + REFERENCE_LEN])));
291 let start = header_len(header.codec);
292 Ok(Checked {
293 header,
294 crc,
295 reference,
296 stored: &bytes[start..checked],
297 })
298}
299
300/// Restores the payload of a checked record stored whole (codec 0 or 1)
301/// and verifies that it hashes to the record's id.
302pub(crate) fn decode(header: &Header, stored: &[u8]) -> Result<Vec<u8>, &'static str> {
303 let payload = match header.codec {
304 CODEC_RAW => stored.to_vec(),
305 CODEC_ZSTD => decompress(stored, header.raw_len)?,
306 CODEC_DELTA | CODEC_CHUNKED => return Err("record needs other objects to decode"),
307 _ => return Err("codec not supported by this version"),
308 };
309 verify(header, &payload)?;
310 Ok(payload)
311}
312
313/// Checks that a decoded payload hashes to its record's id.
314pub(crate) fn verify(header: &Header, payload: &[u8]) -> Result<(), &'static str> {
315 if ObjectId::hash(header.kind, payload) != header.id {
316 return Err("content does not hash to its id");
317 }
318 Ok(())
319}
320
321fn decompress(stored: &[u8], raw_len: u64) -> Result<Vec<u8>, &'static str> {
322 let decoder = zstd::stream::read::Decoder::with_buffer(stored).map_err(|_| "bad zstd data")?;
323 read_capped(decoder, raw_len)
324}
325
326/// Reads a decoder to its end, expecting exactly `raw_len` bytes. It streams
327/// with a cap instead of trusting `raw_len` for one allocation: a damaged
328/// length then costs at most the data actually there.
329pub(crate) fn read_capped(decoder: impl Read, raw_len: u64) -> Result<Vec<u8>, &'static str> {
330 let mut payload = Vec::with_capacity(usize::try_from(raw_len.min(1 << 24)).unwrap_or(0));
331 decoder
332 .take(raw_len.saturating_add(1))
333 .read_to_end(&mut payload)
334 .map_err(|_| "bad zstd data")?;
335 if payload.len() as u64 != raw_len {
336 return Err("decoded length does not match the record");
337 }
338 Ok(payload)
339}
340
341/// Copies a slice of known length into an array.
342pub(crate) fn array<const N: usize>(bytes: &[u8]) -> [u8; N] {
343 let mut out = [0u8; N];
344 out.copy_from_slice(bytes);
345 out
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 fn round_trip(kind: Kind, payload: &[u8]) -> Encoded {
353 let id = ObjectId::hash(kind, payload);
354 let encoded = encode(kind, id, payload).unwrap();
355 assert_eq!(encoded.bytes.len() as u64, encoded.header.record_len());
356 assert_eq!(encoded.bytes.len() % ALIGN as usize, 0);
357 let checked = check(&encoded.bytes).unwrap();
358 assert_eq!(checked.header, encoded.header);
359 assert_eq!(checked.crc, encoded.crc);
360 assert_eq!(checked.reference, None);
361 assert_eq!(decode(&checked.header, checked.stored).unwrap(), payload);
362 encoded
363 }
364
365 #[test]
366 fn small_payloads_are_raw() {
367 for len in [0, 1, 63, 64] {
368 let payload = vec![b'a'; len];
369 let encoded = round_trip(Kind::Blob, &payload);
370 assert_eq!(encoded.header.codec, CODEC_RAW, "{len}");
371 assert_eq!(encoded.header.stored_len as usize, len);
372 }
373 }
374
375 #[test]
376 fn compressible_payloads_use_zstd() {
377 let payload = b"the same line again and again\n".repeat(100);
378 let encoded = round_trip(Kind::Tree, &payload);
379 assert_eq!(encoded.header.codec, CODEC_ZSTD);
380 assert!((encoded.header.stored_len as usize) < payload.len());
381 assert_eq!(encoded.header.raw_len as usize, payload.len());
382 }
383
384 #[test]
385 fn incompressible_payloads_stay_raw() {
386 let payload: Vec<u8> = (0..4096u32)
387 .map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8)
388 .collect();
389 let id = ObjectId::hash(Kind::Blob, &payload);
390 if zstd::bulk::compress(&payload, ZSTD_LEVEL).unwrap().len() >= payload.len() {
391 assert_eq!(
392 encode(Kind::Blob, id, &payload).unwrap().header.codec,
393 CODEC_RAW
394 );
395 }
396 round_trip(Kind::Blob, &payload);
397 // Asked for raw, it stays raw even when it would compress.
398 let text = b"compress me please ".repeat(20);
399 let id = ObjectId::hash(Kind::Blob, &text);
400 let raw = encode_raw(Kind::Blob, id, &text).unwrap();
401 assert_eq!(raw.header.codec, CODEC_RAW);
402 let checked = check(&raw.bytes).unwrap();
403 assert_eq!(decode(&checked.header, checked.stored).unwrap(), text);
404 }
405
406 #[test]
407 fn layout_matches_the_spec() {
408 let encoded = round_trip(Kind::Blob, b"hello\n");
409 let bytes = &encoded.bytes;
410 assert_eq!(&bytes[0..4], &[0xE9, 0xD5, 0xA1, 0xB7]);
411 assert_eq!(bytes[4], 1);
412 assert_eq!(bytes[5], CODEC_RAW);
413 assert_eq!(&bytes[6..8], &[0, 0]);
414 assert_eq!(&bytes[8..12], &6u32.to_le_bytes());
415 assert_eq!(&bytes[12..20], &6u64.to_le_bytes());
416 assert_eq!(
417 &bytes[20..52],
418 ObjectId::hash(Kind::Blob, b"hello\n").as_bytes()
419 );
420 assert_eq!(&bytes[52..58], b"hello\n");
421 let crc = crc32c::crc32c(&bytes[..58]);
422 assert_eq!(&bytes[58..62], &crc.to_le_bytes());
423 assert_eq!(bytes.len(), 64);
424 assert_eq!(&bytes[62..], &[0, 0]);
425 }
426
427 #[test]
428 fn a_reference_follows_the_id() {
429 let base = ObjectId::hash(Kind::Blob, b"base");
430 let id = ObjectId::hash(Kind::Blob, b"not decoded here");
431 let encoded = assemble(Kind::Blob, id, CODEC_DELTA, 16, Some(&base), b"frame").unwrap();
432 let bytes = &encoded.bytes;
433 assert_eq!(bytes[5], CODEC_DELTA);
434 assert_eq!(&bytes[52..84], base.as_bytes());
435 assert_eq!(&bytes[84..89], b"frame");
436 assert_eq!(encoded.header.header_len(), 84);
437 let checked = check(bytes).unwrap();
438 assert_eq!(checked.reference, Some(base));
439 assert_eq!(checked.stored, b"frame");
440 assert_eq!(
441 decode(&checked.header, checked.stored),
442 Err("record needs other objects to decode")
443 );
444
445 // A chunk list has no reference, and only blobs have one.
446 let chunked = assemble(Kind::Blob, id, CODEC_CHUNKED, 16, None, b"list").unwrap();
447 assert_eq!(chunked.header.header_len(), 52);
448 assert_eq!(check(&chunked.bytes).unwrap().stored, b"list");
449 let mut tree = chunked.bytes.clone();
450 tree[4] = Kind::Tree.code();
451 assert_eq!(parse_header(&tree), Err("only blobs are stored in chunks"));
452 }
453
454 #[test]
455 fn every_flipped_byte_is_caught() {
456 for payload in [&b"hello\n"[..], &b"compress me please ".repeat(20)] {
457 let encoded = round_trip(Kind::Blob, payload);
458 let checked = encoded.header.unpadded_len() as usize;
459 for i in 0..checked {
460 let mut damaged = encoded.bytes.clone();
461 damaged[i] ^= 0x01;
462 let caught = match check(&damaged) {
463 Err(_) => true,
464 Ok(found) => decode(&found.header, found.stored).is_err(),
465 };
466 assert!(caught, "flip at byte {i} went unnoticed");
467 }
468 }
469 }
470
471 #[test]
472 fn cut_records_are_rejected() {
473 let encoded = round_trip(Kind::Blob, b"hello\n");
474 for len in 0..encoded.header.unpadded_len() as usize {
475 assert!(check(&encoded.bytes[..len]).is_err(), "{len}");
476 }
477 }
478
479 #[test]
480 fn wrong_id_is_rejected_after_decoding() {
481 let payload = b"some content";
482 let wrong = ObjectId::hash(Kind::Blob, b"other content");
483 let encoded = encode(Kind::Blob, wrong, payload).unwrap();
484 let checked = check(&encoded.bytes).unwrap();
485 assert_eq!(
486 decode(&checked.header, checked.stored),
487 Err("content does not hash to its id")
488 );
489 }
490
491 #[test]
492 fn reserved_codecs_parse_but_do_not_decode() {
493 let mut encoded = round_trip(Kind::Blob, b"x").bytes;
494 encoded[5] = CODEC_DICTIONARY;
495 let header = parse_header(&encoded).unwrap();
496 assert_eq!(header.header_len(), HEADER_LEN as u64 + 32);
497 encoded[5] = 5;
498 assert_eq!(parse_header(&encoded), Err("unknown codec"));
499 }
500
501 #[test]
502 fn copies_rank_whole_first() {
503 assert!(rank(CODEC_RAW) == rank(CODEC_ZSTD));
504 assert!(rank(CODEC_ZSTD) < rank(CODEC_DELTA));
505 assert!(rank(CODEC_DELTA) < rank(CODEC_CHUNKED));
506 assert!(rank(CODEC_CHUNKED) < rank(CODEC_DICTIONARY));
507 assert!(is_whole(CODEC_RAW) && is_whole(CODEC_ZSTD));
508 assert!(!is_whole(CODEC_DELTA) && !is_whole(CODEC_CHUNKED));
509 }
510}