|
| 1 | +# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. |
| 2 | +# SPDX-License-Identifier: AGPL-3.0 |
| 3 | +"""HTTP request/response body dump middleware for trace debugging. |
| 4 | +
|
| 5 | +Attaches the request and response bodies as attributes on the active OpenTelemetry |
| 6 | +root span so they can be inspected in trace UIs (Jaeger, Tempo, etc.). The middleware |
| 7 | +must run inside the trace span context — register it before the http_observability |
| 8 | +middleware in ``create_app``. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +from typing import Awaitable, Callable |
| 14 | + |
| 15 | +from fastapi import Request |
| 16 | +from starlette.responses import Response |
| 17 | + |
| 18 | +try: |
| 19 | + from opentelemetry import trace as otel_trace |
| 20 | +except ImportError: # pragma: no cover - OTel optional |
| 21 | + otel_trace = None |
| 22 | + |
| 23 | +# Skip body capture for content types that are binary, streamed, or otherwise |
| 24 | +# pointless to materialize as a span attribute. |
| 25 | +_SKIP_CONTENT_TYPE_PREFIXES = ( |
| 26 | + "multipart/form-data", |
| 27 | + "application/octet-stream", |
| 28 | + "text/event-stream", |
| 29 | + "audio/", |
| 30 | + "video/", |
| 31 | + "image/", |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +def _should_skip(content_type: str | None) -> bool: |
| 36 | + if not content_type: |
| 37 | + return False |
| 38 | + ct = content_type.lower() |
| 39 | + return any(ct.startswith(p) for p in _SKIP_CONTENT_TYPE_PREFIXES) |
| 40 | + |
| 41 | + |
| 42 | +def _truncate(data: bytes, max_bytes: int) -> str: |
| 43 | + total = len(data) |
| 44 | + head = data[:max_bytes] |
| 45 | + text = head.decode("utf-8", errors="replace") |
| 46 | + if total > max_bytes: |
| 47 | + return f"{text}…[+{total - max_bytes}B truncated, total {total}B]" |
| 48 | + return text |
| 49 | + |
| 50 | + |
| 51 | +def _set_span_attr(key: str, value: object) -> None: |
| 52 | + if otel_trace is None: |
| 53 | + return |
| 54 | + try: |
| 55 | + span = otel_trace.get_current_span() |
| 56 | + if span is None or not span.is_recording(): |
| 57 | + return |
| 58 | + span.set_attribute(key, value) |
| 59 | + except Exception: |
| 60 | + # Body dump must never break the request path. |
| 61 | + pass |
| 62 | + |
| 63 | + |
| 64 | +def create_dump_http_body_middleware( |
| 65 | + max_bytes: int = 4096, |
| 66 | +) -> Callable[[Request, Callable], Awaitable[Response]]: |
| 67 | + """Build a body-dump middleware bound to ``max_bytes``. |
| 68 | +
|
| 69 | + The middleware skips streaming/binary content types and truncates payloads to |
| 70 | + keep span attributes bounded. |
| 71 | + """ |
| 72 | + |
| 73 | + async def middleware( |
| 74 | + request: Request, |
| 75 | + call_next: Callable[[Request], Awaitable[Response]], |
| 76 | + ) -> Response: |
| 77 | + req_ct = request.headers.get("content-type", "") |
| 78 | + if not _should_skip(req_ct): |
| 79 | + try: |
| 80 | + body = await request.body() |
| 81 | + if body: |
| 82 | + _set_span_attr("http.request.body", _truncate(body, max_bytes)) |
| 83 | + _set_span_attr("http.request.body.size", len(body)) |
| 84 | + if req_ct: |
| 85 | + _set_span_attr("http.request.content_type", req_ct) |
| 86 | + except Exception: |
| 87 | + pass |
| 88 | + |
| 89 | + response = await call_next(request) |
| 90 | + |
| 91 | + resp_ct = response.headers.get("content-type", "") |
| 92 | + if _should_skip(resp_ct): |
| 93 | + return response |
| 94 | + |
| 95 | + # Once we start iterating ``response.body_iterator`` we own the bytes; |
| 96 | + # capture failures must not silently truncate the response sent to the |
| 97 | + # client, so we always rebuild a Response from whatever we've collected. |
| 98 | + chunks: list[bytes] = [] |
| 99 | + try: |
| 100 | + async for chunk in response.body_iterator: |
| 101 | + chunks.append(chunk) |
| 102 | + body_bytes = b"".join(chunks) |
| 103 | + if body_bytes: |
| 104 | + _set_span_attr("http.response.body", _truncate(body_bytes, max_bytes)) |
| 105 | + _set_span_attr("http.response.body.size", len(body_bytes)) |
| 106 | + if resp_ct: |
| 107 | + _set_span_attr("http.response.content_type", resp_ct) |
| 108 | + except Exception: |
| 109 | + body_bytes = b"".join(chunks) |
| 110 | + _set_span_attr("http.response.body.capture_error", True) |
| 111 | + |
| 112 | + try: |
| 113 | + new_headers = { |
| 114 | + k: v for k, v in response.headers.items() if k.lower() != "content-length" |
| 115 | + } |
| 116 | + return Response( |
| 117 | + content=body_bytes, |
| 118 | + status_code=response.status_code, |
| 119 | + headers=new_headers, |
| 120 | + media_type=response.media_type, |
| 121 | + ) |
| 122 | + except Exception: |
| 123 | + # Fall back to the original response object as a last resort. Its |
| 124 | + # body_iterator is exhausted at this point, so this only fires if |
| 125 | + # the rebuild path itself is broken. |
| 126 | + return response |
| 127 | + |
| 128 | + return middleware |
0 commit comments