Source code for s365b.storage.backends
"""Storage backends: where repository files physically live.
A backend stores opaque, immutable objects under ``/``-separated keys such as
``packs/ab/ab12…``. It knows nothing about encryption or deduplication; that
is the repository's job. New backends (S3, Azure Blob) implement
:class:`StorageBackend`.
"""
from __future__ import annotations
import abc
import asyncio
import os
import re
import uuid
from collections.abc import AsyncIterator
from pathlib import Path
_KEY_RE = re.compile(r"^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*$")
[docs]
class BackendError(Exception):
"""Raised for storage errors, such as a missing object."""
[docs]
class ObjectNotFoundError(BackendError):
"""Raised when a key does not exist."""
[docs]
def validate_key(key: str) -> str:
"""Check that a key is a safe relative path.
Args:
key: Object key such as ``index/abc``.
Returns:
The key, unchanged.
Raises:
ValueError: If the key is empty, absolute, or contains ``..`` or
unexpected characters.
"""
if not _KEY_RE.match(key) or any(part in {".", ".."} for part in key.split("/")):
raise ValueError(f"invalid storage key: {key!r}")
return key
[docs]
class StorageBackend(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.
"""
@abc.abstractmethod
[docs]
async def put(self, key: str, data: bytes, *, overwrite: bool = False) -> None:
"""Store an object atomically.
Args:
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.
"""
@abc.abstractmethod
[docs]
async def get(self, key: str) -> bytes:
"""Read a whole object.
Args:
key: Object key.
Returns:
The object content.
Raises:
ObjectNotFoundError: If the key does not exist.
"""
@abc.abstractmethod
[docs]
async def get_range(self, key: str, offset: int, length: int) -> bytes:
"""Read part of an object.
Args:
key: Object key.
offset: First byte to read.
length: Number of bytes to read.
Returns:
Exactly ``length`` bytes.
Raises:
ObjectNotFoundError: If the key does not exist.
BackendError: If the object is shorter than requested.
"""
@abc.abstractmethod
[docs]
async def exists(self, key: str) -> bool:
"""Return whether an object exists.
Args:
key: Object key.
Returns:
True if the object exists.
"""
@abc.abstractmethod
[docs]
def list(self, prefix: str) -> AsyncIterator[str]:
"""Yield keys under a prefix (a directory such as ``index``).
Args:
prefix: Key prefix without trailing slash.
Returns:
An async iterator of full keys, in no particular order.
"""
@abc.abstractmethod
[docs]
async def delete(self, key: str) -> None:
"""Delete an object. Deleting a missing object is not an error.
Args:
key: Object key.
"""
[docs]
class FilesystemBackend(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.
Args:
root: Directory holding the repository. Created if missing.
"""
def __init__(self, root: Path) -> None:
def _path(self, key: str) -> Path:
return self.root / validate_key(key)
[docs]
async def put(self, key: str, data: bytes, *, overwrite: bool = False) -> None:
"""Store an object atomically (see :meth:`StorageBackend.put`)."""
await asyncio.to_thread(self._put_sync, self._path(key), data, overwrite)
@staticmethod
def _put_sync(path: Path, data: bytes, overwrite: bool) -> None:
if path.exists() and not overwrite:
raise BackendError(f"object already exists: {path.name}")
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
with tmp.open("wb") as fh:
fh.write(data)
fh.flush()
os.fsync(fh.fileno())
tmp.replace(path)
finally:
tmp.unlink(missing_ok=True)
# Persist the directory entry too, so the rename survives a power cut.
dir_fd = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(dir_fd)
finally:
os.close(dir_fd)
[docs]
async def get(self, key: str) -> bytes:
"""Read a whole object (see :meth:`StorageBackend.get`)."""
path = self._path(key)
try:
return await asyncio.to_thread(path.read_bytes)
except FileNotFoundError as exc:
raise ObjectNotFoundError(key) from exc
[docs]
async def get_range(self, key: str, offset: int, length: int) -> bytes:
"""Read part of an object (see :meth:`StorageBackend.get_range`)."""
path = self._path(key)
def _read() -> bytes:
with path.open("rb") as fh:
fh.seek(offset)
return fh.read(length)
try:
data = await asyncio.to_thread(_read)
except FileNotFoundError as exc:
raise ObjectNotFoundError(key) from exc
if len(data) != length:
raise BackendError(f"short read from {key}: wanted {length}, got {len(data)}")
return data
[docs]
async def exists(self, key: str) -> bool:
"""Return whether an object exists (see :meth:`StorageBackend.exists`)."""
return await asyncio.to_thread(self._path(key).is_file)
[docs]
async def list(self, prefix: str) -> AsyncIterator[str]:
"""Yield keys under a prefix (see :meth:`StorageBackend.list`)."""
base = self._path(prefix)
def _walk() -> list[str]:
if not base.is_dir():
return []
return [
p.relative_to(self.root).as_posix()
for p in base.rglob("*")
if p.is_file() and not p.name.startswith(".")
]
for key in await asyncio.to_thread(_walk):
yield key
[docs]
async def delete(self, key: str) -> None:
"""Delete an object (see :meth:`StorageBackend.delete`)."""
await asyncio.to_thread(self._path(key).unlink, missing_ok=True)