-
Notifications
You must be signed in to change notification settings - Fork 13
refactor: Rewrite server middleware with websocket support #1473
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import logging | ||
|
|
||
| from opentelemetry.context import attach | ||
| from opentelemetry.propagate import get_global_textmap | ||
| from starlette.types import ASGIApp, Message, Receive, Scope, Send | ||
|
|
||
| from blueapi import __version__ | ||
| from blueapi.config import ApplicationConfig | ||
|
|
||
| OBS_LOGGER = logging.getLogger("blueapi.service.middleware.observability") | ||
|
|
||
| CONTEXT_HEADER = ApplicationConfig.CONTEXT_HEADER.encode() | ||
| VENDOR_CONTEXT_HEADER = ApplicationConfig.VENDOR_CONTEXT_HEADER.encode() | ||
|
|
||
| API_VERSION = (b"x-api-version", ApplicationConfig.REST_API_VERSION.encode("utf-8")) | ||
| VERSION = (b"x-blueapi-version", __version__.encode("utf-8")) | ||
|
|
||
|
|
||
| class VersionHeaders: | ||
| def __init__(self, app: ASGIApp): | ||
| self.app = app | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send): | ||
| if scope.get("type") not in ("websocket", "http"): | ||
| return await self.app(scope, receive, send) | ||
|
|
||
| async def local_send(message: Message): | ||
| if message["type"] in ("websocket.accept", "http.response.start"): | ||
| message["headers"].append(VERSION) | ||
| message["headers"].append(API_VERSION) | ||
| await send(message) | ||
|
|
||
| return await self.app(scope, receive, local_send) | ||
|
|
||
|
|
||
| class ObservabilityContextPropagator: | ||
| def __init__(self, app: ASGIApp): | ||
| self.app = app | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send): | ||
| if scope.get("type") not in ("http", "websocket"): | ||
| return await self.app(scope, receive, send) | ||
|
|
||
| ctx = None | ||
| v_ctx = None | ||
| for key, val in scope.get("headers", ()): | ||
| if key == CONTEXT_HEADER: | ||
| ctx = val.decode() | ||
| elif key == VENDOR_CONTEXT_HEADER: | ||
| v_ctx = val.decode() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I assume that
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I hope so. And if not I think the 'last entry wins' approach is probably fine |
||
| if ctx: | ||
| OBS_LOGGER.debug("Propagating observability context: %s, %s", ctx, v_ctx) | ||
| carrier = {ApplicationConfig.CONTEXT_HEADER: ctx} | ||
| if v_ctx: | ||
| carrier[ApplicationConfig.VENDOR_CONTEXT_HEADER] = v_ctx | ||
| attach(get_global_textmap().extract(carrier)) | ||
|
|
||
| return await self.app(scope, receive, send) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| from unittest.mock import AsyncMock, MagicMock, Mock, patch | ||
|
|
||
| import pytest | ||
| from starlette.types import ASGIApp | ||
|
|
||
| from blueapi.config import ApplicationConfig | ||
| from blueapi.service.middleware import ( | ||
| API_VERSION, | ||
| CONTEXT_HEADER, | ||
| VENDOR_CONTEXT_HEADER, | ||
| VERSION, | ||
| ObservabilityContextPropagator, | ||
| VersionHeaders, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def app(): | ||
| return AsyncMock(spec=ASGIApp) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "protocol,message_type", | ||
| [("http", "http.response.start"), ("websocket", "websocket.accept")], | ||
| ) | ||
| async def test_version_headers_added(app: Mock, protocol: str, message_type: str): | ||
| vh = VersionHeaders(app) | ||
|
|
||
| send = AsyncMock() | ||
| scope = {"type": protocol} | ||
| await vh(scope, Mock(), send) | ||
|
|
||
| # the middleware wraps the send function so we need to extract the function | ||
| # the app was actually called with | ||
| local_send = app.call_args[0][2] | ||
|
|
||
| # Calling the wrapped send method here is equivalent to what the downstream | ||
| # framework would do after the middleware has done its thing | ||
| message = {"type": message_type, "headers": []} | ||
| await local_send(message) | ||
|
|
||
| # Check the headers were sent to the original send method | ||
| send.assert_called_once_with( | ||
| {"type": message_type, "headers": [VERSION, API_VERSION]} | ||
| ) | ||
|
|
||
|
|
||
| async def test_version_headers_ignore_non_http_or_websockets(app: Mock): | ||
| vh = VersionHeaders(app) | ||
|
|
||
| scope = {"type": "other"} | ||
| send = Mock() | ||
| recv = Mock() | ||
|
|
||
| await vh(scope, recv, send) | ||
|
|
||
| # for non-http/ws requests, the original args are passed directly | ||
| app.assert_called_once_with(scope, recv, send) | ||
|
|
||
|
|
||
| async def test_obs_context_ignores_non_http_or_websockets(app: Mock): | ||
| ocp = ObservabilityContextPropagator(app) | ||
|
|
||
| scope = MagicMock() | ||
| scope.__getitem__.side_effect = {"type": "other"}.__getitem__ | ||
|
|
||
| with patch("blueapi.service.middleware.attach") as att: | ||
| await ocp(scope, Mock(), Mock()) | ||
|
|
||
| att.assert_not_called() | ||
| scope.get.assert_called_once_with("type") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("protocol", ["http", "websocket"]) | ||
| async def test_obs_context_passes_context(app: Mock, protocol: str): | ||
| ocp = ObservabilityContextPropagator(app) | ||
| scope = {"type": protocol, "headers": ((CONTEXT_HEADER, b"req_context"),)} | ||
|
|
||
| with patch("blueapi.service.middleware.attach") as att: | ||
| with patch("blueapi.service.middleware.get_global_textmap") as get_global: | ||
| get_global.return_value.extract.side_effect = lambda x: x | ||
| await ocp(scope, Mock(), Mock()) | ||
|
|
||
| att.assert_called_once_with({ApplicationConfig.CONTEXT_HEADER: "req_context"}) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("protocol", ["http", "websocket"]) | ||
| async def test_obs_context_passes_vendor_context(app: Mock, protocol: str): | ||
| ocp = ObservabilityContextPropagator(app) | ||
| scope = { | ||
| "type": protocol, | ||
| "headers": ( | ||
| (CONTEXT_HEADER, b"req_context"), | ||
| (VENDOR_CONTEXT_HEADER, b"vendor_context"), | ||
| ), | ||
| } | ||
|
|
||
| with patch("blueapi.service.middleware.attach") as att: | ||
| with patch("blueapi.service.middleware.get_global_textmap") as get_global: | ||
| get_global.return_value.extract.side_effect = lambda x: x | ||
| await ocp(scope, Mock(), Mock()) | ||
|
|
||
| att.assert_called_once_with( | ||
| { | ||
| ApplicationConfig.CONTEXT_HEADER: "req_context", | ||
| ApplicationConfig.VENDOR_CONTEXT_HEADER: "vendor_context", | ||
| } | ||
| ) |
Uh oh!
There was an error while loading. Please reload this page.