Elffuss BraidHub

utopia-ia/elffuss-braid public

38b3e04f7d4a · 20.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Objects in every stored form: whole, as deltas, or in chunks.
5//!
6//! - **Writes.** A blob of 4 MiB or more is cut into chunks, each stored as
7//! a blob of its own, then its chunk list. Anything else is stored whole,
8//! unless the writer names a similar object: a blob under 4 MiB, a tree
9//! or a derived object is then stored as a delta against that object, or
10//! against its base if it is a delta itself, when the delta takes at most
11//! a quarter of the bytes.
12//! - **Reads.** A delta needs its base, stored whole; a chunked blob needs
13//! its chunks, stored whole or as deltas. Whatever the form, what comes
14//! back hashes to the id asked for, or the read fails.
15//! - **Bases.** Each handle keeps the payloads of the bases it read last, so
16//! that reading the versions of one file, or writing them, decodes their
17//! base once.
18
19use std::collections::VecDeque;
20use std::io::{self, Read, Write};
21use std::sync::{Arc, Mutex, PoisonError};
22
23use braid_format::{IdHasher, Kind, ObjectId};
24
25use super::{Location, Record, Segments, Wanted, too_large};
26use crate::chunks::{self, CHUNKED_MIN, ChunkRef};
27use crate::delta;
28use crate::error::Error;
29use crate::record::{self, CODEC_CHUNKED, CODEC_DELTA};
30
31/// How many base payloads a handle keeps.
32const CACHED_BASES: usize = 64;
33
34/// How many bytes the base payloads a handle keeps may take together.
35const CACHED_BASE_BYTES: usize = 16 << 20;
36
37/// The largest base a delta is made against: larger objects are not read
38/// whole into memory to save a few bytes.
39const MAX_BASE: u64 = 64 << 20;
40
41/// The payloads of recently used delta bases, most recent first.
42#[derive(Debug, Default)]
43pub(crate) struct BaseCache {
44 inner: Mutex<Bases>,
45}
46
47#[derive(Debug, Default)]
48struct Bases {
49 entries: VecDeque<(ObjectId, Arc<Vec<u8>>)>,
50 bytes: usize,
51}
52
53impl BaseCache {
54 /// The payload of `id`, if it is kept.
55 pub(crate) fn get(&self, id: &ObjectId) -> Option<Arc<Vec<u8>>> {
56 let mut bases = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
57 let at = bases.entries.iter().position(|(cached, _)| cached == id)?;
58 let entry = bases.entries.remove(at)?;
59 let payload = Arc::clone(&entry.1);
60 bases.entries.push_front(entry);
61 Some(payload)
62 }
63
64 /// Keeps the payload of `id`, dropping the least recently used ones
65 /// past the limits.
66 pub(crate) fn insert(&self, id: ObjectId, payload: Arc<Vec<u8>>) {
67 if payload.len() > CACHED_BASE_BYTES / 4 {
68 return;
69 }
70 let mut bases = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
71 if bases.entries.iter().any(|(cached, _)| *cached == id) {
72 return;
73 }
74 bases.bytes += payload.len();
75 bases.entries.push_front((id, payload));
76 while bases.entries.len() > CACHED_BASES || bases.bytes > CACHED_BASE_BYTES {
77 match bases.entries.pop_back() {
78 Some((_, evicted)) => bases.bytes -= evicted.len(),
79 None => break,
80 }
81 }
82 }
83}
84
85impl Segments {
86 /// Stores an object and returns its id: a blob of 4 MiB or more in
87 /// chunks, anything else whole. Nothing is flushed: call
88 /// [`Segments::sync`] before anything durable refers to the object.
89 pub fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Error> {
90 let id = ObjectId::hash(kind, payload);
91 if kind == Kind::Blob && payload.len() as u64 >= CHUNKED_MIN {
92 if !self.stored(&id, Wanted::Any)? {
93 let mut chunks = Vec::new();
94 for chunk in chunks::cut(payload) {
95 chunks.push(self.put_chunk(chunk)?);
96 }
97 self.finish_chunked(id, payload.len() as u64, &chunks)?;
98 }
99 } else {
100 self.store_record(&id, Wanted::Any, || {
101 record::encode(kind, id, payload).map_err(too_large)
102 })?;
103 }
104 Ok(id)
105 }
106
107 /// Stores an object that is probably close to `similar`. A blob under
108 /// 4 MiB, a tree or a derived object becomes a delta when that takes at
109 /// most a quarter of the bytes of storing it on its own; anything else
110 /// is stored as [`Segments::put`] does. The hint never makes a write
111 /// fail: when the similar object is missing, damaged or unusable as a
112 /// base, the object is stored on its own.
113 pub fn put_similar(
114 &self,
115 kind: Kind,
116 payload: &[u8],
117 similar: &ObjectId,
118 ) -> Result<ObjectId, Error> {
119 if !delta::eligible(kind, payload.len()) {
120 return self.put(kind, payload);
121 }
122 let id = ObjectId::hash(kind, payload);
123 if self.stored(&id, Wanted::Any)? {
124 return Ok(id);
125 }
126 let (codec, alone) = record::standalone(payload);
127 let delta = match self.delta_base(similar) {
128 Some((base_id, base)) => delta::encode(kind, id, payload, &base_id, &base, alone.len()),
129 None => None,
130 };
131 let encoded = match delta {
132 Some(delta) => delta,
133 None => record::assemble(kind, id, codec, payload.len() as u64, None, &alone)
134 .map_err(too_large)?,
135 };
136 self.store_record(&id, Wanted::Any, || Ok(encoded))?;
137 Ok(id)
138 }
139
140 /// Stores a blob read from `reader` without holding it in memory
141 /// whole, and returns its id and size. Up to 4 MiB it is stored like
142 /// [`Segments::put`]; past that, it is cut into chunks as it streams in,
143 /// with chunk sizes for a blob of `size_hint` bytes, the size the caller
144 /// expects. A stream that turns out longer or shorter is still stored
145 /// exactly as read; only how it is cut depends on the hint.
146 pub fn put_blob_from(
147 &self,
148 reader: &mut dyn Read,
149 size_hint: Option<u64>,
150 ) -> Result<(ObjectId, u64), Error> {
151 let read_error = |source| Error::Stream {
152 action: "read",
153 source,
154 };
155 let mut head = Vec::new();
156 (&mut *reader)
157 .take(CHUNKED_MIN)
158 .read_to_end(&mut head)
159 .map_err(read_error)?;
160 if (head.len() as u64) < CHUNKED_MIN {
161 let id = self.put(Kind::Blob, &head)?;
162 return Ok((id, head.len() as u64));
163 }
164 let size = size_hint.unwrap_or(0).max(CHUNKED_MIN);
165 let mut hasher = IdHasher::new(Kind::Blob);
166 let mut chunks = Vec::new();
167 let mut total = 0u64;
168 for chunk in chunks::cut_stream(io::Cursor::new(head).chain(reader), size) {
169 let chunk = chunk.map_err(|err| read_error(err.into()))?;
170 hasher.update(&chunk.data);
171 total += chunk.data.len() as u64;
172 chunks.push(self.put_chunk(&chunk.data)?);
173 }
174 let id = hasher.finalize();
175 self.finish_chunked(id, total, &chunks)?;
176 Ok((id, total))
177 }
178
179 /// Stores one chunk of a chunked blob, whole: a chunk list never names a
180 /// chunked blob.
181 fn put_chunk(&self, chunk: &[u8]) -> Result<ChunkRef, Error> {
182 let id = ObjectId::hash(Kind::Blob, chunk);
183 self.store_record(&id, Wanted::NotChunked, || {
184 chunks::encode_chunk(id, chunk).map_err(too_large)
185 })?;
186 Ok(ChunkRef {
187 id,
188 size: chunk.len() as u64,
189 })
190 }
191
192 /// Stores the chunk list of the blob `id`, whose chunks are stored.
193 fn finish_chunked(&self, id: ObjectId, size: u64, chunks: &[ChunkRef]) -> Result<(), Error> {
194 // A blob of one chunk is that chunk, stored whole already.
195 if chunks.len() == 1 {
196 return Ok(());
197 }
198 self.store_record(&id, Wanted::Any, || {
199 chunks::encode_chunked(id, size, chunks).map_err(too_large)
200 })
201 }
202
203 /// The base to store a delta against, given the object a writer says is
204 /// similar, with its payload: that object if it is stored whole, or its
205 /// base if it is a delta. `None` when there is none to use.
206 fn delta_base(&self, similar: &ObjectId) -> Option<(ObjectId, Arc<Vec<u8>>)> {
207 let location = self.location(similar)?;
208 let (base, location) = match location.entry.codec {
209 codec if record::is_whole(codec) => (*similar, location),
210 CODEC_DELTA => {
211 let base = self.reference(&location).ok()??;
212 (base, self.location(&base)?)
213 }
214 _ => return None,
215 };
216 if location.entry.raw_len > MAX_BASE {
217 return None;
218 }
219 // The base must stay readable for as long as the delta: whole, and
220 // flushed by this handle's next sync if its writer has not yet.
221 if !self.rely_on_base(&location).ok()? {
222 return None;
223 }
224 let payload = self.base_payload(&base, &location).ok()?;
225 Some((base, payload))
226 }
227
228 /// The payload of the base `id`, stored whole at `location`.
229 fn base_payload(&self, id: &ObjectId, location: &Location) -> Result<Arc<Vec<u8>>, Error> {
230 if let Some(payload) = self.bases.get(id) {
231 return Ok(payload);
232 }
233 let base = self.read_record(location)?;
234 let payload = record::decode(&base.header, base.stored()).map_err(|d| base.corrupt(d))?;
235 let payload = Arc::new(payload);
236 self.bases.insert(*id, Arc::clone(&payload));
237 Ok(payload)
238 }
239
240 /// Reads an object, checking every record it takes and its id.
241 pub fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Error> {
242 let Some(location) = self.find(id)? else {
243 return Ok(None);
244 };
245 let payload = if location.entry.codec == CODEC_CHUNKED {
246 let capacity = usize::try_from(location.entry.raw_len.min(1 << 24)).unwrap_or(0);
247 let mut payload = Vec::with_capacity(capacity);
248 self.read_chunked(&location, &mut |bytes| {
249 payload.extend_from_slice(bytes);
250 Ok(())
251 })?;
252 payload
253 } else {
254 self.read_single(&location)?
255 };
256 Ok(Some((location.entry.kind, payload)))
257 }
258
259 /// Writes an object's payload to `out`, a chunk at a time for a chunked
260 /// blob, so that a blob of any size can be read with little memory.
261 /// Returns its kind and size, or `None` if it is not here.
262 ///
263 /// Every chunk is checked before it is written, and the whole blob's id
264 /// after the last one: on an error, discard what `out` received.
265 pub fn read_to(
266 &self,
267 id: &ObjectId,
268 out: &mut dyn Write,
269 ) -> Result<Option<(Kind, u64)>, Error> {
270 let Some(location) = self.find(id)? else {
271 return Ok(None);
272 };
273 let mut write = |bytes: &[u8]| {
274 out.write_all(bytes).map_err(|source| Error::Stream {
275 action: "write",
276 source,
277 })
278 };
279 if location.entry.codec == CODEC_CHUNKED {
280 self.read_chunked(&location, &mut write)?;
281 } else {
282 write(&self.read_single(&location)?)?;
283 }
284 Ok(Some((location.entry.kind, location.entry.raw_len)))
285 }
286
287 /// Reads an object stored in one record: whole, or as a delta.
288 fn read_single(&self, location: &Location) -> Result<Vec<u8>, Error> {
289 let found = self.read_record(location)?;
290 match (found.header.codec, found.reference) {
291 (CODEC_DELTA, Some(base)) => {
292 let base = self.base_of(&found, &base)?;
293 delta::decode(&found.header, found.stored(), &base).map_err(|d| found.corrupt(d))
294 }
295 _ => record::decode(&found.header, found.stored()).map_err(|d| found.corrupt(d)),
296 }
297 }
298
299 /// The payload of the base a delta names. A handle that only knows a
300 /// copy of the base that is not whole looks at the directory again once,
301 /// since the copy the delta was made against may be new to it.
302 fn base_of(&self, delta: &Record, base: &ObjectId) -> Result<Arc<Vec<u8>>, Error> {
303 if let Some(payload) = self.bases.get(base) {
304 return Ok(payload);
305 }
306 let mut location = self.find(base)?;
307 if location.is_some_and(|found| !record::is_whole(found.entry.codec)) {
308 self.rescan()?;
309 location = self.location(base);
310 }
311 let location = match location {
312 None => return Err(delta.corrupt(format_args!("its base {base} is missing"))),
313 Some(found) if !record::is_whole(found.entry.codec) => {
314 return Err(delta.corrupt(format_args!("its base {base} is not stored whole")));
315 }
316 Some(found) => found,
317 };
318 self.base_payload(base, &location).map_err(|err| match err {
319 Error::Corrupt { detail, .. } => delta.corrupt(format_args!("its base: {detail}")),
320 other => other,
321 })
322 }
323
324 /// Reads a chunked blob a chunk at a time, passing each chunk's bytes to
325 /// `sink` in order, then checks that the whole hashes to the blob's id.
326 fn read_chunked(
327 &self,
328 location: &Location,
329 sink: &mut dyn FnMut(&[u8]) -> Result<(), Error>,
330 ) -> Result<(), Error> {
331 let list = self.read_record(location)?;
332 let chunks =
333 chunks::decode_list(list.stored(), list.header.raw_len).map_err(|d| list.corrupt(d))?;
334 let mut hasher = IdHasher::new(Kind::Blob);
335 for chunk in &chunks {
336 let bytes = self.read_chunk(&list, chunk)?;
337 hasher.update(&bytes);
338 sink(&bytes)?;
339 }
340 if hasher.finalize() != list.header.id {
341 return Err(list.corrupt("content does not hash to its id"));
342 }
343 Ok(())
344 }
345
346 /// Reads one chunk of the chunked blob `list`.
347 fn read_chunk(&self, list: &Record, chunk: &ChunkRef) -> Result<Vec<u8>, Error> {
348 let mut location = self.find(&chunk.id)?;
349 if location.is_some_and(|found| found.entry.codec == CODEC_CHUNKED) {
350 self.rescan()?;
351 location = self.location(&chunk.id);
352 }
353 let location = match location {
354 None => {
355 return Err(list.corrupt(format_args!("its chunk {} is missing", chunk.id)));
356 }
357 Some(found)
358 if found.entry.codec == CODEC_CHUNKED
359 || found.entry.kind != Kind::Blob
360 || found.entry.raw_len != chunk.size =>
361 {
362 return Err(list.corrupt(format_args!(
363 "its chunk {} is not stored as a blob of {} bytes",
364 chunk.id, chunk.size
365 )));
366 }
367 Some(found) => found,
368 };
369 self.read_single(&location).map_err(|err| match err {
370 Error::Corrupt { detail, .. } => list.corrupt(format_args!("its chunk: {detail}")),
371 other => other,
372 })
373 }
374}
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use crate::record::{CODEC_RAW, CODEC_ZSTD};
380 use crate::{Options, STORAGE_VERSION};
381
382 fn segments(dir: &std::path::Path) -> Segments {
383 std::fs::create_dir_all(dir.join("seg")).unwrap();
384 Segments::open(dir, &Options::default(), STORAGE_VERSION).unwrap()
385 }
386
387 /// Source-like text: lines that compress only a little on their own.
388 fn text(seed: u64, lines: usize) -> Vec<u8> {
389 let mut state = seed | 1;
390 let mut out = Vec::new();
391 for i in 0..lines {
392 state ^= state << 13;
393 state ^= state >> 7;
394 state ^= state << 17;
395 out.extend_from_slice(format!("{i}: {state:016x}\n").as_bytes());
396 }
397 out
398 }
399
400 fn edit(mut payload: Vec<u8>, at: usize, with: &[u8]) -> Vec<u8> {
401 payload[at..at + with.len()].copy_from_slice(with);
402 payload
403 }
404
405 fn codec(segments: &Segments, id: &ObjectId) -> u8 {
406 segments.location(id).unwrap().entry.codec
407 }
408
409 fn base(segments: &Segments, id: &ObjectId) -> Option<ObjectId> {
410 segments.reference(&segments.location(id).unwrap()).unwrap()
411 }
412
413 #[test]
414 fn deltas_are_one_level_deep() {
415 let dir = tempfile::tempdir().unwrap();
416 let segments = segments(dir.path());
417 let v1 = text(1, 500);
418 let v2 = edit(v1.clone(), 100, b"two");
419 let v3 = edit(v2.clone(), 2000, b"three");
420 let id1 = segments.put(Kind::Blob, &v1).unwrap();
421 let id2 = segments.put_similar(Kind::Blob, &v2, &id1).unwrap();
422 let id3 = segments.put_similar(Kind::Blob, &v3, &id2).unwrap();
423 assert_eq!(codec(&segments, &id1), CODEC_ZSTD);
424 assert_eq!(codec(&segments, &id2), CODEC_DELTA);
425 assert_eq!(codec(&segments, &id3), CODEC_DELTA);
426 // v3 was said to be like v2, a delta: it is made against v2's base.
427 assert_eq!(base(&segments, &id2), Some(id1));
428 assert_eq!(base(&segments, &id3), Some(id1));
429 for (id, payload) in [(id1, &v1), (id2, &v2), (id3, &v3)] {
430 assert_eq!(
431 segments.get(&id).unwrap(),
432 Some((Kind::Blob, payload.clone()))
433 );
434 }
435
436 // Trees too; other kinds, small payloads and large blobs never.
437 let tree = segments.put(Kind::Tree, &v1).unwrap();
438 let tree2 = segments.put_similar(Kind::Tree, &v2, &tree).unwrap();
439 assert_eq!(codec(&segments, &tree2), CODEC_DELTA);
440 let changeset = segments.put_similar(Kind::Changeset, &v2, &id1).unwrap();
441 assert_ne!(codec(&segments, &changeset), CODEC_DELTA);
442 let small = segments.put_similar(Kind::Blob, b"tiny", &id1).unwrap();
443 assert_eq!(codec(&segments, &small), CODEC_RAW);
444 }
445
446 #[test]
447 fn hints_that_cannot_serve_are_ignored() {
448 let dir = tempfile::tempdir().unwrap();
449 let segments = segments(dir.path());
450 let v1 = text(2, 400);
451 let absent = ObjectId::hash(Kind::Blob, b"never stored");
452 let id = segments.put_similar(Kind::Blob, &v1, &absent).unwrap();
453 assert_eq!(codec(&segments, &id), CODEC_ZSTD);
454 // Unrelated content: the delta would not take a quarter or less.
455 let other = text(3, 400);
456 let other_id = segments.put_similar(Kind::Blob, &other, &id).unwrap();
457 assert_eq!(codec(&segments, &other_id), CODEC_ZSTD);
458 // A chunked blob is never a base.
459 let big = vec![7u8; CHUNKED_MIN as usize];
460 let big_id = segments.put(Kind::Blob, &big).unwrap();
461 assert_eq!(codec(&segments, &big_id), CODEC_CHUNKED);
462 let near = edit(big[..1000].to_vec(), 10, b"x");
463 let near_id = segments.put_similar(Kind::Blob, &near, &big_id).unwrap();
464 assert_ne!(codec(&segments, &near_id), CODEC_DELTA);
465 // Storing again is a no-op, hint or not.
466 assert_eq!(
467 segments.put_similar(Kind::Blob, &v1, &other_id).unwrap(),
468 id
469 );
470 assert_eq!(codec(&segments, &id), CODEC_ZSTD);
471 }
472
473 #[test]
474 fn a_copy_stored_whole_wins_over_a_delta() {
475 let dir = tempfile::tempdir().unwrap();
476 let v1 = text(4, 300);
477 let v2 = edit(v1.clone(), 50, b"changed");
478 // Two handles, each unaware of the other's copy of v2.
479 let a = segments(dir.path());
480 let b = segments(dir.path());
481 let id1 = a.put(Kind::Blob, &v1).unwrap();
482 b.rescan().unwrap();
483 let id2 = a.put_similar(Kind::Blob, &v2, &id1).unwrap();
484 assert_eq!(codec(&a, &id2), CODEC_DELTA);
485 let whole = b.put(Kind::Blob, &v2).unwrap();
486 assert_eq!(whole, id2);
487 a.sync().unwrap();
488 b.sync().unwrap();
489 // A third handle sees both copies and keeps the whole one, so that a
490 // delta against v2 has a base stored whole.
491 let c = segments(dir.path());
492 assert_eq!(codec(&c, &id2), CODEC_ZSTD);
493 let v3 = edit(v2.clone(), 900, b"third");
494 let id3 = c.put_similar(Kind::Blob, &v3, &id2).unwrap();
495 assert_eq!(base(&c, &id3), Some(id2));
496 assert_eq!(c.get(&id3).unwrap(), Some((Kind::Blob, v3)));
497 }
498
499 #[test]
500 fn the_base_cache_keeps_the_most_recent() {
501 let cache = BaseCache::default();
502 let id = |n: u32| ObjectId::hash(Kind::Blob, &n.to_le_bytes());
503 for n in 0..(CACHED_BASES as u32 + 10) {
504 cache.insert(id(n), Arc::new(vec![0; 10]));
505 // Keep the first one in use.
506 assert!(cache.get(&id(0)).is_some(), "{n}");
507 }
508 assert!(cache.get(&id(1)).is_none());
509 assert!(cache.get(&id(CACHED_BASES as u32 + 9)).is_some());
510 // Bytes are bounded too, and payloads that are too large stay out.
511 cache.insert(id(1000), Arc::new(vec![0; CACHED_BASE_BYTES / 4 + 1]));
512 assert!(cache.get(&id(1000)).is_none());
513 for n in 2000..2010 {
514 cache.insert(id(n), Arc::new(vec![0; CACHED_BASE_BYTES / 4]));
515 }
516 let bases = cache.inner.lock().unwrap();
517 assert!(bases.bytes <= CACHED_BASE_BYTES);
518 assert_eq!(
519 bases.bytes,
520 bases.entries.iter().map(|(_, p)| p.len()).sum::<usize>()
521 );
522 }
523}