PLBA2-4. Доработка регистрации http эндпоинтов
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
from plba.http.control_api import ControlApi
|
||||
from plba.http.routes import HttpRoute
|
||||
|
||||
__all__ = ["ControlApi"]
|
||||
__all__ = ["ControlApi", "HttpRoute"]
|
||||
|
||||
+113
-38
@@ -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)}
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Typed route definitions and deterministic ASGI path matching."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
ASGIScope = dict[str, Any]
|
||||
ASGIMessage = dict[str, Any]
|
||||
ASGIReceive = Callable[[], Awaitable[ASGIMessage]]
|
||||
ASGISend = Callable[[ASGIMessage], Awaitable[None]]
|
||||
ASGIHandler = Callable[[ASGIScope, ASGIReceive, ASGISend], Awaitable[None]]
|
||||
|
||||
_HTTP_METHOD = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Z]+$")
|
||||
_API_VERSION = re.compile(r"^v[1-9][0-9]*$")
|
||||
_PARAMETER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class HttpRoute:
|
||||
"""Application-owned ASGI handler mounted at a versioned path template."""
|
||||
|
||||
method: str
|
||||
path: str
|
||||
handler: ASGIHandler
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.method, str) or not _HTTP_METHOD.fullmatch(self.method):
|
||||
raise ValueError("HTTP method must be a non-empty uppercase token")
|
||||
if not callable(self.handler):
|
||||
raise ValueError("HTTP route handler must be callable")
|
||||
_parse_path(self.path)
|
||||
|
||||
@property
|
||||
def segments(self) -> tuple[str, ...]:
|
||||
return tuple(self.path.split("/")[1:])
|
||||
|
||||
@property
|
||||
def static_segment_count(self) -> int:
|
||||
return sum(not _is_parameter(segment) for segment in self.segments)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RouteMatch:
|
||||
route: HttpRoute
|
||||
path_params: dict[str, str]
|
||||
|
||||
|
||||
class RouteNotFound(LookupError):
|
||||
"""Raised when no registered path template matches a request path."""
|
||||
|
||||
|
||||
class MethodNotAllowed(LookupError):
|
||||
"""Raised when a path matches, but its registered methods do not."""
|
||||
|
||||
def __init__(self, allowed_methods: tuple[str, ...]) -> None:
|
||||
super().__init__("HTTP method is not allowed for this path")
|
||||
self.allowed_methods = allowed_methods
|
||||
|
||||
|
||||
class HttpRouter:
|
||||
"""Immutable route table with static-segment precedence."""
|
||||
|
||||
def __init__(self, routes: Sequence[HttpRoute]) -> None:
|
||||
self._routes = tuple(routes)
|
||||
self._validate_conflicts()
|
||||
|
||||
def resolve(self, method: str, path: str) -> RouteMatch:
|
||||
request_segments = tuple(path.split("/")[1:]) if path.startswith("/") else ()
|
||||
path_matches = [
|
||||
(route, params)
|
||||
for route in self._routes
|
||||
if (params := _match_path(route, request_segments)) is not None
|
||||
]
|
||||
if not path_matches:
|
||||
raise RouteNotFound(path)
|
||||
|
||||
method_matches = [
|
||||
(route, params)
|
||||
for route, params in path_matches
|
||||
if route.method == method
|
||||
]
|
||||
if not method_matches:
|
||||
methods = tuple(sorted({route.method for route, _ in path_matches}))
|
||||
raise MethodNotAllowed(methods)
|
||||
|
||||
highest_specificity = max(
|
||||
route.static_segment_count for route, _ in method_matches
|
||||
)
|
||||
best_match = next(
|
||||
item
|
||||
for item in method_matches
|
||||
if item[0].static_segment_count == highest_specificity
|
||||
)
|
||||
return RouteMatch(*best_match)
|
||||
|
||||
def _validate_conflicts(self) -> None:
|
||||
for index, first in enumerate(self._routes):
|
||||
for second in self._routes[index + 1 :]:
|
||||
if (
|
||||
first.method == second.method
|
||||
and first.static_segment_count == second.static_segment_count
|
||||
and _templates_overlap(first, second)
|
||||
):
|
||||
raise ValueError(
|
||||
f"ambiguous {first.method} routes: {first.path} and {second.path}"
|
||||
)
|
||||
|
||||
|
||||
def _parse_path(path: str) -> tuple[str, ...]:
|
||||
if (
|
||||
not isinstance(path, str)
|
||||
or not path.startswith("/")
|
||||
or path.endswith("/")
|
||||
or "//" in path
|
||||
or "?" in path
|
||||
or "#" in path
|
||||
):
|
||||
raise ValueError("HTTP route path must be a canonical absolute path")
|
||||
segments = tuple(path.split("/")[1:])
|
||||
if len(segments) < 3 or segments[0] != "api":
|
||||
raise ValueError("HTTP route path must start with /api/v{version}/...")
|
||||
if not _API_VERSION.fullmatch(segments[1]):
|
||||
raise ValueError("HTTP route version must be a positive integer, such as v1")
|
||||
|
||||
parameters: set[str] = set()
|
||||
for segment in segments[2:]:
|
||||
if "{" not in segment and "}" not in segment:
|
||||
continue
|
||||
name = segment[1:-1] if segment.startswith("{") and segment.endswith("}") else ""
|
||||
if not _PARAMETER.fullmatch(name) or name in parameters:
|
||||
raise ValueError("path parameters must be unique named segments")
|
||||
parameters.add(name)
|
||||
return segments
|
||||
|
||||
|
||||
def _is_parameter(segment: str) -> bool:
|
||||
return segment.startswith("{") and segment.endswith("}")
|
||||
|
||||
|
||||
def _match_path(
|
||||
route: HttpRoute, request_segments: tuple[str, ...]
|
||||
) -> dict[str, str] | None:
|
||||
route_segments = route.segments
|
||||
if len(route_segments) != len(request_segments):
|
||||
return None
|
||||
parameters: dict[str, str] = {}
|
||||
for template_segment, request_segment in zip(route_segments, request_segments):
|
||||
if _is_parameter(template_segment):
|
||||
if not request_segment:
|
||||
return None
|
||||
parameters[template_segment[1:-1]] = request_segment
|
||||
elif template_segment != request_segment:
|
||||
return None
|
||||
return parameters
|
||||
|
||||
|
||||
def _templates_overlap(first: HttpRoute, second: HttpRoute) -> bool:
|
||||
first_segments = first.segments
|
||||
second_segments = second.segments
|
||||
if len(first_segments) != len(second_segments):
|
||||
return False
|
||||
return all(
|
||||
left == right or _is_parameter(left) or _is_parameter(right)
|
||||
for left, right in zip(first_segments, second_segments)
|
||||
)
|
||||
Reference in New Issue
Block a user