|
| 1 | +"""The task service REST API (FastAPI). |
| 2 | +
|
| 3 | +The dashboard, the runner, and in-container skills are clients of this API. (Agents also |
| 4 | +reach artifacts/tools over MCP — see :mod:`panopticon.taskservice.mcp` — but the walking |
| 5 | +skeleton uses REST.) ``create_app`` builds an app around an injected |
| 6 | +:class:`~panopticon.taskservice.service.TaskService`, so tests can wire a deterministic one. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from fastapi import FastAPI, HTTPException, Request, Response |
| 12 | +from fastapi.responses import JSONResponse |
| 13 | +from pydantic import BaseModel, ConfigDict |
| 14 | + |
| 15 | +from panopticon.core.artifacts import ArtifactError |
| 16 | +from panopticon.core.models import Actor, Repo, Status |
| 17 | +from panopticon.core.store import AlreadyExists, NotFound, StoreError |
| 18 | +from panopticon.core.workflow import IllegalTransition, InvalidWorkflow, ResponsibilitiesNotMet |
| 19 | +from panopticon.taskservice.service import TaskService, UnknownWorkflow |
| 20 | + |
| 21 | +# -- wire schemas ------------------------------------------------------------------- |
| 22 | + |
| 23 | + |
| 24 | +# ``*Out`` models read straight off the domain objects (`model_validate`): their fields match |
| 25 | +# the domain attribute names, so `from_attributes=True` does the conversion — incl. nested |
| 26 | +# Task -> History -> Responsibility — with no hand-written copying. |
| 27 | + |
| 28 | + |
| 29 | +class ResponsibilityOut(BaseModel): |
| 30 | + model_config = ConfigDict(from_attributes=True) |
| 31 | + |
| 32 | + key: str |
| 33 | + description: str |
| 34 | + status: Status |
| 35 | + comment: str | None = None |
| 36 | + |
| 37 | + |
| 38 | +class HistoryOut(BaseModel): |
| 39 | + model_config = ConfigDict(from_attributes=True) |
| 40 | + |
| 41 | + at: str |
| 42 | + from_state: str | None |
| 43 | + to_state: str |
| 44 | + trigger: str | None = None |
| 45 | + note: str | None = None |
| 46 | + responsibilities: list[ResponsibilityOut] = [] |
| 47 | + |
| 48 | + |
| 49 | +class TaskOut(BaseModel): |
| 50 | + model_config = ConfigDict(from_attributes=True) |
| 51 | + |
| 52 | + id: str |
| 53 | + repo_id: str |
| 54 | + workflow: str |
| 55 | + state: str |
| 56 | + turn: Actor |
| 57 | + slug: str | None |
| 58 | + history: list[HistoryOut] |
| 59 | + |
| 60 | + |
| 61 | +class RepoIn(BaseModel): |
| 62 | + id: str |
| 63 | + name: str |
| 64 | + git_url: str |
| 65 | + default_base: str = "main" |
| 66 | + |
| 67 | + |
| 68 | +class RepoOut(BaseModel): |
| 69 | + model_config = ConfigDict(from_attributes=True) |
| 70 | + |
| 71 | + id: str |
| 72 | + name: str |
| 73 | + git_url: str |
| 74 | + default_base: str |
| 75 | + |
| 76 | + |
| 77 | +class CreateTaskIn(BaseModel): |
| 78 | + repo_id: str |
| 79 | + workflow: str |
| 80 | + |
| 81 | + |
| 82 | +class ResponsibilityIn(BaseModel): |
| 83 | + key: str |
| 84 | + status: Status |
| 85 | + comment: str | None = None |
| 86 | + |
| 87 | + |
| 88 | +class TransitionIn(BaseModel): |
| 89 | + to_state: str |
| 90 | + trigger: str | None = None |
| 91 | + note: str | None = None |
| 92 | + |
| 93 | + |
| 94 | +class SlugIn(BaseModel): |
| 95 | + slug: str |
| 96 | + |
| 97 | + |
| 98 | +class RegisterIn(BaseModel): |
| 99 | + container_id: str |
| 100 | + runner_id: str | None = None |
| 101 | + |
| 102 | + |
| 103 | +class RegistrationOut(BaseModel): |
| 104 | + model_config = ConfigDict(from_attributes=True) |
| 105 | + |
| 106 | + id: str |
| 107 | + task_id: str |
| 108 | + container_id: str |
| 109 | + runner_id: str | None |
| 110 | + registered_at: str |
| 111 | + last_seen: str |
| 112 | + |
| 113 | + |
| 114 | +def create_app(service: TaskService) -> FastAPI: |
| 115 | + app = FastAPI(title="panopticon task service", version="0.0.1") |
| 116 | + |
| 117 | + # -- error mapping: domain exceptions -> HTTP status -------------------------- |
| 118 | + |
| 119 | + @app.exception_handler(NotFound) |
| 120 | + async def _not_found(_: Request, exc: NotFound) -> JSONResponse: |
| 121 | + return JSONResponse(status_code=404, content={"detail": str(exc)}) |
| 122 | + |
| 123 | + @app.exception_handler(AlreadyExists) |
| 124 | + async def _conflict(_: Request, exc: AlreadyExists) -> JSONResponse: |
| 125 | + return JSONResponse(status_code=409, content={"detail": str(exc)}) |
| 126 | + |
| 127 | + @app.exception_handler(IllegalTransition) |
| 128 | + async def _illegal(_: Request, exc: IllegalTransition) -> JSONResponse: |
| 129 | + return JSONResponse(status_code=409, content={"detail": str(exc)}) |
| 130 | + |
| 131 | + @app.exception_handler(ResponsibilitiesNotMet) |
| 132 | + async def _responsibilities(_: Request, exc: ResponsibilitiesNotMet) -> JSONResponse: |
| 133 | + return JSONResponse(status_code=409, content={"detail": str(exc)}) |
| 134 | + |
| 135 | + @app.exception_handler(UnknownWorkflow) |
| 136 | + async def _unknown_wf(_: Request, exc: UnknownWorkflow) -> JSONResponse: |
| 137 | + return JSONResponse(status_code=400, content={"detail": str(exc)}) |
| 138 | + |
| 139 | + @app.exception_handler(InvalidWorkflow) |
| 140 | + async def _invalid_wf(_: Request, exc: InvalidWorkflow) -> JSONResponse: |
| 141 | + return JSONResponse(status_code=400, content={"detail": str(exc)}) |
| 142 | + |
| 143 | + @app.exception_handler(ArtifactError) |
| 144 | + async def _artifact(_: Request, exc: ArtifactError) -> JSONResponse: |
| 145 | + return JSONResponse(status_code=400, content={"detail": str(exc)}) |
| 146 | + |
| 147 | + @app.exception_handler(StoreError) |
| 148 | + async def _store_error(_: Request, exc: StoreError) -> JSONResponse: |
| 149 | + return JSONResponse(status_code=409, content={"detail": str(exc)}) |
| 150 | + |
| 151 | + # -- health & discovery ------------------------------------------------------- |
| 152 | + |
| 153 | + @app.get("/healthz") |
| 154 | + async def healthz() -> dict[str, str]: |
| 155 | + return {"status": "ok"} |
| 156 | + |
| 157 | + @app.get("/workflows") |
| 158 | + async def list_workflows() -> list[str]: |
| 159 | + return service.workflow_names() |
| 160 | + |
| 161 | + # -- repos -------------------------------------------------------------------- |
| 162 | + |
| 163 | + @app.post("/repos", status_code=201) |
| 164 | + async def create_repo(body: RepoIn) -> RepoOut: |
| 165 | + repo = service.create_repo(Repo(**body.model_dump())) |
| 166 | + return RepoOut.model_validate(repo) |
| 167 | + |
| 168 | + @app.get("/repos") |
| 169 | + async def list_repos() -> list[RepoOut]: |
| 170 | + return [RepoOut.model_validate(r) for r in service.list_repos()] |
| 171 | + |
| 172 | + @app.get("/repos/{repo_id}") |
| 173 | + async def get_repo(repo_id: str) -> RepoOut: |
| 174 | + return RepoOut.model_validate(service.get_repo(repo_id)) |
| 175 | + |
| 176 | + # -- tasks -------------------------------------------------------------------- |
| 177 | + |
| 178 | + @app.post("/tasks", status_code=201) |
| 179 | + async def create_task(body: CreateTaskIn) -> TaskOut: |
| 180 | + return TaskOut.model_validate(service.create_task(body.repo_id, body.workflow)) |
| 181 | + |
| 182 | + @app.get("/tasks") |
| 183 | + async def list_tasks() -> list[TaskOut]: |
| 184 | + return [TaskOut.model_validate(t) for t in service.list_tasks()] |
| 185 | + |
| 186 | + @app.get("/tasks/{task_id}") |
| 187 | + async def get_task(task_id: str) -> TaskOut: |
| 188 | + return TaskOut.model_validate(service.get_task(task_id)) |
| 189 | + |
| 190 | + @app.post("/tasks/{task_id}/transition") |
| 191 | + async def transition(task_id: str, body: TransitionIn) -> TaskOut: |
| 192 | + return TaskOut.model_validate( |
| 193 | + service.request_transition( |
| 194 | + task_id, body.to_state, trigger=body.trigger, note=body.note |
| 195 | + ) |
| 196 | + ) |
| 197 | + |
| 198 | + @app.post("/tasks/{task_id}/responsibilities") |
| 199 | + async def resolve_responsibility(task_id: str, body: ResponsibilityIn) -> TaskOut: |
| 200 | + try: |
| 201 | + task = service.resolve_responsibility( |
| 202 | + task_id, body.key, status=body.status, comment=body.comment |
| 203 | + ) |
| 204 | + except ValueError as exc: # unknown key / PENDING / FAILED without a comment |
| 205 | + raise HTTPException(status_code=400, detail=str(exc)) from exc |
| 206 | + return TaskOut.model_validate(task) |
| 207 | + |
| 208 | + @app.put("/tasks/{task_id}/slug") |
| 209 | + async def set_slug(task_id: str, body: SlugIn) -> TaskOut: |
| 210 | + return TaskOut.model_validate(service.set_slug(task_id, body.slug)) |
| 211 | + |
| 212 | + # -- artifacts ---------------------------------------------------------------- |
| 213 | + |
| 214 | + @app.put("/tasks/{task_id}/artifacts/{name}", status_code=204) |
| 215 | + async def put_artifact(task_id: str, name: str, request: Request) -> Response: |
| 216 | + service.put_artifact(task_id, name, await request.body()) |
| 217 | + return Response(status_code=204) |
| 218 | + |
| 219 | + @app.get("/tasks/{task_id}/artifacts") |
| 220 | + async def list_artifacts(task_id: str) -> list[str]: |
| 221 | + return service.list_artifacts(task_id) |
| 222 | + |
| 223 | + @app.get("/tasks/{task_id}/artifacts/{name}") |
| 224 | + async def get_artifact(task_id: str, name: str) -> Response: |
| 225 | + content = service.get_artifact(task_id, name) |
| 226 | + if content is None: |
| 227 | + raise HTTPException(status_code=404, detail=f"artifact {name!r} not found") |
| 228 | + return Response(content=content, media_type="application/octet-stream") |
| 229 | + |
| 230 | + # -- liveness ----------------------------------------------------------------- |
| 231 | + |
| 232 | + @app.post("/tasks/{task_id}/registrations", status_code=201) |
| 233 | + async def register(task_id: str, body: RegisterIn) -> RegistrationOut: |
| 234 | + return RegistrationOut.model_validate( |
| 235 | + service.register(task_id, body.container_id, body.runner_id) |
| 236 | + ) |
| 237 | + |
| 238 | + @app.get("/tasks/{task_id}/registrations") |
| 239 | + async def list_registrations(task_id: str) -> list[RegistrationOut]: |
| 240 | + service.get_task(task_id) # 404 if the task is unknown |
| 241 | + return [RegistrationOut.model_validate(r) for r in service.registrations(task_id)] |
| 242 | + |
| 243 | + @app.post("/registrations/{registration_id}/heartbeat") |
| 244 | + async def heartbeat(registration_id: str) -> RegistrationOut: |
| 245 | + return RegistrationOut.model_validate(service.heartbeat(registration_id)) |
| 246 | + |
| 247 | + @app.delete("/registrations/{registration_id}", status_code=204) |
| 248 | + async def deregister(registration_id: str) -> Response: |
| 249 | + service.deregister(registration_id) |
| 250 | + return Response(status_code=204) |
| 251 | + |
| 252 | + return app |
0 commit comments