Реализовать observability для лабораторной 6
This commit is contained in:
+3
-2
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from fastapi import Depends, HTTPException, Request, Security, status
|
||||
|
||||
from ..db.redis import RedisSessionStore
|
||||
from ..domain.errors import Unauthorized
|
||||
@@ -11,6 +11,7 @@ from ..services.chats import ChatService
|
||||
from ..services.attachments import AttachmentService
|
||||
from ..services.messages import MessageService
|
||||
from ..services.users import UserService
|
||||
from .security import bearer_auth
|
||||
|
||||
_BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
@@ -56,7 +57,7 @@ def _bearer_error() -> HTTPException:
|
||||
)
|
||||
|
||||
|
||||
async def bearer_token(authorization: str | None = Header(None)) -> str:
|
||||
async def bearer_token(authorization: str | None = Security(bearer_auth)) -> str:
|
||||
if not authorization:
|
||||
raise _bearer_error()
|
||||
scheme, separator, token = authorization.partition(' ')
|
||||
|
||||
+42
-2
@@ -1,10 +1,14 @@
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from opentelemetry import trace
|
||||
from starlette.datastructures import MutableHeaders
|
||||
|
||||
from ..observability import get_metrics
|
||||
from ..observability.logging import safe_extra
|
||||
from .errors import error_response
|
||||
|
||||
logger = logging.getLogger('app')
|
||||
@@ -22,12 +26,16 @@ class RequestContext:
|
||||
|
||||
request_id = uuid4().hex
|
||||
scope.setdefault('state', {})['request_id'] = request_id
|
||||
is_health = scope.get('path') in {'/health/live', '/health/ready'}
|
||||
started_at = time.perf_counter()
|
||||
started = False
|
||||
status_code = 500
|
||||
|
||||
async def send_wrapper(message) -> None:
|
||||
nonlocal started
|
||||
nonlocal started, status_code
|
||||
if message['type'] == 'http.response.start':
|
||||
started = True
|
||||
status_code = message['status']
|
||||
headers = MutableHeaders(scope=message)
|
||||
headers['X-Request-Id'] = request_id
|
||||
headers['X-Instance-Id'] = self.instance_id
|
||||
@@ -36,8 +44,40 @@ class RequestContext:
|
||||
try:
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
except Exception:
|
||||
logger.exception(f'unhandled error request_id={request_id} path={scope.get("path")}')
|
||||
logger.exception(
|
||||
'unhandled HTTP error',
|
||||
extra=safe_extra('http.request.failed', request_id=request_id),
|
||||
)
|
||||
if started:
|
||||
raise
|
||||
response = error_response(500, 'внутренняя ошибка', request_id)
|
||||
await response(scope, receive, send_wrapper)
|
||||
finally:
|
||||
duration = time.perf_counter() - started_at
|
||||
route = getattr(scope.get('route'), 'path', None) or 'unmatched'
|
||||
method = scope.get('method', 'UNKNOWN')
|
||||
status_class = f'{status_code // 100}xx'
|
||||
span = trace.get_current_span()
|
||||
if span.is_recording():
|
||||
span.set_attribute('request.id', request_id)
|
||||
span.set_attribute('http.route', route)
|
||||
if not is_health:
|
||||
attributes = {
|
||||
'http.request.method': method,
|
||||
'http.route': route,
|
||||
'http.response.status_class': status_class,
|
||||
}
|
||||
instruments = get_metrics()
|
||||
instruments.http_requests.add(1, attributes)
|
||||
instruments.http_duration.record(duration, attributes)
|
||||
logger.info(
|
||||
'HTTP request completed',
|
||||
extra=safe_extra(
|
||||
'http.request.completed',
|
||||
request_id=request_id,
|
||||
http_method=method,
|
||||
http_route=route,
|
||||
http_status_code=status_code,
|
||||
duration_seconds=round(duration, 6),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -16,6 +16,21 @@ router = APIRouter(tags=['attachments'])
|
||||
'/api/v1/chats/{chat_id}/attachments',
|
||||
status_code=202,
|
||||
response_model=AttachmentOut,
|
||||
summary='Принять PNG/JPEG на асинхронную обработку',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'description': 'Сырые байты изображения, не multipart/form-data.',
|
||||
'content': {
|
||||
'image/png': {
|
||||
'schema': {'type': 'string', 'format': 'binary'},
|
||||
},
|
||||
'image/jpeg': {
|
||||
'schema': {'type': 'string', 'format': 'binary'},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
async def upload(
|
||||
chat_id: UUID,
|
||||
|
||||
@@ -3,13 +3,14 @@ from __future__ import annotations
|
||||
import base64
|
||||
from binascii import Error as Base64Error
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
|
||||
from ...auth.tokens import create_token
|
||||
from ...db.redis import RedisSessionStore
|
||||
from ...domain.models import User
|
||||
from ...services.users import UserService
|
||||
from ..deps import bearer_token, current_user, session_store, user_service
|
||||
from ..security import basic_auth
|
||||
from ..schemas import SessionOut, UserOut
|
||||
from ..timefmt import to_rfc3339
|
||||
|
||||
@@ -44,7 +45,7 @@ def _parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
|
||||
@router.post('', status_code=status.HTTP_201_CREATED, response_model=SessionOut)
|
||||
async def create_session(
|
||||
authorization: str | None = Header(None),
|
||||
authorization: str | None = Security(basic_auth),
|
||||
users: UserService = Depends(user_service),
|
||||
sessions: RedisSessionStore = Depends(session_store),
|
||||
) -> SessionOut:
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""OpenAPI security-схемы с сохранением собственного разбора Authorization."""
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.openapi.models import HTTPBase as HTTPBaseModel
|
||||
from fastapi.openapi.models import HTTPBearer as HTTPBearerModel
|
||||
from fastapi.security.base import SecurityBase
|
||||
|
||||
|
||||
class RawHTTPAuthorization(SecurityBase):
|
||||
"""Объявляет HTTP security scheme и возвращает исходный Authorization header."""
|
||||
|
||||
def __init__(self, model, scheme_name: str) -> None:
|
||||
self.model = model
|
||||
self.scheme_name = scheme_name
|
||||
|
||||
async def __call__(self, request: Request) -> str | None:
|
||||
"""Возвращает заголовок без разбора, чтобы сохранить текущую валидацию API."""
|
||||
|
||||
return request.headers.get('Authorization')
|
||||
|
||||
|
||||
basic_auth = RawHTTPAuthorization(
|
||||
HTTPBaseModel(scheme='basic'),
|
||||
scheme_name='basicAuth',
|
||||
)
|
||||
bearer_auth = RawHTTPAuthorization(
|
||||
HTTPBearerModel(scheme='bearer', bearerFormat='opaque session token'),
|
||||
scheme_name='bearerAuth',
|
||||
)
|
||||
Reference in New Issue
Block a user