Files
mtusi2026lab6/app/asgi.py
T

125 lines
4.6 KiB
Python

import asyncio
import random
import time
import uuid
from opentelemetry.trace import SpanKind
from app import faults, http, telemetry
from app.errors import AppError
from app.settings import settings
class _TooLarge(Exception):
pass
async def _read_body(receive, limit):
chunks = []
size = 0
while True:
message = await receive()
if message["type"] == "http.disconnect":
return None
if message["type"] != "http.request":
continue
data = message.get("body", b"") or b""
size += len(data)
if size > limit:
raise _TooLarge()
chunks.append(data)
if not message.get("more_body"):
return b"".join(chunks)
def _too_large(scope, limit):
for name, value in scope.get("headers", []):
if name == b"content-length":
try:
return int(value) > limit
except ValueError:
return True
return False
async def app(scope, receive, send):
if scope["type"] == "lifespan":
while True:
message = await receive()
if message["type"] == "lifespan.startup":
telemetry.log_event("service.listening", port=8080)
await send({"type": "lifespan.startup.complete"})
elif message["type"] == "lifespan.shutdown":
await send({"type": "lifespan.shutdown.complete"})
return
return
if scope["type"] != "http":
return
method = scope.get("method", "GET")
path = scope.get("path", "/")
raw_headers = {}
for name, value in scope.get("headers", []):
raw_headers[name.decode("latin-1").lower()] = value.decode("latin-1")
request_id = http.request_id_from(raw_headers)
template, _name, _groups = http.match(method, path)
limit = http.body_limit(path)
started = time.perf_counter()
status = 500
response_headers = {}
body = b""
with telemetry.tracer().start_as_current_span(
f"{method} {template}",
kind=SpanKind.SERVER,
attributes={"http.request.method": method, "http.route": template},
) as span:
try:
if _too_large(scope, limit):
raise AppError(413, "payload_too_large", "Слишком большой объект")
try:
payload = await _read_body(receive, limit)
except _TooLarge as exc:
raise AppError(413, "payload_too_large", "Слишком большой объект") from exc
if payload is None:
return
if method in {"POST", "PUT"} and path.rstrip("/").endswith("/attachments") and len(payload) > settings.max_upload:
raise AppError(413, "payload_too_large", "Слишком большой объект")
query = http.query_from(scope.get("query_string", b"").decode("ascii", "replace"))
if path.startswith("/api/") and random.random() < faults.http_error_ratio():
raise AppError(500, "internal_error", "Внутренняя ошибка")
def run():
return http.handle(method, path, query, raw_headers, payload)
template, status, response_headers, body = await asyncio.to_thread(run)
span.set_attribute("http.route", template)
except Exception as exc:
status, response_headers, body = http.error_response(exc, request_id)
if not isinstance(exc, AppError):
telemetry.log_event("internal_error", severity="ERROR", error_type=type(exc).__name__, request_id=request_id)
if status >= 500:
telemetry.mark_error(span)
span.set_attribute("error.type", type(exc).__name__)
duration = time.perf_counter() - started
span.set_attribute("http.response.status_code", status)
telemetry.record_http(method, template, status, duration)
telemetry.log_event(
"http.request.completed",
request_id=request_id,
http_route=template,
http_method=method,
status=status,
duration_ms=int(duration * 1000),
)
header_list = [
(b"x-request-id", request_id.encode("ascii")),
(b"x-instance-id", settings.instance_id.encode("ascii")),
]
for key, value in response_headers.items():
header_list.append((key.lower().encode("latin-1"), value.encode("latin-1")))
await send({"type": "http.response.start", "status": status, "headers": header_list})
await send({"type": "http.response.body", "body": body})
def new_request_id():
return uuid.uuid4().hex