Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy

This commit is contained in:
Artyom
2026-11-06 09:12:25 +03:00
parent ae9f60fe1f
commit 1217da5f5e
134 changed files with 8243 additions and 1409 deletions
+66 -15
View File
@@ -5,6 +5,7 @@ from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from uuid import uuid4
from starlette.exceptions import HTTPException
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from messenger.shared.application.errors import Unavailable
@@ -57,8 +58,44 @@ async def send_error(
await send({"type": "http.response.body", "body": body})
class Pace:
__slots__ = ("_deadline", "_moved", "_opened", "_rate", "_timeout")
def __init__(self, deadline: asyncio.Timeout, timeout: float, rate: float) -> None:
self._deadline = deadline
self._timeout = timeout
self._rate = rate
self._opened = asyncio.get_running_loop().time()
self._moved = 0
def around(self, receive: Receive, send: Send) -> tuple[Receive, Send]:
async def paced_receive() -> Message:
return self._count(await receive())
async def paced_send(message: Message) -> None:
await send(self._count(message))
return paced_receive, paced_send
def _count(self, message: Message) -> Message:
if size := len(message.get("body", b"")):
self._moved += size
moved = min(asyncio.get_running_loop().time(), self._opened + self._moved / self._rate)
self._deadline.reschedule(moved + self._timeout)
return message
class RequestPipeline:
__slots__ = ("_app", "_guard", "_instance", "_limits", "_logger", "_max_bytes", "_timeout")
__slots__ = (
"_app",
"_guard",
"_instance",
"_limits",
"_logger",
"_max_bytes",
"_min_rate",
"_timeout",
)
def __init__(
self,
@@ -69,12 +106,14 @@ class RequestPipeline:
guard: Guard,
instance: str,
limits: BodyLimits = (),
min_rate: float = 131_072,
) -> None:
self._app = app
self._logger = logger
self._max_bytes = max_bytes
self._limits = limits
self._timeout = timeout
self._min_rate = min_rate
self._guard = guard
self._instance = instance.encode()
@@ -85,9 +124,7 @@ class RequestPipeline:
incoming = header(scope, HEADER_BYTES)
request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex
state = scope.setdefault("state", {})
state["request_id"] = request_id
state["actor"] = None
scope.setdefault("state", {}).update(request_id=request_id, actor=None)
started = time.perf_counter()
status_holder = [500]
answered = [False]
@@ -106,18 +143,23 @@ class RequestPipeline:
message = {**message, "headers": headers}
await send(message)
declared = header(scope, b"content-length")
if declared.isdigit() and int(declared) > self._limit(scope["path"]):
await send_error(wrapped_send, 413, "payload_too_large", request_id)
self._log(scope, status_holder[0], request_id, started)
return
limit = self._limit(scope["path"])
received = [0]
async def limited_receive() -> Message:
message = await receive()
received[0] += len(message.get("body", b""))
if received[0] > limit:
raise HTTPException(413)
return message
rejection: Rejection | None = None
try:
async with asyncio.timeout(self._timeout):
rejection = await self._guard(scope)
async with asyncio.timeout(self._timeout) as deadline:
rejection = await self._guard(scope) or self._oversized(scope, limit)
if rejection is None:
await self._app(scope, receive, wrapped_send)
pace = Pace(deadline, self._timeout, self._min_rate)
await self._app(scope, *pace.around(limited_receive, wrapped_send))
except Unavailable as error:
self._logger.warning(
"dependency.unavailable",
@@ -126,18 +168,21 @@ class RequestPipeline:
request_id=request_id,
)
rejection = Rejection(503, "unavailable")
except TimeoutError:
except (TimeoutError, asyncio.CancelledError) as error:
cancelled = isinstance(error, asyncio.CancelledError)
self._logger.warning(
"request.timeout",
"request.cancelled" if cancelled else "request.timeout",
method=scope["method"],
route=self._route(scope),
request_id=request_id,
limit=self._timeout,
limit=None if cancelled else self._timeout,
duration_ms=round((time.perf_counter() - started) * 1000, 3),
)
if not answered[0]:
await send_error(wrapped_send, 503, "unavailable", request_id)
self._log(scope, status_holder[0], request_id, started)
if cancelled:
raise
return
except Exception:
self._logger.error(
@@ -160,6 +205,12 @@ class RequestPipeline:
return limit
return self._max_bytes
def _oversized(self, scope: Scope, limit: int) -> Rejection | None:
declared = header(scope, b"content-length")
if declared.isdigit() and int(declared) > limit:
return Rejection(413, "payload_too_large")
return None
def _route(self, scope: Scope) -> str:
route = scope.get("route")
return getattr(route, "path", scope["path"])