-
-
Notifications
You must be signed in to change notification settings - Fork 79
feat(ws): native WebSocket transport, drop raw TCP listeners #1093
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
09c2049
feat(ws): native WebSocket transport, drop raw TCP listeners
Brutus5000 ff90608
fix(ws): lint, lockfile, metric double-count, untrusted forwarded IP
Brutus5000 e98d5b8
style: address codacy docstring findings
Brutus5000 3d73bd6
style: swap docstring summary placement (D212 vs D213)
Brutus5000 315774f
style: collapse docstrings to single-line to satisfy D212+D213
Brutus5000 27224f1
feat(ws): default WS_FORWARDED_IP_HEADER to X-Real-IP
Brutus5000 d3ed01c
test: raise WebSocketProtocol and SimpleJson coverage
Brutus5000 f871159
fix(ws): default path to '/' to match existing clients
Brutus5000 aec510b
fix(ws): terminate outgoing frames with '\n' for client framing
Brutus5000 0a27e07
test: assert_awaited for ws.close in abort test
Brutus5000 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
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
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
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,88 @@ | ||
| """A WebSocket-native wire protocol. | ||
|
|
||
| Each message is sent as exactly one WebSocket text frame containing a single | ||
| JSON object. No newline framing — frame boundaries delimit messages. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import contextlib | ||
| import json | ||
|
|
||
| from aiohttp import WSMsgType, web | ||
|
Check failure on line 11 in server/protocol/websocket.py
|
||
|
|
||
| import server.metrics as metrics | ||
|
|
||
| from .protocol import DisconnectedError, Protocol, json_encoder | ||
|
|
||
|
|
||
| class WebSocketProtocol(Protocol): | ||
| def __init__(self, ws, owned_session=None): | ||
| # Intentionally bypass Protocol.__init__: it expects a StreamReader / | ||
| # StreamWriter pair, which we do not have here. | ||
| self.ws = ws | ||
| self._pending: set[asyncio.Task] = set() | ||
| self._owned_session = owned_session | ||
|
|
||
| @staticmethod | ||
| def encode_message(message: dict) -> bytes: | ||
| return json_encoder.encode(message).encode() | ||
|
|
||
| @staticmethod | ||
| def decode_message(data: bytes) -> dict: | ||
| return json.loads(data) | ||
|
|
||
| def is_connected(self) -> bool: | ||
| return not self.ws.closed | ||
|
|
||
| async def read_message(self) -> dict: | ||
| msg = await self.ws.receive() | ||
| if msg.type == WSMsgType.TEXT: | ||
| return json.loads(msg.data) | ||
| if msg.type == WSMsgType.BINARY: | ||
| return json.loads(msg.data) | ||
| raise DisconnectedError("WebSocket connection closed") | ||
|
|
||
| def write_raw(self, data: bytes) -> None: | ||
| metrics.sent_messages.labels(self.__class__.__name__).inc() | ||
| if not self.is_connected(): | ||
| raise DisconnectedError("Protocol is not connected!") | ||
|
|
||
| text = data.decode() if isinstance(data, (bytes, bytearray)) else data | ||
| task = asyncio.create_task(self.ws.send_str(text)) | ||
| self._pending.add(task) | ||
| task.add_done_callback(self._pending.discard) | ||
|
|
||
| def write_message(self, message: dict) -> None: | ||
| if not self.is_connected(): | ||
| raise DisconnectedError("Protocol is not connected!") | ||
| self.write_raw(self.encode_message(message)) | ||
|
|
||
| def write_messages(self, messages: list[dict]) -> None: | ||
| metrics.sent_messages.labels(self.__class__.__name__).inc() | ||
| if not self.is_connected(): | ||
| raise DisconnectedError("Protocol is not connected!") | ||
| for message in messages: | ||
| self.write_raw(self.encode_message(message)) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| async def drain(self) -> None: | ||
| if not self._pending: | ||
| return | ||
| try: | ||
| await asyncio.gather(*self._pending) | ||
| except Exception as e: | ||
| await self.close() | ||
| raise DisconnectedError("Protocol connection lost!") from e | ||
|
|
||
| def abort(self) -> None: | ||
| for task in self._pending: | ||
| task.cancel() | ||
| if not self.ws.closed: | ||
| asyncio.create_task(self.ws.close()) | ||
|
|
||
| async def close(self) -> None: | ||
| with contextlib.suppress(Exception): | ||
| await self.ws.close() | ||
| if self._owned_session is not None: | ||
| with contextlib.suppress(Exception): | ||
| await self._owned_session.close() | ||
| self._owned_session = None | ||
Oops, something went wrong.
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.