"""Claiming an upload for a record: ownership, kind, not already used, bytes present, then mark it attached.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import UTC, datetime from uuid import UUID from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.integrations.storage import StorageClient from app.modules.uploads.models import Upload @dataclass(frozen=True) class UploadErrors: """The exceptions each module raises for a failed claim (they differ in code and wording).""" invalid: Exception # missing or not the caller's used: Exception not_ready: Exception wrong_kind: Exception | None = None # defaults to invalid async def claim_upload( db: AsyncSession, storage: StorageClient, upload_id: UUID, *, owner_id: UUID, kind: str, errors: UploadErrors, in_use: Callable[[], Awaitable[bool]] | None = None, reusable: Callable[[], Awaitable[bool]] | None = None, ) -> None: """Lock the upload row so concurrent claims serialize. in_use also counts rows that reference it without attached_at set; reusable says a claim on an already attached upload is the same record re-sending it.""" upload = await db.scalar(select(Upload).where(Upload.id == upload_id).with_for_update()) if upload is None or upload.owner_id != owner_id: raise errors.invalid if upload.kind != kind: raise errors.wrong_kind or errors.invalid attached = upload.attached_at is not None if attached and not (reusable and await reusable()) or (not attached and in_use and await in_use()): raise errors.used if await storage.head(upload.object_key) is None: raise errors.not_ready if not attached: upload.attached_at = datetime.now(UTC)