Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 26.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The local store of elffuss-braid: objects in shared, append-only segments,
5//! and refs with the history of every operation in an op log.
6//!
7//! A store is a directory that any number of processes share at once, with
8//! no daemon, and any of them may be killed at any instant. Correctness rests
9//! only on what every local file system provides: exclusive create, appends
10//! protected by checksums, advisory locks that the kernel releases when a
11//! process dies, atomic rename, and ordered syncs.
12//!
13//! # Example
14//!
15//! ```
16//! use std::convert::Infallible;
17//!
18//! use braid_store::{Kind, Objects, Options, RefUpdate, Store};
19//!
20//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
21//! # let dir = tempfile::tempdir()?;
22//! let store = Store::init(dir.path().join("store"), Options::default())?;
23//! let id = store.put(Kind::Blob, b"hello\n")?;
24//! store.sync()?;
25//! let op = store.transact("agent-1", "point main at hello", |refs| {
26//! Ok::<_, Infallible>(vec![RefUpdate::new("main", refs.get("main"), Some(id))])
27//! })?;
28//! assert_eq!(op.seq, 1);
29//! assert_eq!(store.refs()?.get("main"), Some(id));
30//! assert_eq!(store.get(&id)?, Some((Kind::Blob, b"hello\n".to_vec())));
31//! assert!(store.fsck()?.is_clean());
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! # Publish order
37//!
38//! The op log must never point at an object that is not durable: write the
39//! objects, call [`Store::sync`], and only then record the operation that
40//! refers to them. [`Store::transact`] enforces this for the objects its
41//! updates point at: before it appends the record, it flushes what this
42//! handle wrote and any other writer's open segment that holds one of them.
43//! Objects that only other objects refer to (the trees under a changeset,
44//! say) are the caller's to sync before the transaction.
45//!
46//! # Sharing
47//!
48//! - A writer appends only to a segment it holds an exclusive, non-blocking
49//! lock on: an unlocked open segment if there is one, else a new one made
50//! with an exclusive create. The kernel releases the lock when the writer
51//! dies, and the next writer resumes after what the segment's journal
52//! lists. Segments are never truncated, since others may be reading them.
53//! - After each record, its writer appends a journal entry, so readers find
54//! new objects without reading payloads.
55//! - A segment past the size threshold, or with as many records as a segment
56//! may hold, is sealed: given a sorted index through a temporary file,
57//! flushed with the segment, and a rename, and its journal removed. It is
58//! never written again.
59//! - Once enough segment indexes pile up, a writer merges them into a
60//! merged index, so that lookups go through few indexes.
61//! - Each handle maps ids to records only for the open segments, from their
62//! journals, which the record limit keeps short. Sealed segments are
63//! looked up in their indexes, which it reads as lookups need them, a
64//! fan-out bucket at a time: opening a store reads no index entry,
65//! whatever it holds. On a miss a handle reads the directory again once.
66//! Short ids, hex prefixes of ids, are looked up the same way
67//! ([`Store::ids_with_prefix`]).
68//! - Transactions hold an exclusive lock on `oplog/lock`; readers of the op
69//! log hold it shared, so they never see an operation before it is
70//! durable.
71//!
72//! # On-disk format
73//!
74//! This is section 7 of the format spec as implemented. It is not hashed:
75//! it can change without changing any id. Fixed-size integers are
76//! little-endian; `uv`, `sv` and `bytes` are the codec of section 1.
77//!
78//! ```text
79//! format object-format=blake3-dk-v1, then storage=<version>
80//! format.lock empty; locked exclusively to raise the storage version
81//! seg/<name>.seg object records, append-only
82//! seg/<name>.jrn journal of a segment that is still open
83//! seg/<name>.idx sorted index of a sealed segment
84//! seg/<name>.midx merged index of several sealed segments
85//! seg/merge.lock empty; locked exclusively while indexes are merged
86//! oplog/lock empty; locked exclusively by transactions, shared by readers
87//! oplog/log operation records, append-only
88//! oplog/ckpt.<seq> every ref as of operation <seq>
89//! derived/index where the records of derived values are, by key
90//! ```
91//!
92//! The derived index is a cache with its own rules: see
93//! [`DerivedIndexFile`].
94//!
95//! Segment names are 32 random lowercase hex digits. Files whose names start
96//! with `tmp-` are still being written, or were left by a writer that died;
97//! they are never read, and are removed once they are a minute old and
98//! unlocked.
99//!
100//! **Storage version.** The second line of `format` says what a reader must
101//! understand: a store without it has version 1 (records stored whole),
102//! version 2 adds deltas and chunked blobs, and version 3
103//! ([`STORAGE_VERSION`]) indexes of version 2 and merged indexes, which take
104//! the place of the indexes they merge. A store of a later version, or with
105//! a line this version does not know, is refused with [`Error::NewerStore`]
106//! or [`Error::UnsupportedFormat`]. New stores start at the current version;
107//! an older one is raised under an exclusive lock on `format.lock`, after
108//! reading `format` again, only right before the first record or index that
109//! needs it is written, or when a handle finds such records already there. A
110//! journal entry or an index that holds its checksum but names a kind or a
111//! codec this version does not know, sets a reserved field, or has a later
112//! index version, was written by a newer version: the store is refused, so
113//! nothing is ever written over it.
114//!
115//! **Object record**, starting at a multiple of 8 bytes:
116//!
117//! ```text
118//! u32 sync = 0xB7A1D5E9 | u8 kind | u8 codec | u16 flags = 0
119//! u32 stored_len | u64 raw_len | [32] id
120//! [32] dictionary or base id, codecs 2 and 3 only
121//! payload, stored_len bytes
122//! u32 crc32c of everything from the sync word to the end of the payload
123//! zero padding to a multiple of 8 bytes
124//! ```
125//!
126//! `raw_len` is always the size of the object itself, so [`Objects::stat`]
127//! answers from the header whatever the codec. After a crash, the next
128//! writer appends at the next multiple of 8 after the end of the file, so
129//! the remains of a cut append stay in place and scans step over them 8
130//! bytes at a time.
131//!
132//! | Codec | Payload | Used for |
133//! |---|---|---|
134//! | 0 raw | the object as it is (`stored_len == raw_len`) | up to 64 bytes, or when zstd does not make it smaller |
135//! | 1 zstd | one zstd frame, level 3 | anything else stored whole |
136//! | 2 | reserved: zstd with a dictionary | never written |
137//! | 3 delta | one zstd frame against the base's raw payload | blobs under 4 MiB, trees and derived objects, given a similar object |
138//! | 4 chunked | the chunk list | blobs of 4 MiB or more |
139//!
140//! **Deltas (codec 3).** [`Objects::put_similar`] names an object the new
141//! one is probably close to, such as the same path in the parent, or the
142//! previous git map. A blob under 4 MiB, a tree or a derived object is then
143//! compressed with zstd at level 3, with the raw payload of the base as a
144//! reference prefix, a window that holds the base and the object together
145//! (at most 2²⁷ bytes), and long-distance matching. The record names the
146//! base in its header. The delta is kept only when it and the base id take
147//! at most a quarter of the bytes of the object stored on its own;
148//! otherwise the object is stored whole. Changesets are never deltas: they
149//! share too little with their parents. Depth is always one: a base is
150//! stored whole, and when the similar object is a delta, the new one is made
151//! against that delta's base instead. Reading a delta reads its base and
152//! applies one delta, never a chain; each handle keeps the payloads of the
153//! bases it used last. A handle that knows several copies of one object
154//! uses the best: stored whole, then delta, then chunked.
155//!
156//! **Chunked blobs (codec 4).** A blob of 4 MiB or more is cut with FastCDC
157//! (the 2020 algorithm, normalisation level 1, the standard gear table)
158//! into chunks of 16 KiB to 256 KiB, 64 KiB on average, or of 256 KiB to
159//! 4 MiB, 1 MiB on average, for blobs of 256 MiB or more. Each chunk is a
160//! blob of its own, whose id is the hash of its bytes, so equal chunks are
161//! stored once across files and versions. A chunk is stored whole: raw when
162//! its first 64 KiB do not compress below 0.9 of their size, else
163//! compressed when that is smaller. The blob's own record holds its chunk
164//! list:
165//!
166//! ```text
167//! uv n | n × ([32] chunk id | uv chunk size)
168//! ```
169//!
170//! The sizes add up to `raw_len`. Reads fetch the chunks in order, each
171//! checked against its id, and check the whole against the blob's id, which
172//! is the hash of the full content as always. [`Store::read_to`] streams a
173//! chunked blob a chunk at a time, and [`Store::put_blob_from`] stores one
174//! from a reader, hashing and cutting it as it comes in, with the chunk
175//! sizes for the size the caller expects; how a blob is cut never changes
176//! its id. A chunk list never names a chunked blob: a chunk is written whole
177//! even when a chunked copy of the same bytes exists.
178//!
179//! **What depends on what.** A delta needs its base, and a chunked blob its
180//! chunks. A copy that a writer finds in place of writing an object again
181//! counts only together with what it needs, and the open segments of other
182//! writers that hold those are flushed by the writer's next sync, as the
183//! copy's own segment is. There is no garbage collection yet (`braid gc` is
184//! planned): nothing is ever removed. When there is, it must never drop a
185//! base while a delta needs it, nor a chunk while a chunk list names it.
186//!
187//! **Journal entry**, 64 bytes at a multiple of 64:
188//!
189//! ```text
190//! [32] id | u64 offset | u32 stored_len | u8 kind | u8 codec | u16 0
191//! u64 raw_len | u32 record crc | u32 crc32c of the 60 bytes before it
192//! ```
193//!
194//! An entry is written after its record. Entries that fail their CRC are
195//! skipped, and a new lease holder writes after the last valid one.
196//!
197//! **Index**, version 2, written once when a segment is sealed
198//! (`<name>.idx`, one segment) or when indexes are merged (`<name>.midx`,
199//! several):
200//!
201//! ```text
202//! [8] "braididx" | u32 version = 2 | u32 0 | u64 count | u32 segments
203//! u32 crc32c of the 28 bytes before it
204//! segments × ([16] segment name | u64 segment length)
205//! 256 × u32 fan-out: entry b counts the ids whose first byte is at most b
206//! u32 crc32c of the segment table and the fan-out
207//! count × 64-byte entries, ids strictly ascending:
208//! [32] id | u64 offset | u32 stored_len | u8 kind | u8 codec | u16 segment
209//! u64 raw_len | u32 record crc | u32 crc32c of the 60 bytes before it
210//! ```
211//!
212//! An entry is a journal entry whose reserved field holds the number of its
213//! segment in the table. A segment's name is the 32 hex digits of its file
214//! name as 16 bytes, its length the size it had when it was sealed. Only
215//! entries whose record checks out go in. Of several copies of an object, a
216//! copy stored whole wins over a delta, a delta over a chunked blob, and the
217//! first of equals wins. Every part has its own checksum, so readers take
218//! in and check the head, then one fan-out bucket at a time. Stores of
219//! storage versions 1 and 2 hold indexes of version 1, read whole:
220//!
221//! ```text
222//! [8] "braididx" | u32 version = 1 | u32 0 | u64 count | u64 segment length
223//! 256 × u32 fan-out: entry b counts the ids whose first byte is at most b
224//! count × [32] ids, strictly ascending
225//! count × (u64 offset | u32 stored_len | u8 kind | u8 codec | u16 0
226//! u64 raw_len | u32 record crc | u32 0), in id order
227//! [32] BLAKE3 hash of everything before it
228//! ```
229//!
230//! A segment is open while it has a journal and no index of its own. Once
231//! merged, it has neither: merging removes its journal, if a sealer that
232//! died left one, makes that durable, and only then removes its index.
233//! There is no filter for fast misses yet.
234//!
235//! **Operation record**:
236//!
237//! ```text
238//! u32 magic = 0xB7A10910 | u32 body_len | body | u32 body_len + 16
239//! u32 crc32c of everything before it
240//!
241//! body: u8 version = 1 | uv seq | sv milliseconds since the Unix epoch
242//! bytes agent | bytes description | uv seq undone, 0 for none
243//! uv n | n × (bytes ref name | u8 which | [32] old | [32] new)
244//! ```
245//!
246//! `which` has bit 0 set when `old` is present and bit 1 when `new` is;
247//! absent values take no bytes. The length at the end lets readers walk the
248//! log backwards. Sequence numbers start at 1 and have no gaps. A record cut
249//! short by a crash is skipped by readers and cut off by the next
250//! transaction, but only when no whole record follows it.
251//!
252//! **Checkpoint**, written through a temporary file and a rename after every
253//! `checkpoint_interval` operations; the newest two are kept:
254//!
255//! ```text
256//! [8] "braidckp" | u32 version = 1 | u32 0 | u64 seq | u64 where record seq ends
257//! uv n | n × (bytes ref name | [32] id), names strictly ascending
258//! [32] BLAKE3 hash of everything before it
259//! ```
260
261#![forbid(unsafe_code)]
262
263mod chunks;
264mod delta;
265mod derived;
266mod error;
267mod format_file;
268mod fsck;
269mod fsutil;
270mod index;
271mod journal;
272mod oplog;
273#[cfg(test)]
274mod power_loss;
275mod prefix;
276mod record;
277mod scan;
278mod segments;
279mod stats;
280
281use std::fmt;
282use std::fs::{self, OpenOptions};
283use std::io::{self, Read, Write};
284use std::path::{Path, PathBuf};
285
286pub use braid_format::{Kind, ObjectId, Objects};
287
288pub use chunks::CHUNKED_MIN;
289pub use derived::{DERIVED_DIR, DerivedIndexFile};
290pub use error::{Error, TransactError};
291pub use fsck::{FsckReport, Problem};
292pub use oplog::{Operation, RefUpdate, Refs, check_ref_name};
293pub use stats::{CodecStats, KindStats, Stats};
294
295use error::io_error;
296use oplog::OpLog;
297use segments::Segments;
298
299/// The first line of the `format` file: the object ids a store uses.
300pub const OBJECT_FORMAT: &str = "object-format=blake3-dk-v1";
301
302/// The storage version this version of braid writes: 3, where records may
303/// be deltas (codec 3) and chunked blobs (codec 4), and indexes are of
304/// version 2 and may be merged. It reads stores of every version up to this
305/// one, and refuses later ones with [`Error::NewerStore`].
306pub const STORAGE_VERSION: u32 = 3;
307
308/// How a record stores its object's payload.
309#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
310pub enum Codec {
311 /// As it is.
312 Raw,
313 /// One zstd frame.
314 Zstd,
315 /// Reserved: zstd with a dictionary. Never written.
316 Dictionary,
317 /// A zstd frame against the raw payload of a base object.
318 Delta,
319 /// A blob's chunk list; the chunks are blobs of their own.
320 Chunked,
321}
322
323/// How hard flushes push data to stable storage.
324///
325/// In both modes [`Objects::put`] only appends, [`Store::sync`] flushes the
326/// segments and journals this handle wrote in one batch, and a transaction
327/// flushes the objects its updates point at, then appends its record and
328/// flushes the log before it returns. Order is what keeps the store
329/// consistent after a crash or a power loss: an op log record is never
330/// written before the objects it refers to are flushed, an index never
331/// reaches the disk before the records it points at, and a file published
332/// through a rename never before its contents.
333#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
334pub enum Durability {
335 /// The default for local work: may lose the last operations on power
336 /// loss, never consistency. Files are flushed with `fdatasync`, their
337 /// contents and the metadata needed to read them back, such as their
338 /// length; on Apple systems a batch ends with a write barrier
339 /// (`F_BARRIERFSYNC`) instead, which keeps the order of writes without
340 /// waiting for the drive to write out its cache. Directories are flushed
341 /// when a file is created, renamed or removed in them and something
342 /// depends on it.
343 #[default]
344 Ordered,
345 /// The default for servers: what a transaction acknowledges is on stable
346 /// storage. Files are flushed with `fsync`, which also writes the rest of
347 /// their metadata, or on Apple systems with `F_FULLFSYNC` once per
348 /// batch, and every sync of segments also flushes their directory.
349 Full,
350}
351
352/// How a store is opened.
353#[derive(Clone, Debug, PartialEq, Eq)]
354pub struct Options {
355 /// How hard flushes push data to stable storage.
356 pub durability: Durability,
357 /// A segment is sealed once it holds this many bytes or more. A single
358 /// object larger than this still goes into one segment.
359 pub segment_size: u64,
360 /// A segment is also sealed once its journal lists this many records,
361 /// so that the journals every handle reads when it opens the store stay
362 /// short. 0 for no limit.
363 pub segment_records: u64,
364 /// Once this many segment indexes are there, a writer merges them into
365 /// a merged index at its next sync or transaction, so that lookups go
366 /// through few indexes. 0 never merges.
367 pub merge_threshold: usize,
368 /// After this many operations the refs are saved in a checkpoint, so that
369 /// opening the op log does not replay all of it. 0 writes none.
370 pub checkpoint_interval: u64,
371}
372
373impl Default for Options {
374 fn default() -> Self {
375 Self {
376 durability: Durability::Ordered,
377 segment_size: 256 << 20,
378 segment_records: 1 << 13,
379 merge_threshold: 8,
380 checkpoint_interval: 1000,
381 }
382 }
383}
384
385/// A store, opened by this process.
386///
387/// A `Store` is `Send` and `Sync`: threads can share one handle. Processes
388/// each open their own. Dropping a handle releases its locks; anything it
389/// wrote and did not sync is still visible to other processes, but may be
390/// lost on power loss.
391pub struct Store {
392 root: PathBuf,
393 options: Options,
394 segments: Segments,
395 oplog: OpLog,
396}
397
398impl fmt::Debug for Store {
399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400 f.debug_struct("Store")
401 .field("root", &self.root)
402 .field("options", &self.options)
403 .finish_non_exhaustive()
404 }
405}
406
407impl Store {
408 /// Creates a store at `root` if there is none, then opens it. Safe to run
409 /// from several processes at once.
410 pub fn init(root: impl AsRef<Path>, options: Options) -> Result<Self, Error> {
411 let root = root.as_ref();
412 let seg = root.join("seg");
413 let oplog = root.join("oplog");
414 for dir in [&seg, &oplog] {
415 fs::create_dir_all(dir).map_err(io_error("create", dir))?;
416 }
417 for name in ["lock", "log"] {
418 let path = oplog.join(name);
419 OpenOptions::new()
420 .write(true)
421 .create(true)
422 .truncate(false)
423 .open(&path)
424 .map_err(io_error("create", &path))?;
425 }
426 let durability = options.durability;
427 fsutil::sync_dir(&seg, durability)?;
428 fsutil::sync_dir(&oplog, durability)?;
429 fsutil::sync_dir(root, durability)?;
430 if let Some(parent) = root
431 .parent()
432 .filter(|parent| !parent.as_os_str().is_empty())
433 {
434 fsutil::sync_dir(parent, durability)?;
435 }
436 let format = root.join("format");
437 match fs::metadata(&format) {
438 Ok(_) => {}
439 Err(err) if err.kind() == io::ErrorKind::NotFound => {
440 // Several processes may get here at once; they all publish
441 // the same bytes. Opening reads what won.
442 fsutil::publish_file(
443 root,
444 "format",
445 format_file::contents(STORAGE_VERSION).as_bytes(),
446 durability,
447 &[],
448 )?;
449 }
450 Err(err) => return Err(io_error("read", &format)(err)),
451 }
452 Self::open(root, options)
453 }
454
455 /// Opens an existing store and reads the journals of its open segments.
456 /// Indexes are read as lookups need them: opening reads no index entry,
457 /// whatever the store holds.
458 ///
459 /// A store that needs a newer version of braid is refused with
460 /// [`Error::NewerStore`]: its `format` file names a later storage
461 /// version, or one of its journals holds an entry this version does not
462 /// know; an index that does is refused when a lookup first reads it. A
463 /// store of an earlier storage version is raised when this handle finds
464 /// records that need a later one, and otherwise only when it is about to
465 /// write the first record or index that does.
466 pub fn open(root: impl AsRef<Path>, options: Options) -> Result<Self, Error> {
467 let root = root.as_ref().to_path_buf();
468 let storage = format_file::read(&root)?;
469 let segments = Segments::open(&root, &options, storage)?;
470 let oplog = OpLog::new(root.join("oplog"), &options);
471 Ok(Self {
472 root,
473 options,
474 segments,
475 oplog,
476 })
477 }
478
479 /// The store's directory.
480 pub fn root(&self) -> &Path {
481 &self.root
482 }
483
484 /// The options the store was opened with.
485 pub fn options(&self) -> &Options {
486 &self.options
487 }
488
489 /// Makes everything this handle wrote durable: every segment it appended
490 /// to, their journals, and the open segments of other writers whose
491 /// copies it relied on instead of writing an object again.
492 ///
493 /// If this handle sealed enough segments that their indexes should be
494 /// merged, it merges them next, outside any transaction. A merge that
495 /// fails leaves the store as it was, and the sync succeeds all the same.
496 pub fn sync(&self) -> Result<(), Error> {
497 self.segments.sync()?;
498 self.merge_if_due();
499 Ok(())
500 }
501
502 /// Merges the indexes of sealed segments into one merged index, so that
503 /// lookups go through one index for all of them. Writers do this by
504 /// themselves once enough indexes pile up; this does it now, whatever
505 /// their number. Returns whether there was anything to merge; `false`
506 /// too while another process merges.
507 pub fn merge_indexes(&self) -> Result<bool, Error> {
508 oplog::not_in_transaction()?;
509 self.segments.merge(true)
510 }
511
512 /// Merges indexes if this handle sealed enough segments, unless a
513 /// transaction's closure is running on this thread. Best effort: a merge
514 /// only makes lookups cheaper, and the next one tries again.
515 fn merge_if_due(&self) {
516 if oplog::not_in_transaction().is_ok() {
517 let _ = self.segments.merge_if_due();
518 }
519 }
520
521 /// Reads what other processes wrote or sealed since this handle last
522 /// looked. Lookups that miss do this by themselves.
523 pub fn rescan(&self) -> Result<(), Error> {
524 self.segments.rescan()
525 }
526
527 /// The ids of the stored objects whose hex form starts with `prefix`,
528 /// sorted, at most `limit` of them: how a short id is looked up.
529 ///
530 /// `prefix` is lowercase hex digits, at most 64 of them; anything else
531 /// matches nothing, and the empty prefix matches every object. The ids
532 /// come from the journals and indexes this handle knows of, and no record
533 /// is read; when none matches, the directory is read again once, as a
534 /// lookup by id does on a miss. Of each index, only the fan-out buckets
535 /// the prefix falls in are read: with two digits or more, one.
536 pub fn ids_with_prefix(&self, prefix: &str, limit: usize) -> Result<Vec<ObjectId>, Error> {
537 let Some(prefix) = prefix::HexPrefix::parse(prefix) else {
538 return Ok(Vec::new());
539 };
540 let mut found = self.segments.ids_with_prefix(&prefix)?;
541 if found.is_empty() {
542 self.segments.rescan()?;
543 found = self.segments.ids_with_prefix(&prefix)?;
544 }
545 found.truncate(limit);
546 Ok(found)
547 }
548
549 /// Stores a blob read from `reader` without holding it in memory whole,
550 /// and returns its id and size: the content is hashed and, from 4 MiB
551 /// on, cut into chunks as it streams in. `size_hint` is the size the
552 /// caller expects, such as a file's length: blobs of 256 MiB or more are
553 /// cut into larger chunks. A stream that turns out longer or shorter is
554 /// still stored exactly as read. Nothing is flushed: see [`Store::sync`].
555 pub fn put_blob_from(
556 &self,
557 mut reader: impl Read,
558 size_hint: Option<u64>,
559 ) -> Result<(ObjectId, u64), Error> {
560 self.segments.put_blob_from(&mut reader, size_hint)
561 }
562
563 /// Writes an object's payload to `out` and returns its kind and size,
564 /// or `None` if it is not in the store. A chunked blob is read a chunk at
565 /// a time, so a blob of any size never sits in memory whole.
566 ///
567 /// Every chunk is checked against its id before it is written, and the
568 /// whole blob against its id after the last one: if this fails, what
569 /// `out` received must be discarded.
570 pub fn read_to(
571 &self,
572 id: &ObjectId,
573 mut out: impl Write,
574 ) -> Result<Option<(Kind, u64)>, Error> {
575 self.segments.read_to(id, &mut out)
576 }
577}
578
579impl Objects for Store {
580 type Error = Error;
581
582 /// Reads an object. The record's checksum, length and id are all checked,
583 /// and so are the base of a delta and the chunks of a chunked blob:
584 /// damaged data is an error, never a wrong answer. A miss rescans the
585 /// directory once before answering `None`.
586 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Error> {
587 self.segments.get(id)
588 }
589
590 /// Appends an object, unless this handle already knows a copy: a blob
591 /// of 4 MiB or more in chunks, anything else whole. Nothing is flushed:
592 /// see [`Store::sync`].
593 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Error> {
594 self.segments.put(kind, payload)
595 }
596
597 /// Appends an object like [`Objects::put`], as a delta against
598 /// `similar` (or against its base, if it is a delta itself) when it is a
599 /// blob under 4 MiB, a tree or a derived object and the delta takes at
600 /// most a quarter of the bytes. Changesets are never deltas. A hint
601 /// naming an object that is missing or cannot serve as a base is
602 /// ignored.
603 fn put_similar(
604 &self,
605 kind: Kind,
606 payload: &[u8],
607 similar: &ObjectId,
608 ) -> Result<ObjectId, Error> {
609 self.segments.put_similar(kind, payload, similar)
610 }
611
612 /// Whether an index or a journal lists the object. A miss rescans the
613 /// directory once before answering `false`.
614 fn contains(&self, id: &ObjectId) -> Result<bool, Error> {
615 self.segments.contains(id)
616 }
617
618 /// The kind and payload size of an object, from its record's header: the
619 /// payload is neither read nor decompressed, so this costs the same for
620 /// any size. The header is checked against the object's index or journal
621 /// entry; damage to the payload only shows on [`Objects::get`]. A miss
622 /// rescans the directory once before answering `None`.
623 fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Error> {
624 self.segments.stat(id)
625 }
626}