|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import time |
| 6 | +import uuid |
| 7 | +from typing import Any, Callable |
| 8 | + |
| 9 | +from .config import ObserverConfig |
| 10 | +from .logger import build_logger, log_event |
| 11 | +from .models import LogEvent |
| 12 | + |
| 13 | +try: |
| 14 | + from starlette.middleware.base import BaseHTTPMiddleware |
| 15 | + from starlette.requests import Request |
| 16 | + from starlette.responses import Response |
| 17 | +except ModuleNotFoundError as exc: # pragma: no cover - guarded runtime fallback |
| 18 | + _IMPORT_ERROR = exc |
| 19 | +else: |
| 20 | + _IMPORT_ERROR = None |
| 21 | + |
| 22 | + |
| 23 | +def _redact_sensitive(value: Any, redact_fields: set[str]) -> Any: |
| 24 | + if isinstance(value, dict): |
| 25 | + redacted: dict[str, Any] = {} |
| 26 | + for key, nested_value in value.items(): |
| 27 | + if str(key).lower() in redact_fields: |
| 28 | + redacted[key] = "***" |
| 29 | + else: |
| 30 | + redacted[key] = _redact_sensitive(nested_value, redact_fields) |
| 31 | + return redacted |
| 32 | + if isinstance(value, list): |
| 33 | + return [_redact_sensitive(item, redact_fields) for item in value] |
| 34 | + return value |
| 35 | + |
| 36 | + |
| 37 | +def _redact_headers(headers: dict[str, str], redact_headers: set[str]) -> dict[str, str]: |
| 38 | + result: dict[str, str] = {} |
| 39 | + for key, value in headers.items(): |
| 40 | + if key.lower() in redact_headers: |
| 41 | + result[key] = "***" |
| 42 | + else: |
| 43 | + result[key] = value |
| 44 | + return result |
| 45 | + |
| 46 | + |
| 47 | +def _to_log_level(status_code: int) -> str: |
| 48 | + if status_code >= 500: |
| 49 | + return "ERROR" |
| 50 | + if status_code >= 400: |
| 51 | + return "WARNING" |
| 52 | + return "INFO" |
| 53 | + |
| 54 | + |
| 55 | +if _IMPORT_ERROR is None: |
| 56 | + |
| 57 | + class ObserverMiddleware(BaseHTTPMiddleware): |
| 58 | + def __init__( |
| 59 | + self, |
| 60 | + app: Any, |
| 61 | + *, |
| 62 | + config: ObserverConfig | None = None, |
| 63 | + logger: logging.Logger | None = None, |
| 64 | + ) -> None: |
| 65 | + super().__init__(app) |
| 66 | + self.config = config or ObserverConfig() |
| 67 | + self.logger = logger or build_logger(self.config) |
| 68 | + |
| 69 | + async def dispatch( |
| 70 | + self, |
| 71 | + request: Request, |
| 72 | + call_next: Callable[[Request], Any], |
| 73 | + ) -> Response: |
| 74 | + if not self.config.enabled: |
| 75 | + return await call_next(request) |
| 76 | + |
| 77 | + path = request.url.path |
| 78 | + method = request.method |
| 79 | + if not self.config.should_log_method(method) or not self.config.should_log_path(path): |
| 80 | + return await call_next(request) |
| 81 | + |
| 82 | + correlation_id = self._resolve_correlation_id(request) |
| 83 | + request_body_for_log: Any | None = None |
| 84 | + request_for_next = request |
| 85 | + if self.config.log_request_body: |
| 86 | + body = await request.body() |
| 87 | + request_body_for_log = self._format_body_for_log(body) |
| 88 | + request_for_next = Request(request.scope, receive=_build_body_replay_receive(body)) |
| 89 | + |
| 90 | + start = time.perf_counter() |
| 91 | + try: |
| 92 | + response = await call_next(request_for_next) |
| 93 | + except Exception as exc: |
| 94 | + duration_ms = round((time.perf_counter() - start) * 1000, 3) |
| 95 | + log_event( |
| 96 | + self.logger, |
| 97 | + self.config, |
| 98 | + LogEvent( |
| 99 | + level="ERROR", |
| 100 | + message="HTTP request failed", |
| 101 | + method=method, |
| 102 | + path=path, |
| 103 | + status_code=500, |
| 104 | + duration_ms=duration_ms, |
| 105 | + correlation_id=correlation_id, |
| 106 | + error=str(exc), |
| 107 | + metadata=self._build_metadata( |
| 108 | + request, |
| 109 | + request_body=request_body_for_log, |
| 110 | + ), |
| 111 | + ), |
| 112 | + ) |
| 113 | + raise |
| 114 | + |
| 115 | + duration_ms = round((time.perf_counter() - start) * 1000, 3) |
| 116 | + response_body_for_log = ( |
| 117 | + self._extract_response_body_for_log(response) |
| 118 | + if self.config.log_response_body |
| 119 | + else None |
| 120 | + ) |
| 121 | + |
| 122 | + log_event( |
| 123 | + self.logger, |
| 124 | + self.config, |
| 125 | + LogEvent( |
| 126 | + level=_to_log_level(response.status_code), |
| 127 | + message="HTTP request completed", |
| 128 | + method=method, |
| 129 | + path=path, |
| 130 | + status_code=response.status_code, |
| 131 | + duration_ms=duration_ms, |
| 132 | + correlation_id=correlation_id, |
| 133 | + metadata=self._build_metadata( |
| 134 | + request, |
| 135 | + request_body=request_body_for_log, |
| 136 | + response_body=response_body_for_log, |
| 137 | + ), |
| 138 | + ), |
| 139 | + ) |
| 140 | + |
| 141 | + if correlation_id: |
| 142 | + response.headers.setdefault(self.config.correlation_id_header, correlation_id) |
| 143 | + return response |
| 144 | + |
| 145 | + def _resolve_correlation_id(self, request: Request) -> str | None: |
| 146 | + value = request.headers.get(self.config.correlation_id_header) |
| 147 | + if value: |
| 148 | + request.state.correlation_id = value |
| 149 | + return value |
| 150 | + if self.config.generate_correlation_id: |
| 151 | + generated = str(uuid.uuid4()) |
| 152 | + request.state.correlation_id = generated |
| 153 | + return generated |
| 154 | + return None |
| 155 | + |
| 156 | + def _build_metadata( |
| 157 | + self, |
| 158 | + request: Request, |
| 159 | + *, |
| 160 | + request_body: Any | None = None, |
| 161 | + response_body: Any | None = None, |
| 162 | + ) -> dict[str, Any]: |
| 163 | + metadata: dict[str, Any] = { |
| 164 | + "query_params": dict(request.query_params), |
| 165 | + } |
| 166 | + if request.client: |
| 167 | + metadata["client"] = { |
| 168 | + "host": request.client.host, |
| 169 | + "port": request.client.port, |
| 170 | + } |
| 171 | + if self.config.log_headers: |
| 172 | + metadata["headers"] = _redact_headers( |
| 173 | + dict(request.headers), |
| 174 | + self.config.redact_headers, |
| 175 | + ) |
| 176 | + if request_body is not None: |
| 177 | + metadata["request_body"] = request_body |
| 178 | + if response_body is not None: |
| 179 | + metadata["response_body"] = response_body |
| 180 | + return metadata |
| 181 | + |
| 182 | + def _extract_response_body_for_log(self, response: Response) -> Any | None: |
| 183 | + body = getattr(response, "body", None) |
| 184 | + if body is None: |
| 185 | + return None |
| 186 | + if isinstance(body, bytes): |
| 187 | + return self._format_body_for_log(body) |
| 188 | + if isinstance(body, str): |
| 189 | + return self._format_body_for_log(body.encode("utf-8")) |
| 190 | + return None |
| 191 | + |
| 192 | + def _format_body_for_log(self, body: bytes) -> Any: |
| 193 | + body_size = len(body) |
| 194 | + body_for_parse = body[: self.config.max_body_bytes] |
| 195 | + parsed: Any |
| 196 | + try: |
| 197 | + parsed = json.loads(body_for_parse.decode("utf-8")) |
| 198 | + except (UnicodeDecodeError, json.JSONDecodeError): |
| 199 | + parsed = body_for_parse.decode("utf-8", errors="replace") |
| 200 | + |
| 201 | + redacted = _redact_sensitive(parsed, self.config.redact_fields) |
| 202 | + if body_size <= self.config.max_body_bytes: |
| 203 | + return redacted |
| 204 | + return { |
| 205 | + "truncated": True, |
| 206 | + "original_size": body_size, |
| 207 | + "content": redacted, |
| 208 | + } |
| 209 | + |
| 210 | + |
| 211 | + def _build_body_replay_receive(body: bytes) -> Callable[[], Any]: |
| 212 | + sent = False |
| 213 | + |
| 214 | + async def receive() -> dict[str, Any]: |
| 215 | + nonlocal sent |
| 216 | + if not sent: |
| 217 | + sent = True |
| 218 | + return {"type": "http.request", "body": body, "more_body": False} |
| 219 | + return {"type": "http.request", "body": b"", "more_body": False} |
| 220 | + |
| 221 | + return receive |
| 222 | + |
| 223 | + |
| 224 | +else: |
| 225 | + |
| 226 | + class ObserverMiddleware: # pragma: no cover - import-time guard only |
| 227 | + def __init__(self, *_args: Any, **_kwargs: Any) -> None: |
| 228 | + raise RuntimeError( |
| 229 | + "ObserverMiddleware requires FastAPI/Starlette. " |
| 230 | + "Install optional runtime dependencies first." |
| 231 | + ) from _IMPORT_ERROR |
| 232 | + |
| 233 | + |
| 234 | +__all__ = ["ObserverMiddleware"] |
0 commit comments