166 lines
7.1 KiB
Python
166 lines
7.1 KiB
Python
"""Authenticated asynchronous jobs API, with no model/GPU imports.
|
|
|
|
Launch via ``uvicorn llm_services.api:app --host 0.0.0.0 --port 18190`` inside
|
|
the restricted container; publish only to host loopback during deployment.
|
|
"""
|
|
from contextlib import asynccontextmanager
|
|
import hmac
|
|
import mimetypes
|
|
import os
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
from fastapi import Depends, FastAPI, Header, HTTPException, Query
|
|
from fastapi.responses import StreamingResponse
|
|
from pydantic import BaseModel, Field, ConfigDict
|
|
from typing import Literal
|
|
import time
|
|
from .scheduling import normalize_scheduling, policy_status
|
|
|
|
from .store import (IdempotencyConflict, Settings, confined_path, initialize_store,
|
|
open_confined_file, validate_request)
|
|
|
|
|
|
class Submission(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
task_type: str
|
|
input: dict = Field(default_factory=dict)
|
|
parameters: dict = Field(default_factory=dict)
|
|
timeout_seconds: float = Field(default=3600, gt=0, le=86400)
|
|
scheduling: dict | None = None
|
|
|
|
|
|
class Control(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
desired_state: Literal['run', 'pause', 'cancel']
|
|
command_id: str = Field(min_length=1, max_length=128)
|
|
expected_execution_id: str | None = Field(default=None, max_length=64)
|
|
expected_version: int | None = Field(default=None, ge=0)
|
|
|
|
|
|
def create_app(settings=None):
|
|
@asynccontextmanager
|
|
async def lifespan(application):
|
|
application.state.settings = settings or Settings.from_env()
|
|
application.state.store = initialize_store(application.state.settings)
|
|
yield
|
|
|
|
application = FastAPI(title="Workspace LLM Jobs", docs_url=None, redoc_url=None,
|
|
openapi_url=None, lifespan=lifespan)
|
|
|
|
def authenticate(authorization: str | None = Header(default=None),
|
|
x_api_key: str | None = Header(default=None)):
|
|
configuration = application.state.settings
|
|
try:
|
|
with open_confined_file(configuration.key_file, configuration.workspace_root) as handle:
|
|
expected = handle.read(4097).decode("utf-8").strip()
|
|
if not expected or len(expected) > 4096:
|
|
raise ValueError("Invalid key file")
|
|
except (OSError, ValueError, UnicodeError):
|
|
raise HTTPException(503, "API authentication is not configured")
|
|
supplied = x_api_key or ""
|
|
if authorization and authorization.startswith("Bearer "):
|
|
supplied = authorization[7:]
|
|
if not hmac.compare_digest(supplied.encode(), expected.encode()):
|
|
raise HTTPException(401, "Invalid API key", headers={"WWW-Authenticate": "Bearer"})
|
|
|
|
secured = [Depends(authenticate)]
|
|
|
|
def get_job(job_id):
|
|
job = application.state.store.get(job_id)
|
|
if job is None:
|
|
raise HTTPException(404, "Job not found")
|
|
return job
|
|
|
|
@application.get("/health", dependencies=secured)
|
|
def health():
|
|
configuration = application.state.settings
|
|
unresolved = application.state.store.running()
|
|
return {"status": "ok", "running_jobs": len(unresolved),
|
|
"runner_marker_present": bool(configuration.active_markers())}
|
|
|
|
@application.get("/capabilities", dependencies=secured)
|
|
def capabilities():
|
|
return {"protocol_version": 2, "admission_policy": True,
|
|
"features": {"scheduling": True, "admission_pause": True, "control_versions": True,
|
|
"result_manifest": True, "final_output_indices": True, "forced_window_stop": False},
|
|
"execution_policy": policy_status(time.time(), policy_file=application.state.settings.runtime_policy_file)}
|
|
|
|
@application.post("/jobs", status_code=202, dependencies=secured)
|
|
def submit(body: Submission, idempotency_key: str | None = Header(default=None)):
|
|
configuration = application.state.settings
|
|
try:
|
|
inputs, parameters = validate_request(body.task_type, body.input, body.parameters,
|
|
configuration.workspace_root)
|
|
return application.state.store.submit(body.task_type, inputs, parameters,
|
|
body.timeout_seconds, idempotency_key=idempotency_key,
|
|
scheduling=normalize_scheduling(body.scheduling))
|
|
except IdempotencyConflict as exc:
|
|
raise HTTPException(409, str(exc))
|
|
except (ValueError, TypeError, OSError) as exc:
|
|
raise HTTPException(422, str(exc))
|
|
|
|
@application.get("/jobs/{job_id}", dependencies=secured)
|
|
def query(job_id: str):
|
|
return get_job(job_id)
|
|
|
|
@application.post("/jobs/{job_id}/cancel", status_code=202, dependencies=secured)
|
|
def cancel(job_id: str):
|
|
get_job(job_id)
|
|
return application.state.store.cancel(job_id)
|
|
|
|
@application.put("/jobs/{job_id}/control", status_code=202, dependencies=secured)
|
|
def control(job_id: str, body: Control):
|
|
get_job(job_id)
|
|
try:
|
|
return application.state.store.control(job_id, body.desired_state,
|
|
command_id=body.command_id, expected_execution_id=body.expected_execution_id,
|
|
expected_version=body.expected_version)
|
|
except IdempotencyConflict as exc:
|
|
raise HTTPException(409, str(exc))
|
|
except ValueError as exc:
|
|
raise HTTPException(422, str(exc))
|
|
|
|
def output_response(job_id, index):
|
|
job = get_job(job_id)
|
|
if job["state"] != "succeeded":
|
|
raise HTTPException(409, "Results are available only for succeeded jobs")
|
|
outputs = (job.get("result") or {}).get("outputs", [])
|
|
if index < 0 or index >= len(outputs):
|
|
raise HTTPException(404, "Output not found")
|
|
item = outputs[index]
|
|
path = item.get("path") if isinstance(item, dict) else item
|
|
configuration = application.state.settings
|
|
try:
|
|
output_dir = confined_path(configuration.outputs_dir / job_id,
|
|
configuration.workspace_root, must_exist=True)
|
|
handle = open_confined_file(path, output_dir)
|
|
except (ValueError, OSError, TypeError):
|
|
raise HTTPException(404, "Output is unavailable or outside its job directory")
|
|
size = os.fstat(handle.fileno()).st_size
|
|
name = Path(path).name
|
|
|
|
def chunks():
|
|
try:
|
|
while data := handle.read(1024 * 1024):
|
|
yield data
|
|
finally:
|
|
handle.close()
|
|
|
|
return StreamingResponse(chunks(), media_type=mimetypes.guess_type(name)[0] or "application/octet-stream",
|
|
headers={"Content-Length": str(size),
|
|
"Content-Disposition": "attachment; filename*=UTF-8''" + quote(name, safe="")})
|
|
|
|
@application.get("/jobs/{job_id}/outputs/{index}", dependencies=secured)
|
|
def download_output(job_id: str, index: int):
|
|
return output_response(job_id, index)
|
|
|
|
@application.get("/jobs/{job_id}/download", dependencies=secured)
|
|
def download(job_id: str, index: int = Query(default=0, ge=0)):
|
|
return output_response(job_id, index)
|
|
|
|
return application
|
|
|
|
|
|
app = create_app()
|