s365b.storage

Backup repository: content-addressed, compressed, encrypted storage.

The repository holds backup content. Which item a blob belongs to, and when, is recorded in the catalog (PostgreSQL). See the “Backup storage” planning page for the format rationale.

Typical use:

backend = FilesystemBackend(Path("/repo"))
repo = await Repository.init(backend, passphrase)   # once
repo = await Repository.open(backend, passphrase)   # afterwards
ref = await repo.put_content(stream)
await repo.flush()
async for chunk in repo.get_content(ref):
    ...

Submodules

Exceptions

RepositoryError

Raised for repository-level problems (missing, corrupt, wrong passphrase).

Classes

FilesystemBackend

Stores objects as files under a root directory.

StorageBackend

Interface every storage backend implements.

ContentRef

Reference to a piece of content stored in the repository.

Repository

An open backup repository.

Package Contents

class s365b.storage.FilesystemBackend(root: pathlib.Path)[source]

Bases: StorageBackend

Stores objects as files under a root directory.

Works for local disks and for NFS/SMB shares mounted into the container. Writes go to a temporary file that is fsynced and then renamed into place, so a crash never leaves a half-written object under its final name.

Parameters:

root – Directory holding the repository. Created if missing.

root
async put(key: str, data: bytes, *, overwrite: bool = False) → None[source]

Store an object atomically (see StorageBackend.put()).

async get(key: str) → bytes[source]

Read a whole object (see StorageBackend.get()).

async get_range(key: str, offset: int, length: int) → bytes[source]

Read part of an object (see StorageBackend.get_range()).

async exists(key: str) → bool[source]

Return whether an object exists (see StorageBackend.exists()).

async list(prefix: str) → collections.abc.AsyncIterator[str][source]

Yield keys under a prefix (see StorageBackend.list()).

async delete(key: str) → None[source]

Delete an object (see StorageBackend.delete()).

class s365b.storage.StorageBackend[source]

Bases: abc.ABC

Interface every storage backend implements.

Objects are write-once: the repository never modifies an object in place, which is what makes object-lock immutability possible on S3.

abstractmethod put(key: str, data: bytes, *, overwrite: bool = False) → None[source]
Async:

Store an object atomically.

Parameters:
  • key – Object key.

  • data – Object content.

  • overwrite – Allow replacing an existing object. Only used for the repository config during key changes.

Raises:

BackendError – If the object exists and overwrite is false.

abstractmethod get(key: str) → bytes[source]
Async:

Read a whole object.

Parameters:

key – Object key.

Returns:

The object content.

Raises:

ObjectNotFoundError – If the key does not exist.

abstractmethod get_range(key: str, offset: int, length: int) → bytes[source]
Async:

Read part of an object.

Parameters:
  • key – Object key.

  • offset – First byte to read.

  • length – Number of bytes to read.

Returns:

Exactly length bytes.

Raises:
abstractmethod exists(key: str) → bool[source]
Async:

Return whether an object exists.

Parameters:

key – Object key.

Returns:

True if the object exists.

abstractmethod list(prefix: str) → collections.abc.AsyncIterator[str][source]

Yield keys under a prefix (a directory such as index).

Parameters:

prefix – Key prefix without trailing slash.

Returns:

An async iterator of full keys, in no particular order.

abstractmethod delete(key: str) → None[source]
Async:

Delete an object. Deleting a missing object is not an error.

Parameters:

key – Object key.

class s365b.storage.ContentRef[source]

Reference to a piece of content stored in the repository.

This is what the catalog saves for each item version.

Variables:
  • blobs – Blob IDs in order; concatenated they form the content.

  • size – Total plaintext size in bytes.

blobs: tuple[str, ...]
size: int
to_json() → dict[str, Any][source]

Serialise for storage in the catalog.

Returns:

A JSON-compatible dict.

classmethod from_json(data: dict[str, Any]) → ContentRef[source]

Load from to_json() output.

Parameters:

data – The stored dict.

Returns:

The reference.

class s365b.storage.Repository(backend: s365b.storage.backends.StorageBackend, keys: s365b.storage.crypto.RepoKeys, config: dict[str, Any])[source]

An open backup repository.

Create one with init() (new repository) or open(). A repository object is safe to share between tasks in one process; writes from several processes are safe too, at worst storing a blob twice.

Parameters:
  • backend – Where the files live.

  • keys – Unwrapped repository keys.

  • config – Parsed config file.

backend
config
repo_id: str
chunk_size: int
pack_size: int
classmethod init(backend: s365b.storage.backends.StorageBackend, passphrase: str, *, chunk_size: int = DEFAULT_CHUNK_SIZE, pack_size: int = DEFAULT_PACK_SIZE, kdf: s365b.storage.crypto.KdfParams | None = None) → Repository[source]
Async:

Create a new, empty repository.

Parameters:
  • backend – Empty storage location.

  • passphrase – Passphrase protecting the repository key. Losing it means losing access to every backup in the repository.

  • chunk_size – Maximum chunk size in bytes.

  • pack_size – Target pack file size in bytes.

  • kdf – Argon2id parameters (defaults are used if omitted; tests pass cheaper ones).

Returns:

The open repository.

Raises:

RepositoryError – If a repository already exists there.

classmethod open(backend: s365b.storage.backends.StorageBackend, passphrase: str) → Repository[source]
Async:

Open an existing repository and load its index.

Parameters:
  • backend – Storage location.

  • passphrase – Repository passphrase.

Returns:

The open repository.

Raises:

RepositoryError – If there is no repository, the format is unsupported, or the passphrase is wrong.

async reload_index() → None[source]

Re-read all index files, picking up blobs written by other processes.

async put_blob(data: bytes) → str[source]

Store one blob (deduplicated).

Parameters:

data – Plaintext, at most chunk_size bytes.

Returns:

The blob ID.

async put_content(source: bytes | collections.abc.Iterable[bytes] | collections.abc.AsyncIterable[bytes]) → ContentRef[source]

Store content of any size, splitting it into chunks.

Parameters:

source – The whole content, or an (async) iterable of byte pieces of any size, e.g. a streamed HTTP download.

Returns:

Reference to save in the catalog.

async flush() → None[source]

Write buffered blobs as a pack and index file.

Call this at the end of every job; content is not durable until it has been flushed.

async read_generation() → int[source]

Return the catalog generation recorded in the repository (0 if none).

Every catalog commit raises the generation in the catalog database and then writes it here, so the repository’s number is never ahead of the database that wrote to it. When it is, the database is older than the repository (a fresh install, or a restored dump) and does not know all of its data: space must not be reclaimed (see s365b.core.generation).

Returns:

The highest generation written.

async write_generation(generation: int) → None[source]

Record a catalog generation in the repository.

Each number is a file of its own, and lower ones are removed after: writers finishing out of order cannot lower the highest.

Parameters:

generation – The catalog’s new generation.

async compact(live: set[str], *, min_garbage: float = 0.2) → CompactStats[source]

Delete blobs nothing refers to, reclaiming their space.

Packs holding only unreferenced blobs are deleted. Packs where at least min_garbage of the bytes are unreferenced are rewritten with only the referenced blobs (copied sealed, never decrypted). New packs are written before old ones are deleted, so a crash leaves duplicates, never gaps.

The caller must make sure nothing writes to the repository while this runs (a backup could otherwise reuse a blob being deleted).

Parameters:
  • live – IDs of every blob the catalog still refers to.

  • min_garbage – Share of unreferenced bytes at which a pack is rewritten.

Returns:

What was done.

async remove_blobs(blob_ids: set[str]) → CompactStats[source]

Delete these blobs and nothing else.

Packs holding them are rewritten without them. Blobs the catalog may not know about are kept, unlike compact() with a live set.

Parameters:

blob_ids – The blobs to delete.

Returns:

What was done.

has_blob(blob_id: str) → bool[source]

Return whether a blob is stored or buffered.

Parameters:

blob_id – Blob ID.

Returns:

True if present.

async get_blob(blob_id: str) → bytes[source]

Read and verify one blob.

Parameters:

blob_id – Blob ID.

Returns:

The plaintext.

Raises:

RepositoryError – If the blob is missing, corrupt or tampered with.

async get_content(ref: ContentRef) → collections.abc.AsyncIterator[bytes][source]

Stream stored content chunk by chunk.

Parameters:

ref – Reference from put_content().

Yields:

Plaintext chunks in order.

async check(*, read_data: bool = False) → list[str][source]

Verify the repository.

Parameters:

read_data – Also read and verify every blob (slow). Otherwise only checks that every indexed pack exists.

Returns:

A list of problems; empty if the repository is healthy.

async unreadable_blobs() → set[str][source]

Read every blob; return the IDs of those that fail verification.

Returns:

IDs of missing, corrupt or tampered blobs.

stats() → RepositoryStats[source]

Return statistics about flushed data.

Returns:

Repository statistics.

exception s365b.storage.RepositoryError[source]

Bases: Exception

Raised for repository-level problems (missing, corrupt, wrong passphrase).