diff --git a/src/sap_cloud_sdk/core/runtime_context/starlette.py b/src/sap_cloud_sdk/core/runtime_context/starlette.py index eb0fcb05..e76cae57 100644 --- a/src/sap_cloud_sdk/core/runtime_context/starlette.py +++ b/src/sap_cloud_sdk/core/runtime_context/starlette.py @@ -1,6 +1,6 @@ """Starlette/FastAPI context middleware.""" -from typing import Any, List +from typing import Any, Callable, List from sap_cloud_sdk.core.runtime_context._context import ( RuntimeContext, @@ -10,9 +10,7 @@ from sap_cloud_sdk.core.runtime_context._protocol import ContextProvider try: - from starlette.middleware.base import BaseHTTPMiddleware - from starlette.requests import Request - from starlette.responses import Response + from starlette.datastructures import Headers except ImportError as exc: raise ImportError( "The 'starlette' package is required to use StarletteContextMiddleware. " @@ -29,24 +27,33 @@ def _merge(contexts: List[RuntimeContext]) -> RuntimeContext: return RuntimeContext(merged) -class StarletteContextMiddleware(BaseHTTPMiddleware): +class StarletteContextMiddleware: """Starlette/FastAPI middleware that populates the SDK runtime context. + Implemented as a pure ASGI middleware (no dependency on ``BaseHTTPMiddleware``), + so it is compatible with both Starlette and FastAPI via ``app.add_middleware()``. + Builds a :class:`~sap_cloud_sdk.core.runtime_context.RequestEnvelope` from each inbound request, runs all *providers* against it, and merges the results into a single :class:`~sap_cloud_sdk.core.runtime_context.RuntimeContext` available via :func:`~sap_cloud_sdk.core.runtime_context.get_context` for the duration of that request. + Non-HTTP scopes (lifespan, websocket) are forwarded without modification. First writer wins per key when merging across providers. """ def __init__(self, app: Any, providers: List[ContextProvider]) -> None: - super().__init__(app) + self.app = app self._providers = providers - async def dispatch(self, request: Request, call_next: Any) -> Response: - envelope = RequestEnvelope(headers=dict(request.headers)) + 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)) ctx = _merge([p.extract(envelope) for p in self._providers]) async with async_sdk_context(ctx): - return await call_next(request) + await self.app(scope, receive, send)