Skip to content
Myr

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

5 files+91 added−21 removed

modified:http3/dispatch/http11.py+13 added-1 removed
1import typing23import h1145from ..concurrency import TimeoutFlag6from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes7from ..exceptions import ConnectTimeout, ReadTimeout8from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend9from ..models import AsyncRequest, AsyncResponse
28 unmodified lines
38 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()4344 async def send(45 self, request: AsyncRequest, timeout: TimeoutTypes = None46 ) -> AsyncResponse:
57 unmodified lines
104 # 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()111112 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 to
9 unmodified lines
124 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 lines
156 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 lines
171 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()180181 if self.on_release is not None:
5 unmodified lines
modified:http3/dispatch/http2.py+16 added-4 removed
2 unmodified lines
34import h2.connection5import h2.events67from ..concurrency import TimeoutFlag8from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes9from ..exceptions import ConnectTimeout, ReadTimeout10from ..interfaces import BaseReader, BaseWriter, ConcurrencyBackend11from ..models import AsyncRequest, AsyncResponse
14 unmodified lines
26 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 = False3233 async def send(34 self, request: AsyncRequest, timeout: TimeoutTypes = None
5 unmodified lines
40 self.initiate_connection()4142 stream_id = await self.send_headers(request, timeout)43 self.events[stream_id] = []44 self.timeout_flags[stream_id] = TimeoutFlag()4546 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 lines
87 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()9899 async def send_data(100 self, stream_id: int, data: bytes, timeout: TimeoutConfig = None101 ) -> None:
17 unmodified lines
119 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 break128129 status_code = 200
19 unmodified lines
149 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 lines
163 return self.events[stream_id].pop(0)164165 async def response_closed(self, stream_id: int) -> None:166 del self.events[stream_id]167 del self.timeout_flags[stream_id]168169 if not self.events and self.on_release is not None:170 await self.on_release()171
3 unmodified lines
modified:http3/concurrency.py+58 added-14 removed
47 unmodified lines
4849 MonkeyPatch.write = _fixed_write505152class TimeoutFlag:53 """54 A timeout flag holds a state of either read-timeout or write-timeout mode.5556 We use this so that we can attempt both reads and writes concurrently, while57 only enforcing timeouts in one direction.5859 During a request/response cycle we start in write-timeout mode.6061 Once we've sent a request fully, or once we start seeing a response,62 then we switch to read-timeout mode instead.63 """6465 def __init__(self) -> None:66 self.raise_on_read_timeout = False67 self.raise_on_write_timeout = True6869 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 = False7576 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 = True828384class Reader(BaseReader):85 def __init__(86 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig87 ) -> None:88 self.stream_reader = stream_reader89 self.timeout = timeout9059 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.timeout9697 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()107108 return data109110
4 unmodified lines
115116 def write_no_block(self, data: bytes) -> None:117 self.stream_writer.write(data) # pragma: nocover11881 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 return124125 if timeout is None:126 timeout = self.timeout127128 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()139140 async def close(self) -> None:141 self.stream_writer.close()142
125 unmodified lines
modified:http3/interfaces.py+3 added-1 removed
125 unmodified lines
126 into a more generic base class, that we can use with alternate127 backend, or for stand-alone test cases.128 """129130 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 cover134135136class BaseWriter:
93 unmodified lines
modified:tests/dispatch/utils.py+1 added-1 removed
43 unmodified lines
44 self.requests = {}4546 # BaseReader interface4748 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