| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | import uuid |
| 4 | from collections.abc import Awaitable |
| 5 | |
| 6 | from starlette.datastructures import Headers, MutableHeaders |
| 7 | from starlette.types import ASGIApp, Message, Receive, Scope, Send |
| 8 | |
| 9 | |
| 10 | class XRequestIdMiddleware: |
| 11 | """Middleware the set's the X-Request-Id header for each response |
| 12 | to a random uuid4 (hex) value if the header isn't already |
| 13 | present in the request, otherwise use the provided request id. |
| 14 | """ |
| 15 | |
| 16 | def __init__(self, app: ASGIApp) -> None: |
| 17 | self.app = app |
| 18 | |
| 19 | def __call__(self, scope: Scope, receive: Receive, send: Send) -> Awaitable[None]: |
| 20 | if scope["type"] not in ("http", "websocket"): |
| 21 | return self.app(scope, receive, send) |
| 22 | |
| 23 | # Extract the request headers. |
| 24 | request_headers = Headers(scope=scope) |
| 25 | |
| 26 | async def send_with_request_id(message: Message) -> None: |
| 27 | """Custom send function to mutate the response headers |
| 28 | and append X-Request-Id to it. |
| 29 | """ |
| 30 | if message["type"] == "http.response.start": |
| 31 | response_headers = MutableHeaders(raw=message["headers"]) |
| 32 | request_id = request_headers.get("X-Request-Id", uuid.uuid4().hex) |
| 33 | response_headers.append("X-Request-Id", request_id) |
| 34 | await send(message) |
| 35 | |
| 36 | return self.app(scope, receive, send_with_request_id) |