Spaces:
Running on T4
Running on T4
Download backend/app/modules/swing_reports/queue.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 1.84 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/swing_reports/queue.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/modules/swing_reports/queue.py
-
curl -L -o queue.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/swing_reports/queue.py
1.84 kB
| """The report queue worker: background tasks in the API process that build queued reports one at a time. | |
| The queue is the sessions table (queued_payload), so it survives restarts and needs no extra service. kick() is | |
| called after a payload is queued and once at startup. Rows are claimed with FOR UPDATE SKIP LOCKED, so several API | |
| processes can run workers side by side. | |
| """ | |
| import asyncio | |
| import logging | |
| from app.core.database import get_session_factory | |
| from app.integrations.push import get_push_client | |
| from app.modules.swing_reports.service import SwingReportService | |
| log = logging.getLogger(__name__) | |
| # Reports built at once per API process. Each holds one database connection and one model call for its build, | |
| # so this stays well under the connection pool. | |
| MAX_WORKERS = 2 | |
| WORKERS: set[asyncio.Task] = set() | |
| async def build_next() -> bool: | |
| async with get_session_factory()() as db: | |
| built = await SwingReportService(db).build_next_queued(get_push_client()) | |
| await db.commit() | |
| return built | |
| async def _drain() -> None: | |
| task = asyncio.current_task() | |
| try: | |
| while True: | |
| while await build_next(): | |
| pass | |
| # Leave the pool before the last look: a payload queued during the empty poll above either finds room | |
| # for its own worker or is caught here. | |
| WORKERS.discard(task) | |
| if not await build_next(): | |
| return | |
| WORKERS.add(task) | |
| except Exception: | |
| log.exception("report worker stopped; queued sessions wait for the next kick or restart") | |
| finally: | |
| WORKERS.discard(task) | |
| def kick() -> None: | |
| """Make sure a worker is looking at the queue. Call after the queued payload is committed.""" | |
| if len(WORKERS) < MAX_WORKERS: | |
| WORKERS.add(asyncio.create_task(_drain())) | |