Add ConcurrencyBackend.start_tls() (#263)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Seth Michael Larson · committed by GitHub · parent a4b93b9 · Browse files · 8 files·+85 added−7 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+85 added−7 removed
- tests:+31 added−0 removed
- other:+54 added−7 removed
Provenance
- Commit
1872ae8- Tree
4f81f3b- Author
Seth Michael Larson <sethmichaellarson@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
a4b93b9
8 files changed+85 added−7 removed
modified:httpx/concurrency/asyncio.py+39 added-1 removed
16 unmodified lines17 from ..config import PoolLimits, TimeoutConfig18 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19 from .base import (20 BaseBackgroundManager,21- BasePoolSemaphore,21 BaseEvent,22+ BasePoolSemaphore,23 BaseQueue,24 BaseStream,25 ConcurrencyBackend,26 TimeoutFlag,166 unmodified lines193 return Stream(194 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout195 )196 197+ async def start_tls(198+ self,199+ stream: BaseStream,200+ hostname: str,201+ ssl_context: ssl.SSLContext,202+ timeout: TimeoutConfig,203+ ) -> BaseStream:204+205+ loop = self.loop206+ if not hasattr(loop, "start_tls"): # pragma: no cover207+ raise NotImplementedError(208+ "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"209+ )210+211+ assert isinstance(stream, Stream)212+213+ stream_reader = asyncio.StreamReader()214+ protocol = asyncio.StreamReaderProtocol(stream_reader)215+ transport = stream.stream_writer.transport216+217+ loop_start_tls = loop.start_tls # type: ignore218+ transport = await asyncio.wait_for(219+ loop_start_tls(220+ transport=transport,221+ protocol=protocol,222+ sslcontext=ssl_context,223+ server_hostname=hostname,224+ ),225+ timeout=timeout.connect_timeout,226+ )227+228+ stream_reader.set_transport(transport)229+ stream.stream_reader = stream_reader230+ stream.stream_writer = asyncio.StreamWriter(231+ transport=transport, protocol=protocol, reader=stream_reader, loop=loop232+ )233+ return stream234+235 async def run_in_threadpool(236 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any237 ) -> typing.Any:238 if kwargs:49 unmodified linesmodified:httpx/concurrency/base.py+9 added
114 unmodified lines115 timeout: TimeoutConfig,116 ) -> BaseStream:117 raise NotImplementedError() # pragma: no cover118 119+ async def start_tls(120+ self,121+ stream: BaseStream,122+ hostname: str,123+ ssl_context: ssl.SSLContext,124+ timeout: TimeoutConfig,125+ ) -> BaseStream:126+ raise NotImplementedError() # pragma: no cover127+128 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:129 raise NotImplementedError() # pragma: no cover130 131 async def run_in_threadpool(55 unmodified linesmodified:httpx/dispatch/asgi.py+2 added-2 removed
1 import typing2 3-from .base import AsyncDispatcher4-from ..concurrency.base import ConcurrencyBackend3 from ..concurrency.asyncio import AsyncioBackend4+from ..concurrency.base import ConcurrencyBackend5 from ..config import CertTypes, TimeoutTypes, VerifyTypes6 from ..models import AsyncRequest, AsyncResponse7+from .base import AsyncDispatcher8 9 10 class ASGIDispatch(AsyncDispatcher):11 """183 unmodified linesmodified:httpx/dispatch/connection_pool.py+1 added-1 removed
1 import typing2 3-from .base import AsyncDispatcher3 from ..concurrency.asyncio import AsyncioBackend4 from ..concurrency.base import ConcurrencyBackend5 from ..config import (6 DEFAULT_POOL_LIMITS,4 unmodified lines11 TimeoutTypes,12 VerifyTypes,13 )14 from ..models import AsyncRequest, AsyncResponse, Origin15+from .base import AsyncDispatcher16 from .connection import HTTPConnection17 18 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]19 150 unmodified linesmodified:httpx/dispatch/connection.py+1 added-1 removed
1 import functools2 import ssl3 import typing4 5-from .base import AsyncDispatcher5 from ..concurrency.asyncio import AsyncioBackend6 from ..concurrency.base import ConcurrencyBackend7 from ..config import (8 DEFAULT_TIMEOUT_CONFIG,5 unmodified lines14 TimeoutTypes,15 VerifyTypes,16 )17 from ..models import AsyncRequest, AsyncResponse, Origin18+from .base import AsyncDispatcher19 from .http2 import HTTP2Connection20 from .http11 import HTTP11Connection21 22 # Callback signature: async def callback(conn: HTTPConnection) -> None105 unmodified linesmodified:httpx/dispatch/threaded.py+1 added-1 removed
1-from .base import AsyncDispatcher, Dispatcher1 from ..concurrency.base import ConcurrencyBackend2 from ..config import CertTypes, TimeoutTypes, VerifyTypes3 from ..models import (4 AsyncRequest,4 unmodified lines9 RequestData,10 Response,11 ResponseContent,12 )13+from .base import AsyncDispatcher, Dispatcher14 15 16 class ThreadedDispatcher(AsyncDispatcher):17 """80 unmodified linesmodified:httpx/dispatch/wsgi.py+1 added-1 removed
1 import io2 import typing3 4-from .base import Dispatcher4 from ..config import CertTypes, TimeoutTypes, VerifyTypes5 from ..models import Request, Response6+from .base import Dispatcher7 8 9 class WSGIDispatch(Dispatcher):10 """154 unmodified linesadded:tests/test_concurrency.py+31 added
1+import sys2+3+import pytest4+5+from httpx import AsyncioBackend, HTTPVersionConfig, SSLConfig, TimeoutConfig6+7+8+@pytest.mark.xfail(9+ sys.version_info < (3, 7),10+ reason="Requires Python 3.7+ for AbstractEventLoop.start_tls()",11+)12+@pytest.mark.asyncio13+async def test_start_tls_on_socket_stream(https_server):14+ """15+ See that the backend can make a connection without TLS then16+ start TLS on an existing connection.17+ """18+ backend = AsyncioBackend()19+ ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())20+ timeout = TimeoutConfig(5)21+22+ stream = await backend.connect("127.0.0.1", 8001, None, timeout)23+ assert stream.is_connection_dropped() is False24+ assert stream.stream_writer.get_extra_info("cipher", default=None) is None25+26+ stream = await backend.start_tls(stream, "127.0.0.1", ctx, timeout)27+ assert stream.is_connection_dropped() is False28+ assert stream.stream_writer.get_extra_info("cipher", default=None) is not None29+30+ await stream.write(b"GET / HTTP/1.1\r\n\r\n")31+ assert (await stream.read(8192, timeout)).startswith(b"HTTP/1.1 200 OK\r\n")