Spaces:
Running on T4
Running on T4
File size: 1,841 Bytes
be69d1e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | """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()))
|