Elffuss BraidHub

utopia-ia/elffuss-braid public

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