Spaces:
Running on T4
Running on T4
Download backend/app/common/uploads.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 1.81 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/common/uploads.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/common/uploads.py
-
curl -L -o uploads.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/common/uploads.py
1.81 kB
| """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 | |
| 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) | |