"""Runs live in Dagster: the API starts them and reads their state, never computes.""" import os from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError from fastapi import APIRouter, Depends, HTTPException router = APIRouter(prefix="/runs", tags=["runs"]) def dagster() -> DagsterGraphQLClient: return DagsterGraphQLClient( os.environ.get("DAGSTER_HOST", "localhost"), port_number=int(os.environ.get("DAGSTER_PORT", "3000")), ) @router.post("/rebuild") def rebuild_gold(client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: """Starts rebuilding silver and gold with the deployed code (after an upgrade, before any new data arrives); follow it at /runs. Risk tables keep the last scores.""" try: return {"run_id": client.submit_job_execution("rebuild")} except DagsterGraphQLClientError as e: raise HTTPException(502, detail=str(e)) from e @router.get("/{run_id}") def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: try: return {"id": run_id, "status": client.get_run_status(run_id).value} except DagsterGraphQLClientError as e: raise HTTPException(404 if "RunNotFound" in str(e) else 502, detail=str(e)) from e @router.post("/{run_id}/terminate") def terminate_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: """Stop a run (one started by mistake): Dagster cancels it.""" try: client.terminate_run(run_id) return {"id": run_id, "status": client.get_run_status(run_id).value} except DagsterGraphQLClientError as e: raise HTTPException(404 if "RunNotFound" in str(e) else 409, detail=str(e)) from e