"""Relay v4 router — push-based, batch-first, artifact-capable. Prefix (mounted by main.py): /dataset_verification Agent endpoints (AGENT_API_KEY): POST /desktop/batch submit a batch -> {batch_id, ...} GET /desktop/batch/{batch_id} poll; ?consume=true to fetch-and-delete DELETE /desktop/batch/{batch_id} cancel a pending batch GET /desktop/artifact/{artifact_id} stream artifact bytes (image/audio/file) GET /desktop/status schema / counters / worker liveness (URLs redacted) Runner endpoints (RUNNER_API_KEY): POST /worker/register mint/refresh identity (same worker_id + new url supersedes old generation) POST /worker/result report one cell result POST /worker/artifact upload artifact bytes (raw body, streamed to disk) POST /worker/done declare draining; releases claims GET /health unauthenticated liveness Delivery is PUSH: after a runner registers (or a batch is submitted), the store atomically claims matchable queued cells and POSTs them to the runner's own intake URL (a Cloudflare quick tunnel the runner opened outbound). There is NO poll/stream endpoint — runners never call in to ask for work. """ import os import secrets import threading from pathlib import Path from urllib.parse import urlparse from fastapi import APIRouter, Depends, HTTPException, Query, Request from fastapi.responses import FileResponse from .models import ResultObject, WorkerRegisterRequest from .store import Store, push_shutdown import os as _os router = APIRouter() store = Store(_os.getenv("PERSIST_DIR", "./persist"), push_bearer=_os.getenv("RUNNER_API_KEY", "")) RUNNER_API_KEY = _os.getenv("RUNNER_API_KEY", "") AGENT_API_KEY = _os.getenv("AGENT_API_KEY", "") def _auth(expected): from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer security = HTTPBearer(auto_error=False) def dep(credentials: HTTPAuthorizationCredentials = Depends(security)): if (not expected or not credentials or credentials.scheme.lower() != "bearer" or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())): raise HTTPException(status_code=401, detail="Unauthorized") return dep worker_auth = _auth(RUNNER_API_KEY) desktop_auth = _auth(AGENT_API_KEY) def _check_push_url(url: str) -> str | None: """Quick tunnels are the supported push target. PUSH_URL_HOST_SUFFIX='*' disables the check (local dev/tests only). Pull-mode workers register an opaque pull:// token instead of a reachable URL.""" if url.startswith("pull://") and len(url) > len("pull://") + 8: return None suffix = _os.getenv("PUSH_URL_HOST_SUFFIX", ".trycloudflare.com") if suffix == "*": return None p = urlparse(url) if p.scheme != "https" or not p.hostname: return "push URL must be https://" if not p.hostname.endswith(suffix): return f"push URL host must end with {suffix}" return None # ---------------- agent endpoints ---------------- @router.post("/desktop/batch", dependencies=[Depends(desktop_auth)]) def desktop_submit_batch(body: dict): from .models import BatchSubmission try: batch = BatchSubmission(**body) except Exception as e: raise HTTPException(status_code=422, detail=str(e)) try: return store.submit_batch(batch) except ValueError as e: raise HTTPException(status_code=409, detail=str(e)) @router.get("/desktop/batch/{batch_id}", dependencies=[Depends(desktop_auth)]) def desktop_get_batch(batch_id: str, consume: bool = Query(False)): res = store.get_batch(batch_id, consume=consume) if res is None: raise HTTPException(status_code=404, detail="batch not found") return res @router.delete("/desktop/batch/{batch_id}", dependencies=[Depends(desktop_auth)]) def desktop_cancel_batch(batch_id: str): res = store.cancel_batch(batch_id) if res is None: raise HTTPException(status_code=404, detail="batch not found") return res @router.get("/desktop/artifact/{artifact_id}", dependencies=[Depends(desktop_auth)]) def desktop_get_artifact(artifact_id: str): meta, path = store.get_artifact(artifact_id) if meta is None: raise HTTPException(status_code=404, detail="artifact not found or expired") return FileResponse(path, media_type=meta["content_type"], headers={"X-Artifact-Kind": meta["kind"], "X-Artifact-SHA256": meta["sha256"], "Content-Disposition": f'inline; filename="{Path(meta["path"]).name}"'}) @router.get("/desktop/status", dependencies=[Depends(desktop_auth)]) def desktop_status(): return store.get_status() # ---------------- runner endpoints ---------------- @router.post("/worker/register", dependencies=[Depends(worker_auth)]) def worker_register(body: WorkerRegisterRequest): url = body.url.strip() err = _check_push_url(url) if err: raise HTTPException(status_code=422, detail=err) urls = [u.strip() for u in (body.urls or []) if u and u.strip()] for i, u in enumerate(urls): err = _check_push_url(u) if err: raise HTTPException(status_code=422, detail=f"urls[{i}]: {err}") public, old_url = store.register_worker(body.worker_id, url, body.environment.model_dump(), urls=urls or None) if old_url: # tell the superseded generation to drain now instead of at its lifetime end threading.Thread(target=push_shutdown, args=(old_url, RUNNER_API_KEY), daemon=True).start() return public @router.post("/worker/next", dependencies=[Depends(worker_auth)]) def worker_next(body: dict): try: worker_id = int(body.get("worker_id") or 0) except (TypeError, ValueError): raise HTTPException(status_code=422, detail="worker_id must be an int") url = str(body.get("url") or "") if not worker_id or not url: raise HTTPException(status_code=422, detail="worker_id and url are required") try: limit = int(body.get("limit", 1)) except (TypeError, ValueError): limit = 1 cells = store.claim_next(worker_id, url, limit=max(1, min(limit, 16))) if cells is None: raise HTTPException(status_code=409, detail="url mismatch for this worker instance") return {"cells": cells} @router.post("/worker/result", dependencies=[Depends(worker_auth)]) def worker_result(body: ResultObject, worker_id: int = Query(...), url: str = Query(...)): try: out = store.report_result(worker_id, url, body) if out and out.get("already_recorded"): return {"status": "already_recorded", "job_id": body.job_id} return {"status": "recorded", "job_id": body.job_id} except KeyError: raise HTTPException(status_code=404, detail="cell not found") except PermissionError: raise HTTPException(status_code=409, detail="cell not claimed by this worker instance") @router.post("/worker/artifact", dependencies=[Depends(worker_auth)]) async def worker_artifact(request: Request, job_id: str = Query(""), batch_id: str = Query(""), path: str = Query(...), kind: str = Query(None), content_type: str = Query(None)): # streamed to disk in chunks — no whole-body RAM spike, no size constants tmp = Path(_os.getenv("PERSIST_DIR", "./persist")) / "artifacts" / f".upload-{secrets.token_hex(8)}.bin" tmp.parent.mkdir(parents=True, exist_ok=True) with open(tmp, "wb") as fh: async for chunk in request.stream(): fh.write(chunk) data = tmp.read_bytes() # sha256 needs bytes; artifacts are outputs, typically <100MB tmp.unlink() meta = store.store_artifact(batch_id or None, job_id or None, path, kind, content_type, data) return meta @router.post("/worker/done", dependencies=[Depends(worker_auth)]) def worker_done(body: dict): released = store.report_done(int(body["worker_id"]), body["url"]) return {"released_job_ids": released} @router.get("/health") def health(): s = store.get_status() return {"online": "yes", "schema": s["schema"], "pending_batches": s["pending_batches"], "queued": s["jobs_by_status"]["queued"], "workers_online": sum(1 for w in s["workers"] if w["status"] not in ("unresponsive", "draining"))}