254 lines
13 KiB
Python
254 lines
13 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 hashlib
|
||
import hmac
|
||
import mimetypes
|
||
import os
|
||
from pathlib import Path
|
||
from urllib.parse import quote
|
||
|
||
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
|
||
from fastapi.responses import StreamingResponse
|
||
from starlette.requests import ClientDisconnect
|
||
from pydantic import BaseModel, Field, ConfigDict
|
||
from typing import Literal
|
||
import time
|
||
from .scheduling import normalize_scheduling, policy_status
|
||
from .remote_bridge import INPUT_NAME, input_writer, runtime_status
|
||
from .reference_profiles import capabilities as reference_capabilities, validate_submission
|
||
|
||
from .dialogue import KEYS as DIALOGUE_TASKS
|
||
from .dialogue.profiles import capabilities as dialogue_capabilities, admit as admit_dialogue
|
||
from .video_edit.profiles import capabilities as video_capabilities
|
||
|
||
from .store import (IdempotencyConflict, Settings, confined_path, initialize_store,
|
||
open_confined_file, validate_request)
|
||
|
||
|
||
MAX_INPUT_BYTES = 512 * 1024 * 1024
|
||
|
||
|
||
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():
|
||
from .video_profiles import capabilities as video_generation_capabilities
|
||
return {"protocol_version": 2, "admission_policy": True,
|
||
'video_generation': video_generation_capabilities(application.state.settings),
|
||
"reference_generation": reference_capabilities(application.state.settings),
|
||
"video_edit": video_capabilities(application.state.settings),
|
||
"dialogue": dialogue_capabilities(application.state.settings),
|
||
"features": {"scheduling": True, "admission_pause": True, "control_versions": True,
|
||
"project_gpu_window": 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.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
|
||
|
||
@application.post("/jobs", status_code=202, dependencies=secured)
|
||
def submit(body: Submission, idempotency_key: str | None = Header(default=None)):
|
||
configuration = application.state.settings
|
||
try:
|
||
if body.task_type == "image.reference.generate":
|
||
validate_submission(configuration, body.input, body.parameters)
|
||
if body.task_type == 'video.generate':
|
||
from .video_profiles import validate_submission as validate_generation, is_native_av
|
||
if not is_native_av(body.parameters):
|
||
validate_generation(configuration, body.parameters)
|
||
inputs, parameters = validate_request(body.task_type, body.input, body.parameters,
|
||
configuration.workspace_root)
|
||
if body.task_type == 'video.generate' and is_native_av(parameters):
|
||
schedule = normalize_scheduling(body.scheduling) or {}
|
||
# 认证收窄不能切断已有请求的幂等恢复;同owner及完整冻结请求才返回旧ID。
|
||
# 查无匹配时仍走当前画布准入;worker执行前也会按当前认证重新检查。
|
||
if idempotency_key:
|
||
existing = application.state.store.submit(
|
||
body.task_type, inputs, parameters, body.timeout_seconds,
|
||
idempotency_key=idempotency_key, scheduling=normalize_scheduling(body.scheduling),
|
||
recover_only=True,
|
||
)
|
||
if existing is not None:
|
||
return existing
|
||
# 路径与参数通过规范化验证后,再按已审计画布准入;worker派发前会再次检查。
|
||
validate_generation(configuration, parameters, inputs, principal=schedule.get('principal_id'),
|
||
idempotency_key=idempotency_key)
|
||
if body.task_type in DIALOGUE_TASKS:
|
||
schedule=normalize_scheduling(body.scheduling) or {}
|
||
admit_dialogue(configuration,body.task_type,parameters,inputs,
|
||
principal=schedule.get("principal_id"),idempotency_key=idempotency_key)
|
||
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)))
|
||
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()
|