Stream -> TCPStream (#339)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by Seth Michael Larson · parent 4616031 · Browse files · 8 files·+27 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+27 added−37 removed
- tests:+6 added−6 removed
- other:+21 added−31 removed
Provenance
- Commit
315a18b- Tree
9e0dbc2- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
4616031
8 files changed+27 added−37 removed
modified:httpx/concurrency/asyncio.py+8 added-18 removed
1-"""2-The `Stream` class here provides a lightweight layer over3-`asyncio.StreamReader` and `asyncio.StreamWriter`.4-5-Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6-7-These classes help encapsulate the timeout logic, make it easier to unit-test8-protocols, and help keep the rest of the package more `async`/`await`9-based, and less strictly `asyncio`-specific.10-"""1 import asyncio2 import functools3 import ssl4 import typing5 unmodified lines10 BaseBackgroundManager,11 BaseEvent,12 BasePoolSemaphore,13 BaseQueue,24- BaseStream,14+ BaseTCPStream,15 ConcurrencyBackend,16 TimeoutFlag,17 )18 20 unmodified lines39 40 MonkeyPatch.write = _fixed_write41 42 53-class Stream(BaseStream):43+class TCPStream(BaseTCPStream):44 def __init__(45 self,46 stream_reader: asyncio.StreamReader,47 stream_writer: asyncio.StreamWriter,117 unmodified lines165 except RuntimeError:166 self._loop = asyncio.new_event_loop()167 return self._loop168 179- async def connect(169+ async def open_tcp_stream(170 self,171 hostname: str,172 port: int,173 ssl_context: typing.Optional[ssl.SSLContext],174 timeout: TimeoutConfig,185- ) -> BaseStream:175+ ) -> BaseTCPStream:176 try:177 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore178 asyncio.open_connection(hostname, port, ssl=ssl_context),179 timeout.connect_timeout,180 )181 except asyncio.TimeoutError:182 raise ConnectTimeout()183 194- return Stream(184+ return TCPStream(185 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout186 )187 188 async def start_tls(189 self,200- stream: BaseStream,190+ stream: BaseTCPStream,191 hostname: str,192 ssl_context: ssl.SSLContext,193 timeout: TimeoutConfig,204- ) -> BaseStream:194+ ) -> BaseTCPStream:195 196 loop = self.loop197 if not hasattr(loop, "start_tls"): # pragma: no cover198 raise NotImplementedError(199 "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"200 )201 212- assert isinstance(stream, Stream)202+ assert isinstance(stream, TCPStream)203 204 stream_reader = asyncio.StreamReader()205 protocol = asyncio.StreamReaderProtocol(stream_reader)206 transport = stream.stream_writer.transport72 unmodified linesmodified:httpx/concurrency/base.py+6 added-6 removed
35 unmodified lines36 self.raise_on_read_timeout = False37 self.raise_on_write_timeout = True38 39 40-class BaseStream:40+class BaseTCPStream:41 """42- A stream with read/write operations. Abstracts away any asyncio-specific42+ A TCP stream with read/write operations. Abstracts away any asyncio-specific43 interfaces into a more generic base class, that we can use with alternate44 backends, or for stand-alone test cases.45 """46 62 unmodified lines109 raise NotImplementedError() # pragma: no cover110 111 112 class ConcurrencyBackend:113- async def connect(113+ async def open_tcp_stream(114 self,115 hostname: str,116 port: int,117 ssl_context: typing.Optional[ssl.SSLContext],118 timeout: TimeoutConfig,119- ) -> BaseStream:119+ ) -> BaseTCPStream:120 raise NotImplementedError() # pragma: no cover121 122 async def start_tls(123 self,124- stream: BaseStream,124+ stream: BaseTCPStream,125 hostname: str,126 ssl_context: ssl.SSLContext,127 timeout: TimeoutConfig,128- ) -> BaseStream:128+ ) -> BaseTCPStream:129 raise NotImplementedError() # pragma: no cover130 131 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:132 raise NotImplementedError() # pragma: no cover57 unmodified linesmodified:httpx/dispatch/connection.py+1 added-1 removed
83 unmodified lines84 else:85 on_release = functools.partial(self.release_func, self)86 87 logger.debug(f"start_connect host={host!r} port={port!r} timeout={timeout!r}")88- stream = await self.backend.connect(host, port, ssl_context, timeout)88+ stream = await self.backend.open_tcp_stream(host, port, ssl_context, timeout)89 http_version = stream.get_http_version()90 logger.debug(f"connected http_version={http_version!r}")91 92 if http_version == "HTTP/2":47 unmodified linesmodified:httpx/dispatch/http11.py+2 added-2 removed
1 import typing2 3 import h114 5-from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag5+from ..concurrency.base import BaseTCPStream, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7 from ..models import AsyncRequest, AsyncResponse8 from ..utils import get_logger9 20 unmodified lines30 READ_NUM_BYTES = 409631 32 def __init__(33 self,34- stream: BaseStream,34+ stream: BaseTCPStream,35 backend: ConcurrencyBackend,36 on_release: typing.Optional[OnReleaseCallback] = None,37 ):38 self.stream = stream170 unmodified linesmodified:httpx/dispatch/http2.py+2 added-2 removed
2 unmodified lines3 4 import h2.connection5 import h2.events6 7-from ..concurrency.base import BaseEvent, BaseStream, ConcurrencyBackend, TimeoutFlag7+from ..concurrency.base import BaseEvent, BaseTCPStream, ConcurrencyBackend, TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9 from ..models import AsyncRequest, AsyncResponse10 from ..utils import get_logger11 4 unmodified lines16 READ_NUM_BYTES = 409617 18 def __init__(19 self,20- stream: BaseStream,20+ stream: BaseTCPStream,21 backend: ConcurrencyBackend,22 on_release: typing.Callable = None,23 ):24 self.stream = stream200 unmodified linesmodified:httpx/__init__.py+2 added-2 removed
3 unmodified lines4 from .concurrency.asyncio import AsyncioBackend5 from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8- BaseStream,8+ BaseTCPStream,9 ConcurrencyBackend,10 )11 from .config import (12 USER_AGENT,98 unmodified lines111 "Timeout",112 "TooManyRedirects",113 "WriteTimeout",114 "AsyncDispatcher",115- "BaseStream",115+ "BaseTCPStream",116 "ConcurrencyBackend",117 "Dispatcher",118 "URL",119 "URLTypes",24 unmodified linesmodified:tests/dispatch/utils.py+5 added-5 removed
3 unmodified lines4 import h2.config5 import h2.connection6 import h2.events7 8-from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig8+from httpx import AsyncioBackend, BaseTCPStream, Request, TimeoutConfig9 from tests.concurrency import sleep10 11 12 class MockHTTP2Backend:1 unmodified line14 self.app = app15 self.backend = AsyncioBackend() if backend is None else backend16 self.server = None17 18- async def connect(18+ async def open_tcp_stream(19 self,20 hostname: str,21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: TimeoutConfig,24- ) -> BaseStream:24+ ) -> BaseTCPStream:25 self.server = MockHTTP2Server(self.app, backend=self.backend)26 return self.server27 28 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)31 32 33-class MockHTTP2Server(BaseStream):33+class MockHTTP2Server(BaseTCPStream):34 def __init__(self, app, backend):35 config = h2.config.H2Configuration(client_side=False)36 self.conn = h2.connection.H2Connection(config=config)37 self.app = app3 unmodified lines41 self.close_connection = False42 self.return_data = {}43 self.returning = {}44 45- # Stream interface45+ # TCP stream interface46 47 def get_http_version(self) -> str:48 return "HTTP/2"49 171 unmodified linesmodified:tests/test_concurrency.py+1 added-1 removed
17 unmodified lines18 backend = AsyncioBackend()19 ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())20 timeout = TimeoutConfig(5)21 22- stream = await backend.connect(22+ stream = await backend.open_tcp_stream(23 https_server.url.host, https_server.url.port, None, timeout24 )25 26 try:12 unmodified lines