Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 9.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The object stream, `application/x-braid-objects`: the 10 bytes
5//! [`MAGIC`], then records, then a terminator.
6//!
7//! A record is 1 byte of kind code ([`Kind::code`]), the 32-byte id, the
8//! payload's length as a little-endian u64, and the payload. The terminator
9//! is one byte 0: a stream without it is truncated. [`Reader`] checks every
10//! record's id against its kind and payload.
11
12use std::io::{self, Read, Write};
13
14use braid_format::{Kind, ObjectId};
15
16/// The bytes an object stream starts with.
17pub const MAGIC: &[u8; 10] = b"BRAIDOBJ1\n";
18
19/// Why a stream could not be read.
20#[derive(Debug, thiserror::Error)]
21pub enum StreamError {
22 /// Reading failed.
23 #[error("reading the object stream failed: {0}")]
24 Io(#[from] io::Error),
25 /// The stream does not start with [`MAGIC`].
26 #[error("not an object stream")]
27 Magic,
28 /// The stream ended before its terminator.
29 #[error("the object stream is truncated")]
30 Truncated,
31 /// A record names a kind that does not exist.
32 #[error("unknown object kind code {0}")]
33 Kind(u8),
34 /// A record's payload is larger than the reader allows.
35 #[error("object {id} is {len} bytes, more than the {limit} allowed")]
36 TooLarge {
37 /// The record's id.
38 id: ObjectId,
39 /// Its length.
40 len: u64,
41 /// The reader's limit.
42 limit: u64,
43 },
44 /// A record's id is not the hash of its kind and payload.
45 #[error("object {claimed} does not match its content, which hashes to {actual}")]
46 Mismatch {
47 /// The id the record claims.
48 claimed: ObjectId,
49 /// The id its kind and payload hash to.
50 actual: ObjectId,
51 },
52}
53
54/// Writes an object stream to `out`.
55#[derive(Debug)]
56pub struct Writer<W: Write> {
57 out: W,
58}
59
60impl<W: Write> Writer<W> {
61 /// Starts a stream: writes [`MAGIC`].
62 pub fn new(mut out: W) -> io::Result<Writer<W>> {
63 out.write_all(MAGIC)?;
64 Ok(Writer { out })
65 }
66
67 /// Writes one record.
68 pub fn object(&mut self, kind: Kind, id: &ObjectId, payload: &[u8]) -> io::Result<()> {
69 self.header(kind, id, payload.len() as u64)?;
70 self.out.write_all(payload)
71 }
72
73 /// Writes the start of a record whose payload of `len` bytes the caller
74 /// then writes through [`payload`](Self::payload), so that a large blob
75 /// never has to be in memory whole. Anything but exactly `len` bytes
76 /// breaks the stream.
77 pub fn header(&mut self, kind: Kind, id: &ObjectId, len: u64) -> io::Result<()> {
78 self.out.write_all(&[kind.code()])?;
79 self.out.write_all(id.as_bytes())?;
80 self.out.write_all(&len.to_le_bytes())
81 }
82
83 /// Where the payload announced by [`header`](Self::header) goes.
84 pub fn payload(&mut self) -> &mut W {
85 &mut self.out
86 }
87
88 /// Writes the terminator and returns the writer.
89 pub fn finish(mut self) -> io::Result<W> {
90 self.out.write_all(&[0])?;
91 self.out.flush()?;
92 Ok(self.out)
93 }
94}
95
96/// One record of a stream.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Record {
99 /// The object's kind.
100 pub kind: Kind,
101 /// Its id, checked against `kind` and `payload`.
102 pub id: ObjectId,
103 /// Its payload.
104 pub payload: Vec<u8>,
105}
106
107/// Reads an object stream, checking every record.
108#[derive(Debug)]
109pub struct Reader<R: Read> {
110 input: R,
111 max_object: u64,
112 done: bool,
113}
114
115impl<R: Read> Reader<R> {
116 /// Starts reading: checks [`MAGIC`]. A record larger than `max_object`
117 /// bytes is an error.
118 pub fn new(mut input: R, max_object: u64) -> Result<Reader<R>, StreamError> {
119 let mut magic = [0u8; MAGIC.len()];
120 read_exact(&mut input, &mut magic)?;
121 if &magic != MAGIC {
122 return Err(StreamError::Magic);
123 }
124 Ok(Reader {
125 input,
126 max_object,
127 done: false,
128 })
129 }
130
131 /// The input, positioned after what was read: after the terminator, once
132 /// [`next_record`](Self::next_record) has returned `None`, so a reader
133 /// that refuses data after the terminator can look for it.
134 pub fn into_inner(self) -> R {
135 self.input
136 }
137
138 /// The next record, or `None` after the terminator.
139 pub fn next_record(&mut self) -> Result<Option<Record>, StreamError> {
140 if self.done {
141 return Ok(None);
142 }
143 let mut code = [0u8; 1];
144 read_exact(&mut self.input, &mut code)?;
145 if code[0] == 0 {
146 self.done = true;
147 return Ok(None);
148 }
149 let kind = Kind::from_code(code[0]).ok_or(StreamError::Kind(code[0]))?;
150 let mut id = [0u8; ObjectId::LEN];
151 read_exact(&mut self.input, &mut id)?;
152 let id = ObjectId::from_bytes(id);
153 let mut len = [0u8; 8];
154 read_exact(&mut self.input, &mut len)?;
155 let len = u64::from_le_bytes(len);
156 if len > self.max_object {
157 return Err(StreamError::TooLarge {
158 id,
159 len,
160 limit: self.max_object,
161 });
162 }
163 let mut payload = Vec::new();
164 (&mut self.input).take(len).read_to_end(&mut payload)?;
165 if payload.len() as u64 != len {
166 return Err(StreamError::Truncated);
167 }
168 let actual = ObjectId::hash(kind, &payload);
169 if actual != id {
170 return Err(StreamError::Mismatch {
171 claimed: id,
172 actual,
173 });
174 }
175 Ok(Some(Record { kind, id, payload }))
176 }
177}
178
179impl<R: Read> Iterator for Reader<R> {
180 type Item = Result<Record, StreamError>;
181
182 fn next(&mut self) -> Option<Self::Item> {
183 self.next_record().transpose()
184 }
185}
186
187/// `read_exact`, with an early end reported as [`StreamError::Truncated`].
188fn read_exact<R: Read>(input: &mut R, buf: &mut [u8]) -> Result<(), StreamError> {
189 input.read_exact(buf).map_err(|error| {
190 if error.kind() == io::ErrorKind::UnexpectedEof {
191 StreamError::Truncated
192 } else {
193 StreamError::Io(error)
194 }
195 })
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 fn stream(objects: &[(Kind, &[u8])]) -> Vec<u8> {
203 let mut writer = Writer::new(Vec::new()).unwrap();
204 for (kind, payload) in objects {
205 writer
206 .object(*kind, &ObjectId::hash(*kind, payload), payload)
207 .unwrap();
208 }
209 writer.finish().unwrap()
210 }
211
212 #[test]
213 fn round_trip() {
214 let objects: Vec<(Kind, &[u8])> = vec![
215 (Kind::Blob, b"hello\n"),
216 (Kind::Blob, b""),
217 (Kind::Tree, b"not checked here"),
218 ];
219 let bytes = stream(&objects);
220 let records: Vec<Record> = Reader::new(&bytes[..], 1 << 20)
221 .unwrap()
222 .collect::<Result<_, _>>()
223 .unwrap();
224 assert_eq!(records.len(), 3);
225 for (record, (kind, payload)) in records.iter().zip(&objects) {
226 assert_eq!(record.kind, *kind);
227 assert_eq!(record.payload, *payload);
228 assert_eq!(record.id, ObjectId::hash(*kind, payload));
229 }
230 }
231
232 #[test]
233 fn a_payload_written_after_its_header_reads_back() {
234 let payload = b"streamed in pieces";
235 let id = ObjectId::hash(Kind::Blob, payload);
236 let mut writer = Writer::new(Vec::new()).unwrap();
237 writer
238 .header(Kind::Blob, &id, payload.len() as u64)
239 .unwrap();
240 writer.payload().write_all(&payload[..8]).unwrap();
241 writer.payload().write_all(&payload[8..]).unwrap();
242 let bytes = writer.finish().unwrap();
243 assert_eq!(bytes, stream(&[(Kind::Blob, payload)]));
244 }
245
246 #[test]
247 fn refuses_bad_streams() {
248 let good = stream(&[(Kind::Blob, b"data")]);
249 // No terminator.
250 let cut = &good[..good.len() - 1];
251 let result: Result<Vec<_>, _> = Reader::new(cut, 1 << 20).unwrap().collect();
252 assert!(matches!(result, Err(StreamError::Truncated)));
253 // Cut inside the payload.
254 let cut = &good[..good.len() - 3];
255 let result: Result<Vec<_>, _> = Reader::new(cut, 1 << 20).unwrap().collect();
256 assert!(matches!(result, Err(StreamError::Truncated)));
257 // A flipped payload byte.
258 let mut flipped = good.clone();
259 let at = flipped.len() - 2;
260 flipped[at] ^= 1;
261 let result: Result<Vec<_>, _> = Reader::new(&flipped[..], 1 << 20).unwrap().collect();
262 assert!(matches!(result, Err(StreamError::Mismatch { .. })));
263 // Too large.
264 let result: Result<Vec<_>, _> = Reader::new(&good[..], 2).unwrap().collect();
265 assert!(matches!(result, Err(StreamError::TooLarge { .. })));
266 // Wrong magic, unknown kind.
267 assert!(matches!(
268 Reader::new(&b"BRAIDOBJ2\n\0"[..], 10),
269 Err(StreamError::Magic)
270 ));
271 let mut unknown = MAGIC.to_vec();
272 unknown.push(9);
273 let result: Result<Vec<_>, _> = Reader::new(&unknown[..], 10).unwrap().collect();
274 assert!(matches!(result, Err(StreamError::Kind(9))));
275 }
276}