143 lines
5.5 KiB
Python
143 lines
5.5 KiB
Python
import os
|
|
import uuid
|
|
import logging
|
|
import asyncio
|
|
import time
|
|
from contextlib import asynccontextmanager
|
|
|
|
from app.telemetry import setup_telemetry
|
|
tracer_provider, meter_provider, logger_provider = setup_telemetry()
|
|
|
|
from app.queue_metrics import collect_queue_metrics
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
from opentelemetry import trace, propagate, metrics
|
|
from opentelemetry.trace import SpanKind, StatusCode
|
|
from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
|
|
from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor
|
|
|
|
from app.routers import auth, chats, attachments
|
|
from app.broker import run_relay
|
|
|
|
logger = logging.getLogger(__name__)
|
|
tracer = trace.get_tracer("messenger-api")
|
|
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8])
|
|
|
|
# HTTP-метрики
|
|
_http_meter = metrics.get_meter("messenger.http")
|
|
_http_duration = _http_meter.create_histogram(
|
|
"http.server.duration", unit="ms",
|
|
description="Measures the duration of inbound HTTP requests",
|
|
)
|
|
|
|
|
|
class OtelASGIMiddleware:
|
|
def __init__(self, app):
|
|
self.app = app
|
|
|
|
async def __call__(self, scope, receive, send):
|
|
if scope["type"] != "http":
|
|
await self.app(scope, receive, send)
|
|
return
|
|
method = scope.get("method", "?")
|
|
path = scope.get("path", "?")
|
|
carrier = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
|
|
parent_ctx = propagate.extract(carrier)
|
|
started = time.perf_counter()
|
|
status_holder = {"code": 0}
|
|
|
|
with tracer.start_as_current_span(
|
|
name=f"{method} {path}", context=parent_ctx, kind=SpanKind.SERVER,
|
|
attributes={"http.method": method, "http.target": path},
|
|
) as span:
|
|
tid = format(span.get_span_context().trace_id, "032x")
|
|
print(f"!!! MW SPAN: {method} {path} trace_id={tid}", flush=True)
|
|
out = {}
|
|
propagate.inject(out)
|
|
scope.setdefault("state", {})["trace_carrier"] = out
|
|
scope["state"]["request_id"] = carrier.get("x-request-id") or str(uuid.uuid4())
|
|
|
|
async def send_wrapper(message):
|
|
if message["type"] == "http.response.start":
|
|
status_holder["code"] = message.get("status", 0)
|
|
span.set_attribute("http.status_code", status_holder["code"])
|
|
if status_holder["code"] >= 500:
|
|
span.set_status(StatusCode.ERROR)
|
|
h = list(message.get("headers", []))
|
|
h.append((b"x-request-id", scope["state"]["request_id"].encode()))
|
|
h.append((b"x-instance-id", INSTANCE_ID.encode()))
|
|
message["headers"] = h
|
|
await send(message)
|
|
|
|
try:
|
|
await self.app(scope, receive, send_wrapper)
|
|
finally:
|
|
dur_ms = (time.perf_counter() - started) * 1000.0
|
|
if status_holder["code"] == 0:
|
|
status_holder["code"] = 500
|
|
attrs = {
|
|
"http.method": method,
|
|
"http.target": path,
|
|
"http.status_code": status_holder["code"],
|
|
}
|
|
print(f"!!! METRIC: {method} {path} {dur_ms:.1f}ms", flush=True)
|
|
_http_duration.record(dur_ms, attrs)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
task = asyncio.create_task(run_relay())
|
|
queue_task = asyncio.create_task(collect_queue_metrics())
|
|
yield
|
|
tracer_provider.force_flush(timeout_millis=5000)
|
|
meter_provider.force_flush(timeout_millis=5000)
|
|
task.cancel()
|
|
queue_task.cancel()
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
app.include_router(auth.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(attachments.router)
|
|
AsyncPGInstrumentor().instrument(tracer_provider=tracer_provider)
|
|
AioPikaInstrumentor().instrument(tracer_provider=tracer_provider)
|
|
app.add_middleware(OtelASGIMiddleware)
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
detail = exc.detail
|
|
code = detail.get("code", "internal_error") if isinstance(detail, dict) else "internal_error"
|
|
message = detail.get("message", str(detail)) if isinstance(detail, dict) else str(detail)
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={"error": {"code": code, "message": message,
|
|
"request_id": getattr(request.state, "request_id", "")}},
|
|
headers=exc.headers,
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content={"error": {"code": "invalid_request", "message": "Validation error",
|
|
"request_id": getattr(request.state, "request_id", "")}},
|
|
headers={"X-Request-Id": getattr(request.state, "request_id", ""), "X-Instance-Id": INSTANCE_ID},
|
|
)
|
|
|
|
@app.get("/health/live")
|
|
async def health_live():
|
|
cur = trace.get_current_span().get_span_context()
|
|
print(f"!!! ENDPOINT trace_id={format(cur.trace_id,'032x')}", flush=True)
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/health/ready")
|
|
async def health_ready():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/debug/boom")
|
|
async def debug_boom():
|
|
raise RuntimeError("demo failure for 5xx alerting")
|