Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions src/sap_cloud_sdk/core/runtime_context/starlette.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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. "
Expand All @@ -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))
Comment on lines +50 to +56

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to use a Starlette type instead of a dictionary for scope?

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)
Loading