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
Provenance
- Commit
83fc092- Tree
02f822b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
ab41a5d
4 files changed+52 added−150 removed
modified:httpx/concurrency/asyncio.py+16 added-47 removed
4 unmodified lines5 import typing6 7 from ..config import PoolLimits, Timeout8 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9-from .base import (10- BaseEvent,11- BasePoolSemaphore,12- BaseSocketStream,13- ConcurrencyBackend,14- TimeoutFlag,15-)9+from .base import BaseEvent, BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend10 11 SSL_MONKEY_PATCH_APPLIED = False12 13 105 unmodified lines119 120 ident = ssl_object.selected_alpn_protocol()121 return "HTTP/2" if ident == "h2" else "HTTP/1.1"122 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_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- break131 152- return data153-154- 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 return135 136 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 None143 144 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 we151 unmodified linesmodified:httpx/concurrency/base.py+1 added-33 removed
24 unmodified lines25 26 raise RuntimeError(f"Unknown or unsupported concurrency backend {backend!r}")27 28 29-class TimeoutFlag:30- """31- A timeout flag holds a state of either read-timeout or write-timeout mode.32-33- We use this so that we can attempt both reads and writes concurrently, while34- only enforcing timeouts in one direction.35-36- During a request/response cycle we start in write-timeout mode.37-38- Once we've sent a request fully, or once we start seeing a response,39- then we switch to read-timeout mode instead.40- """41-42- def __init__(self) -> None:43- self.raise_on_read_timeout = False44- self.raise_on_write_timeout = True45-46- 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 = False52-53- 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 = True59-60-29 class 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 alternate7 unmodified lines40 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout41 ) -> "BaseSocketStream":42 raise NotImplementedError() # pragma: no cover43 76- 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 cover46 47 async def write(self, data: bytes, timeout: Timeout) -> None:48 raise NotImplementedError() # pragma: no cover92 unmodified linesmodified:httpx/concurrency/trio.py+33 added-58 removed
4 unmodified lines5 import trio6 7 from ..config import PoolLimits, Timeout8 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9-from .base import (10- BaseEvent,11- BasePoolSemaphore,12- BaseSocketStream,13- ConcurrencyBackend,14- TimeoutFlag,15-)9+from .base import BaseEvent, BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend10 11 18-def _or_inf(value: typing.Optional[float]) -> float:12+def none_as_inf(value: typing.Optional[float]) -> float:13 return value if value is not None else float("inf")14 15 16 class SocketStream(BaseSocketStream):6 unmodified lines23 24 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 )31 38- 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)35 41- if cancel_scope.cancelled_caught:42- raise ConnectTimeout()36+ raise ConnectTimeout()37 44- return SocketStream(ssl_stream)45-38 def get_http_version(self) -> str:39 if not isinstance(self.stream, trio.SSLStream):40 return "HTTP/1.1"41 42 ident = self.stream.selected_alpn_protocol()43 return "HTTP/2" if ident == "h2" else "HTTP/1.1"44 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_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)47 60- 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)51 64- if should_raise:65- raise ReadTimeout() from None52+ raise ReadTimeout()53 54+ async def write(self, data: bytes, timeout: Timeout) -> None:55+ if not data:56+ return57+58+ write_timeout = none_as_inf(timeout.write_timeout)59+60+ with trio.move_on_after(write_timeout):61+ async with self.write_lock:62+ return await self.stream.send_all(data)63+64+ raise WriteTimeout()65+66 def is_connection_dropped(self) -> bool:67 # Adapted from: https://github.com/encode/httpx/pull/143#issuecomment-51520298268 stream = self.stream69 7 unmodified lines77 # 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()80 82- async def write(83- self, data: bytes, timeout: Timeout, flag: TimeoutFlag = None84- ) -> None:85- if not data:86- return87-88- write_timeout = _or_inf(timeout.write_timeout)89-90- 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 None101-81 async def close(self) -> None:82 await self.stream.aclose()83 84 16 unmodified lines101 async def acquire(self, timeout: float = None) -> None:102 if self.semaphore is None:103 return104 126- timeout = _or_inf(timeout)105+ timeout = none_as_inf(timeout)106 107 with trio.move_on_after(timeout):108 await self.semaphore.acquire()109 return14 unmodified lines124 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)129 151- 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)136 157- if cancel_scope.cancelled_caught:158- raise ConnectTimeout()137+ raise ConnectTimeout()138 160- return SocketStream(stream=stream)161-139 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)147 171- 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)154 177- if cancel_scope.cancelled_caught:178- raise ConnectTimeout()155+ raise ConnectTimeout()156 180- return SocketStream(stream=stream)181-157 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 linesmodified:httpx/dispatch/http11.py+2 added-12 removed
1 import typing2 3 import h114 5-from ..concurrency.base import BaseSocketStream, TimeoutFlag5+from ..concurrency.base import BaseSocketStream6 from ..config import Timeout7 from ..exceptions import ConnectionClosed, ProtocolError8 from ..models import Request, Response9 from ..utils import get_logger27 unmodified lines37 ):38 self.socket = socket39 self.on_release = on_release40 self.h11_state = h11.Connection(our_role=h11.CLIENT)41- self.timeout_flag = TimeoutFlag()41 42 async def send(self, request: Request, timeout: Timeout = None) -> Response:43 timeout = Timeout() if timeout is None else timeout44 55 unmodified lines100 # 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()104 105 async def _send_event(self, event: H11Event, timeout: Timeout) -> None:106 """107 Send a single `h11` event to the network, waiting for the data to9 unmodified lines117 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 lines163 logger.trace(f"receive_event event={event!r}")164 165 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 lines184 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()190 191 if self.on_release is not None:8 unmodified lines