s365b.storage.repository ======================== .. py:module:: s365b.storage.repository .. autoapi-nested-parse:: The backup repository format. Layout on the backend:: config plaintext JSON: format version, repo ID, KDF parameters, wrapped repository key packs// encrypted blobs, concatenated index/ encrypted JSON: which blobs are in which pack How content is stored: 1. Content is split into chunks of at most ``chunk_size`` bytes (fixed-size chunking; the format allows switching to content-defined chunking later because chunks are addressed by hash, not position). 2. Each chunk's ID is ``BLAKE3(id_key, plaintext)``. A chunk whose ID is already in the index is not stored again (deduplication). 3. New chunks are zstd-compressed (kept raw if compression does not help), encrypted with AES-256-GCM using the blob ID as associated data, and buffered. 4. When the buffer reaches ``pack_size`` (or on :meth:`Repository.flush`), it is written as one pack file plus one index file. Blob on-disk format: ``nonce(12) || AESGCM(flag(1) || payload)`` where the flag is ``0`` for raw and ``1`` for zstd. Every index file is self-contained, so the full index is the union of all index files and can always be rebuilt by listing ``index/``. Attributes ---------- .. autoapisummary:: s365b.storage.repository.FORMAT_VERSION s365b.storage.repository.DEFAULT_CHUNK_SIZE s365b.storage.repository.DEFAULT_PACK_SIZE s365b.storage.repository.GENERATION_KEY s365b.storage.repository.GENERATIONS Exceptions ---------- .. autoapisummary:: s365b.storage.repository.RepositoryError Classes ------- .. autoapisummary:: s365b.storage.repository.BlobLocation s365b.storage.repository.ContentRef s365b.storage.repository.CompactStats s365b.storage.repository.RepositoryStats s365b.storage.repository.Repository Functions --------- .. autoapisummary:: s365b.storage.repository.content_blobs s365b.storage.repository.extra_ref Module Contents --------------- .. py:data:: FORMAT_VERSION :value: 1 .. py:data:: DEFAULT_CHUNK_SIZE :value: 4194304 .. py:data:: DEFAULT_PACK_SIZE :value: 16777216 .. py:exception:: RepositoryError Bases: :py:obj:`Exception` Raised for repository-level problems (missing, corrupt, wrong passphrase). .. py:class:: BlobLocation Where a blob lives inside a pack. :ivar pack: Pack key. :ivar offset: Byte offset in the pack. :ivar length: Stored (encrypted) length. :ivar raw_length: Plaintext length. .. py:attribute:: pack :type: str .. py:attribute:: offset :type: int .. py:attribute:: length :type: int .. py:attribute:: raw_length :type: int .. py:class:: ContentRef Reference to a piece of content stored in the repository. This is what the catalog saves for each item version. :ivar blobs: Blob IDs in order; concatenated they form the content. :ivar size: Total plaintext size in bytes. .. py:attribute:: blobs :type: tuple[str, ...] .. py:attribute:: size :type: int .. py:method:: to_json() -> dict[str, Any] Serialise for storage in the catalog. :returns: A JSON-compatible dict. .. py:method:: from_json(data: dict[str, Any]) -> ContentRef :classmethod: Load from :meth:`to_json` output. :param data: The stored dict. :returns: The reference. .. py:function:: content_blobs(content: dict[str, Any] | None) -> list[str] Every blob a catalog content entry uses, its extra copies included. :param content: An item version's stored content (``ContentRef`` JSON, with an optional ``"extra"`` map of named ``ContentRef`` JSON). :returns: Blob IDs. .. py:function:: extra_ref(content: dict[str, Any] | None, name: str) -> ContentRef | None Return a named extra copy of an item version's content, if stored. :param content: An item version's stored content. :param name: Copy name, e.g. ``"fts"``. :returns: Its reference, or ``None``. .. py:class:: CompactStats Outcome of :meth:`Repository.compact`. :ivar packs_deleted: Packs that held only unreferenced blobs. :ivar packs_rewritten: Packs rewritten without their unreferenced blobs. :ivar blobs_deleted: Unreferenced blobs removed. :ivar bytes_freed: Stored (compressed, encrypted) bytes removed. .. py:attribute:: packs_deleted :type: int :value: 0 .. py:attribute:: packs_rewritten :type: int :value: 0 .. py:attribute:: blobs_deleted :type: int :value: 0 .. py:attribute:: bytes_freed :type: int :value: 0 .. py:class:: RepositoryStats Basic repository statistics. :ivar blobs: Number of unique blobs. :ivar packs: Number of pack files. :ivar stored_bytes: Bytes stored (compressed and encrypted). :ivar raw_bytes: Plaintext bytes of unique blobs. .. py:attribute:: blobs :type: int .. py:attribute:: packs :type: int .. py:attribute:: stored_bytes :type: int .. py:attribute:: raw_bytes :type: int .. py:data:: GENERATION_KEY :value: 'catalog-generation' .. py:data:: GENERATIONS :value: 'generation' .. py:class:: Repository(backend: s365b.storage.backends.StorageBackend, keys: s365b.storage.crypto.RepoKeys, config: dict[str, Any]) An open backup repository. Create one with :meth:`init` (new repository) or :meth:`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. :param backend: Where the files live. :param keys: Unwrapped repository keys. :param config: Parsed config file. .. py:attribute:: backend .. py:attribute:: config .. py:attribute:: repo_id :type: str .. py:attribute:: chunk_size :type: int .. py:attribute:: pack_size :type: int .. py:method:: 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 :classmethod: :async: Create a new, empty repository. :param backend: Empty storage location. :param passphrase: Passphrase protecting the repository key. Losing it means losing access to every backup in the repository. :param chunk_size: Maximum chunk size in bytes. :param pack_size: Target pack file size in bytes. :param kdf: Argon2id parameters (defaults are used if omitted; tests pass cheaper ones). :returns: The open repository. :raises RepositoryError: If a repository already exists there. .. py:method:: open(backend: s365b.storage.backends.StorageBackend, passphrase: str) -> Repository :classmethod: :async: Open an existing repository and load its index. :param backend: Storage location. :param passphrase: Repository passphrase. :returns: The open repository. :raises RepositoryError: If there is no repository, the format is unsupported, or the passphrase is wrong. .. py:method:: reload_index() -> None :async: Re-read all index files, picking up blobs written by other processes. .. py:method:: put_blob(data: bytes) -> str :async: Store one blob (deduplicated). :param data: Plaintext, at most ``chunk_size`` bytes. :returns: The blob ID. .. py:method:: put_content(source: bytes | collections.abc.Iterable[bytes] | collections.abc.AsyncIterable[bytes]) -> ContentRef :async: Store content of any size, splitting it into chunks. :param 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. .. py:method:: flush() -> None :async: 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. .. py:method:: read_generation() -> int :async: 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 :mod:`s365b.core.generation`). :returns: The highest generation written. .. py:method:: write_generation(generation: int) -> None :async: 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. :param generation: The catalog's new generation. .. py:method:: compact(live: set[str], *, min_garbage: float = 0.2) -> CompactStats :async: 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). :param live: IDs of every blob the catalog still refers to. :param min_garbage: Share of unreferenced bytes at which a pack is rewritten. :returns: What was done. .. py:method:: remove_blobs(blob_ids: set[str]) -> CompactStats :async: Delete these blobs and nothing else. Packs holding them are rewritten without them. Blobs the catalog may not know about are kept, unlike :meth:`compact` with a live set. :param blob_ids: The blobs to delete. :returns: What was done. .. py:method:: has_blob(blob_id: str) -> bool Return whether a blob is stored or buffered. :param blob_id: Blob ID. :returns: True if present. .. py:method:: get_blob(blob_id: str) -> bytes :async: Read and verify one blob. :param blob_id: Blob ID. :returns: The plaintext. :raises RepositoryError: If the blob is missing, corrupt or tampered with. .. py:method:: get_content(ref: ContentRef) -> collections.abc.AsyncIterator[bytes] :async: Stream stored content chunk by chunk. :param ref: Reference from :meth:`put_content`. :Yields: Plaintext chunks in order. .. py:method:: check(*, read_data: bool = False) -> list[str] :async: Verify the repository. :param 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. .. py:method:: unreadable_blobs() -> set[str] :async: Read every blob; return the IDs of those that fail verification. :returns: IDs of missing, corrupt or tampered blobs. .. py:method:: stats() -> RepositoryStats Return statistics about flushed data. :returns: Repository statistics.