"""Jobs: status, live Server-Sent Events, cancel and retry (only the requesting visitor's jobs).""" from __future__ import annotations import asyncio import time from collections.abc import AsyncIterator from fastapi import APIRouter, Depends, HTTPException, Request from fastapi.responses import StreamingResponse from sqlmodel import Session from stemdeck import quotas from stemdeck.db import get_engine, get_session from stemdeck.jobrunner import runner from stemdeck.library import owned_job from stemdeck.models import TERMINAL_JOB_STATUSES, Job, Song from stemdeck.schemas import JobOut, job_out from stemdeck.settings import get_settings from stemdeck.visitors import client_key, current_owner router = APIRouter(tags=["jobs"]) SSE_POLL_SEC = 0.5 SSE_HEARTBEAT_SEC = 15.0 @router.get("/jobs/{job_id}", response_model=JobOut) def get_job(job_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> JobOut: return job_out(session, owned_job(session, job_id, owner)) def _snapshot(job_id: str) -> tuple[str | None, bool]: with Session(get_engine()) as session: job = session.get(Job, job_id) if job is None: return None, True return job_out(session, job).model_dump_json(), job.status in TERMINAL_JOB_STATUSES def _check_owner(job_id: str, owner: str) -> None: with Session(get_engine()) as session: owned_job(session, job_id, owner) @router.get("/jobs/{job_id}/events") async def job_events(job_id: str, request: Request, owner: str = Depends(current_owner)) -> StreamingResponse: await asyncio.to_thread(_check_owner, job_id, owner) if not get_settings().live_updates: # e.g. behind a Cloudflare quick tunnel: the page polls instead raise HTTPException(503, "Live updates are off on this server; progress is checked every few seconds.") first, _ = await asyncio.to_thread(_snapshot, job_id) if first is None: raise HTTPException(404, "Job not found.") async def stream() -> AsyncIterator[str]: last: str | None = None last_sent = time.monotonic() while not await request.is_disconnected(): payload, terminal = await asyncio.to_thread(_snapshot, job_id) if payload is None: return if payload != last: yield f"data: {payload}\n\n" last, last_sent = payload, time.monotonic() elif time.monotonic() - last_sent > SSE_HEARTBEAT_SEC: yield ": keep-alive\n\n" last_sent = time.monotonic() if terminal: return await asyncio.sleep(SSE_POLL_SEC) return StreamingResponse(stream(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) @router.post("/jobs/{job_id}/cancel", response_model=JobOut) def cancel_job(job_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner)) -> JobOut: owned_job(session, job_id, owner) runner.cancel(job_id) session.expire_all() return job_out(session, owned_job(session, job_id, owner)) @router.post("/jobs/{job_id}/retry", response_model=JobOut, status_code=201) def retry_job(job_id: str, session: Session = Depends(get_session), owner: str = Depends(current_owner), client: str = Depends(client_key)) -> JobOut: old = owned_job(session, job_id, owner) if old.status not in ("failed", "cancelled"): raise HTTPException(409, "Only failed or cancelled jobs can be retried.") song = session.get(Song, old.song_id) if song is None: raise HTTPException(404, "Song not found.") if old.type == "split": folder = get_settings().songs_dir / song.id if next(folder.glob("original.*"), None) is None and not old.params.get("source_url"): raise HTTPException(409, "The original upload is missing; please upload the file again.") with quotas.admit(session, owner, client, "retry", new_song=False): if old.type == "split": song.status = "queued" session.add(song) job = Job(song_id=old.song_id, type=old.type, params=dict(old.params or {})) session.add(job) session.commit() session.refresh(job) return job_out(session, job)