"""Serial job queue manager for the single Applio GPU worker.""" from __future__ import annotations import logging import threading from .enums import JobPhase, JobStatus from .models import Job from .store import JobStore logger = logging.getLogger(__name__) class JobQueue: """Runs exactly one real Applio job at a time.""" def __init__(self, store: JobStore) -> None: self._store = store self._running: dict[str, Job] = {} self._lock = threading.Lock() self._cancel_events: dict[str, threading.Event] = {} self._worker_thread: threading.Thread | None = None self._queue: list[str] = [] self._queue_lock = threading.Lock() self._shutdown = False def start(self) -> None: if self._worker_thread and self._worker_thread.is_alive(): return self._shutdown = False # Never replay an interrupted GPU command automatically. recovered_ids: set[str] = set() for job in self._store.list(status=JobStatus.RUNNING): job.mark_failed("Der UI-Dienst wurde während dieses Auftrags neu gestartet. Aus Sicherheitsgründen wurde der GPU-Auftrag nicht automatisch erneut ausgeführt.") self._store.save(job) recovered_ids.add(job.id) for job in self._store.list(status=JobStatus.WAITING): if job.id not in recovered_ids and job.id not in self._queue: self._queue.append(job.id) self._worker_thread = threading.Thread(target=self._worker_loop, daemon=True) self._worker_thread.start() def stop(self) -> None: self._shutdown = True with self._lock: for event in self._cancel_events.values(): event.set() if self._worker_thread: self._worker_thread.join(timeout=10) def submit(self, job: Job) -> None: job.status = JobStatus.WAITING job.set_phase(JobPhase.QUEUED, "Auftrag wird in die Warteschlange aufgenommen") self._store.save(job) with self._queue_lock: self._queue.append(job.id) logger.info("Job %s submitted (type=%s)", job.id, job.type.value) def cancel(self, job_id: str) -> bool: with self._lock: if job_id in self._running: job = self._running[job_id] job.status = JobStatus.CANCELLING job.cancelled = True self._store.save(job) event = self._cancel_events.get(job_id) if event: event.set() return True job = self._store.get(job_id) if job and job.status == JobStatus.WAITING: job.mark_cancelled() self._store.save(job) return True return False def get_running(self) -> list[Job]: with self._lock: return list(self._running.values()) def _worker_loop(self) -> None: while not self._shutdown: job_id = None with self._queue_lock: if self._queue: job_id = self._queue.pop(0) if job_id is None: waiting = self._store.list(status=JobStatus.WAITING, limit=1) if waiting: job_id = waiting[0].id else: import time time.sleep(0.5) continue job = self._store.get(job_id) if job is None or job.is_terminal(): continue self._execute_job(job) def _execute_job(self, job: Job) -> None: from ..adapters.runner import get_runner cancel_event = threading.Event() with self._lock: self._running[job.id] = job self._cancel_events[job.id] = cancel_event job.mark_running() self._store.save(job) logger.info("Job %s started (type=%s)", job.id, job.type.value) try: runner = get_runner() runner.execute(job, cancel_event) except Exception as e: logger.exception("Job %s crashed", job.id) job.mark_failed(f"Unerwarteter Fehler: {e}") self._store.save(job) finally: with self._lock: self._running.pop(job.id, None) self._cancel_events.pop(job.id, None) self._store.save(job) logger.info("Job %s finished (status=%s)", job.id, job.status.value)