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
base: main
Are you sure you want to change the base?
Add AsyncIO backend #155
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,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: | ||||||
|
Member
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.
Suggested change
|
||||||
| 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: | ||||||
|
Member
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.
Suggested change
|
||||||
| 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() | ||||||
| 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()) | ||
|
Comment on lines
+34
to
+45
Member
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. Can we drop the mock test? |
||
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.