Repository navigation
refactor: replace BaseHTTPMiddleware with pure ASGI - #475
Open
lentzvitoria wants to merge 2 commits into
Open
lentzvitoria wants to merge 2 commits into
lentzvitoria wants to merge 2 commits into
Conversation
…mentation Removes the dependency on BaseHTTPMiddleware in StarletteContextMiddleware, implementing it as a pure ASGI callable instead. This avoids the double-wrapping issue in Starlette that breaks streaming responses and SSE.
lentzvitoria
commented
Nov 16, 2026
lentzvitoria
left a comment
Contributor
Author
There was a problem hiding this comment.
PR Review: #475: refactor: replace BaseHTTPMiddleware with pure ASGI
Author: lentzvitoria Branch: refactor/starlette-pure-asgi-middleware → main
Verdict:
Summary: Clean, correct refactor — one __call__ path.
A: Process & Compliance
| # | Criterion | Status | Finding |
|---|---|---|---|
| A1 | PR template complete | Closes #<issue_number> is a placeholder — replace with a real issue or remove the line |
|
| A2 | Conventional Commits | PR title is refactor: replace BaseHTTPMiddleware with pure ASGI — missing scope. Should be refactor(middleware): ... to match the commit message on the branch |
|
| A3 | Issue linked | No issue linked (placeholder not replaced) | |
| A4 | AI-generated code disclosure | ➖ | N/A — change is small and clearly human-authored |
B: Security & Sensitive Data
| # | Criterion | Status | Finding |
|---|---|---|---|
| B1 | No sensitive data in code | ✅ | Clean |
| B2 | No sensitive data in PR body | ✅ | Clean |
C: Code Quality
| # | Criterion | Status | Finding |
|---|---|---|---|
| C1 | CI checks passing | All jobs pass except SDK review label present (❌ fail) — expected, no sdk-review label applied yet |
|
| C2 | Version bump | ➖ | N/A — no version change |
| C3 | Type hints | ✅ | __call__ fully annotated: scope: dict, receive: Callable, send: Callable, return None |
| C4 | No hardcoded values | ✅ | "http" string is the ASGI spec literal, not a magic value |
| C5 | Import organization | ✅ | Callable added to stdlib typing imports correctly |
| C6 | Naming conventions | ✅ | No new names introduced |
| C7 | No unused code | ✅ | Removed Request, Response, BaseHTTPMiddleware — no dead imports remain |
| C8 | No unjustified new dependencies | ✅ | starlette.datastructures.Headers is already in the starlette optional dep |
| C9 | Proto code freshness | ➖ | N/A |
D: API & Design
| # | Criterion | Status | Finding |
|---|---|---|---|
| D1 | API future-proofing | ✅ | Constructor unchanged |
| D2 | Public API hygiene | ✅ | Class not exported publicly — internal only |
| D3 | Breaking changes marked | ✅ | PR body explicitly documents why this is non-breaking |
| D4 | Pagination & tenant filtering | ➖ | N/A |
| D5 | Telemetry instrumentation | ➖ | N/A |
| D6 | Multi-tenancy support | ➖ | N/A |
E: Tests & Documentation
| # | Criterion | Status | Finding |
|---|---|---|---|
| E1 | Tests added/updated | No test exercises the new __call__ path directly — specifically the non-HTTP scope forwarding (scope["type"] != "http") is untested. Existing tests cover the HTTP path via TestClient but the websocket/lifespan passthrough has no coverage |
|
| E2 | Documentation quality | ✅ | Docstring updated to reflect pure ASGI nature and non-HTTP scope forwarding |
| E2a | Multi-tenancy documentation | ➖ | N/A — no user-guide.md changed |
| E3 | Module structure compliance | ➖ | N/A — no new module |
⚠️ Non-Blocking Suggestions
- [A1/A3]: Replace
Closes #<issue_number>with a real issue number or remove the line — the placeholder reads as an oversight - [A2]: PR title missing scope — update to
refactor(middleware): replace BaseHTTPMiddleware with pure ASGIto match the commit message - [E1]: Add a test for the non-HTTP scope passthrough, e.g. a WebSocket or lifespan scope that verifies the middleware forwards without touching the context — small addition, but it documents the behavior and catches regressions
✅ Things Done Well
- Correct pure ASGI pattern:
__call__(scope, receive, send)with scope-type guard Headers(scope=scope)is the right zero-copy way to read headers in pure ASGI — avoids materializing the full request- Docstring clearly explains the behavioral change and compatibility
self.appstored directly — no unnecessary wrapping- CI is green on all substantive checks (quality, tests, build, CodeQL, CLA)
Comment on lines
+50
to
+56
| async def __call__(self, scope: dict, receive: Callable, send: Callable) -> None: | ||
| if scope["type"] != "http": | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| headers = Headers(raw=scope["headers"]) | ||
| envelope = RequestEnvelope(headers=dict(headers)) |
Contributor
There was a problem hiding this comment.
Would it be possible to use a Starlette type instead of a dictionary for scope?
This branch has not been deployed
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.
Removes the dependency on BaseHTTPMiddleware in StarletteContextMiddleware, implementing it as a pure ASGI callable instead. This avoids the double-wrapping issue in Starlette that breaks streaming responses and SSE.
Description
Replaces
BaseHTTPMiddlewarewith a pure ASGI callable inStarletteContextMiddleware. Removes unused imports (Request,Response) — onlyHeadersfromstarlette.datastructuresis needed. Non-HTTP scopes (lifespan, websocket) are forwarded without modification.This is not a breaking change because:
__init__(self, app, providers)— no changeapp.add_middleware()call site is unaffected: Starlette forwardskwargsthe same way for bothBaseHTTPMiddlewaresubclasses and pure ASGI classesStarletteContextMiddlewareis not exported from any__init__.py— only used internally viaadapters/_starlette.pyBaseHTTPMiddleware-specific behavior (dispatch,Request,Response)Related Issue
Closes #<issue_number>
(Link to the GitHub issue this PR addresses)
Type of Change
Please check the relevant option:
How to Test
StarletteContextMiddlewareto a FastAPI app viaapp.add_middleware(StarletteContextMiddleware, providers=[...])get_context())Checklist
Before submitting your PR, please review and check the following:
/security-reviewand addressed all ❌ findingsBreaking Changes
N/A — this refactor does not introduce any breaking changes. See the "This is not a breaking change" section above.
Additional Notes
BaseHTTPMiddlewarein Starlette has a known double-wrapping issue that breaks streaming responses and SSE (Server-Sent Events). Pure ASGI middleware avoids this entirely. See: https://www.starlette.io/middleware/#basehttpmiddleware