Source code for s365b.storage.repository

"""The backup repository format.

Layout on the backend::

    config                  plaintext JSON: format version, repo ID, KDF
                            parameters, wrapped repository key
    packs/<aa>/<pack-id>    encrypted blobs, concatenated
    index/<index-id>        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/``.
"""

from __future__ import annotations

import asyncio
import contextlib
import json
import secrets
import threading
from collections.abc import AsyncIterable, AsyncIterator, Iterable
from dataclasses import dataclass, field
from typing import Any

import zstandard

from s365b.storage.backends import BackendError, ObjectNotFoundError, StorageBackend
from s365b.storage.crypto import CryptoError, KdfParams, RepoKeys

[docs] FORMAT_VERSION = 1
[docs] DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024
[docs] DEFAULT_PACK_SIZE = 16 * 1024 * 1024
_RAW, _ZSTD = 0, 1
[docs] class RepositoryError(Exception): """Raised for repository-level problems (missing, corrupt, wrong passphrase)."""
@dataclass(frozen=True, slots=True)
[docs] class BlobLocation: """Where a blob lives inside a pack. Attributes: pack: Pack key. offset: Byte offset in the pack. length: Stored (encrypted) length. raw_length: Plaintext length. """
[docs] pack: str
[docs] offset: int
[docs] length: int
[docs] raw_length: int
@dataclass(frozen=True, slots=True)
[docs] class ContentRef: """Reference to a piece of content stored in the repository. This is what the catalog saves for each item version. Attributes: blobs: Blob IDs in order; concatenated they form the content. size: Total plaintext size in bytes. """
[docs] blobs: tuple[str, ...]
[docs] size: int
[docs] def to_json(self) -> dict[str, Any]: """Serialise for storage in the catalog. Returns: A JSON-compatible dict. """ return {"blobs": list(self.blobs), "size": self.size}
@classmethod
[docs] def from_json(cls, data: dict[str, Any]) -> ContentRef: """Load from :meth:`to_json` output. Args: data: The stored dict. Returns: The reference. """ return cls(tuple(data["blobs"]), int(data["size"]))
[docs] def content_blobs(content: dict[str, Any] | None) -> list[str]: """Every blob a catalog content entry uses, its extra copies included. Args: content: An item version's stored content (``ContentRef`` JSON, with an optional ``"extra"`` map of named ``ContentRef`` JSON). Returns: Blob IDs. """ if not content: return [] blobs = list(content.get("blobs", [])) for ref in (content.get("extra") or {}).values(): blobs.extend(ref.get("blobs", [])) return blobs
[docs] def extra_ref(content: dict[str, Any] | None, name: str) -> ContentRef | None: """Return a named extra copy of an item version's content, if stored. Args: content: An item version's stored content. name: Copy name, e.g. ``"fts"``. Returns: Its reference, or ``None``. """ ref = ((content or {}).get("extra") or {}).get(name) return ContentRef.from_json(ref) if ref else None
@dataclass(slots=True) class _PendingPack: data: bytearray = field(default_factory=bytearray) entries: dict[str, BlobLocation] = field(default_factory=dict) @dataclass(slots=True)
[docs] class CompactStats: """Outcome of :meth:`Repository.compact`. Attributes: packs_deleted: Packs that held only unreferenced blobs. packs_rewritten: Packs rewritten without their unreferenced blobs. blobs_deleted: Unreferenced blobs removed. bytes_freed: Stored (compressed, encrypted) bytes removed. """
[docs] packs_deleted: int = 0
[docs] packs_rewritten: int = 0
[docs] blobs_deleted: int = 0
[docs] bytes_freed: int = 0
@dataclass(frozen=True, slots=True)
[docs] class RepositoryStats: """Basic repository statistics. Attributes: blobs: Number of unique blobs. packs: Number of pack files. stored_bytes: Bytes stored (compressed and encrypted). raw_bytes: Plaintext bytes of unique blobs. """
[docs] blobs: int
[docs] packs: int
[docs] stored_bytes: int
[docs] raw_bytes: int
[docs] GENERATION_KEY = "catalog-generation" # earlier format: one file, overwritten
[docs] GENERATIONS = "generation" # one file per number written
[docs] class Repository: """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. Args: backend: Where the files live. keys: Unwrapped repository keys. config: Parsed config file. """ def __init__(self, backend: StorageBackend, keys: RepoKeys, config: dict[str, Any]) -> None:
[docs] self.backend = backend
self._keys = keys
[docs] self.config = config
[docs] self.repo_id: str = config["id"]
[docs] self.chunk_size: int = config["chunk_size"]
[docs] self.pack_size: int = config["pack_size"]
self._index: dict[str, BlobLocation] = {} self._pending = _PendingPack() self._lock = asyncio.Lock() # zstd contexts are not thread-safe, and sealing/opening runs in # worker threads (several objects back up in parallel): one per thread. self._zstd = threading.local() # -- lifecycle ----------------------------------------------------------- @classmethod
[docs] async def init( cls, backend: StorageBackend, passphrase: str, *, chunk_size: int = DEFAULT_CHUNK_SIZE, pack_size: int = DEFAULT_PACK_SIZE, kdf: KdfParams | None = None, ) -> Repository: """Create a new, empty repository. Args: 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. """ if not passphrase: raise RepositoryError("a repository passphrase is required") if await backend.exists("config"): raise RepositoryError("a repository already exists at this location") kdf = kdf or KdfParams.new() keys = RepoKeys.generate() config = { # Historic format ID (the project was called Simple365Backup); never change it. "format": "simple365backup-repository", "version": FORMAT_VERSION, "id": secrets.token_hex(16), "chunk_size": chunk_size, "pack_size": pack_size, "chunker": "fixed", "compression": "zstd", "encryption": "aes-256-gcm", "blob_id": "blake3-keyed", "kdf": { "algorithm": "argon2id", "time_cost": kdf.time_cost, "memory_kib": kdf.memory_kib, "parallelism": kdf.parallelism, "salt": kdf.salt, }, "key": keys.wrap(kdf.derive(passphrase)).hex(), } await backend.put("config", json.dumps(config, indent=2).encode()) return cls(backend, keys, config)
@classmethod
[docs] async def open(cls, backend: StorageBackend, passphrase: str) -> Repository: """Open an existing repository and load its index. Args: 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. """ try: config = json.loads(await backend.get("config")) except ObjectNotFoundError as exc: raise RepositoryError("no repository found at this location") from exc if config.get("format") != "simple365backup-repository": raise RepositoryError("not a Mail Safehouse repository") if config.get("version") != FORMAT_VERSION: raise RepositoryError(f"unsupported repository version {config.get('version')}") k = config["kdf"] params = KdfParams(k["time_cost"], k["memory_kib"], k["parallelism"], k["salt"]) try: keys = RepoKeys.unwrap(bytes.fromhex(config["key"]), params.derive(passphrase)) except CryptoError as exc: raise RepositoryError(str(exc)) from exc repo = cls(backend, keys, config) await repo.reload_index() return repo
[docs] async def reload_index(self) -> None: """Re-read all index files, picking up blobs written by other processes.""" index: dict[str, BlobLocation] = {} async for key in self.backend.list("index"): name = key.rsplit("/", 1)[-1] raw = self._keys.decrypt(await self.backend.get(key), f"index:{name}".encode()) doc = json.loads(raw) for blob_id, offset, length, raw_length in doc["blobs"]: index[blob_id] = BlobLocation(doc["pack"], offset, length, raw_length) async with self._lock: self._index = index
# -- writing -------------------------------------------------------------
[docs] async def put_blob(self, data: bytes) -> str: """Store one blob (deduplicated). Args: data: Plaintext, at most ``chunk_size`` bytes. Returns: The blob ID. """ if len(data) > self.chunk_size: raise ValueError("blob larger than chunk size; use put_content") blob_id = self._keys.blob_id(data) async with self._lock: if blob_id in self._index or blob_id in self._pending.entries: return blob_id sealed = await asyncio.to_thread(self._seal, blob_id, data) async with self._lock: if blob_id in self._index or blob_id in self._pending.entries: return blob_id pending = self._pending pending.entries[blob_id] = BlobLocation("", len(pending.data), len(sealed), len(data)) pending.data += sealed full = len(pending.data) >= self.pack_size if full: await self.flush() return blob_id
[docs] async def put_content( self, source: bytes | Iterable[bytes] | AsyncIterable[bytes] ) -> ContentRef: """Store content of any size, splitting it into chunks. Args: 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. """ blobs: list[str] = [] size = 0 buf = bytearray() async for piece in _aiter_bytes(source): buf += piece while len(buf) >= self.chunk_size: chunk = bytes(buf[: self.chunk_size]) del buf[: self.chunk_size] blobs.append(await self.put_blob(chunk)) size += len(chunk) if buf or not blobs: blobs.append(await self.put_blob(bytes(buf))) size += len(buf) return ContentRef(tuple(blobs), size)
[docs] async def flush(self) -> None: """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 with self._lock: pending = self._pending if not pending.entries: return # The pending pack is only replaced once both files are written: # if either write fails, a retry writes everything again. pack_id = secrets.token_hex(16) pack_key = f"packs/{pack_id[:2]}/{pack_id}" index_doc = { "pack": pack_key, "blobs": [ [bid, loc.offset, loc.length, loc.raw_length] for bid, loc in pending.entries.items() ], } index = self._keys.encrypt(json.dumps(index_doc).encode(), f"index:{pack_id}".encode()) # Cancelling does not stop a write already running in a thread: # let both writes (and any clean-up) finish before deciding. write = asyncio.ensure_future( self._write_pack(pack_key, bytes(pending.data), f"index/{pack_id}", index) ) try: await asyncio.shield(write) except asyncio.CancelledError: with contextlib.suppress(Exception): await write if write.done() and not write.cancelled() and write.exception() is None: self._published(pending, pack_key) raise self._published(pending, pack_key)
async def _write_pack(self, pack_key: str, data: bytes, index_key: str, index: bytes) -> None: """Write a pack and then its index; no pack is left without one.""" await self.backend.put(pack_key, data) try: await self.backend.put(index_key, index) except Exception: # A pack without an index is never read nor reclaimed. with contextlib.suppress(Exception): await self.backend.delete(pack_key) raise def _published(self, pending: _PendingPack, pack_key: str) -> None: """Move a written pack's blobs from pending to the index.""" for bid, loc in pending.entries.items(): self._index[bid] = BlobLocation(pack_key, loc.offset, loc.length, loc.raw_length) if self._pending is pending: self._pending = _PendingPack() # -- catalog generation ---------------------------------------------------
[docs] async def read_generation(self) -> int: """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. """ keys = [k async for k in self.backend.list(GENERATIONS)] if await self.backend.exists(GENERATION_KEY): keys.append(GENERATION_KEY) best = 0 for key in keys: try: raw = self._keys.decrypt(await self.backend.get(key), key.encode()) except ObjectNotFoundError: continue # removed by another writer meanwhile best = max(best, int(json.loads(raw)["generation"])) return best
[docs] async def write_generation(self, generation: int) -> None: """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. Args: generation: The catalog's new generation. """ key = f"{GENERATIONS}/{generation:020d}" doc = json.dumps({"generation": generation}).encode() await self.backend.put(key, self._keys.encrypt(doc, key.encode()), overwrite=True) async for old in self.backend.list(GENERATIONS): if old < key: # zero-padded: text order is number order with contextlib.suppress(BackendError): await self.backend.delete(old)
# -- space reclamation ---------------------------------------------------
[docs] async def compact(self, live: set[str], *, min_garbage: float = 0.2) -> CompactStats: """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). Args: 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. """ await self.flush() await self.reload_index() by_pack: dict[str, dict[str, BlobLocation]] = {} for blob_id, loc in self._index.items(): by_pack.setdefault(loc.pack, {})[blob_id] = loc stats = CompactStats() for pack, blobs in sorted(by_pack.items()): total = sum(loc.length for loc in blobs.values()) keep = {b: loc for b, loc in blobs.items() if b in live} kept = sum(loc.length for loc in keep.values()) garbage = total - kept if not garbage or (keep and garbage / total < min_garbage): continue if keep: async with self._lock: for blob_id, loc in sorted(keep.items(), key=lambda kv: kv[1].offset): sealed = await self.backend.get_range(pack, loc.offset, loc.length) pending = self._pending pending.entries[blob_id] = BlobLocation( "", len(pending.data), len(sealed), loc.raw_length ) pending.data += sealed await self.flush() stats.packs_rewritten += 1 else: stats.packs_deleted += 1 await self.backend.delete(f"index/{pack.rsplit('/', 1)[-1]}") await self.backend.delete(pack) stats.blobs_deleted += len(blobs) - len(keep) stats.bytes_freed += garbage async with self._lock: for blob_id in blobs: if blob_id not in keep and self._index.get(blob_id, None) is blobs[blob_id]: del self._index[blob_id] return stats
[docs] async def remove_blobs(self, blob_ids: set[str]) -> CompactStats: """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. Args: blob_ids: The blobs to delete. Returns: What was done. """ await self.flush() await self.reload_index() return await self.compact(set(self._index) - blob_ids, min_garbage=0.0)
# -- reading -------------------------------------------------------------
[docs] def has_blob(self, blob_id: str) -> bool: """Return whether a blob is stored or buffered. Args: blob_id: Blob ID. Returns: True if present. """ return blob_id in self._index or blob_id in self._pending.entries
[docs] async def get_blob(self, blob_id: str) -> bytes: """Read and verify one blob. Args: blob_id: Blob ID. Returns: The plaintext. Raises: RepositoryError: If the blob is missing, corrupt or tampered with. """ sealed: bytes | None = None async with self._lock: loc = self._index.get(blob_id) if loc is None: pending = self._pending.entries.get(blob_id) if pending is None: raise RepositoryError(f"blob {blob_id} not found in repository") sealed = bytes(self._pending.data[pending.offset : pending.offset + pending.length]) if sealed is None: assert loc is not None # noqa: S101 - narrowed above try: sealed = await self.backend.get_range(loc.pack, loc.offset, loc.length) except ObjectNotFoundError: # Retention may have rewritten the pack since the index was # read: the blob now lives in a new pack. await self.reload_index() async with self._lock: loc = self._index.get(blob_id) if loc is None: raise RepositoryError(f"blob {blob_id} not found in repository") from None sealed = await self.backend.get_range(loc.pack, loc.offset, loc.length) try: data = await asyncio.to_thread(self._open_sealed, blob_id, sealed) except (CryptoError, zstandard.ZstdError) as exc: raise RepositoryError(f"blob {blob_id}: {exc}") from exc if self._keys.blob_id(data) != blob_id: raise RepositoryError(f"blob {blob_id}: content does not match its ID") return data
[docs] async def get_content(self, ref: ContentRef) -> AsyncIterator[bytes]: """Stream stored content chunk by chunk. Args: ref: Reference from :meth:`put_content`. Yields: Plaintext chunks in order. """ for blob_id in ref.blobs: yield await self.get_blob(blob_id)
[docs] async def check(self, *, read_data: bool = False) -> list[str]: """Verify the repository. Args: 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. """ problems: list[str] = [] packs = {loc.pack for loc in self._index.values()} for pack in sorted(packs): if not await self.backend.exists(pack): problems.append(f"missing pack {pack}") if read_data: problems.extend(f"blob {b}: unreadable" for b in sorted(await self.unreadable_blobs())) return problems
[docs] async def unreadable_blobs(self) -> set[str]: """Read every blob; return the IDs of those that fail verification. Returns: IDs of missing, corrupt or tampered blobs. """ bad: set[str] = set() for blob_id in list(self._index): try: await self.get_blob(blob_id) except (RepositoryError, BackendError): bad.add(blob_id) return bad
[docs] def stats(self) -> RepositoryStats: """Return statistics about flushed data. Returns: Repository statistics. """ locs = self._index.values() return RepositoryStats( blobs=len(self._index), packs=len({loc.pack for loc in locs}), stored_bytes=sum(loc.length for loc in locs), raw_bytes=sum(loc.raw_length for loc in locs), )
# -- internals ----------------------------------------------------------- def _cctx(self) -> zstandard.ZstdCompressor: cctx = getattr(self._zstd, "cctx", None) if cctx is None: cctx = self._zstd.cctx = zstandard.ZstdCompressor(level=3) return cctx def _dctx(self) -> zstandard.ZstdDecompressor: dctx = getattr(self._zstd, "dctx", None) if dctx is None: dctx = self._zstd.dctx = zstandard.ZstdDecompressor() return dctx def _seal(self, blob_id: str, data: bytes) -> bytes: compressed = self._cctx().compress(data) payload = ( (bytes([_ZSTD]) + compressed) if len(compressed) < len(data) else (bytes([_RAW]) + data) ) return self._keys.encrypt(payload, blob_id.encode()) def _open_sealed(self, blob_id: str, sealed: bytes) -> bytes: payload = self._keys.decrypt(sealed, blob_id.encode()) flag, body = payload[0], payload[1:] if flag == _ZSTD: return bytes(self._dctx().decompress(body)) if flag == _RAW: return body raise CryptoError(f"unknown blob encoding {flag}")
async def _aiter_bytes( source: bytes | Iterable[bytes] | AsyncIterable[bytes], ) -> AsyncIterator[bytes]: """Normalise bytes / iterable / async iterable into an async iterator.""" if isinstance(source, (bytes, bytearray, memoryview)): yield bytes(source) elif isinstance(source, AsyncIterable): async for piece in source: yield piece else: for piece in source: yield piece