-
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
Open
tpoliaw
wants to merge
4
commits into
main
Choose a base branch
from
common-middleware
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| 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() | ||
|
tpoliaw marked this conversation as resolved.
|
||
| 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) | ||
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
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
| 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", | ||
| } | ||
| ) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.