PLBA2-4. Доработка регистрации http эндпоинтов
PLBA package CI / Python tests (push) Successful in 23s
PLBA package CI / Package version increment (push) Skipped

This commit is contained in:
2026-10-11 10:44:59 +03:00
parent a0d2db6bd0
commit d46993a092
30 changed files with 1666 additions and 583 deletions
+113 -38
View File
@@ -1,32 +1,98 @@
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
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: dict[str, Any], receive: Any, send: Any) -> None:
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:
status, payload = await self._dispatch(scope, receive)
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:
@@ -37,45 +103,54 @@ class ControlApi:
status, payload = 500, self._error("CONTROL_API_FAILED", error)
await self._transport.send_json(send, status, payload)
async def _dispatch(self, scope: dict[str, Any], receive: Any) -> tuple[int, dict[str, Any]]:
method = scope.get("method", "").upper()
path = scope.get("path", "")
query = scope.get("query_string", b"")
if path in {"/health", "/runtime/status", "/runtime/start", "/runtime/stop"} and query:
raise ControlRequestError("query parameters are not accepted")
if path == "/health":
if method != "GET":
return 405, self._error("METHOD_NOT_ALLOWED", "GET required")
await self._require_empty_body(receive)
report = await self._health_aggregator.aggregate()
return 200, health_report_payload(report)
if path == "/runtime/start":
if method != "POST":
return 405, self._error("METHOD_NOT_ALLOWED", "POST required")
await self._require_empty_body(receive)
result = await self._runtime.start()
return 200, {"status": result.lifecycle.value}
if path == "/runtime/status":
if method != "GET":
return 405, self._error("METHOD_NOT_ALLOWED", "GET required")
await self._require_empty_body(receive)
return 200, {"status": self._runtime.lifecycle.value}
if path == "/runtime/stop":
if method != "POST":
return 405, self._error("METHOD_NOT_ALLOWED", "POST required")
request = StopRequest.parse(await self._transport.read_body(receive))
result = await self._runtime.stop(
force=request.force, timeout_seconds=request.timeout_seconds
)
status_code = 200 if result.lifecycle.value == "stopped" else 202
return status_code, {"status": result.lifecycle.value}
return 404, self._error("NOT_FOUND", "control route not found")
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 _require_empty_body(self, receive: Any) -> None:
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)}