JFLib

cas#

content-addressed backup repositories: chunking, packs, signed encrypted snapshots, GC -- crate root lib/cas/lib.rs

cas -- a content-addressed, deduplicating, encrypted chunk store (BackupCraft's repository
format "bcrepo-1")

  Repo::create(path, &CreateOptions) / Repo::open(path, Unlock::{Master, Passphrase,
       Recovery})                       a repository in a folder (store::Folder)
  Repo::create_in(store, ..) / open_in(store, ..)   in any Store (store.rs: objects by kind
                                        and name, the way S3, SFTP or WebDAV keep them);
                                        one holder at a time (Store::lock)
  repo.writer() -> Writer               put(kind, bytes) / put_stream(reader) -> chunk ids,
                                        finish() (packs and indexes are durable);
                                        finish_unsaved() -> (stats, Unsaved): the same, and
                                        gc stays out until unsaved.save_snapshot(..) -- the
                                        way of a backup where a gc can run beside it;
                                        .codec(c, level): this writer's compression
                                        (the repository's own is the default)
  repo.read_chunk(id) / read_tree(id)   repo.save_snapshot / load_snapshot / snapshot_ids /
                                        delete_snapshot (refused while immutable)
  repo.check(read_data, progress)       snapshots, signatures, references, every blob
  repo.gc(progress)                     mark & sweep, repack sparse packs
  repo.add_passphrase / set_recovery / set_immutable_days / trust_signer

Signers: snapshots are saved and loaded only with trusted keys -- CreateOptions::signer and
the keys given to trust_signer (save_snapshot: UntrustedSigner, load_snapshot: Corrupt).
The list sits in repo.json under the MAC of the repository key, so it keeps out other keys
and mistakes, not someone who holds the repository key (who could call trust_signer).  A
repo.json without a MAC (taken away) does not open (Corrupt).

Objects: the config "repo" (repo.json), packs, their indexes, snapshots; a Folder keeps them
         as repo.json  data/<xx>/<pack>.pack  index/<pack>.idx  snapshots/<id>.snap  LOCK
Keys:    one random repository key, wrapped in repo.json for the server's master key, for
         passphrases (Argon2id) and for the recovery kit (sealed box); per purpose keys are
         derived from it with BLAKE3 derive_key (chunk ids, data, index, snapshots, gear).
Chunks:  id = BLAKE3-keyed(id key, plain) -> identical data is stored once, the ids reveal
         nothing without the key.  Commit order of a backup: packs -> indexes -> snapshot,
         each put atomic and durable (Store's rule; Folder: synced, renamed, the folder
         synced); a crash leaves at most unreferenced packs, which gc removes.  A listing
         that fails stops gc (it is no empty repository).  Until its snapshot is there a
         backup's chunks are such packs too: gc waits for open writers and for an Unsaved,
         and a snapshot saved the plain way after a gc took chunks of it is refused
         (save_snapshot).

cas crate root#

FORMAT: &str = "bcrepo-1"
  • type ChunkId = [u8; 32]
KIND_DATA: u8 = 0
KIND_TREE: u8 = 1
  • enum CasError

    • Io(String)
    • Corrupt(String) -- damaged or forged data
    • Locked -- none of the unlock methods fits
    • InUse -- another process uses the repository
    • NotARepository
    • NotEmpty
    • Immutable(i64) -- a snapshot that may not be deleted yet
    • NotFound(String)
    • Cancelled
    • TooLarge
    • UntrustedSigner -- save_snapshot with a key the repository does not trust (CreateOptions::signer and the keys of trust_signer are trusted)
  • type CasResult<T> = Result<T, CasError>

  • fn hex_id(id: &ChunkId) -> String

  • fn parse_id(s: &str) -> Option<ChunkId>

  • struct Keys the per-purpose keys of a repository

    • id: [u8; 32]
    • data: [u8; 32]
    • index: [u8; 32]
    • snapshot: [u8; 32]
    • gear: [u8; 32]

impl Keys

  • fn chunk_id(&self, data: &[u8]) -> ChunkId

  • enum Unlock<'a> how to open a repository

    • Master(&'a [u8; 32]) -- the server's repository wrap key
    • Passphrase(&'a str)
    • Recovery(&'a [u8; 32]) -- the recovery kit's X25519 secret
  • struct CreateOptions

    • id: String
    • chunk_avg: usize -- average chunk size (a power of two; 1 MiB)
    • compression: Codec
    • master: [u8; 32] -- the server's wrap key
    • recovery: Option<[u8; 32]>
    • signer: [u8; 32] -- the public key whose snapshots this repository trusts (the only one that may save snapshots until trust_signer adds another)
    • immutable_days: u32
  • struct WriteStats statistics of a writer

    • chunks: u64
    • raw: u64
    • new_chunks: u64
    • new_raw: u64
    • new_stored: u64 -- bytes added to pack files
  • struct CheckReport

    • snapshots: u64
    • bad_snapshots: Vec<String>
    • chunks_referenced: u64
    • missing: u64
    • damaged: u64
    • packs: u64
    • orphan_packs: u64 -- packs without an index (left by an interrupted write)
    • bytes_read: u64

impl CheckReport

  • fn ok(&self) -> bool

  • struct GcReport

    • packs_deleted: u64
    • packs_repacked: u64
    • bytes_freed: u64
    • chunks_removed: u64
  • type Progress<'a> = &'a mut dyn FnMut(u64, u64) -> bool progress: (done, total) -> false to cancel

  • struct Repo

impl Repo

  • fn create(path: &str, o: &CreateOptions) -> CasResult<Repo> create a repository in an empty (or new) folder

  • fn create_in(store: impl Store + 'static, o: &CreateOptions) -> CasResult<Repo> create a repository in a store that holds nothing yet (NotEmpty)

  • fn open(path: &str, unlock: Unlock) -> CasResult<Repo> open the repository in a folder

  • fn open_in(store: impl Store + 'static, unlock: Unlock) -> CasResult<Repo> open the repository in a store

  • fn path(&self) -> &str where the repository is: its folder (Repo::open), else the store's location

  • fn store(&self) -> &dyn Store the store the repository lives in

  • fn id(&self) -> String

  • fn immutable_days(&self) -> u32

  • fn chunker(&self) -> &Chunker

  • fn keys(&self) -> &Keys

  • fn chunk_count(&self) -> usize chunks in the index

  • fn has_chunk(&self, id: &ChunkId) -> bool

  • fn stored_bytes(&self) -> u64 bytes of all pack files (0 when the store cannot list them)

  • fn add_passphrase(&self, pass: &str, label: &str, repo_key_from: Unlock) -> CasResult<()> let a passphrase open the repository (Argon2id, 64 MiB)

  • fn has_passphrase(&self, label: &str) -> bool whether a passphrase with this label opens the repository

  • fn set_recovery(&self, pk: &[u8; 32], repo_key_from: Unlock) -> CasResult<()> seal the repository key for a (new) recovery kit

  • fn set_immutable_days(&self, days: u32) -> CasResult<()> raise the immutability (never lowers it)

  • fn trust_signer(&self, pk: &[u8; 32]) -> CasResult<()> trust snapshots signed by another key too (a restored server with a new key): only trusted keys may save snapshots, and load_snapshot refuses the others. The list is protected by the repository key: whoever opens the repository can call this, so the check keeps out other keys and mistakes, not a holder of the repository key.

  • fn writer(&self) -> Writer<'_> a writer for new chunks (backups run several at once; gc waits for them)

  • fn read_chunk(&self, id: &ChunkId) -> CasResult<Vec<u8>> the plain content of a chunk

  • fn read_tree(&self, id: &ChunkId) -> CasResult<Tree>

  • fn save_snapshot(&self, snap: &Snapshot, signer: &ed25519::Keypair) -> CasResult<()> store a snapshot (after its writer finished); signed by signer, a key the repository trusts (CreateOptions::signer or one given to trust_signer), else UntrustedSigner.

    Between the writer's finish and this call the new chunks belong to no snapshot, and a gc of another thread -- one that waited for the writer runs at that very moment -- removes them. Where a gc can run beside the backup, finish the writer with finish_unsaved and save through the Unsaved it returns: gc waits for it. This call cannot keep a gc out afterwards; it refuses the snapshot instead (NotFound) when chunks of it are gone -- looked up once a gc of this process has removed anything. It waits for a running gc: not to be called while the same thread holds a Writer or an Unsaved.

  • fn snapshot_ids(&self) -> Vec<String> the ids of the snapshots, sorted (none when the store cannot list them)

  • fn load_snapshot(&self, id: &str) -> CasResult<Snapshot> a snapshot, checked (signature by a trusted key, authentic encryption)

  • fn delete_snapshot(&self, id: &str, now: i64) -> CasResult<()> delete a snapshot (its chunks go with the next gc) -- refused while it is immutable

  • fn referenced(&self, snap: &Snapshot, out: &mut BTreeSet<ChunkId>) -> CasResult<()> every chunk a snapshot references (trees and data)

  • fn check(&self, read_data: bool, progress: Progress) -> CasResult<CheckReport> check the repository: every snapshot opens and verifies, every referenced chunk is indexed; with read_data every blob is read, decrypted and compared with its id

  • fn gc(&self, progress: Progress) -> CasResult<GcReport> remove what no snapshot references: empty packs are deleted, sparse packs (less than 60 % in use) are rewritten with their live blobs. Waits for open writers and for what finish_unsaved left of them. Lost index files are rebuilt from the packs' trailers first (repair_index). Refused (Corrupt), nothing removed, while a snapshot does not open, or while a chunk it references is not in the index and a pack without an index (and without a readable trailer) is left: the chunk may be in that pack

  • fn repair_index(&self) -> CasResult<u64> rebuild missing index files from the packs' trailers

  • fn peek_id(path: &str) -> CasResult<String> the id of a repository folder without opening it

  • fn peek_id_in(store: &dyn Store) -> CasResult<String> the id of the repository in a store without opening it

  • struct Writer<'a> writes new chunks into packs

    • stats: WriteStats

impl<'a> Writer<'a>

  • fn codec(mut self, codec: Codec, level: i32) -> Self compress this writer's data chunks with codec (level: zstd's level); trees stay LZ4

  • fn put(&mut self, kind: u8, data: &[u8]) -> CasResult<ChunkId> store a chunk (once) -> its id

  • fn put_stream(&mut self, read: &mut dyn FnMut(&mut [u8]) -> Result<usize, String>, cancel: &dyn Fn() -> bool) -> CasResult<(Vec<ChunkId>, u64)> chunk a stream and store it -> (chunk ids, size); read fills the buffer, Ok(0) = end

  • fn put_tree(&mut self, t: &Tree) -> CasResult<ChunkId>

  • fn finish(mut self) -> CasResult<WriteStats> write the last pack; every chunk put so far is durable afterwards. gc may run from here on, and it removes chunks no snapshot holds: a backup whose snapshot follows uses finish_unsaved where a gc of another thread is possible (Repo::save_snapshot)

  • fn finish_unsaved(mut self) -> CasResult<(WriteStats, Unsaved<'a>)> finish, and gc stays out until the snapshot of these chunks is saved through the returned Unsaved (or that is dropped: a backup given up)

  • struct Unsaved<'a> what a writer finished with finish_unsaved leaves: its chunks -- new ones and those it found stored already -- before a snapshot holds them. gc waits while this lives, so the thread that holds it starts no gc, check or further writer before it is saved or dropped.

impl Unsaved<'_>

  • fn save_snapshot(self, snap: &Snapshot, signer: &ed25519::Keypair) -> CasResult<()> store the snapshot of these chunks (signed by signer, a trusted key, else UntrustedSigner); gc may run again afterwards

cas/chunker.rs#

Source: lib/cas/chunker.rs

chunker -- content-defined chunking (FastCDC with normalized chunking, level 2)

Boundaries depend on the content only, so an insertion early in a file moves one boundary
and leaves the later chunks (and their deduplication) intact.  The gear table is derived
from the repository key: chunk sizes do not reveal known files to someone who sees the
repository without its key.
  • struct Chunker
    • min: usize
    • avg: usize
    • max: usize

impl Chunker

  • fn new(gear_key: &[u8; 32], avg: usize) -> Chunker avg must be a power of two; min = avg / 4, max = avg * 4
  • fn cut(&self, data: &[u8], last: bool) -> Option<usize> the length of the first chunk of data (last: no more data follows)
  • fn split(&self, data: &[u8]) -> Vec<usize> split a whole buffer into chunk lengths

cas/pack.rs#

Source: lib/cas/pack.rs

pack -- blobs, pack files and their indexes

  blob     kind:u8 codec:u8 | nonce:24 | XChaCha20-Poly1305(data key, nonce,
           aad = chunk id ‖ kind ‖ codec, payload)       payload: plain, an LZ4 block or a
                                                         zstd frame (the codec byte says which)
  pack     "BCK1" | blobs ... | sealed index (as below) | len:u32 | "BCKI"
           (the trailer repeats the index: a lost index file can be rebuilt from the pack)
  index    "BCI1" | nonce:24 | XChaCha20-Poly1305(index key, aad = pack id, JSON
           [[id hex, offset, length, kind, raw length], ...])

Pack files are written to a temporary name, synced, renamed; then their index.  A crash
leaves at most a pack without an index (garbage that check reports and gc removes).
PACK_MAGIC: &[u8; 4] = b"BCK1"
PACK_TRAILER: &[u8; 4] = b"BCKI"
INDEX_MAGIC: &[u8; 4] = b"BCI1"
/// a pack is closed when it reaches this size
PACK_TARGET: usize = 32 << 20
BLOB_OVERHEAD: usize = 2 + 24 + 16
  • type PackId = [u8; 16]

  • struct Loc where a chunk lives

    • pack: PackId
    • off: u32
    • len: u32
    • kind: u8
    • raw: u32 -- the plain length
  • fn seal_blob(keys: &Keys, id: &ChunkId, kind: u8, data: &[u8], codec: Codec, level: i32) -> Vec<u8> seal one chunk into a blob (compressed with codec when that saves something; level: zstd's level)

  • fn open_blob(keys: &Keys, id: &ChunkId, blob: &[u8], raw_len: usize) -> Result<Vec<u8>, CasError> open a blob: the plain chunk (checked against its id)

  • fn seal_index(keys: &Keys, pack: &PackId, entries: &[(ChunkId, Loc)]) -> Vec<u8> an index (entries of one pack) as sealed bytes

  • fn open_index(keys: &Keys, pack: &PackId, b: &[u8]) -> Result<Vec<(ChunkId, Loc)>, CasError> the entries of a sealed index

  • fn trailer_index(keys: &Keys, pack: &PackId, b: &[u8]) -> Result<Vec<(ChunkId, Loc)>, CasError> the index stored in a pack's trailer

  • struct PackBuf a pack being filled

    • id: PackId
    • data: Vec<u8>
    • entries: Vec<(ChunkId, Loc)>

impl PackBuf

  • fn new() -> PackBuf

  • fn push(&mut self, id: ChunkId, kind: u8, raw: usize, blob: &[u8]) -> Loc

  • fn fits(&self, blob_len: usize, raw: usize) -> bool whether a blob of blob_len bytes (raw unpacked) still has u32 offsets and lengths

  • fn is_empty(&self) -> bool

  • fn finish(&mut self, keys: &Keys) -> Vec<u8> the complete pack file (with its trailer)

  • fn pack_hex(p: &PackId) -> String

  • fn parse_pack(s: &str) -> Option<PackId>

cas/snapshot.rs#

Source: lib/cas/snapshot.rs

snapshot -- what a restore point holds: a tree of nodes per backed-up root, stored as
chunks (an unchanged directory produces the same tree chunk and is stored once), and the
snapshot record that names the roots, signed with Ed25519 and encrypted

  snapshot file  "BCN1" | nonce:24 | XChaCha20-Poly1305(snapshot key, aad = snapshot id,
                 signature:64 ‖ signer public key:32 ‖ JSON of the Snapshot)
SNAP_MAGIC: &[u8; 4] = b"BCN1"
  • enum NodeKind
    • File
    • Dir
    • Symlink
    • Other

impl NodeKind

  • fn as_str(&self) -> &'static str

  • fn parse(s: &str) -> NodeKind

  • struct Node one entry of a directory (or a root)

    • name: String
    • kind: NodeKind
    • size: u64
    • mtime_ns: i64
    • atime_ns: i64
    • ctime_ns: i64
    • mode: u32
    • uid: u32
    • gid: u32
    • attrs: u32
    • ino: u64
    • dev: u64
    • link: String -- symbolic links: the target as stored in the link
    • chunks: Vec<ChunkId> -- files: the content chunks in order
    • tree: Option<ChunkId> -- directories: the tree chunk of their entries
    • error: String -- a message when the entry could not be read completely (locked file, permission)
    • count: u64 -- directories: the files below (with size = their bytes); 0 in older snapshots

impl Node

  • fn to_json(&self) -> Value

  • fn from_json(v: &Value) -> Option<Node>

  • struct Tree the entries of a directory, sorted by name

    • nodes: Vec<Node>

impl Tree

  • fn encode(&self) -> Vec<u8>

  • fn decode(b: &[u8]) -> Option<Tree>

  • fn find(&self, name: &str) -> Option<&Node>

  • struct SnapStats totals of a snapshot

    • files: u64
    • dirs: u64
    • bytes: u64 -- the plain size of all files
    • new_bytes: u64 -- stored bytes added by this snapshot (after dedupe, compression, encryption)
    • new_chunks: u64
    • new_raw: u64 -- plain bytes of the new chunks
    • errors: u64 -- files that could not be read (completely)
  • struct Snapshot a restore point

    • id: String
    • created: i64
    • job_id: String
    • job_name: String
    • host: String
    • roots: Vec<Node> -- one node per backed-up source; its name is the full source path
    • parent: String
    • full: bool
    • stats: SnapStats
    • immutable_until: i64 -- not deletable before this time (seconds)
    • meta: Value -- the caller's extra data (session id, ...)

impl Snapshot

  • fn to_json(&self) -> Value

  • fn from_json(v: &Value) -> Option<Snapshot>

  • fn seal(key: &[u8; 32], signer: &crypto::ed25519::Keypair, snap: &Snapshot) -> Result<Vec<u8>, CasError> seal a snapshot (signed by signer)

  • fn open(key: &[u8; 32], id: &str, b: &[u8]) -> Result<(Snapshot, [u8; 32]), CasError> open a snapshot file: the snapshot and its signer (the signature is checked; whether the signer is trusted is the caller's decision)

cas/store.rs#

Source: lib/cas/store.rs

store -- where a repository keeps its objects: the Store trait and Folder, a folder of the
file system (plat::fs, so also a vfs mount such as mem://)

  Store                 init, lock, get, get_range, put, delete, list, location: objects by
                        kind and name, the way S3, SFTP or WebDAV keep them
  Kind                  Config ("repo"), Pack, Index, Snapshot
  Folder::new(path)     repo.json  data/<xx>/<pack>.pack  index/<pack>.idx
                        snapshots/<id>.snap  LOCK

What the repository asks of a store (Repo::create_in / open_in):
  - put is atomic and durable: once it returns Ok, get and list see the whole object, also
    after a crash, and a put that failed leaves the old object or none (the commit order of a
    backup -- packs, indexes, snapshot -- rests on it)
  - a delete that returned Ok stays done; deleting what is not there is Ok
  - get and list see every put that returned before them (read after write)
  - lock keeps a second holder out, also one of another process or host, until the guard
    is dropped
Nothing that comes back from a store is trusted: packs, indexes and snapshots are sealed and
repo.json carries a MAC, so a store that changes, swaps or replays objects is found out (a
rollback to older objects of the same repository is not); names and sizes of a listing are
checked before use.  A store sees the names, the sizes and when objects come and go: pack
and index names are random, snapshot names are the ids given to save_snapshot.
  • enum Kind what an object of a repository is

    • Config -- the repository's settings and wrapped keys; the repository uses one, named "repo"
    • Pack -- a pack of sealed chunks (written once, read in ranges, deleted by gc)
    • Index -- the sealed index of the pack of the same name
    • Snapshot -- a sealed and signed snapshot, named by its id
  • type StoreLock = Box<dyn Any + Send + Sync> what [Store::lock] hands out: the repository is held until it is dropped

  • trait Store: Send + Sync Where a repository keeps its objects. A name is not empty and has none of '/', '\\', '.', ':' (pack and index names are hex, snapshot names the ids given to save_snapshot). The rules a store keeps are those in the header of this module: put atomic and durable, read after write, a lock that keeps every other holder out.

    • fn location(&self) -> String where it is, for messages and Repo::path ("D:/Backups/repo", "s3://bucket/prefix")
    • fn init(&self) -> CasResult<()> make the place of a new repository: NotEmpty when it already holds anything
    • fn lock(&self) -> CasResult<StoreLock> hold the repository (InUse while another holder has it)
    • fn get(&self, kind: Kind, name: &str) -> CasResult<Option<Vec<u8>>> the whole object; Ok(None) when there is none
    • fn get_range(&self, kind: Kind, name: &str, off: u64, len: usize) -> CasResult<Vec<u8>> len bytes from off on, fewer only where the object ends (NotFound when there is none). The default reads the whole object: a store with ranged reads does better
    • fn put(&self, kind: Kind, name: &str, data: &[u8]) -> CasResult<()> store an object (replacing one of the same name), atomic and durable
    • fn delete(&self, kind: Kind, name: &str) -> CasResult<()> remove an object; one that is not there is fine
    • fn list(&self, kind: Kind) -> CasResult<Vec<(String, u64)>> the names and sizes of the objects of a kind, in any order
  • fn name_ok(name: &str) -> bool whether a store may be asked for this name (Store's rule)

  • struct Folder A repository in a folder of the file system: repo.json, data/<xx>/<pack>.pack (the first two hex digits), index/<pack>.idx, snapshots/<id>.snap and LOCK (plat::FileLock: one holder at a time on this machine). Files and folders are the owner's only (write_file_private, mkdir_private); a write goes to a temporary sibling that is synced and renamed into place. The path can be a vfs name too (mem://, a mount). Listings and removals go through open folders (plat::fs::Dir): the repository's folder is taken as it is, a folder below it that is a link (data, a pack folder, index, snapshots) is refused, so gc never removes another repository's packs through it.

impl Folder

  • fn new(path: &str) -> Folder
  • fn path(&self) -> &str

Source: docs/API.md in the JFLib repository.