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
Provenance
- Commit
bc54dd0- Tree
b0c8d26- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
f55db15
3 files changed+18 added−42 removed
modified:httpx/concurrency/asyncio.py+6 added-22 removed
38 unmodified lines39 40 41 class 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()48 49 self._inner: typing.Optional[SocketStream] = None50 58 unmodified lines109 stream_writer = asyncio.StreamWriter(110 transport=transport, protocol=protocol, reader=stream_reader, loop=loop111 )112 117- 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 = self7 unmodified lines125 126 ident = ssl_object.selected_alpn_protocol()127 return "HTTP/2" if ident == "h2" else "HTTP/1.1"128 133- async def read(134- self, n: int, timeout: Timeout = None, flag: TimeoutFlag = None135- ) -> bytes:136- if timeout is None:137- timeout = self.timeout138-129+ 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_timeout17 unmodified lines151 152 return data153 154 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 return159 169- if timeout is None:170- timeout = self.timeout171-160 self.stream_writer.write(data)161 while True:162 try:163 await asyncio.wait_for( # type: ignore92 unmodified lines256 )257 except asyncio.TimeoutError:258 raise ConnectTimeout()259 272- return SocketStream(273- stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout274- )260+ return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)261 262 async def open_uds_stream(263 self,264 path: str,12 unmodified lines277 )278 except asyncio.TimeoutError:279 raise ConnectTimeout()280 295- return SocketStream(296- stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout297- )281+ return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)282 283 async def run_in_threadpool(284 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any285 ) -> typing.Any:43 unmodified linesmodified:httpx/concurrency/trio.py+6 added-15 removed
19 unmodified lines20 21 22 class 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()29 30 async def start_tls(9 unmodified lines40 41 if cancel_scope.cancelled_caught:42 raise ConnectTimeout()43 45- return SocketStream(ssl_stream, self.timeout)44+ return SocketStream(ssl_stream)45 46 def get_http_version(self) -> str:47 if not isinstance(self.stream, trio.SSLStream):48 return "HTTP/1.1"49 50 ident = self.stream.selected_alpn_protocol()51 return "HTTP/2" if ident == "h2" else "HTTP/1.1"52 54- async def read(55- self, n: int, timeout: Timeout = None, flag: TimeoutFlag = None56- ) -> bytes:57- if timeout is None:58- timeout = self.timeout59-53+ 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_timeout21 unmodified lines79 # See: https://github.com/encode/httpx/pull/143#issuecomment-51518177880 return stream.socket.is_readable()81 82 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 return87 94- if timeout is None:95- timeout = self.timeout96-88 write_timeout = _or_inf(timeout.write_timeout)89 90 while True:91 with trio.move_on_after(write_timeout):64 unmodified lines156 157 if cancel_scope.cancelled_caught:158 raise ConnectTimeout()159 169- return SocketStream(stream=stream, timeout=timeout)160+ return SocketStream(stream=stream)161 162 async def open_uds_stream(163 self,164 path: str,11 unmodified lines176 177 if cancel_scope.cancelled_caught:178 raise ConnectTimeout()179 189- return SocketStream(stream=stream, timeout=timeout)180+ return SocketStream(stream=stream)181 182 async def run_in_threadpool(183 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any184 ) -> typing.Any:51 unmodified linesmodified:tests/test_concurrency.py+6 added-5 removed
14 unmodified lines15 def get_trio_cipher(stream):16 return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None17 18 19-async def read_response(stream, timeout: float, should_contain: bytes) -> bytes:19+async 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 = False32 unmodified lines56 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 None59 60- 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)61 62 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 lines88 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 None91 92- 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)93 94 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 lines104 """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