Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 20.7 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::{ANY, Location, NOT_CHUNKED, Record, Segments, WHOLE, 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.locate(similar, NOT_CHUNKED).ok()??;
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.locate(&base, WHOLE).ok()??)
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, ANY)? 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, ANY)? 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 knows no copy
300 /// of the base stored whole looks at the directory again once, since the
301 /// 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 location = match self.find(base, WHOLE)? {
307 Some(found) => found,
308 None if self.locate(base, ANY)?.is_some() => {
309 return Err(delta.corrupt(format_args!("its base {base} is not stored whole")));
310 }
311 None => return Err(delta.corrupt(format_args!("its base {base} is missing"))),
312 };
313 self.base_payload(base, &location).map_err(|err| match err {
314 Error::Corrupt { detail, .. } => delta.corrupt(format_args!("its base: {detail}")),
315 other => other,
316 })
317 }
318
319 /// Reads a chunked blob a chunk at a time, passing each chunk's bytes to
320 /// `sink` in order, then checks that the whole hashes to the blob's id.
321 fn read_chunked(
322 &self,
323 location: &Location,
324 sink: &mut dyn FnMut(&[u8]) -> Result<(), Error>,
325 ) -> Result<(), Error> {
326 let list = self.read_record(location)?;
327 let chunks =
328 chunks::decode_list(list.stored(), list.header.raw_len).map_err(|d| list.corrupt(d))?;
329 let mut hasher = IdHasher::new(Kind::Blob);
330 for chunk in &chunks {
331 let bytes = self.read_chunk(&list, chunk)?;
332 hasher.update(&bytes);
333 sink(&bytes)?;
334 }
335 if hasher.finalize() != list.header.id {
336 return Err(list.corrupt("content does not hash to its id"));
337 }
338 Ok(())
339 }
340
341 /// Reads one chunk of the chunked blob `list`.
342 fn read_chunk(&self, list: &Record, chunk: &ChunkRef) -> Result<Vec<u8>, Error> {
343 let location = match self.find(&chunk.id, NOT_CHUNKED)? {
344 None if self.locate(&chunk.id, ANY)?.is_none() => {
345 return Err(list.corrupt(format_args!("its chunk {} is missing", chunk.id)));
346 }
347 None => None,
348 found => found,
349 };
350 let location = match location {
351 Some(found)
352 if found.entry.codec != CODEC_CHUNKED
353 && found.entry.kind == Kind::Blob
354 && found.entry.raw_len == chunk.size =>
355 {
356 found
357 }
358 _ => {
359 return Err(list.corrupt(format_args!(
360 "its chunk {} is not stored as a blob of {} bytes",
361 chunk.id, chunk.size
362 )));
363 }
364 };
365 self.read_single(&location).map_err(|err| match err {
366 Error::Corrupt { detail, .. } => list.corrupt(format_args!("its chunk: {detail}")),
367 other => other,
368 })
369 }
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375 use crate::record::{CODEC_RAW, CODEC_ZSTD};
376 use crate::{Options, STORAGE_VERSION};
377
378 fn segments(dir: &std::path::Path) -> Segments {
379 std::fs::create_dir_all(dir.join("seg")).unwrap();
380 Segments::open(dir, &Options::default(), STORAGE_VERSION).unwrap()
381 }
382
383 /// Source-like text: lines that compress only a little on their own.
384 fn text(seed: u64, lines: usize) -> Vec<u8> {
385 let mut state = seed | 1;
386 let mut out = Vec::new();
387 for i in 0..lines {
388 state ^= state << 13;
389 state ^= state >> 7;
390 state ^= state << 17;
391 out.extend_from_slice(format!("{i}: {state:016x}\n").as_bytes());
392 }
393 out
394 }
395
396 fn edit(mut payload: Vec<u8>, at: usize, with: &[u8]) -> Vec<u8> {
397 payload[at..at + with.len()].copy_from_slice(with);
398 payload
399 }
400
401 fn codec(segments: &Segments, id: &ObjectId) -> u8 {
402 segments.locate(id, ANY).unwrap().unwrap().entry.codec
403 }
404
405 fn base(segments: &Segments, id: &ObjectId) -> Option<ObjectId> {
406 segments
407 .reference(&segments.locate(id, ANY).unwrap().unwrap())
408 .unwrap()
409 }
410
411 #[test]
412 fn deltas_are_one_level_deep() {
413 let dir = tempfile::tempdir().unwrap();
414 let segments = segments(dir.path());
415 let v1 = text(1, 500);
416 let v2 = edit(v1.clone(), 100, b"two");
417 let v3 = edit(v2.clone(), 2000, b"three");
418 let id1 = segments.put(Kind::Blob, &v1).unwrap();
419 let id2 = segments.put_similar(Kind::Blob, &v2, &id1).unwrap();
420 let id3 = segments.put_similar(Kind::Blob, &v3, &id2).unwrap();
421 assert_eq!(codec(&segments, &id1), CODEC_ZSTD);
422 assert_eq!(codec(&segments, &id2), CODEC_DELTA);
423 assert_eq!(codec(&segments, &id3), CODEC_DELTA);
424 // v3 was said to be like v2, a delta: it is made against v2's base.
425 assert_eq!(base(&segments, &id2), Some(id1));
426 assert_eq!(base(&segments, &id3), Some(id1));
427 for (id, payload) in [(id1, &v1), (id2, &v2), (id3, &v3)] {
428 assert_eq!(
429 segments.get(&id).unwrap(),
430 Some((Kind::Blob, payload.clone()))
431 );
432 }
433
434 // Trees too; other kinds, small payloads and large blobs never.
435 let tree = segments.put(Kind::Tree, &v1).unwrap();
436 let tree2 = segments.put_similar(Kind::Tree, &v2, &tree).unwrap();
437 assert_eq!(codec(&segments, &tree2), CODEC_DELTA);
438 let changeset = segments.put_similar(Kind::Changeset, &v2, &id1).unwrap();
439 assert_ne!(codec(&segments, &changeset), CODEC_DELTA);
440 let small = segments.put_similar(Kind::Blob, b"tiny", &id1).unwrap();
441 assert_eq!(codec(&segments, &small), CODEC_RAW);
442 }
443
444 #[test]
445 fn hints_that_cannot_serve_are_ignored() {
446 let dir = tempfile::tempdir().unwrap();
447 let segments = segments(dir.path());
448 let v1 = text(2, 400);
449 let absent = ObjectId::hash(Kind::Blob, b"never stored");
450 let id = segments.put_similar(Kind::Blob, &v1, &absent).unwrap();
451 assert_eq!(codec(&segments, &id), CODEC_ZSTD);
452 // Unrelated content: the delta would not take a quarter or less.
453 let other = text(3, 400);
454 let other_id = segments.put_similar(Kind::Blob, &other, &id).unwrap();
455 assert_eq!(codec(&segments, &other_id), CODEC_ZSTD);
456 // A chunked blob is never a base.
457 let big = vec![7u8; CHUNKED_MIN as usize];
458 let big_id = segments.put(Kind::Blob, &big).unwrap();
459 assert_eq!(codec(&segments, &big_id), CODEC_CHUNKED);
460 let near = edit(big[..1000].to_vec(), 10, b"x");
461 let near_id = segments.put_similar(Kind::Blob, &near, &big_id).unwrap();
462 assert_ne!(codec(&segments, &near_id), CODEC_DELTA);
463 // Storing again is a no-op, hint or not.
464 assert_eq!(
465 segments.put_similar(Kind::Blob, &v1, &other_id).unwrap(),
466 id
467 );
468 assert_eq!(codec(&segments, &id), CODEC_ZSTD);
469 }
470
471 #[test]
472 fn a_copy_stored_whole_wins_over_a_delta() {
473 let dir = tempfile::tempdir().unwrap();
474 let v1 = text(4, 300);
475 let v2 = edit(v1.clone(), 50, b"changed");
476 // Two handles, each unaware of the other's copy of v2.
477 let a = segments(dir.path());
478 let b = segments(dir.path());
479 let id1 = a.put(Kind::Blob, &v1).unwrap();
480 b.rescan().unwrap();
481 let id2 = a.put_similar(Kind::Blob, &v2, &id1).unwrap();
482 assert_eq!(codec(&a, &id2), CODEC_DELTA);
483 let whole = b.put(Kind::Blob, &v2).unwrap();
484 assert_eq!(whole, id2);
485 a.sync().unwrap();
486 b.sync().unwrap();
487 // A third handle sees both copies and keeps the whole one, so that a
488 // delta against v2 has a base stored whole.
489 let c = segments(dir.path());
490 assert_eq!(codec(&c, &id2), CODEC_ZSTD);
491 let v3 = edit(v2.clone(), 900, b"third");
492 let id3 = c.put_similar(Kind::Blob, &v3, &id2).unwrap();
493 assert_eq!(base(&c, &id3), Some(id2));
494 assert_eq!(c.get(&id3).unwrap(), Some((Kind::Blob, v3)));
495 }
496
497 #[test]
498 fn the_base_cache_keeps_the_most_recent() {
499 let cache = BaseCache::default();
500 let id = |n: u32| ObjectId::hash(Kind::Blob, &n.to_le_bytes());
501 for n in 0..(CACHED_BASES as u32 + 10) {
502 cache.insert(id(n), Arc::new(vec![0; 10]));
503 // Keep the first one in use.
504 assert!(cache.get(&id(0)).is_some(), "{n}");
505 }
506 assert!(cache.get(&id(1)).is_none());
507 assert!(cache.get(&id(CACHED_BASES as u32 + 9)).is_some());
508 // Bytes are bounded too, and payloads that are too large stay out.
509 cache.insert(id(1000), Arc::new(vec![0; CACHED_BASE_BYTES / 4 + 1]));
510 assert!(cache.get(&id(1000)).is_none());
511 for n in 2000..2010 {
512 cache.insert(id(n), Arc::new(vec![0; CACHED_BASE_BYTES / 4]));
513 }
514 let bases = cache.inner.lock().unwrap();
515 assert!(bases.bytes <= CACHED_BASE_BYTES);
516 assert_eq!(
517 bases.bytes,
518 bases.entries.iter().map(|(_, p)| p.len()).sum::<usize>()
519 );
520 }
521}