Add request-ID middleware that propagates X-Request-ID via ContextVar#45
Open
mvanhorn wants to merge 1 commit intoClimate-Vision:mainfrom
Open
Add request-ID middleware that propagates X-Request-ID via ContextVar#45mvanhorn wants to merge 1 commit intoClimate-Vision:mainfrom
mvanhorn wants to merge 1 commit intoClimate-Vision:mainfrom
Conversation
Closes Climate-Vision#44. Adds a `RequestIDMiddleware` (in `src/climatevision/api/middleware.py`) that reads the inbound `X-Request-ID` header, falls back to a fresh UUID4 when absent, stores the value on a `contextvars.ContextVar` (`request_id_var`), and echoes it back on the response. Pairs the middleware with a `RequestIDLogFilter` and wires it into `setup_logging` so every log record emitted during the request lifecycle -- including from `inference/pipeline.py` and helper modules that don't hold the FastAPI `Request` object -- carries `%(request_id)s` in the JSON log format. The middleware is registered last in `create_app` so it sits outermost in the stack, ensuring the ContextVar is set before any other middleware or route handler runs. Tests in `tests/test_request_id_middleware.py` cover the three cases the issue called out: - request without `X-Request-ID` -> response carries a UUID-shaped value - request with explicit `X-Request-ID` -> response echoes it back - log record emitted inside the handler exposes `record.request_id` Plus a leak test asserting the ContextVar resets after the response.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #44.
Why
AuditLogMiddlewarealready attaches a UUID torequest.state.request_id, but anything that runs in the request lifecycle without access to the FastAPIRequestobject - notablyinference/pipeline.pyand the helper modules below it - emits log lines that aren't correlated to the inbound HTTP request.What
Added in
src/climatevision/api/middleware.py:request_id_var: ContextVar[str | None]so non-FastAPI code can read the active request ID.RequestIDMiddleware(BaseHTTPMiddleware) that readsX-Request-ID(UUID4 fallback), stores it on the ContextVar, mirrors it ontorequest.state.request_idso the existingRequestLoggingMiddleware/AuditLogMiddlewarekeep working, and echoes the value back on the response. ContextVar isreset()in afinallyblock so requests don't leak.RequestIDLogFilter(logging.Filter)that exposes the ContextVar asrecord.request_idfor log formatters.setup_loggingnow installs the filter on the root logger and attaches it to existing handlers, and the JSON log format gains"request_id":"%(request_id)s".create_appregistersRequestIDMiddlewarelast inadd_middleware, which means starlette runs it OUTERMOST -- the ContextVar is set before any other middleware or route handler runs.Tests
tests/test_request_id_middleware.pycovers the three cases in the issue plus a leak check:X-Request-ID-> response has a UUID-shapedX-Request-IDand the route reads the same valueX-Request-ID: <id>-> response echoes the same value backrecord.request_idmatching the inbound id (verified via the filter on aStreamHandlerand pytest'scaplog)request_id_var.get()is back toNoneLocally:
reports 4 passed in 0.10s. (The repo's full conftest pulls the inference pipeline which needs GDAL/fiona; the new test file builds a minimal FastAPI app of its own and stays independent.)