Spaces:
Runtime error

File size: 3,045 Bytes
241b96d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6599b30
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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