"""Single-writer cache transaction with an owned recovery journal.""" from __future__ import annotations import hashlib import os import re import shutil from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from tempfile import mkdtemp from typing import TYPE_CHECKING, Annotated, Final, Literal from pydantic import Field from models import ( ASSET_BYTES, CATALOG_BYTES, AssetId, Catalog, FailureReason, Frozen, ImportFailureError, Pack, ) if TYPE_CHECKING: from collections.abc import Iterator OWNER: Final = b"wowmine-stickers-importer-v1\n" JOB_NAME: Final = re.compile(r"job-[a-z0-9_]{8}") def load_catalog(path: Path) -> Catalog: """Read bounded catalog before trusting any asset ownership or references.""" if not path.exists(): return Catalog() with path.open("rb") as source: raw = source.read(CATALOG_BYTES + 1) if len(raw) > CATALOG_BYTES: raise ImportFailureError(FailureReason.CATALOG_EXCEEDS_512_KIB) return Catalog.model_validate_json(raw) class Journal(Frozen): """Only IDs recorded before publication may be reclaimed.""" version: Literal[1] = 1 assets: Annotated[list[AssetId], Field(max_length=2248)] def reclaim(stage: Path, output: Path) -> None: """Reclaim owned jobs while retaining live IDs, symlinks and unrelated files.""" catalog = load_catalog(output / "catalog.json") live = {s.id for pack in catalog.packs for s in pack.stickers} journal_path = stage / "journal.json" if journal_path.is_file(): with journal_path.open("rb") as source: raw = source.read(CATALOG_BYTES + 1) journal = Journal.model_validate_json(raw) for asset_id in set(journal.assets) - live: asset = output / "assets" / (asset_id + ".png") if asset.is_file() and not asset.is_symlink(): with asset.open("rb") as source: png = source.read(ASSET_BYTES + 1) if ( len(png) <= ASSET_BYTES and hashlib.sha256(png).hexdigest() == asset_id ): asset.unlink() # Reserved job directories contain importer scratch only. shutil.rmtree(stage) @dataclass(frozen=True, slots=True) class Cache: """Stage and publish one pack, under server's global single-writer lock.""" output: Path stage: Path def publish(self, pack: Pack) -> None: """Validate whole merged catalog before publishing even one asset.""" old = load_catalog(self.output / "catalog.json") merged = Catalog(packs=[p for p in old.packs if p.id != pack.id] + [pack]) raw = merged.model_dump_json().encode() if len(raw) > CATALOG_BYTES: raise ImportFailureError(FailureReason.CATALOG_SIZE_LIMIT_EXCEEDED) ids = {s.id for p in old.packs for s in p.stickers} | { s.id for s in pack.stickers } temporary = self.stage / "journal.new" _ = temporary.write_text(Journal(assets=sorted(ids)).model_dump_json()) _ = temporary.replace(self.stage / "journal.json") assets = self.output / "assets" assets.mkdir(exist_ok=True) for sticker in pack.stickers: _ = (self.stage / (sticker.id + ".png")).replace( assets / (sticker.id + ".png") ) temporary = self.stage / "catalog.new" with temporary.open("wb") as target: _ = target.write(raw) target.flush() os.fsync(target.fileno()) _ = temporary.replace(self.output / "catalog.json") @contextmanager def transaction(output: Path) -> Iterator[Cache]: """Recover only importer-owned staging before allocating another job.""" _ = load_catalog(output / "catalog.json") output.mkdir(parents=True, exist_ok=True) root = output / ".wowmine-stickers-importer-v1" if root.is_symlink(): raise ImportFailureError(FailureReason.STAGING_ROOT_IS_A_SYMLINK) root.mkdir(exist_ok=True) marker = root / "owner" if not marker.exists(): if any(root.iterdir()): raise ImportFailureError(FailureReason.UNOWNED_STAGING_DIRECTORY) _ = marker.write_bytes(OWNER) with marker.open("rb") as source: if source.read(len(OWNER) + 1) != OWNER: raise ImportFailureError(FailureReason.UNOWNED_STAGING_DIRECTORY) for child in root.iterdir(): if JOB_NAME.fullmatch(child.name) and child.is_dir() and not child.is_symlink(): reclaim(child, output) stage = Path(mkdtemp(prefix="job-", dir=root)) try: yield Cache(output, stage) finally: reclaim(stage, output)