Skip to content
Myr

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

6 files+72 added−87 removed

modified:httpx/concurrency/asyncio.py+38 added-38 removed
49 unmodified lines
50 self.stream_reader = stream_reader51 self.stream_writer = stream_writer52 self.timeout = timeout5354 self._inner: typing.Optional[TCPStream] = None5556 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 )6465 stream_reader = asyncio.StreamReader()66 protocol = asyncio.StreamReaderProtocol(stream_reader)67 transport = self.stream_writer.transport6869 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 )7980 stream_reader.set_transport(transport)81 stream_writer = asyncio.StreamWriter(82 transport=transport, protocol=protocol, reader=stream_reader, loop=loop83 )8485 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_stream9192 def get_http_version(self) -> str:93 ssl_object = self.stream_writer.get_extra_info("ssl_object")9495 if ssl_object is None:
142 unmodified lines
238 return TCPStream(239 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout240 )241204 async def start_tls(205 self,206 stream: BaseTCPStream,207 hostname: str,208 ssl_context: ssl.SSLContext,209 timeout: TimeoutConfig,210 ) -> BaseTCPStream:211212 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 )217218 assert isinstance(stream, TCPStream)219220 stream_reader = asyncio.StreamReader()221 protocol = asyncio.StreamReaderProtocol(stream_reader)222 transport = stream.stream_writer.transport223224 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 )234235 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 stream241242 async def run_in_threadpool(243 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any244 ) -> typing.Any:245 if kwargs:
49 unmodified lines
modified:httpx/concurrency/base.py+5 added-9 removed
45 unmodified lines
4647 def get_http_version(self) -> str:48 raise NotImplementedError() # pragma: no cover4950 async def start_tls(51 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig52 ) -> "BaseTCPStream":53 raise NotImplementedError() # pragma: no cover5455 async def read(56 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None57 ) -> bytes:58 raise NotImplementedError() # pragma: no cover
64 unmodified lines
123 timeout: TimeoutConfig,124 ) -> BaseTCPStream:125 raise NotImplementedError() # pragma: no cover126122 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 cover130127 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:128 raise NotImplementedError() # pragma: no cover129130 async def run_in_threadpool(
62 unmodified lines
modified:httpx/concurrency/trio.py+20 added-24 removed
32 unmodified lines
33 self.timeout = timeout34 self.write_buffer = b""35 self.write_lock = trio.Lock()3637 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""4344 connect_timeout = _or_inf(timeout.connect_timeout)45 ssl_stream = trio.SSLStream(46 self.stream, ssl_context=ssl_context, server_hostname=hostname47 )4849 with trio.move_on_after(connect_timeout) as cancel_scope:50 await ssl_stream.do_handshake()5152 if cancel_scope.cancelled_caught:53 raise ConnectTimeout()5455 return TCPStream(ssl_stream, self.timeout)5657 def get_http_version(self) -> str:58 if not isinstance(self.stream, trio.SSLStream):59 return "HTTP/1.1"60
129 unmodified lines
190 raise ConnectTimeout()191192 return TCPStream(stream=stream, timeout=timeout)193174 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)182183 connect_timeout = _or_inf(timeout.connect_timeout)184 ssl_stream = trio.SSLStream(185 stream.stream, ssl_context=ssl_context, server_hostname=hostname186 )187188 with trio.move_on_after(connect_timeout) as cancel_scope:189 await ssl_stream.do_handshake()190191 if cancel_scope.cancelled_caught:192 raise ConnectTimeout()193194 stream.stream = ssl_stream195196 return stream197194 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 lines
modified:httpx/dispatch/proxy_http.py+2 added-5 removed
190 unmodified lines
191 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 lines
modified:tests/dispatch/utils.py+6 added-10 removed
182 unmodified lines
183 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)184 )185 return self.stream186187 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.stream196187 # 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 line
192class MockRawSocketStream(BaseTCPStream):193 def __init__(self, backend: MockRawSocketBackend):194 self.backend = backend195196 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)201202 def get_http_version(self) -> str:203 return "HTTP/1.1"204205 def write_no_block(self, data: bytes) -> None:
17 unmodified lines
modified:tests/test_concurrency.py+1 added-1 removed
43 unmodified lines
44 try:45 assert stream.is_connection_dropped() is False46 assert get_cipher(stream) is None4748 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 None5152 await stream.write(b"GET / HTTP/1.1\r\n\r\n")
4 unmodified lines