import asyncio, time from dataclasses import dataclass, field from pathlib import Path from typing import Optional from config import JOB_TTL from progress import ProgressSnapshot @dataclass class JobRecord: job_id: str work_dir: Path status: str = "pending" progress: ProgressSnapshot = field(default_factory=ProgressSnapshot) error: Optional[str] = None result: Optional[str] = None created_at: float = field(default_factory=time.time) task: Optional[asyncio.Task] = None class JobQueue: def __init__(self, max_workers: int = 4): self._max_workers = max_workers self._jobs: dict[str, JobRecord] = {} self._sem = asyncio.Semaphore(max_workers) self._lock = asyncio.Lock() def create(self, job_id: str, work_dir: Path) -> JobRecord: rec = JobRecord(job_id=job_id, work_dir=work_dir) self._jobs[job_id] = rec return rec def get(self, job_id: str) -> Optional[JobRecord]: return self._jobs.get(job_id) async def submit(self, job_id: str, coro): rec = self._jobs.get(job_id) if not rec: return rec.status = "queued" async def _run(): async with self._sem: rec.status = "running" try: result = await coro rec.status = "done" rec.result = result except Exception as e: rec.status = "failed" rec.error = str(e) rec.task = asyncio.create_task(_run()) def update_progress(self, job_id: str, snap: ProgressSnapshot): rec = self._jobs.get(job_id) if rec: rec.progress = snap async def purge_expired(self) -> int: now = time.time() expired = [jid for jid, rec in self._jobs.items() if rec.status in ("done", "failed") and now - rec.created_at > JOB_TTL] for jid in expired: rec = self._jobs.pop(jid, None) if rec and rec.work_dir.exists(): import shutil shutil.rmtree(rec.work_dir, ignore_errors=True) return len(expired) def list_all(self): return [ { "job_id": jid, "status": rec.status, "progress": rec.progress.to_dict(), "error": rec.error, "age_seconds": round(time.time() - rec.created_at, 1), } for jid, rec in self._jobs.items() ] def delete(self, job_id: str) -> bool: """Delete a job and its working directory. Returns True if deleted.""" rec = self._jobs.pop(job_id, None) if not rec: return False # Cancel task if still running if rec.task and not rec.task.done(): rec.task.cancel() # Remove working directory if rec.work_dir.exists(): import shutil shutil.rmtree(rec.work_dir, ignore_errors=True) return True