Repository navigation
Add AsyncIO backend #155
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
Draft
cgl
wants to merge
1
commit into
main
Choose a base branch
from
feat/asyncio-backend
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.
Draft
Add AsyncIO backend #155
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import ssl | ||
| import types | ||
| import typing | ||
| from typing import Self | ||
|
|
||
| import truststore | ||
|
|
||
| from .base import AsyncNetworkBackend, AsyncNetworkStream | ||
|
|
||
| __all__ = ["AsyncioBackend", "AsyncioServer", "AsyncioStream"] | ||
|
|
||
|
|
||
| class AsyncioStream(AsyncNetworkStream): | ||
| def __init__( | ||
| self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter | ||
| ) -> None: | ||
| self._reader = reader | ||
| self._writer = writer | ||
| self._is_closed = False | ||
|
|
||
| async def read(self, size: int = -1) -> bytes: | ||
| if size == 0: | ||
| raise ValueError("Size must be greater than zero.") | ||
| max_bytes = 64 * 1024 if size < 0 else size | ||
| return await self._reader.read(max_bytes) | ||
|
|
||
| async def write(self, data: bytes) -> None: | ||
| if not data: | ||
| return | ||
| self._writer.write(data) | ||
| await self._writer.drain() | ||
|
|
||
| async def aclose(self) -> None: | ||
| if self._is_closed: | ||
| return # pragma: no cover | ||
| self._is_closed = True | ||
| self._writer.close() | ||
| try: | ||
| await self._writer.wait_closed() | ||
| except (ConnectionError, OSError): # pragma: no cover | ||
| pass | ||
|
|
||
| async def __aenter__(self) -> Self: | ||
| return self | ||
|
|
||
| async def __aexit__( | ||
| self, | ||
| exc_type: type[BaseException] | None = None, | ||
| exc_value: BaseException | None = None, | ||
| traceback: types.TracebackType | None = None, | ||
| ) -> None: | ||
| await self.aclose() | ||
|
|
||
| def __repr__(self) -> str: | ||
| description = " CLOSED" if self._is_closed else "" | ||
| return f"<AsyncioStream{description}>" | ||
|
|
||
|
|
||
| class AsyncioBackend(AsyncNetworkBackend): | ||
| def __init__(self, ssl_ctx: ssl.SSLContext | None = None) -> None: | ||
| self._ssl_ctx = self.create_default_context() if ssl_ctx is None else ssl_ctx | ||
|
|
||
| def create_default_context(self) -> ssl.SSLContext: | ||
| return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) | ||
|
|
||
| async def connect(self, host: str, port: int) -> AsyncioStream: | ||
| reader, writer = await asyncio.open_connection(host, port) | ||
| return AsyncioStream(reader, writer) | ||
|
|
||
| async def connect_tls( | ||
| self, host: str, port: int, hostname: str = "" | ||
| ) -> AsyncioStream: | ||
| reader, writer = await asyncio.open_connection( | ||
| host, | ||
| port, | ||
| ssl=self._ssl_ctx, | ||
| server_hostname=hostname or host, | ||
| ) | ||
| return AsyncioStream(reader, writer) | ||
|
|
||
| def serve( | ||
| self, | ||
| host: str, | ||
| port: int, | ||
| handler: typing.Callable[[AsyncioStream], typing.Awaitable[None]], | ||
| ) -> AsyncioServer: | ||
| return AsyncioServer(host, port, handler) | ||
|
|
||
| def __repr__(self) -> str: | ||
| return "<AsyncioBackend>" | ||
|
|
||
|
|
||
| class AsyncioServer: | ||
| def __init__( | ||
| self, | ||
| host: str, | ||
| port: int, | ||
| handler: typing.Callable[[AsyncioStream], typing.Awaitable[None]], | ||
| ) -> None: | ||
| self.host = host | ||
| self.port = port | ||
| self._handler = handler | ||
| self._server: asyncio.Server | None = None | ||
| self._tasks: set[asyncio.Task[None]] = set() | ||
|
|
||
| async def __aenter__(self) -> Self: | ||
| self._server = await asyncio.start_server(self._accept, self.host, self.port) | ||
| sockets = self._server.sockets | ||
| if self.port == 0 and sockets: | ||
| self.port = int(sockets[0].getsockname()[1]) | ||
| return self | ||
|
|
||
| async def __aexit__( | ||
| self, | ||
| exc_type: type[BaseException] | None = None, | ||
| exc_value: BaseException | None = None, | ||
| traceback: types.TracebackType | None = None, | ||
| ) -> None: | ||
| assert self._server is not None | ||
| self._server.close() | ||
| await self._server.wait_closed() | ||
|
|
||
| tasks = tuple(self._tasks) | ||
| for task in tasks: | ||
| task.cancel() | ||
| if tasks: | ||
| await asyncio.gather(*tasks, return_exceptions=True) # pragma: no cover | ||
|
|
||
| def _accept( | ||
| self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter | ||
| ) -> None: | ||
| task = asyncio.create_task(self._handle_stream(reader, writer)) | ||
| self._tasks.add(task) | ||
| task.add_done_callback(self._tasks.discard) | ||
|
|
||
| async def _handle_stream( | ||
| self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter | ||
| ) -> None: | ||
| stream = AsyncioStream(reader, writer) | ||
| try: | ||
| await self._handler(stream) | ||
| finally: | ||
| await stream.aclose() | ||
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,45 @@ | ||
| import asyncio | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
|
|
||
| from hip.backends.asyncio import AsyncioBackend, AsyncioStream | ||
|
|
||
|
|
||
| def test_connect_serve_context_managers(): | ||
| async def send_hello(stream): | ||
| await stream.write(b"hello") | ||
|
|
||
| async def run(): | ||
| backend = AsyncioBackend() | ||
| assert repr(backend) == "<AsyncioBackend>" | ||
|
|
||
| async with backend.serve("127.0.0.1", 0, send_hello) as server: | ||
| stream = await backend.connect(server.host, server.port) | ||
|
|
||
| async with stream: | ||
| with pytest.raises(ValueError, match="Size must be greater than zero"): | ||
| await stream.read(0) | ||
|
|
||
| received = b"" | ||
| while chunk := await stream.read(): | ||
| received += chunk | ||
| assert received == b"hello" | ||
|
|
||
| assert "CLOSED" in repr(stream) | ||
|
|
||
| asyncio.run(run()) | ||
|
|
||
|
|
||
| def test_write_empty(): | ||
| async def run(): | ||
| reader = AsyncMock() | ||
| writer = AsyncMock() | ||
| stream = AsyncioStream(reader, writer) | ||
|
|
||
| await stream.write(b"") | ||
|
|
||
| writer.write.assert_not_called() | ||
| writer.drain.assert_not_awaited() | ||
|
|
||
| asyncio.run(run()) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IOin caps (?)