s365b.storage ============= .. py:module:: s365b.storage .. autoapi-nested-parse:: 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 ---------- .. toctree:: :maxdepth: 1 /reference/api/s365b/storage/backends/index /reference/api/s365b/storage/crypto/index /reference/api/s365b/storage/repository/index Exceptions ---------- .. autoapisummary:: s365b.storage.RepositoryError Classes ------- .. autoapisummary:: s365b.storage.FilesystemBackend s365b.storage.StorageBackend s365b.storage.ContentRef s365b.storage.Repository Package Contents ---------------- .. py:class:: FilesystemBackend(root: pathlib.Path) Bases: :py:obj:`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. :param root: Directory holding the repository. Created if missing. .. py:attribute:: root .. py:method:: put(key: str, data: bytes, *, overwrite: bool = False) -> None :async: Store an object atomically (see :meth:`StorageBackend.put`). .. py:method:: get(key: str) -> bytes :async: Read a whole object (see :meth:`StorageBackend.get`). .. py:method:: get_range(key: str, offset: int, length: int) -> bytes :async: Read part of an object (see :meth:`StorageBackend.get_range`). .. py:method:: exists(key: str) -> bool :async: Return whether an object exists (see :meth:`StorageBackend.exists`). .. py:method:: list(prefix: str) -> collections.abc.AsyncIterator[str] :async: Yield keys under a prefix (see :meth:`StorageBackend.list`). .. py:method:: delete(key: str) -> None :async: Delete an object (see :meth:`StorageBackend.delete`). .. py:class:: StorageBackend Bases: :py:obj:`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. .. py:method:: put(key: str, data: bytes, *, overwrite: bool = False) -> None :abstractmethod: :async: Store an object atomically. :param key: Object key. :param data: Object content. :param 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. .. py:method:: get(key: str) -> bytes :abstractmethod: :async: Read a whole object. :param key: Object key. :returns: The object content. :raises ObjectNotFoundError: If the key does not exist. .. py:method:: get_range(key: str, offset: int, length: int) -> bytes :abstractmethod: :async: Read part of an object. :param key: Object key. :param offset: First byte to read. :param length: Number of bytes to read. :returns: Exactly ``length`` bytes. :raises ObjectNotFoundError: If the key does not exist. :raises BackendError: If the object is shorter than requested. .. py:method:: exists(key: str) -> bool :abstractmethod: :async: Return whether an object exists. :param key: Object key. :returns: True if the object exists. .. py:method:: list(prefix: str) -> collections.abc.AsyncIterator[str] :abstractmethod: Yield keys under a prefix (a directory such as ``index``). :param prefix: Key prefix without trailing slash. :returns: An async iterator of full keys, in no particular order. .. py:method:: delete(key: str) -> None :abstractmethod: :async: Delete an object. Deleting a missing object is not an error. :param key: Object key. .. 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: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. .. py:exception:: RepositoryError Bases: :py:obj:`Exception` Raised for repository-level problems (missing, corrupt, wrong passphrase).