Read/Write timeout modes (#104)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Read/Write timeout modes * Read/Write timeout modes
authored by Tom Christie · committed by GitHub · parent d3a12e7 · Browse files · 5 files·+91 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+91 added−21 removed
- tests:+1 added−1 removed
- other:+90 added−20 removed
Provenance
- Commit
f4f05e3- Tree
b27df6d- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
d3a12e7
5 files changed+91 added−21 removed
modified:http3/dispatch/http11.py+13 added-1 removed
1 import typing2 3 import h114 5+from ..concurrency import TimeoutFlag6 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes7 from ..exceptions import ConnectTimeout, ReadTimeout8 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9 from ..models import AsyncRequest, AsyncResponse28 unmodified lines38 self.writer = writer39 self.backend = backend40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)42+ self.timeout_flag = TimeoutFlag()43 44 async def send(45 self, request: AsyncRequest, timeout: TimeoutTypes = None46 ) -> AsyncResponse:57 unmodified lines104 # Once we've sent the initial part of the request we don't actually105 # care about connection errors that occur when sending the body.106 # Ignore these, and defer to any exceptions on reading the response.107 self.h11_state.send_failed()108+ finally:109+ # Once we've sent the request, we enable read timeouts.110+ self.timeout_flag.set_read_timeouts()111 112 async def _send_event(self, event: H11Event, timeout: TimeoutConfig = None) -> None:113 """114 Send a single `h11` event to the network, waiting for the data to9 unmodified lines124 Read the response status and headers from the network.125 """126 while True:127 event = await self._receive_event(timeout)128+ # As soon as we start seeing response events, we should enable129+ # read timeouts, if we haven't already.130+ self.timeout_flag.set_read_timeouts()131 if isinstance(event, h11.InformationalResponse):132 continue133 else:134 assert isinstance(event, h11.Response)21 unmodified lines156 while True:157 event = self.h11_state.next_event()158 if event is h11.NEED_DATA:159 try:152- data = await self.reader.read(self.READ_NUM_BYTES, timeout)160+ data = await self.reader.read(161+ self.READ_NUM_BYTES, timeout, flag=self.timeout_flag162+ )163 except OSError: # pragma: nocover164 data = b""165 self.h11_state.receive_data(data)166 else:4 unmodified lines171 if (172 self.h11_state.our_state is h11.DONE173 and self.h11_state.their_state is h11.DONE174 ):175+ # Get ready for another request/response cycle.176 self.h11_state.start_next_cycle()177+ self.timeout_flag.set_write_timeouts()178 else:179 await self.close()180 181 if self.on_release is not None:5 unmodified linesmodified:http3/dispatch/http2.py+16 added-4 removed
2 unmodified lines3 4 import h2.connection5 import h2.events6 7+from ..concurrency import TimeoutFlag8 from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes9 from ..exceptions import ConnectTimeout, ReadTimeout10 from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11 from ..models import AsyncRequest, AsyncResponse14 unmodified lines26 self.backend = backend27 self.on_release = on_release28 self.h2_state = h2.connection.H2Connection()29 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]30+ self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]31 self.initialized = False32 33 async def send(34 self, request: AsyncRequest, timeout: TimeoutTypes = None5 unmodified lines40 self.initiate_connection()41 42 stream_id = await self.send_headers(request, timeout)43 self.events[stream_id] = []44+ self.timeout_flags[stream_id] = TimeoutFlag()45 46 task, args = self.send_request_data, [stream_id, request.stream(), timeout]47 async with self.backend.background_manager(task, args=args):48 status_code, headers = await self.receive_response(stream_id, timeout)38 unmodified lines87 stream_id: int,88 stream: typing.AsyncIterator[bytes],89 timeout: TimeoutConfig = None,90 ) -> None:91+ try:88- async for data in stream:89- await self.send_data(stream_id, data, timeout)90- await self.end_stream(stream_id, timeout)92+ async for data in stream:93+ await self.send_data(stream_id, data, timeout)94+ await self.end_stream(stream_id, timeout)95+ finally:96+ # Once we've sent the request we should enable read timeouts.97+ self.timeout_flags[stream_id].set_read_timeouts()98 99 async def send_data(100 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None101 ) -> None:17 unmodified lines119 Read the response status and headers from the network.120 """121 while True:122 event = await self.receive_event(stream_id, timeout)123+ # As soon as we start seeing response events, we should enable124+ # read timeouts, if we haven't already.125+ self.timeout_flags[stream_id].set_read_timeouts()126 if isinstance(event, h2.events.ResponseReceived):127 break128 129 status_code = 20019 unmodified lines149 async def receive_event(150 self, stream_id: int, timeout: TimeoutConfig = None151 ) -> h2.events.Event:152 while not self.events[stream_id]:153+ flag = self.timeout_flags[stream_id]143- data = await self.reader.read(self.READ_NUM_BYTES, timeout)154+ data = await self.reader.read(self.READ_NUM_BYTES, timeout, flag=flag)155 events = self.h2_state.receive_data(data)156 for event in events:157 if getattr(event, "stream_id", 0):158 self.events[event.stream_id].append(event)4 unmodified lines163 return self.events[stream_id].pop(0)164 165 async def response_closed(self, stream_id: int) -> None:166 del self.events[stream_id]167+ del self.timeout_flags[stream_id]168 169 if not self.events and self.on_release is not None:170 await self.on_release()171 3 unmodified linesmodified:http3/concurrency.py+58 added-14 removed
47 unmodified lines48 49 MonkeyPatch.write = _fixed_write50 51 52+class TimeoutFlag:53+ """54+ A timeout flag holds a state of either read-timeout or write-timeout mode.55+56+ We use this so that we can attempt both reads and writes concurrently, while57+ only enforcing timeouts in one direction.58+59+ During a request/response cycle we start in write-timeout mode.60+61+ Once we've sent a request fully, or once we start seeing a response,62+ then we switch to read-timeout mode instead.63+ """64+65+ def __init__(self) -> None:66+ self.raise_on_read_timeout = False67+ self.raise_on_write_timeout = True68+69+ def set_read_timeouts(self) -> None:70+ """71+ Set the flag to read-timeout mode.72+ """73+ self.raise_on_read_timeout = True74+ self.raise_on_write_timeout = False75+76+ def set_write_timeouts(self) -> None:77+ """78+ Set the flag to write-timeout mode.79+ """80+ self.raise_on_read_timeout = False81+ self.raise_on_write_timeout = True82+83+84 class Reader(BaseReader):85 def __init__(86 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87 ) -> None:88 self.stream_reader = stream_reader89 self.timeout = timeout90 59- async def read(self, n: int, timeout: TimeoutConfig = None) -> bytes:91+ async def read(92+ self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None93+ ) -> bytes:94 if timeout is None:95 timeout = self.timeout96 97+ while True:98+ should_raise = flag is None or flag.raise_on_read_timeout63- try:64- data = await asyncio.wait_for(65- self.stream_reader.read(n), timeout.read_timeout66- )67- except asyncio.TimeoutError:68- raise ReadTimeout()99+ try:100+ data = await asyncio.wait_for(101+ self.stream_reader.read(n), timeout.read_timeout102+ )103+ break104+ except asyncio.TimeoutError:105+ if should_raise:106+ raise ReadTimeout()107 108 return data109 110 4 unmodified lines115 116 def write_no_block(self, data: bytes) -> None:117 self.stream_writer.write(data) # pragma: nocover118 81- async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:119+ async def write(120+ self, data: bytes, timeout: TimeoutConfig = None, flag: TimeoutFlag = None121+ ) -> None:122 if not data:123 return124 125 if timeout is None:126 timeout = self.timeout127 128 self.stream_writer.write(data)129+ while True:89- try:90- await asyncio.wait_for( # type: ignore91- self.stream_writer.drain(), timeout.write_timeout92- )93- except asyncio.TimeoutError:94- raise WriteTimeout()130+ try:131+ await asyncio.wait_for( # type: ignore132+ self.stream_writer.drain(), timeout.write_timeout133+ )134+ break135+ except asyncio.TimeoutError:136+ should_raise = flag is None or flag.raise_on_write_timeout137+ if should_raise:138+ raise WriteTimeout()139 140 async def close(self) -> None:141 self.stream_writer.close()142 125 unmodified linesmodified:http3/interfaces.py+3 added-1 removed
125 unmodified lines126 into a more generic base class, that we can use with alternate127 backend, or for stand-alone test cases.128 """129 130- async def read(self, n: int, timeout: TimeoutConfig = None) -> bytes:130+ async def read(131+ self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None132+ ) -> bytes:133 raise NotImplementedError() # pragma: no cover134 135 136 class BaseWriter:93 unmodified linesmodified:tests/dispatch/utils.py+1 added-1 removed
43 unmodified lines44 self.requests = {}45 46 # BaseReader interface47 48- async def read(self, n, timeout) -> bytes:48+ async def read(self, n, timeout, flag=None) -> bytes:49 await asyncio.sleep(0)50 send, self.buffer = self.buffer[:n], self.buffer[n:]51 return send52 65 unmodified lines