Skip to content
Myr

Backend operations like .read(), .write() now have a manadatory timeout argument. (#611)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent f55db15 · Browse files · 3 files+18 added−42 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+18 added−42 removed

  • tests:+6 added−5 removed
  • other:+12 added−37 removed

3 files+18 added−42 removed

modified:httpx/concurrency/asyncio.py+6 added-22 removed
38 unmodified lines
394041class SocketStream(BaseSocketStream):42 def __init__(43 self,44 stream_reader: asyncio.StreamReader,45 stream_writer: asyncio.StreamWriter,46 timeout: Timeout,43 self, stream_reader: asyncio.StreamReader, stream_writer: asyncio.StreamWriter,44 ):45 self.stream_reader = stream_reader46 self.stream_writer = stream_writer50 self.timeout = timeout47 self.read_lock = asyncio.Lock()4849 self._inner: typing.Optional[SocketStream] = None50
58 unmodified lines
109 stream_writer = asyncio.StreamWriter(110 transport=transport, protocol=protocol, reader=stream_reader, loop=loop111 )112117 ssl_stream = SocketStream(stream_reader, stream_writer, self.timeout)113 ssl_stream = SocketStream(stream_reader, stream_writer)114 # When we return a new SocketStream with new StreamReader/StreamWriter instances115 # we need to keep references to the old StreamReader/StreamWriter so that they116 # are not garbage collected and closed while we're still using them.117 ssl_stream._inner = self
7 unmodified lines
125126 ident = ssl_object.selected_alpn_protocol()127 return "HTTP/2" if ident == "h2" else "HTTP/1.1"128133 async def read(134 self, n: int, timeout: Timeout = None, flag: TimeoutFlag = None135 ) -> bytes:136 if timeout is None:137 timeout = self.timeout138129 async def read(self, n: int, timeout: Timeout, flag: TimeoutFlag = None) -> bytes:130 while True:131 # Check our flag at the first possible moment, and use a fine132 # grained retry loop if we're not yet in read-timeout mode.133 should_raise = flag is None or flag.raise_on_read_timeout
17 unmodified lines
151152 return data153154 async def write(164 self, data: bytes, timeout: Timeout = None, flag: TimeoutFlag = None155 self, data: bytes, timeout: Timeout, flag: TimeoutFlag = None156 ) -> None:157 if not data:158 return159169 if timeout is None:170 timeout = self.timeout171160 self.stream_writer.write(data)161 while True:162 try:163 await asyncio.wait_for( # type: ignore
92 unmodified lines
256 )257 except asyncio.TimeoutError:258 raise ConnectTimeout()259272 return SocketStream(273 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout274 )260 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)261262 async def open_uds_stream(263 self,264 path: str,
12 unmodified lines
277 )278 except asyncio.TimeoutError:279 raise ConnectTimeout()280295 return SocketStream(296 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout297 )281 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)282283 async def run_in_threadpool(284 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any285 ) -> typing.Any:
43 unmodified lines
modified:httpx/concurrency/trio.py+6 added-15 removed
19 unmodified lines
202122class SocketStream(BaseSocketStream):23 def __init__(24 self, stream: typing.Union[trio.SocketStream, trio.SSLStream], timeout: Timeout,24 self, stream: typing.Union[trio.SocketStream, trio.SSLStream],25 ) -> None:26 self.stream = stream27 self.timeout = timeout27 self.read_lock = trio.Lock()28 self.write_lock = trio.Lock()2930 async def start_tls(
9 unmodified lines
4041 if cancel_scope.cancelled_caught:42 raise ConnectTimeout()4345 return SocketStream(ssl_stream, self.timeout)44 return SocketStream(ssl_stream)4546 def get_http_version(self) -> str:47 if not isinstance(self.stream, trio.SSLStream):48 return "HTTP/1.1"4950 ident = self.stream.selected_alpn_protocol()51 return "HTTP/2" if ident == "h2" else "HTTP/1.1"5254 async def read(55 self, n: int, timeout: Timeout = None, flag: TimeoutFlag = None56 ) -> bytes:57 if timeout is None:58 timeout = self.timeout5953 async def read(self, n: int, timeout: Timeout, flag: TimeoutFlag = None) -> bytes:54 while True:55 # Check our flag at the first possible moment, and use a fine56 # grained retry loop if we're not yet in read-timeout mode.57 should_raise = flag is None or flag.raise_on_read_timeout
21 unmodified lines
79 # See: https://github.com/encode/httpx/pull/143#issuecomment-51518177880 return stream.socket.is_readable()8182 async def write(89 self, data: bytes, timeout: Timeout = None, flag: TimeoutFlag = None83 self, data: bytes, timeout: Timeout, flag: TimeoutFlag = None84 ) -> None:85 if not data:86 return8794 if timeout is None:95 timeout = self.timeout9688 write_timeout = _or_inf(timeout.write_timeout)8990 while True:91 with trio.move_on_after(write_timeout):
64 unmodified lines
156157 if cancel_scope.cancelled_caught:158 raise ConnectTimeout()159169 return SocketStream(stream=stream, timeout=timeout)160 return SocketStream(stream=stream)161162 async def open_uds_stream(163 self,164 path: str,
11 unmodified lines
176177 if cancel_scope.cancelled_caught:178 raise ConnectTimeout()179189 return SocketStream(stream=stream, timeout=timeout)180 return SocketStream(stream=stream)181182 async def run_in_threadpool(183 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any184 ) -> typing.Any:
51 unmodified lines
modified:tests/test_concurrency.py+6 added-5 removed
14 unmodified lines
15def get_trio_cipher(stream):16 return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None171819async def read_response(stream, timeout: float, should_contain: bytes) -> bytes:19async def read_response(stream, timeout: Timeout, should_contain: bytes) -> bytes:20 # stream.read() only gives us *up to* as much data as we ask for. In order to21 # cleanly close the stream, we must read until the end of the HTTP response.22 response = b""23 ended = False
32 unmodified lines
56 stream = await stream.start_tls(https_server.url.host, ctx, timeout)57 assert stream.is_connection_dropped() is False58 assert get_cipher(stream) is not None5960 await stream.write(b"GET / HTTP/1.1\r\n\r\n")60 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)6162 response = await read_response(stream, timeout, should_contain=b"Hello, world")63 assert response.startswith(b"HTTP/1.1 200 OK\r\n")64
23 unmodified lines
88 stream = await stream.start_tls(https_uds_server.url.host, ctx, timeout)89 assert stream.is_connection_dropped() is False90 assert get_cipher(stream) is not None9192 await stream.write(b"GET / HTTP/1.1\r\n\r\n")92 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)9394 response = await read_response(stream, timeout, should_contain=b"Hello, world")95 assert response.startswith(b"HTTP/1.1 200 OK\r\n")96
7 unmodified lines
104 """105 stream = await backend.open_tcp_stream(106 server.url.host, server.url.port, ssl_context=None, timeout=Timeout(5)107 )108 timeout = Timeout(5)109 try:109 await stream.write(b"GET / HTTP/1.1\r\n\r\n")110 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)111 await run_concurrently(111 backend, lambda: stream.read(10), lambda: stream.read(10)112 backend, lambda: stream.read(10, timeout), lambda: stream.read(10, timeout)113 )114 finally:115 await stream.close()116
45 unmodified lines