Make start_tls a method on streams & return a new stream (#484)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Move start_tls to stream & return a new stream * asyncio: Keep a reference to the inner stream when upgrading to TLS
authored by Jamie Hewland · committed by Florimond Manca · parent ad38db8 · Browse files · 6 files·+72 added−87 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+72 added−87 removed
- tests:+7 added−11 removed
- other:+65 added−76 removed
Provenance
- Commit
644e8fc- Tree
3556e3d- Author
Jamie Hewland <jhewland@gmail.com>- Committer
Florimond Manca <florimond.manca@gmail.com>- Parent
ad38db8
6 files changed+72 added−87 removed
modified:httpx/concurrency/asyncio.py+38 added-38 removed
49 unmodified lines50 self.stream_reader = stream_reader51 self.stream_writer = stream_writer52 self.timeout = timeout53 54+ self._inner: typing.Optional[TCPStream] = None55+56+ async def start_tls(57+ self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig58+ ) -> BaseTCPStream:59+ loop = asyncio.get_event_loop()60+ if not hasattr(loop, "start_tls"): # pragma: no cover61+ raise NotImplementedError(62+ "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"63+ )64+65+ stream_reader = asyncio.StreamReader()66+ protocol = asyncio.StreamReaderProtocol(stream_reader)67+ transport = self.stream_writer.transport68+69+ loop_start_tls = loop.start_tls # type: ignore70+ transport = await asyncio.wait_for(71+ loop_start_tls(72+ transport=transport,73+ protocol=protocol,74+ sslcontext=ssl_context,75+ server_hostname=hostname,76+ ),77+ timeout=timeout.connect_timeout,78+ )79+80+ stream_reader.set_transport(transport)81+ stream_writer = asyncio.StreamWriter(82+ transport=transport, protocol=protocol, reader=stream_reader, loop=loop83+ )84+85+ ssl_stream = TCPStream(stream_reader, stream_writer, self.timeout)86+ # When we return a new TCPStream with new StreamReader/StreamWriter instances,87+ # we need to keep references to the old StreamReader/StreamWriter so that they88+ # are not garbage collected and closed while we're still using them.89+ ssl_stream._inner = self90+ return ssl_stream91+92 def get_http_version(self) -> str:93 ssl_object = self.stream_writer.get_extra_info("ssl_object")94 95 if ssl_object is None:142 unmodified lines238 return TCPStream(239 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout240 )241 204- async def start_tls(205- self,206- stream: BaseTCPStream,207- hostname: str,208- ssl_context: ssl.SSLContext,209- timeout: TimeoutConfig,210- ) -> BaseTCPStream:211-212- loop = self.loop213- if not hasattr(loop, "start_tls"): # pragma: no cover214- raise NotImplementedError(215- "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"216- )217-218- assert isinstance(stream, TCPStream)219-220- stream_reader = asyncio.StreamReader()221- protocol = asyncio.StreamReaderProtocol(stream_reader)222- transport = stream.stream_writer.transport223-224- loop_start_tls = loop.start_tls # type: ignore225- transport = await asyncio.wait_for(226- loop_start_tls(227- transport=transport,228- protocol=protocol,229- sslcontext=ssl_context,230- server_hostname=hostname,231- ),232- timeout=timeout.connect_timeout,233- )234-235- stream_reader.set_transport(transport)236- stream.stream_reader = stream_reader237- stream.stream_writer = asyncio.StreamWriter(238- transport=transport, protocol=protocol, reader=stream_reader, loop=loop239- )240- return stream241-242 async def run_in_threadpool(243 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any244 ) -> typing.Any:245 if kwargs:49 unmodified linesmodified:httpx/concurrency/base.py+5 added-9 removed
45 unmodified lines46 47 def get_http_version(self) -> str:48 raise NotImplementedError() # pragma: no cover49 50+ async def start_tls(51+ self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig52+ ) -> "BaseTCPStream":53+ raise NotImplementedError() # pragma: no cover54+55 async def read(56 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None57 ) -> bytes:58 raise NotImplementedError() # pragma: no cover64 unmodified lines123 timeout: TimeoutConfig,124 ) -> BaseTCPStream:125 raise NotImplementedError() # pragma: no cover126 122- async def start_tls(123- self,124- stream: BaseTCPStream,125- hostname: str,126- ssl_context: ssl.SSLContext,127- timeout: TimeoutConfig,128- ) -> BaseTCPStream:129- raise NotImplementedError() # pragma: no cover130-127 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:128 raise NotImplementedError() # pragma: no cover129 130 async def run_in_threadpool(62 unmodified linesmodified:httpx/concurrency/trio.py+20 added-24 removed
32 unmodified lines33 self.timeout = timeout34 self.write_buffer = b""35 self.write_lock = trio.Lock()36 37+ async def start_tls(38+ self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig39+ ) -> BaseTCPStream:40+ # Check that the write buffer is empty. We should never start a TLS stream41+ # while there is still pending data to write.42+ assert self.write_buffer == b""43+44+ connect_timeout = _or_inf(timeout.connect_timeout)45+ ssl_stream = trio.SSLStream(46+ self.stream, ssl_context=ssl_context, server_hostname=hostname47+ )48+49+ with trio.move_on_after(connect_timeout) as cancel_scope:50+ await ssl_stream.do_handshake()51+52+ if cancel_scope.cancelled_caught:53+ raise ConnectTimeout()54+55+ return TCPStream(ssl_stream, self.timeout)56+57 def get_http_version(self) -> str:58 if not isinstance(self.stream, trio.SSLStream):59 return "HTTP/1.1"60 129 unmodified lines190 raise ConnectTimeout()191 192 return TCPStream(stream=stream, timeout=timeout)193 174- async def start_tls(175- self,176- stream: BaseTCPStream,177- hostname: str,178- ssl_context: ssl.SSLContext,179- timeout: TimeoutConfig,180- ) -> BaseTCPStream:181- assert isinstance(stream, TCPStream)182-183- connect_timeout = _or_inf(timeout.connect_timeout)184- ssl_stream = trio.SSLStream(185- stream.stream, ssl_context=ssl_context, server_hostname=hostname186- )187-188- with trio.move_on_after(connect_timeout) as cancel_scope:189- await ssl_stream.do_handshake()190-191- if cancel_scope.cancelled_caught:192- raise ConnectTimeout()193-194- stream.stream = ssl_stream195-196- return stream197-194 async def run_in_threadpool(195 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any196 ) -> typing.Any:197 return await trio.to_thread.run_sync(75 unmodified linesmodified:httpx/dispatch/proxy_http.py+2 added-5 removed
190 unmodified lines191 f"tunnel_start_tls "192 f"proxy_url={self.proxy_url!r} "193 f"origin={origin!r}"194 )195- stream = await self.backend.start_tls(196- stream=stream,197- hostname=origin.host,198- ssl_context=ssl_context,199- timeout=timeout,195+ stream = await stream.start_tls(196+ hostname=origin.host, ssl_context=ssl_context, timeout=timeout197 )198 http_version = stream.get_http_version()199 logger.debug(200 f"tunnel_tls_complete "53 unmodified linesmodified:tests/dispatch/utils.py+6 added-10 removed
182 unmodified lines183 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)184 )185 return self.stream186 187- async def start_tls(188- self,189- stream: BaseTCPStream,190- hostname: str,191- ssl_context: ssl.SSLContext,192- timeout: TimeoutConfig,193- ) -> BaseTCPStream:194- self.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())195- return self.stream196-187 # Defer all other attributes and methods to the underlying backend.188 def __getattr__(self, name: str) -> typing.Any:189 return getattr(self.backend, name)190 1 unmodified line192 class MockRawSocketStream(BaseTCPStream):193 def __init__(self, backend: MockRawSocketBackend):194 self.backend = backend195 196+ async def start_tls(197+ self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig198+ ) -> BaseTCPStream:199+ self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())200+ return MockRawSocketStream(self.backend)201+202 def get_http_version(self) -> str:203 return "HTTP/1.1"204 205 def write_no_block(self, data: bytes) -> None:17 unmodified linesmodified:tests/test_concurrency.py+1 added-1 removed
43 unmodified lines44 try:45 assert stream.is_connection_dropped() is False46 assert get_cipher(stream) is None47 48- stream = await backend.start_tls(stream, https_server.url.host, ctx, timeout)48+ stream = await stream.start_tls(https_server.url.host, ctx, timeout)49 assert stream.is_connection_dropped() is False50 assert get_cipher(stream) is not None51 52 await stream.write(b"GET / HTTP/1.1\r\n\r\n")4 unmodified lines