Skip to content
Myr

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

7 files+55 added−77 removed

modified:httpx/concurrency/asyncio.py+19 added-21 removed
1"""2The `Reader` and `Writer` classes here provide a lightweight layer over2The `Stream` class here provides a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6
6 unmodified lines
13import ssl14import typing15from types import TracebackType1617from ..config import PoolLimits, TimeoutConfig18from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout19from .base import (20 BaseBackgroundManager,21 BasePoolSemaphore,22 BaseEvent,23 BaseQueue,22 BaseReader,23 BaseWriter,24 BaseStream,25 ConcurrencyBackend,26 TimeoutFlag,27)27from ..config import PoolLimits, TimeoutConfig28from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout2829SSL_MONKEY_PATCH_APPLIED = False3031
17 unmodified lines
4950 MonkeyPatch.write = _fixed_write515254class Reader(BaseReader):53class 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 = timeout6364 async def read(65 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None
14 unmodified lines
80 raise ReadTimeout() from None8182 return data8381 def is_connection_dropped(self) -> bool:82 return self.stream_reader.at_eof()838485class Writer(BaseWriter):86 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):87 self.stream_writer = stream_writer88 self.timeout = timeout8984 def write_no_block(self, data: bytes) -> None:85 self.stream_writer.write(data) # pragma: nocover8687 async def write(
19 unmodified lines
107 should_raise = flag is None or flag.raise_on_write_timeout108 if should_raise:109 raise WriteTimeout() from None110111 def is_connection_dropped(self) -> bool:112 return self.stream_reader.at_eof()113114 async def close(self) -> None:115 self.stream_writer.close()116117
50 unmodified lines
168 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 lines
185 ident = ssl_object.selected_alpn_protocol()186 if ident is None:187 ident = ssl_object.selected_npn_protocol()188192 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"193196 return reader, writer, http_version194 return stream, http_version195196 async def run_in_threadpool(197 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any198 ) -> typing.Any:
50 unmodified lines
modified:httpx/concurrency/base.py+8 added-16 removed
35 unmodified lines
36 self.raise_on_read_timeout = False37 self.raise_on_write_timeout = True383940class BaseReader:40class 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 """4647 async def read(48 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None49 ) -> bytes:50 raise NotImplementedError() # pragma: no cover5152 def is_connection_dropped(self) -> bool:53 raise NotImplementedError() # pragma: no cover545556class 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 """6252 def write_no_block(self, data: bytes) -> None:53 raise NotImplementedError() # pragma: no cover5455 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:
1 unmodified line
5758 async def close(self) -> None:59 raise NotImplementedError() # pragma: no cover6061 def is_connection_dropped(self) -> bool:62 raise NotImplementedError() # pragma: no cover636465class BaseQueue:66 """67 A FIFO queue. Abstracts away any asyncio-specific interfaces.68 """
40 unmodified lines
109 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 cover115116 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:117 raise NotImplementedError() # pragma: no cover
57 unmodified lines
modified:httpx/dispatch/connection.py+3 added-3 removed
77 unmodified lines
78 on_release = None79 else:80 on_release = functools.partial(self.release_func, self)8182 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 )9495 async def get_ssl_context(self, ssl: SSLConfig) -> typing.Optional[ssl.SSLContext]:96 if not self.origin.is_ssl:
31 unmodified lines
modified:httpx/dispatch/http11.py+7 added-9 removed
1import typing23import h1145from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag5from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..models import AsyncRequest, AsyncResponse89H11Event = typing.Union[
16 unmodified lines
26 READ_NUM_BYTES = 40962728 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 lines
64 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()6970 async def _send_request(71 self, request: AsyncRequest, timeout: TimeoutConfig = None72 ) -> None:
35 unmodified lines
108 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)113114 async def _receive_response(115 self, timeout: TimeoutConfig = None116 ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:
34 unmodified lines
151 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 lines
181 def is_closed(self) -> bool:182 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)183184 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 lines
34import h2.connection5import h2.events67from ..concurrency.base import BaseReader, BaseWriter, ConcurrencyBackend, TimeoutFlag7from ..concurrency.base import BaseStream, ConcurrencyBackend, TimeoutFlag8from ..config import TimeoutConfig, TimeoutTypes9from ..models import AsyncRequest, AsyncResponse1011
1 unmodified line
13 READ_NUM_BYTES = 40961415 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 lines
55 request=request,56 )5758 async def close(self) -> None:61 await self.writer.close()59 await self.stream.close()6061 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 = True6667 async def send_headers(68 self, request: AsyncRequest, timeout: TimeoutConfig = None
6 unmodified lines
75 (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_id8182 async def send_request_data(83 self,
17 unmodified lines
101 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)106107 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)111112 async def receive_response(113 self, stream_id: int, timeout: TimeoutConfig = None114 ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:
32 unmodified lines
147 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)156157 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)159160 return self.events[stream_id].pop(0)161162 async def response_closed(self, stream_id: int) -> None:
7 unmodified lines
170 def is_closed(self) -> bool:171 return False172173 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 lines
4from .concurrency.asyncio import AsyncioBackend5from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8 BaseReader,9 BaseWriter,8 BaseStream,9 ConcurrencyBackend,10)11from .config import (12 USER_AGENT,
90 unmodified lines
103 "Timeout",104 "TooManyRedirects",105 "WriteTimeout",106 "AsyncDispatcher",108 "BaseReader",109 "BaseWriter",107 "BaseStream",108 "ConcurrencyBackend",109 "Dispatcher",110 "URL",111 "URLTypes",
23 unmodified lines
modified:tests/dispatch/utils.py+5 added-11 removed
4 unmodified lines
5import h2.config6import h2.connection7import h2.events89from httpx import AsyncioBackend, BaseReader, BaseWriter, Request, TimeoutConfig9from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig101112class MockHTTP2Backend(AsyncioBackend):13 def __init__(self, app):
5 unmodified lines
19 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"262728class MockHTTP2Server(BaseReader, BaseWriter):29 """30 This class exposes Reader and Writer style interfaces.31 """3228class 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 = False3641 # BaseReader interface37 # Stream interface3839 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 send4348 # BaseWriter interface4944 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