Unify BaseReader and BaseWriter as BaseStream
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by florimondmanca · committed by florimondmanca · parent 2e91d8c · Browse files · 7 files·+55 added−77 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+55 added−77 removed
- tests:+5 added−11 removed
- other:+50 added−66 removed
Provenance
- Commit
14eb81f- Tree
d4ff4ab- Author
florimondmanca <florimond.manca@gmail.com>- Committer
florimondmanca <florimond.manca@gmail.com>- Parent
2e91d8c
7 files changed+55 added−77 removed
modified:httpx/concurrency/asyncio.py+19 added-21 removed
1 """2-The `Reader` and `Writer` classes here provide a lightweight layer over2+The `Stream` class here provides a lightweight layer over3 `asyncio.StreamReader` and `asyncio.StreamWriter`.4 5 Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6 6 unmodified lines13 import ssl14 import typing15 from types import TracebackType16 17+from ..config import PoolLimits, TimeoutConfig18+from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19 from .base import (20 BaseBackgroundManager,21 BasePoolSemaphore,22 BaseEvent,23 BaseQueue,22- BaseReader,23- BaseWriter,24+ BaseStream,25 ConcurrencyBackend,26 TimeoutFlag,27 )27-from ..config import PoolLimits, TimeoutConfig28-from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout28 29 SSL_MONKEY_PATCH_APPLIED = False30 31 17 unmodified lines49 50 MonkeyPatch.write = _fixed_write51 52 54-class Reader(BaseReader):53+class Stream(BaseStream):54 def __init__(56- self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig57- ) -> None:55+ self,56+ stream_reader: asyncio.StreamReader,57+ stream_writer: asyncio.StreamWriter,58+ timeout: TimeoutConfig,59+ ):60 self.stream_reader = stream_reader61+ self.stream_writer = stream_writer62 self.timeout = timeout63 64 async def read(65 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None14 unmodified lines80 raise ReadTimeout() from None81 82 return data83 81- def is_connection_dropped(self) -> bool:82- return self.stream_reader.at_eof()83-84-85-class Writer(BaseWriter):86- def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):87- self.stream_writer = stream_writer88- self.timeout = timeout89-84 def write_no_block(self, data: bytes) -> None:85 self.stream_writer.write(data) # pragma: nocover86 87 async def write(19 unmodified lines107 should_raise = flag is None or flag.raise_on_write_timeout108 if should_raise:109 raise WriteTimeout() from None110 111+ def is_connection_dropped(self) -> bool:112+ return self.stream_reader.at_eof()113+114 async def close(self) -> None:115 self.stream_writer.close()116 117 50 unmodified lines168 hostname: str,169 port: int,170 ssl_context: typing.Optional[ssl.SSLContext],171 timeout: TimeoutConfig,175- ) -> typing.Tuple[BaseReader, BaseWriter, str]:172+ ) -> typing.Tuple[BaseStream, str]:173 try:174 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore175 asyncio.open_connection(hostname, port, ssl=ssl_context),176 timeout.connect_timeout,8 unmodified lines185 ident = ssl_object.selected_alpn_protocol()186 if ident is None:187 ident = ssl_object.selected_npn_protocol()188 192- reader = Reader(stream_reader=stream_reader, timeout=timeout)193- writer = Writer(stream_writer=stream_writer, timeout=timeout)189+ stream = Stream(190+ stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout191+ )192 http_version = "HTTP/2" if ident == "h2" else "HTTP/1.1"193 196- return reader, writer, http_version194+ return stream, http_version195 196 async def run_in_threadpool(197 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any198 ) -> typing.Any:50 unmodified linesmodified:httpx/concurrency/base.py+8 added-16 removed
35 unmodified lines36 self.raise_on_read_timeout = False37 self.raise_on_write_timeout = True38 39 40-class BaseReader:40+class BaseStream:41 """42- A stream reader. Abstracts away any asyncio-specific interfaces43- into a more generic base class, that we can use with alternate44- backend, or for stand-alone test cases.42+ A stream with read/write operations. Abstracts away any asyncio-specific43+ interfaces into a more generic base class, that we can use with alternate44+ backends, or for stand-alone test cases.45 """46 47 async def read(48 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None49 ) -> bytes:50 raise NotImplementedError() # pragma: no cover51 52- def is_connection_dropped(self) -> bool:53- raise NotImplementedError() # pragma: no cover54-55-56-class BaseWriter:57- """58- A stream writer. Abstracts away any asyncio-specific interfaces59- into a more generic base class, that we can use with alternate60- backend, or for stand-alone test cases.61- """62-52 def write_no_block(self, data: bytes) -> None:53 raise NotImplementedError() # pragma: no cover54 55 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:1 unmodified line57 58 async def close(self) -> None:59 raise NotImplementedError() # pragma: no cover60 61+ def is_connection_dropped(self) -> bool:62+ raise NotImplementedError() # pragma: no cover63 64+65 class BaseQueue:66 """67 A FIFO queue. Abstracts away any asyncio-specific interfaces.68 """40 unmodified lines109 hostname: str,110 port: int,111 ssl_context: typing.Optional[ssl.SSLContext],112 timeout: TimeoutConfig,121- ) -> typing.Tuple[BaseReader, BaseWriter, str]:113+ ) -> typing.Tuple[BaseStream, str]:114 raise NotImplementedError() # pragma: no cover115 116 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:117 raise NotImplementedError() # pragma: no cover57 unmodified linesmodified:httpx/dispatch/connection.py+3 added-3 removed
77 unmodified lines78 on_release = None79 else:80 on_release = functools.partial(self.release_func, self)81 82- reader, writer, http_version = await self.backend.connect(82+ stream, http_version = await self.backend.connect(83 host, port, ssl_context, timeout84 )85 if http_version == "HTTP/2":86 self.h2_connection = HTTP2Connection(87- reader, writer, self.backend, on_release=on_release87+ stream, self.backend, on_release=on_release88 )89 else:90 assert http_version == "HTTP/1.1"91 self.h11_connection = HTTP11Connection(92- reader, writer, self.backend, on_release=on_release92+ stream, self.backend, on_release=on_release93 )94 95 async def get_ssl_context(self, ssl: SSLConfig) -> typing.Optional[ssl.SSLContext]:96 if not self.origin.is_ssl:31 unmodified linesmodified:httpx/dispatch/http11.py+7 added-9 removed
1 import typing2 3 import h114 5-from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag5+from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7 from ..models import AsyncRequest, AsyncResponse8 9 H11Event = typing.Union[16 unmodified lines26 READ_NUM_BYTES = 409627 28 def __init__(29 self,30- reader: BaseReader,31- writer: BaseWriter,30+ stream: BaseStream,31 backend: ConcurrencyBackend,32 on_release: typing.Optional[OnReleaseCallback] = None,33 ):35- self.reader = reader36- self.writer = writer34+ self.stream = stream35 self.backend = backend36 self.on_release = on_release37 self.h11_state = h11.Connection(our_role=h11.CLIENT)38 self.timeout_flag = TimeoutFlag()25 unmodified lines64 self.h11_state.send(event)65 except h11.LocalProtocolError: # pragma: no cover66 # Premature client disconnect67 pass70- await self.writer.close()68+ await self.stream.close()69 70 async def _send_request(71 self, request: AsyncRequest, timeout: TimeoutConfig = None72 ) -> None:35 unmodified lines108 Send a single `h11` event to the network, waiting for the data to109 drain before returning.110 """111 bytes_to_send = self.h11_state.send(event)114- await self.writer.write(bytes_to_send, timeout)112+ await self.stream.write(bytes_to_send, timeout)113 114 async def _receive_response(115 self, timeout: TimeoutConfig = None116 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:34 unmodified lines151 while True:152 event = self.h11_state.next_event()153 if event is h11.NEED_DATA:154 try:157- data = await self.reader.read(155+ data = await self.stream.read(156 self.READ_NUM_BYTES, timeout, flag=self.timeout_flag157 )158 except OSError: # pragma: nocover159 data = b""21 unmodified lines181 def is_closed(self) -> bool:182 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)183 184 def is_connection_dropped(self) -> bool:187- return self.reader.is_connection_dropped()185+ return self.stream.is_connection_dropped()modified:httpx/dispatch/http2.py+11 added-13 removed
2 unmodified lines3 4 import h2.connection5 import h2.events6 7-from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag7+from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag8 from ..config import TimeoutConfig, TimeoutTypes9 from ..models import AsyncRequest, AsyncResponse10 11 1 unmodified line13 READ_NUM_BYTES = 409614 15 def __init__(16 self,17- reader: BaseReader,18- writer: BaseWriter,17+ stream: BaseStream,18 backend: ConcurrencyBackend,19 on_release: typing.Callable = None,20 ):22- self.reader = reader23- self.writer = writer21+ self.stream = stream22 self.backend = backend23 self.on_release = on_release24 self.h2_state = h2.connection.H2Connection()25 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]29 unmodified lines55 request=request,56 )57 58 async def close(self) -> None:61- await self.writer.close()59+ await self.stream.close()60 61 def initiate_connection(self) -> None:62 self.h2_state.initiate_connection()63 data_to_send = self.h2_state.data_to_send()66- self.writer.write_no_block(data_to_send)64+ self.stream.write_no_block(data_to_send)65 self.initialized = True66 67 async def send_headers(68 self, request: AsyncRequest, timeout: TimeoutConfig = None6 unmodified lines75 (b":path", request.url.full_path.encode("ascii")),76 ] + [(k, v) for k, v in request.headers.raw if k != b"host"]77 self.h2_state.send_headers(stream_id, headers)78 data_to_send = self.h2_state.data_to_send()81- await self.writer.write(data_to_send, timeout)79+ await self.stream.write(data_to_send, timeout)80 return stream_id81 82 async def send_request_data(83 self,17 unmodified lines101 for idx in range(0, len(data), chunk_size):102 chunk = data[idx : idx + chunk_size]103 self.h2_state.send_data(stream_id, chunk)104 data_to_send = self.h2_state.data_to_send()107- await self.writer.write(data_to_send, timeout)105+ await self.stream.write(data_to_send, timeout)106 107 async def end_stream(self, stream_id: int, timeout: TimeoutConfig = None) -> None:108 self.h2_state.end_stream(stream_id)109 data_to_send = self.h2_state.data_to_send()112- await self.writer.write(data_to_send, timeout)110+ await self.stream.write(data_to_send, timeout)111 112 async def receive_response(113 self, stream_id: int, timeout: TimeoutConfig = None114 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:32 unmodified lines147 self, stream_id: int, timeout: TimeoutConfig = None148 ) -> h2.events.Event:149 while not self.events[stream_id]:150 flag = self.timeout_flags[stream_id]153- data = await self.reader.read(self.READ_NUM_BYTES, timeout, flag=flag)151+ data = await self.stream.read(self.READ_NUM_BYTES, timeout, flag=flag)152 events = self.h2_state.receive_data(data)153 for event in events:154 if getattr(event, "stream_id", 0):155 self.events[event.stream_id].append(event)156 157 data_to_send = self.h2_state.data_to_send()160- await self.writer.write(data_to_send, timeout)158+ await self.stream.write(data_to_send, timeout)159 160 return self.events[stream_id].pop(0)161 162 async def response_closed(self, stream_id: int) -> None:7 unmodified lines170 def is_closed(self) -> bool:171 return False172 173 def is_connection_dropped(self) -> bool:176- return self.reader.is_connection_dropped()174+ return self.stream.is_connection_dropped()modified:httpx/__init__.py+2 added-4 removed
3 unmodified lines4 from .concurrency.asyncio import AsyncioBackend5 from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8- BaseReader,9- BaseWriter,8+ BaseStream,9 ConcurrencyBackend,10 )11 from .config import (12 USER_AGENT,90 unmodified lines103 "Timeout",104 "TooManyRedirects",105 "WriteTimeout",106 "AsyncDispatcher",108- "BaseReader",109- "BaseWriter",107+ "BaseStream",108 "ConcurrencyBackend",109 "Dispatcher",110 "URL",111 "URLTypes",23 unmodified linesmodified:tests/dispatch/utils.py+5 added-11 removed
4 unmodified lines5 import h2.config6 import h2.connection7 import h2.events8 9-from httpx import AsyncioBackend, BaseReader, BaseWriter, Request, TimeoutConfig9+from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig10 11 12 class MockHTTP2Backend(AsyncioBackend):13 def __init__(self, app):5 unmodified lines19 hostname: str,20 port: int,21 ssl_context: typing.Optional[ssl.SSLContext],22 timeout: TimeoutConfig,23- ) -> typing.Tuple[BaseReader, BaseWriter, str]:23+ ) -> typing.Tuple[BaseStream, str]:24 self.server = MockHTTP2Server(self.app)25- return self.server, self.server, "HTTP/2"25+ return self.server, "HTTP/2"26 27 28-class MockHTTP2Server(BaseReader, BaseWriter):29- """30- This class exposes Reader and Writer style interfaces.31- """32-28+class MockHTTP2Server(BaseStream):29 def __init__(self, app):30 config = h2.config.H2Configuration(client_side=False)31 self.conn = h2.connection.H2Connection(config=config)32 self.app = app33 self.buffer = b""34 self.requests = {}35 self.close_connection = False36 41- # BaseReader interface37+ # Stream interface38 39 async def read(self, n, timeout, flag=None) -> bytes:40 await asyncio.sleep(0)41 send, self.buffer = self.buffer[:n], self.buffer[n:]42 return send43 48- # BaseWriter interface49-44 def write_no_block(self, data: bytes) -> None:45 events = self.conn.receive_data(data)46 self.buffer += self.conn.data_to_send()47 for event in events:62 unmodified lines