PLBA2-2. Реализация
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
from plba.http.control_api import ControlApi
|
||||
|
||||
__all__ = ["ControlApi"]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,41 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from plba.http.errors import ControlRequestError
|
||||
|
||||
|
||||
class ASGIHttpTransport:
|
||||
async def read_body(self, receive: Any) -> bytes:
|
||||
chunks: list[bytes] = []
|
||||
while True:
|
||||
message = await receive()
|
||||
if message.get("type") == "http.disconnect":
|
||||
raise ControlRequestError("client disconnected before request completed")
|
||||
if message.get("type") != "http.request":
|
||||
continue
|
||||
chunks.append(message.get("body", b""))
|
||||
if not message.get("more_body", False):
|
||||
return b"".join(chunks)
|
||||
|
||||
async def send_json(self, send: Any, status: int, payload: dict[str, Any]) -> None:
|
||||
body = json.dumps(payload, allow_nan=False).encode("utf-8")
|
||||
await send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": status,
|
||||
"headers": [
|
||||
(b"content-type", b"application/json; charset=utf-8"),
|
||||
(b"content-length", str(len(body)).encode("ascii")),
|
||||
],
|
||||
}
|
||||
)
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
|
||||
async def handle_lifespan(self, receive: Any, send: Any) -> None:
|
||||
while True:
|
||||
message = await receive()
|
||||
if message.get("type") == "lifespan.startup":
|
||||
await send({"type": "lifespan.startup.complete"})
|
||||
elif message.get("type") == "lifespan.shutdown":
|
||||
await send({"type": "lifespan.shutdown.complete"})
|
||||
return
|
||||
@@ -0,0 +1,81 @@
|
||||
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.serialization import health_report_payload
|
||||
from plba.runtime.application import ApplicationRuntime, RuntimeLifecycleError
|
||||
|
||||
|
||||
class ControlApi:
|
||||
"""ASGI route adapter; it owns no server, socket, or listener."""
|
||||
|
||||
def __init__(
|
||||
self, runtime: ApplicationRuntime, health_aggregator: HealthAggregator
|
||||
) -> None:
|
||||
self._runtime = runtime
|
||||
self._health_aggregator = health_aggregator
|
||||
self._transport = ASGIHttpTransport()
|
||||
|
||||
async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> 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)
|
||||
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 _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 _require_empty_body(self, receive: Any) -> None:
|
||||
if await self._transport.read_body(receive):
|
||||
raise ControlRequestError("request body is not accepted")
|
||||
|
||||
@staticmethod
|
||||
def _error(code: str, error: Exception | str) -> dict[str, str]:
|
||||
return {"error": code, "message": str(error)}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
class ControlRequestError(ValueError):
|
||||
pass
|
||||
@@ -0,0 +1,39 @@
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from plba.http.errors import ControlRequestError
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StopRequest:
|
||||
force: bool = False
|
||||
timeout_seconds: float | None = None
|
||||
|
||||
@classmethod
|
||||
def parse(cls, body: bytes) -> "StopRequest":
|
||||
if not body:
|
||||
raise ControlRequestError("stop request must contain a JSON object")
|
||||
try:
|
||||
decoded: Any = json.loads(body.decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as error:
|
||||
raise ControlRequestError("stop request must contain valid UTF-8 JSON") from error
|
||||
if not isinstance(decoded, dict):
|
||||
raise ControlRequestError("stop request must be a JSON object")
|
||||
if set(decoded) - {"force", "timeout_seconds"}:
|
||||
raise ControlRequestError("stop request contains unsupported fields")
|
||||
force = decoded.get("force", False)
|
||||
timeout_seconds = decoded.get("timeout_seconds")
|
||||
if not isinstance(force, bool):
|
||||
raise ControlRequestError("force must be a boolean")
|
||||
if "timeout_seconds" in decoded and timeout_seconds is None:
|
||||
raise ControlRequestError("timeout_seconds cannot be null")
|
||||
if timeout_seconds is not None and (
|
||||
isinstance(timeout_seconds, bool)
|
||||
or not isinstance(timeout_seconds, (int, float))
|
||||
or not math.isfinite(timeout_seconds)
|
||||
or timeout_seconds <= 0
|
||||
):
|
||||
raise ControlRequestError("timeout_seconds must be a positive finite number")
|
||||
return cls(force=force, timeout_seconds=timeout_seconds)
|
||||
@@ -0,0 +1,21 @@
|
||||
from typing import Any
|
||||
|
||||
from plba.health.models import HealthReport
|
||||
|
||||
|
||||
def health_report_payload(report: HealthReport) -> dict[str, Any]:
|
||||
return {
|
||||
"application_id": report.application_id,
|
||||
"lifecycle": report.lifecycle,
|
||||
"status": report.status,
|
||||
"components": [
|
||||
{
|
||||
"name": item.name,
|
||||
"status": item.status.value,
|
||||
"critical": item.critical,
|
||||
"detail": item.detail,
|
||||
"meta": dict(item.meta),
|
||||
}
|
||||
for item in report.components
|
||||
],
|
||||
}
|
||||
Reference in New Issue
Block a user