Skip to content
Myr

Drop TimeoutFlag (#618)

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 ab41a5d · Browse files · 4 files+52 added−150 removed
This commit

State

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

Diff stats

4 files+52 added−150 removed

  • other:+52 added−150 removed

4 files+52 added−150 removed

modified:httpx/concurrency/asyncio.py+16 added-47 removed
4 unmodified lines
5import typing67from ..config import PoolLimits, Timeout8from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9from .base import (10 BaseEvent,11 BasePoolSemaphore,12 BaseSocketStream,13 ConcurrencyBackend,14 TimeoutFlag,15)9from .base import BaseEvent, BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend1011SSL_MONKEY_PATCH_APPLIED = False1213
105 unmodified lines
119120 ident = ssl_object.selected_alpn_protocol()121 return "HTTP/2" if ident == "h2" else "HTTP/1.1"122129 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_timeout134 read_timeout = timeout.read_timeout if should_raise else 0.01135 try:136 async with self.read_lock:137 data = await asyncio.wait_for(138 self.stream_reader.read(n), read_timeout139 )140 except asyncio.TimeoutError:141 if should_raise:123 async def read(self, n: int, timeout: Timeout) -> bytes:124 try:125 async with self.read_lock:126 return await asyncio.wait_for(127 self.stream_reader.read(n), timeout.read_timeout128 )129 except asyncio.TimeoutError:130 raise ReadTimeout() from None142 raise ReadTimeout() from None143 # FIX(py3.6): yield control back to the event loop to give it a chance144 # to cancel `.read(n)` before we retry.145 # This prevents concurrent `.read()` calls, which asyncio146 # doesn't seem to allow on 3.6.147 # See: https://github.com/encode/httpx/issues/382148 await asyncio.sleep(0)149 else:150 break131152 return data153154 async def write(155 self, data: bytes, timeout: Timeout, flag: TimeoutFlag = None156 ) -> None:132 async def write(self, data: bytes, timeout: Timeout) -> None:133 if not data:134 return135136 self.stream_writer.write(data)161 while True:162 try:163 await asyncio.wait_for( # type: ignore164 self.stream_writer.drain(), timeout.write_timeout165 )166 break167 except asyncio.TimeoutError:168 # We check our flag at the first possible moment, in order to169 # allow us to suppress write timeouts, if we've since170 # switched over to read-timeout mode.171 should_raise = flag is None or flag.raise_on_write_timeout172 if should_raise:173 raise WriteTimeout() from None137 try:138 return await asyncio.wait_for(139 self.stream_writer.drain(), timeout.write_timeout140 )141 except asyncio.TimeoutError:142 raise WriteTimeout() from None143144 def is_connection_dropped(self) -> bool:145 # Counter-intuitively, what we really want to know here is whether the socket is146 # *readable*, i.e. whether it would return immediately with empty bytes if we
151 unmodified lines
modified:httpx/concurrency/base.py+1 added-33 removed
24 unmodified lines
2526 raise RuntimeError(f"Unknown or unsupported concurrency backend {backend!r}")272829class TimeoutFlag:30 """31 A timeout flag holds a state of either read-timeout or write-timeout mode.3233 We use this so that we can attempt both reads and writes concurrently, while34 only enforcing timeouts in one direction.3536 During a request/response cycle we start in write-timeout mode.3738 Once we've sent a request fully, or once we start seeing a response,39 then we switch to read-timeout mode instead.40 """4142 def __init__(self) -> None:43 self.raise_on_read_timeout = False44 self.raise_on_write_timeout = True4546 def set_read_timeouts(self) -> None:47 """48 Set the flag to read-timeout mode.49 """50 self.raise_on_read_timeout = True51 self.raise_on_write_timeout = False5253 def set_write_timeouts(self) -> None:54 """55 Set the flag to write-timeout mode.56 """57 self.raise_on_read_timeout = False58 self.raise_on_write_timeout = True596029class BaseSocketStream:30 """31 A socket stream with read/write operations. Abstracts away any asyncio-specific32 interfaces into a more generic base class, that we can use with alternate
7 unmodified lines
40 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout41 ) -> "BaseSocketStream":42 raise NotImplementedError() # pragma: no cover4376 async def read(self, n: int, timeout: Timeout, flag: typing.Any = None) -> bytes:44 async def read(self, n: int, timeout: Timeout) -> bytes:45 raise NotImplementedError() # pragma: no cover4647 async def write(self, data: bytes, timeout: Timeout) -> None:48 raise NotImplementedError() # pragma: no cover
92 unmodified lines
modified:httpx/concurrency/trio.py+33 added-58 removed
4 unmodified lines
5import trio67from ..config import PoolLimits, Timeout8from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9from .base import (10 BaseEvent,11 BasePoolSemaphore,12 BaseSocketStream,13 ConcurrencyBackend,14 TimeoutFlag,15)9from .base import BaseEvent, BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend101118def _or_inf(value: typing.Optional[float]) -> float:12def none_as_inf(value: typing.Optional[float]) -> float:13 return value if value is not None else float("inf")141516class SocketStream(BaseSocketStream):
6 unmodified lines
2324 async def start_tls(25 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout26 ) -> "SocketStream":33 connect_timeout = _or_inf(timeout.connect_timeout)27 connect_timeout = none_as_inf(timeout.connect_timeout)28 ssl_stream = trio.SSLStream(29 self.stream, ssl_context=ssl_context, server_hostname=hostname30 )3138 with trio.move_on_after(connect_timeout) as cancel_scope:32 with trio.move_on_after(connect_timeout):33 await ssl_stream.do_handshake()34 return SocketStream(ssl_stream)3541 if cancel_scope.cancelled_caught:42 raise ConnectTimeout()36 raise ConnectTimeout()3744 return SocketStream(ssl_stream)4538 def get_http_version(self) -> str:39 if not isinstance(self.stream, trio.SSLStream):40 return "HTTP/1.1"4142 ident = self.stream.selected_alpn_protocol()43 return "HTTP/2" if ident == "h2" else "HTTP/1.1"4453 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_timeout58 read_timeout = _or_inf(timeout.read_timeout if should_raise else 0.01)45 async def read(self, n: int, timeout: Timeout) -> bytes:46 read_timeout = none_as_inf(timeout.read_timeout)4760 with trio.move_on_after(read_timeout):61 async with self.read_lock:62 return await self.stream.receive_some(max_bytes=n)48 with trio.move_on_after(read_timeout):49 async with self.read_lock:50 return await self.stream.receive_some(max_bytes=n)5164 if should_raise:65 raise ReadTimeout() from None52 raise ReadTimeout()5354 async def write(self, data: bytes, timeout: Timeout) -> None:55 if not data:56 return5758 write_timeout = none_as_inf(timeout.write_timeout)5960 with trio.move_on_after(write_timeout):61 async with self.write_lock:62 return await self.stream.send_all(data)6364 raise WriteTimeout()6566 def is_connection_dropped(self) -> bool:67 # Adapted from: https://github.com/encode/httpx/pull/143#issuecomment-51520298268 stream = self.stream69
7 unmodified lines
77 # called `.recv()` on it, indicating that the other end has closed the socket.78 # See: https://github.com/encode/httpx/pull/143#issuecomment-51518177879 return stream.socket.is_readable()8082 async def write(83 self, data: bytes, timeout: Timeout, flag: TimeoutFlag = None84 ) -> None:85 if not data:86 return8788 write_timeout = _or_inf(timeout.write_timeout)8990 while True:91 with trio.move_on_after(write_timeout):92 async with self.write_lock:93 await self.stream.send_all(data)94 break95 # We check our flag at the first possible moment, in order to96 # allow us to suppress write timeouts, if we've since97 # switched over to read-timeout mode.98 should_raise = flag is None or flag.raise_on_write_timeout99 if should_raise:100 raise WriteTimeout() from None10181 async def close(self) -> None:82 await self.stream.aclose()8384
16 unmodified lines
101 async def acquire(self, timeout: float = None) -> None:102 if self.semaphore is None:103 return104126 timeout = _or_inf(timeout)105 timeout = none_as_inf(timeout)106107 with trio.move_on_after(timeout):108 await self.semaphore.acquire()109 return
14 unmodified lines
124 port: int,125 ssl_context: typing.Optional[ssl.SSLContext],126 timeout: Timeout,127 ) -> SocketStream:149 connect_timeout = _or_inf(timeout.connect_timeout)128 connect_timeout = none_as_inf(timeout.connect_timeout)129151 with trio.move_on_after(connect_timeout) as cancel_scope:130 with trio.move_on_after(connect_timeout):131 stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)132 if ssl_context is not None:133 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)134 await stream.do_handshake()135 return SocketStream(stream=stream)136157 if cancel_scope.cancelled_caught:158 raise ConnectTimeout()137 raise ConnectTimeout()138160 return SocketStream(stream=stream)161139 async def open_uds_stream(140 self,141 path: str,142 hostname: typing.Optional[str],143 ssl_context: typing.Optional[ssl.SSLContext],144 timeout: Timeout,145 ) -> SocketStream:169 connect_timeout = _or_inf(timeout.connect_timeout)146 connect_timeout = none_as_inf(timeout.connect_timeout)147171 with trio.move_on_after(connect_timeout) as cancel_scope:148 with trio.move_on_after(connect_timeout):149 stream: trio.SocketStream = await trio.open_unix_socket(path)150 if ssl_context is not None:151 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)152 await stream.do_handshake()153 return SocketStream(stream=stream)154177 if cancel_scope.cancelled_caught:178 raise ConnectTimeout()155 raise ConnectTimeout()156180 return SocketStream(stream=stream)181157 async def run_in_threadpool(158 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any159 ) -> typing.Any:160 return await trio.to_thread.run_sync(
50 unmodified lines
modified:httpx/dispatch/http11.py+2 added-12 removed
1import typing23import h1145from ..concurrency.base import BaseSocketStream, TimeoutFlag5from ..concurrency.base import BaseSocketStream6from ..config import Timeout7from ..exceptions import ConnectionClosed, ProtocolError8from ..models import Request, Response9from ..utils import get_logger
27 unmodified lines
37 ):38 self.socket = socket39 self.on_release = on_release40 self.h11_state = h11.Connection(our_role=h11.CLIENT)41 self.timeout_flag = TimeoutFlag()4142 async def send(self, request: Request, timeout: Timeout = None) -> Response:43 timeout = Timeout() if timeout is None else timeout44
55 unmodified lines
100 # Once we've sent the initial part of the request we don't actually101 # care about connection errors that occur when sending the body.102 # Ignore these, and defer to any exceptions on reading the response.103 self.h11_state.send_failed()105 finally:106 # Once we've sent the request, we enable read timeouts.107 self.timeout_flag.set_read_timeouts()104105 async def _send_event(self, event: H11Event, timeout: Timeout) -> None:106 """107 Send a single `h11` event to the network, waiting for the data to
9 unmodified lines
117 Read the response status and headers from the network.118 """119 while True:120 event = await self._receive_event(timeout)125 # As soon as we start seeing response events, we should enable126 # read timeouts, if we haven't already.127 self.timeout_flag.set_read_timeouts()121 if isinstance(event, h11.InformationalResponse):122 continue123 else:124 assert isinstance(event, h11.Response)
38 unmodified lines
163 logger.trace(f"receive_event event={event!r}")164165 if event is h11.NEED_DATA:166 try:174 data = await self.socket.read(175 self.READ_NUM_BYTES, timeout, flag=self.timeout_flag176 )167 data = await self.socket.read(self.READ_NUM_BYTES, timeout)168 except OSError: # pragma: nocover169 data = b""170 self.h11_state.receive_data(data)171 else:
12 unmodified lines
184 and self.h11_state.their_state is h11.DONE185 ):186 # Get ready for another request/response cycle.187 self.h11_state.start_next_cycle()197 self.timeout_flag.set_write_timeouts()188 else:189 await self.close()190191 if self.on_release is not None:
8 unmodified lines