from collections.abc import Awaitable, Callable, Sequence from typing import Any from plba.health.aggregator import HealthAggregator, HealthInputInvalid from plba.http.asgi import ASGIHttpTransport from plba.http.errors import ControlRequestError from plba.http.requests import StopRequest from plba.http.routes import ( ASGIScope, ASGIReceive, ASGISend, HttpRoute, HttpRouter, MethodNotAllowed, RouteNotFound, ) from plba.http.serialization import health_report_payload from plba.runtime.application import ApplicationRuntime, RuntimeLifecycleError _ControlAction = Callable[ [ASGIScope, ASGIReceive], Awaitable[tuple[int, dict[str, Any]]] ] class ControlApi: """ASGI route adapter; it owns no server, socket, or listener.""" def __init__( self, runtime: ApplicationRuntime, health_aggregator: HealthAggregator, application_routes: Sequence[HttpRoute] = (), ) -> None: self._runtime = runtime self._health_aggregator = health_aggregator self._transport = ASGIHttpTransport() routes = ( HttpRoute("GET", "/api/v1/health", self._handle_health), HttpRoute("POST", "/api/v1/runtime/start", self._handle_start), HttpRoute("POST", "/api/v1/runtime/stop", self._handle_stop), HttpRoute("GET", "/api/v1/runtime/status", self._handle_status), *application_routes, ) self._router = HttpRouter(routes) async def __call__(self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend) -> None: scope_type = scope.get("type") if scope_type == "lifespan": await self._transport.handle_lifespan(receive, send) return if scope_type != "http": return try: match = self._router.resolve(scope.get("method", ""), scope.get("path", "")) except RouteNotFound: await self._send_routing_error(send, 404, "HTTP_ROUTE_NOT_FOUND") return except MethodNotAllowed: await self._send_routing_error(send, 405, "HTTP_METHOD_NOT_ALLOWED") return route_scope = dict(scope) route_scope["path_params"] = match.path_params await match.route.handler(route_scope, receive, send) async def _handle_health( self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend ) -> None: await self._execute_control_action(self._health_action, scope, receive, send) async def _handle_start( self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend ) -> None: await self._execute_control_action(self._start_action, scope, receive, send) async def _handle_stop( self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend ) -> None: await self._execute_control_action(self._stop_action, scope, receive, send) async def _handle_status( self, scope: ASGIScope, receive: ASGIReceive, send: ASGISend ) -> None: await self._execute_control_action(self._status_action, scope, receive, send) async def _execute_control_action( self, action: _ControlAction, scope: ASGIScope, receive: ASGIReceive, send: ASGISend, ) -> None: try: status, payload = await action(scope, receive) except HealthInputInvalid as error: status, payload = 500, self._error("HEALTH_INPUT_INVALID", error) except RuntimeLifecycleError as error: status, payload = 409, self._error("APPLICATION_CONTROL_CONFLICT", error) except ControlRequestError as error: status, payload = 400, self._error("HTTP_CONTROL_REJECTED", error) except Exception as error: status, payload = 500, self._error("CONTROL_API_FAILED", error) await self._transport.send_json(send, status, payload) async def _health_action( self, scope: ASGIScope, receive: ASGIReceive ) -> tuple[int, dict[str, Any]]: self._require_no_query(scope) await self._require_empty_body(receive) report = await self._health_aggregator.aggregate() return 200, health_report_payload(report) async def _start_action( self, scope: ASGIScope, receive: ASGIReceive ) -> tuple[int, dict[str, Any]]: self._require_no_query(scope) await self._require_empty_body(receive) result = await self._runtime.start() return 200, {"status": result.lifecycle.value} async def _stop_action( self, scope: ASGIScope, receive: ASGIReceive ) -> tuple[int, dict[str, Any]]: self._require_no_query(scope) request = StopRequest.parse(await self._transport.read_body(receive)) result = await self._runtime.stop( force=request.force, timeout_seconds=request.timeout_seconds ) status = 200 if result.lifecycle.value == "stopped" else 202 return status, {"status": result.lifecycle.value} async def _status_action( self, scope: ASGIScope, receive: ASGIReceive ) -> tuple[int, dict[str, Any]]: self._require_no_query(scope) await self._require_empty_body(receive) return 200, {"status": self._runtime.lifecycle.value} async def _require_empty_body(self, receive: ASGIReceive) -> None: if await self._transport.read_body(receive): raise ControlRequestError("request body is not accepted") @staticmethod def _require_no_query(scope: ASGIScope) -> None: if scope.get("query_string", b""): raise ControlRequestError("query parameters are not accepted") async def _send_routing_error( self, send: ASGISend, status: int, code: str ) -> None: await self._transport.send_json(send, status, self._error(code, code)) @staticmethod def _error(code: str, error: Exception | str) -> dict[str, str]: return {"error": code, "message": str(error)}