feat(simulation): add Worker AI polygon runtime and terrain navigation
This commit is contained in:
@@ -0,0 +1,231 @@
|
||||
"""Control Station and authenticated simulation-worker ports for AI polygon."""
|
||||
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Request, Response
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
|
||||
from k1link.simulation.ai_polygon.composition import compose, registry
|
||||
from k1link.simulation.ai_polygon.contracts import (
|
||||
RealtimeSnapshot,
|
||||
RunApplied,
|
||||
RunCreate,
|
||||
RunProgress,
|
||||
RunSample,
|
||||
ViewControl,
|
||||
WorkerHello,
|
||||
WorkerPoll,
|
||||
WorkerResult,
|
||||
WorkerWorldCreate,
|
||||
WorldCreate,
|
||||
WorldSettings,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.runs import RunStore
|
||||
from k1link.simulation.ai_polygon.worlds import CHUNK_BYTES, SOURCES, WorldStore
|
||||
|
||||
|
||||
def build_ai_polygon_router(
|
||||
data_dir: Path, queue: ObservatoryRecordedJobQueue | None = None
|
||||
) -> APIRouter:
|
||||
worlds = WorldStore(data_dir)
|
||||
runs = RunStore(worlds, queue)
|
||||
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
|
||||
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
|
||||
|
||||
def invoke(fn, *args):
|
||||
try:
|
||||
return fn(*args)
|
||||
except FileNotFoundError as exc:
|
||||
raise HTTPException(404, "Локация или прогон не найдены.") from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
def authenticate(authorization: str | None) -> None:
|
||||
expected = f"Bearer {runs.token}"
|
||||
if not authorization or not secrets.compare_digest(authorization, expected):
|
||||
raise HTTPException(401, "Worker authentication required")
|
||||
|
||||
@router.get("/catalog")
|
||||
def catalog():
|
||||
return {
|
||||
"schema_version": "missioncore.ai-polygon-catalog/v1",
|
||||
"sources": SOURCES,
|
||||
"worlds": worlds.list(),
|
||||
"runtime": runs.status(),
|
||||
"runs": runs.list()[:30],
|
||||
}
|
||||
|
||||
@router.post("/worlds", status_code=201)
|
||||
def create_world(body: WorldCreate):
|
||||
return invoke(worlds.create, body)
|
||||
|
||||
@router.get("/worlds/{world_id}")
|
||||
def get_world(world_id: str):
|
||||
return invoke(worlds.get, world_id)
|
||||
|
||||
@router.get("/worlds/{world_id}/upload-prefix")
|
||||
def upload_prefix(world_id: str):
|
||||
return invoke(worlds.prefix_hashes, world_id)
|
||||
|
||||
@router.patch("/worlds/{world_id}/source")
|
||||
async def upload(
|
||||
world_id: str, request: Request, upload_offset: int = Header(alias="Upload-Offset", ge=0)
|
||||
):
|
||||
data = bytearray()
|
||||
async for block in request.stream():
|
||||
if len(data) + len(block) > CHUNK_BYTES:
|
||||
raise HTTPException(413, "Фрагмент загрузки превышает 4 МБ.")
|
||||
data.extend(block)
|
||||
return invoke(worlds.append, world_id, upload_offset, bytes(data))
|
||||
|
||||
@router.post("/worlds/{world_id}/complete")
|
||||
def complete(world_id: str):
|
||||
return invoke(worlds.complete, world_id)
|
||||
|
||||
@router.put("/worlds/{world_id}/settings")
|
||||
def settings(world_id: str, body: WorldSettings):
|
||||
return invoke(worlds.configure, world_id, body)
|
||||
|
||||
@router.get("/worlds/{world_id}/source.ply")
|
||||
def source(world_id: str):
|
||||
row = invoke(worlds.get, world_id)
|
||||
if row["status"] != "available":
|
||||
raise HTTPException(409, "Импорт не завершён.")
|
||||
if row.get("storage", {}).get("kind") == "worker":
|
||||
raise HTTPException(409, "Исходник локации хранится на Worker.")
|
||||
return FileResponse(
|
||||
worlds.directory(world_id) / "source.ply",
|
||||
media_type="application/octet-stream",
|
||||
headers={
|
||||
"ETag": f'"{row["sha256"]}"',
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
},
|
||||
)
|
||||
|
||||
@router.post("/runs", status_code=201)
|
||||
def start(body: RunCreate, idempotency_key: str = Header(alias="Idempotency-Key")):
|
||||
if body.clock == "realtime":
|
||||
graph = invoke(compose, adapters, body.composition)
|
||||
body = body.model_copy(update={"composition": graph.selection_document()})
|
||||
return invoke(runs.start, body, idempotency_key)
|
||||
|
||||
@router.get("/ai-modules")
|
||||
def modules():
|
||||
installed = invoke(registry, adapters)
|
||||
graph = invoke(compose, adapters)
|
||||
return {
|
||||
"catalog": {**installed.catalog(), "authority": "virtual-only"},
|
||||
"selection": graph.selection_document(),
|
||||
"composition_sha256": graph.sha256,
|
||||
}
|
||||
|
||||
@router.get("/runs/{run_id}")
|
||||
def get_run(run_id: str):
|
||||
runs.status()
|
||||
return invoke(runs.get, run_id)
|
||||
|
||||
@router.post("/runs/{run_id}/{command}")
|
||||
def control(run_id: str, command: Literal["pause", "play", "step", "stop"]):
|
||||
return invoke(runs.control, run_id, command)
|
||||
|
||||
@router.get("/runs/{run_id}/frames/{sequence}.jpg")
|
||||
def frame(run_id: str, sequence: int):
|
||||
row = invoke(runs.get, run_id)
|
||||
if not 0 <= sequence < row["samples"]:
|
||||
raise HTTPException(404, "Кадр не найден.")
|
||||
return FileResponse(
|
||||
runs.directory(run_id) / "frames" / f"{sequence:06d}.jpg",
|
||||
media_type="image/jpeg",
|
||||
headers={"Cache-Control": "private, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
@router.put("/runs/{run_id}/view")
|
||||
def view(run_id: str, body: ViewControl):
|
||||
return invoke(runs.view, run_id, body.camera)
|
||||
|
||||
@router.get("/runs/{run_id}/decisions")
|
||||
def decisions(run_id: str):
|
||||
directory = invoke(runs.directory, run_id)
|
||||
path = directory / "decisions.jsonl"
|
||||
if not path.exists():
|
||||
return Response("", media_type="application/x-ndjson")
|
||||
return FileResponse(path, media_type="application/x-ndjson", filename="decisions.jsonl")
|
||||
|
||||
@router.post("/worker/register")
|
||||
def register(body: WorkerHello, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.register, body)
|
||||
|
||||
@router.post("/worker/worlds", status_code=201)
|
||||
def register_worker_world(
|
||||
body: WorkerWorldCreate,
|
||||
authorization: str | None = Header(default=None),
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
):
|
||||
authenticate(authorization)
|
||||
with runs.lock:
|
||||
invoke(runs.heartbeat, instance_id)
|
||||
worker = runs.status()["worker"]
|
||||
return invoke(worlds.register_worker_asset, body, worker["worker_id"])
|
||||
|
||||
@router.post("/worker/heartbeat")
|
||||
def heartbeat(body: WorkerPoll, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.heartbeat, body.instance_id)
|
||||
|
||||
@router.post("/worker/poll")
|
||||
def poll(body: WorkerPoll, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.poll, body.instance_id, body.run_id)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/progress")
|
||||
def progress(
|
||||
run_id: str,
|
||||
body: RunProgress,
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.progress, run_id, instance_id, body.phase)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/samples")
|
||||
def sample(
|
||||
run_id: str,
|
||||
body: RunSample,
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.sample, run_id, instance_id, body)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/snapshot")
|
||||
def snapshot(
|
||||
run_id: str,
|
||||
body: RealtimeSnapshot,
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.snapshot, run_id, instance_id, body)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/finish")
|
||||
def finish(run_id: str, body: WorkerResult, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.finish, run_id, body.instance_id, body.outcome, body.message)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/applied")
|
||||
def applied(
|
||||
run_id: str,
|
||||
body: RunApplied,
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.applied, run_id, instance_id, body)
|
||||
|
||||
return router
|
||||
@@ -238,6 +238,7 @@ from k1link.missions.registration_runs import RegistrationRuns
|
||||
from k1link.web.mission_registration_api import build_mission_registration_router
|
||||
from k1link.web.mission_planner_api import build_mission_planner_router
|
||||
from k1link.web.simulation_projects_api import build_simulation_projects_router
|
||||
from k1link.web.ai_polygon_api import build_ai_polygon_router
|
||||
from k1link.web.simulation_world_provider_api import build_simulation_world_provider_router
|
||||
from k1link.web.system_telemetry_api import build_system_telemetry_router
|
||||
from k1link.web.vegetation_shadow_lab_api import (
|
||||
@@ -1996,6 +1997,10 @@ app.include_router(
|
||||
)
|
||||
)
|
||||
frontend_dist = REPOSITORY_ROOT / "apps" / "control-station" / "dist"
|
||||
try:
|
||||
app.include_router(build_ai_polygon_router(session_store.data_dir, OBSERVATORY_RECORDED_JOB_QUEUE))
|
||||
except (OSError, ValueError):
|
||||
logging.getLogger(__name__).exception("AI polygon could not load its private runtime state")
|
||||
app.include_router(
|
||||
build_viewer_diagnostics_router(
|
||||
expected_ui_build_id=lambda: frontend_build_id(frontend_dist),
|
||||
|
||||
Reference in New Issue
Block a user