Skip to content
Myr

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

8 files+27 added−37 removed

modified:httpx/concurrency/asyncio.py+8 added-18 removed
1"""2The `Stream` class here provides a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.67These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""1import asyncio2import functools3import ssl4import typing
5 unmodified lines
10 BaseBackgroundManager,11 BaseEvent,12 BasePoolSemaphore,13 BaseQueue,24 BaseStream,14 BaseTCPStream,15 ConcurrencyBackend,16 TimeoutFlag,17)18
20 unmodified lines
3940 MonkeyPatch.write = _fixed_write414253class Stream(BaseStream):43class TCPStream(BaseTCPStream):44 def __init__(45 self,46 stream_reader: asyncio.StreamReader,47 stream_writer: asyncio.StreamWriter,
117 unmodified lines
165 except RuntimeError:166 self._loop = asyncio.new_event_loop()167 return self._loop168179 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()183194 return Stream(184 return TCPStream(185 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout186 )187188 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:195196 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 )201212 assert isinstance(stream, Stream)202 assert isinstance(stream, TCPStream)203204 stream_reader = asyncio.StreamReader()205 protocol = asyncio.StreamReaderProtocol(stream_reader)206 transport = stream.stream_writer.transport
72 unmodified lines
modified:httpx/concurrency/base.py+6 added-6 removed
35 unmodified lines
36 self.raise_on_read_timeout = False37 self.raise_on_write_timeout = True383940class BaseStream:40class 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 lines
109 raise NotImplementedError() # pragma: no cover110111112class 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 cover121122 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 cover130131 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:132 raise NotImplementedError() # pragma: no cover
57 unmodified lines
modified:httpx/dispatch/connection.py+1 added-1 removed
83 unmodified lines
84 else:85 on_release = functools.partial(self.release_func, self)8687 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}")9192 if http_version == "HTTP/2":
47 unmodified lines
modified:httpx/dispatch/http11.py+2 added-2 removed
1import typing23import h1145from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag5from ..concurrency.base import BaseTCPStream, ConcurrencyBackend, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..models import AsyncRequest, AsyncResponse8from ..utils import get_logger9
20 unmodified lines
30 READ_NUM_BYTES = 40963132 def __init__(33 self,34 stream: BaseStream,34 stream: BaseTCPStream,35 backend: ConcurrencyBackend,36 on_release: typing.Optional[OnReleaseCallback] = None,37 ):38 self.stream = stream
170 unmodified lines
modified:httpx/dispatch/http2.py+2 added-2 removed
2 unmodified lines
34import h2.connection5import h2.events67from ..concurrency.base import BaseEvent, BaseStream, ConcurrencyBackend, TimeoutFlag7from ..concurrency.base import BaseEvent, BaseTCPStream, ConcurrencyBackend, TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..models import AsyncRequest, AsyncResponse10from ..utils import get_logger11
4 unmodified lines
16 READ_NUM_BYTES = 40961718 def __init__(19 self,20 stream: BaseStream,20 stream: BaseTCPStream,21 backend: ConcurrencyBackend,22 on_release: typing.Callable = None,23 ):24 self.stream = stream
200 unmodified lines
modified:httpx/__init__.py+2 added-2 removed
3 unmodified lines
4from .concurrency.asyncio import AsyncioBackend5from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8 BaseStream,8 BaseTCPStream,9 ConcurrencyBackend,10)11from .config import (12 USER_AGENT,
98 unmodified lines
111 "Timeout",112 "TooManyRedirects",113 "WriteTimeout",114 "AsyncDispatcher",115 "BaseStream",115 "BaseTCPStream",116 "ConcurrencyBackend",117 "Dispatcher",118 "URL",119 "URLTypes",
24 unmodified lines
modified:tests/dispatch/utils.py+5 added-5 removed
3 unmodified lines
4import h2.config5import h2.connection6import h2.events78from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig8from httpx import AsyncioBackend, BaseTCPStream, Request, TimeoutConfig9from tests.concurrency import sleep101112class MockHTTP2Backend:
1 unmodified line
14 self.app = app15 self.backend = AsyncioBackend() if backend is None else backend16 self.server = None1718 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.server2728 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)313233class MockHTTP2Server(BaseStream):33class 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 = app
3 unmodified lines
41 self.close_connection = False42 self.return_data = {}43 self.returning = {}4445 # Stream interface45 # TCP stream interface4647 def get_http_version(self) -> str:48 return "HTTP/2"49
171 unmodified lines
modified:tests/test_concurrency.py+1 added-1 removed
17 unmodified lines
18 backend = AsyncioBackend()19 ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())20 timeout = TimeoutConfig(5)2122 stream = await backend.connect(22 stream = await backend.open_tcp_stream(23 https_server.url.host, https_server.url.port, None, timeout24 )2526 try:
12 unmodified lines