2026-11-10 23:56:50 +08:00
|
|
|
"""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
|
2026-11-14 14:07:26 +08:00
|
|
|
import hashlib
|
2026-11-10 23:56:50 +08:00
|
|
|
import hmac
|
|
|
|
|
import mimetypes
|
|
|
|
|
import os
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
from urllib.parse import quote
|
|
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
|
2026-11-10 23:56:50 +08:00
|
|
|
from fastapi.responses import StreamingResponse
|
2026-11-14 14:07:26 +08:00
|
|
|
from starlette.requests import ClientDisconnect
|
2026-11-10 23:56:50 +08:00
|
|
|
from pydantic import BaseModel, Field, ConfigDict
|
|
|
|
|
from typing import Literal
|
|
|
|
|
import time
|
|
|
|
|
from .scheduling import normalize_scheduling, policy_status
|
2026-11-14 14:07:26 +08:00
|
|
|
from .remote_bridge import INPUT_NAME, input_writer, runtime_status
|
|
|
|
|
from .reference_profiles import capabilities as reference_capabilities, validate_submission
|
|
|
|
|
|
|
|
|
|
from .video_edit.profiles import capabilities as video_capabilities
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
from .store import (IdempotencyConflict, Settings, confined_path, initialize_store,
|
|
|
|
|
open_confined_file, validate_request)
|
|
|
|
|
|
|
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
MAX_INPUT_BYTES = 512 * 1024 * 1024
|
|
|
|
|
|
|
|
|
|
|
2026-11-10 23:56:50 +08:00
|
|
|
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),
|
2026-11-11 10:59:33 +08:00
|
|
|
"runner_marker_present": bool(configuration.active_markers())}
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
@application.get("/capabilities", dependencies=secured)
|
|
|
|
|
def capabilities():
|
2026-11-26 21:06:27 +08:00
|
|
|
from .video_profiles import capabilities as video_generation_capabilities
|
2026-11-10 23:56:50 +08:00
|
|
|
return {"protocol_version": 2, "admission_policy": True,
|
2026-11-26 21:06:27 +08:00
|
|
|
'video_generation': video_generation_capabilities(application.state.settings),
|
2026-11-14 14:07:26 +08:00
|
|
|
"reference_generation": reference_capabilities(application.state.settings),
|
|
|
|
|
"video_edit": video_capabilities(application.state.settings),
|
2026-11-10 23:56:50 +08:00
|
|
|
"features": {"scheduling": True, "admission_pause": True, "control_versions": True,
|
2026-11-26 21:06:27 +08:00
|
|
|
"project_gpu_window": True,
|
2026-11-10 23:56:50 +08:00
|
|
|
"result_manifest": True, "final_output_indices": True, "forced_window_stop": False},
|
2026-11-11 00:36:30 +08:00
|
|
|
"execution_policy": policy_status(time.time(), policy_file=application.state.settings.runtime_policy_file)}
|
2026-11-10 23:56:50 +08:00
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
@application.get('/runtime/status', dependencies=secured)
|
|
|
|
|
def remote_runtime_status():
|
|
|
|
|
return runtime_status(application.state.settings)
|
|
|
|
|
|
|
|
|
|
@application.post('/inputs/{name}', status_code=201, dependencies=secured)
|
|
|
|
|
async def upload_input(name: str, request: Request):
|
|
|
|
|
match = INPUT_NAME.fullmatch(name)
|
|
|
|
|
if match is None:
|
|
|
|
|
raise HTTPException(422, 'Input name must be a SHA-256 digest and supported media suffix')
|
|
|
|
|
if request.headers.get('content-type', '').split(';', 1)[0].strip().lower() != 'application/octet-stream':
|
|
|
|
|
raise HTTPException(415, 'Expected application/octet-stream')
|
|
|
|
|
declared = request.headers.get('content-length')
|
|
|
|
|
if declared is not None:
|
|
|
|
|
if not declared.isascii() or not declared.isdigit() or len(declared) > 20:
|
|
|
|
|
raise HTTPException(400, 'Invalid input length')
|
|
|
|
|
declared = int(declared)
|
|
|
|
|
if declared > MAX_INPUT_BYTES:
|
|
|
|
|
raise HTTPException(413, 'Input exceeds the transfer size limit')
|
|
|
|
|
digest, size = hashlib.sha256(), 0
|
|
|
|
|
try:
|
|
|
|
|
with input_writer(application.state.settings.workspace_root, name) as (stream, target):
|
|
|
|
|
async for chunk in request.stream():
|
|
|
|
|
size += len(chunk)
|
|
|
|
|
if size > MAX_INPUT_BYTES:
|
|
|
|
|
raise HTTPException(413, 'Input exceeds the transfer size limit')
|
|
|
|
|
if declared is not None and size > declared:
|
|
|
|
|
raise HTTPException(400, 'Input length does not match the transfer')
|
|
|
|
|
digest.update(chunk)
|
|
|
|
|
stream.write(chunk)
|
|
|
|
|
if declared is not None and size != declared:
|
|
|
|
|
raise HTTPException(400, 'Input length does not match the transfer')
|
|
|
|
|
if not size or not hmac.compare_digest(digest.hexdigest(), match[1]):
|
|
|
|
|
raise HTTPException(422, 'Input is empty or its SHA-256 digest does not match')
|
|
|
|
|
return {'path': str(target), 'sha256': digest.hexdigest(), 'size_bytes': size}
|
|
|
|
|
except ClientDisconnect:
|
|
|
|
|
raise HTTPException(400, 'Input transfer was interrupted') from None
|
|
|
|
|
except (OSError, ValueError):
|
|
|
|
|
raise HTTPException(503, 'Input storage is unavailable') from None
|
|
|
|
|
|
2026-11-10 23:56:50 +08:00
|
|
|
@application.post("/jobs", status_code=202, dependencies=secured)
|
|
|
|
|
def submit(body: Submission, idempotency_key: str | None = Header(default=None)):
|
|
|
|
|
configuration = application.state.settings
|
|
|
|
|
try:
|
2026-11-14 14:07:26 +08:00
|
|
|
if body.task_type == "image.reference.generate":
|
|
|
|
|
validate_submission(configuration, body.input, body.parameters)
|
2026-11-26 21:06:27 +08:00
|
|
|
if body.task_type == 'video.generate':
|
|
|
|
|
from .video_profiles import validate_submission as validate_generation
|
|
|
|
|
validate_generation(configuration, body.parameters)
|
2026-11-10 23:56:50 +08:00
|
|
|
inputs, parameters = validate_request(body.task_type, body.input, body.parameters,
|
|
|
|
|
configuration.workspace_root)
|
2026-11-14 14:07:26 +08:00
|
|
|
if body.task_type in {"video.people.analyze", "video.replace"}:
|
|
|
|
|
from .video_edit.profiles import validate_submission as validate_video
|
|
|
|
|
from .video_edit.bindings import principal, analysis_manifest
|
|
|
|
|
validate_video(configuration, inputs, parameters)
|
|
|
|
|
if body.task_type == "video.replace":
|
|
|
|
|
analysis_manifest(configuration, application.state.store, inputs, parameters,
|
|
|
|
|
principal(configuration, normalize_scheduling(body.scheduling)))
|
2026-11-10 23:56:50 +08:00
|
|
|
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()
|