Skip to content
Myr

Merge pull request #255 from encode/refactor/stream-interface

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Unify BaseReader and BaseWriter as BaseStream

authored by Tom Christie · committed by GitHub · parents 2e91d8c, fdb1359 · Browse files · 7 files+75 added−90 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+75 added−90 removed

  • tests:+8 added−11 removed
  • other:+67 added−79 removed

7 files+75 added−90 removed

modified:httpx/concurrency/asyncio.py+30 added-31 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 def get_http_version(self) -> str:65 ssl_object = self.stream_writer.get_extra_info("ssl_object")6667 if ssl_object is None:68 return "HTTP/1.1"6970 ident = ssl_object.selected_alpn_protocol()71 if ident is None:72 ident = ssl_object.selected_npn_protocol()7374 return "HTTP/2" if ident == "h2" else "HTTP/1.1"7576 async def read(77 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None78 ) -> bytes:79 if timeout is None:
12 unmodified lines
92 raise ReadTimeout() from None9394 return data9581 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 = timeout8996 def write_no_block(self, data: bytes) -> None:97 self.stream_writer.write(data) # pragma: nocover9899 async def write(
19 unmodified lines
119 should_raise = flag is None or flag.raise_on_write_timeout120 if should_raise:121 raise WriteTimeout() from None122123 def is_connection_dropped(self) -> bool:124 return self.stream_reader.at_eof()125126 async def close(self) -> None:127 self.stream_writer.close()128129
50 unmodified lines
180 hostname: str,181 port: int,182 ssl_context: typing.Optional[ssl.SSLContext],183 timeout: TimeoutConfig,175 ) -> typing.Tuple[BaseReader, BaseWriter, str]:184 ) -> BaseStream:185 try:186 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore187 asyncio.open_connection(hostname, port, ssl=ssl_context),188 timeout.connect_timeout,189 )190 except asyncio.TimeoutError:191 raise ConnectTimeout()192184 ssl_object = stream_writer.get_extra_info("ssl_object")185 if ssl_object is None:186 ident = "http/1.1"187 else:188 ident = ssl_object.selected_alpn_protocol()189 if ident is None:190 ident = ssl_object.selected_npn_protocol()193 return Stream(194 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout195 )196192 reader = Reader(stream_reader=stream_reader, timeout=timeout)193 writer = Writer(stream_writer=stream_writer, timeout=timeout)194 http_version = "HTTP/2" if ident == "h2" else "HTTP/1.1"195196 return reader, writer, http_version197197 async def run_in_threadpool(198 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any199 ) -> typing.Any:200 if kwargs:
49 unmodified lines
modified:httpx/concurrency/base.py+11 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 def get_http_version(self) -> str:48 raise NotImplementedError() # pragma: no cover4950 async def read(51 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None52 ) -> bytes:53 raise NotImplementedError() # pragma: no cover5452 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 """6255 def write_no_block(self, data: bytes) -> None:56 raise NotImplementedError() # pragma: no cover5758 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:
1 unmodified line
6061 async def close(self) -> None:62 raise NotImplementedError() # pragma: no cover6364 def is_connection_dropped(self) -> bool:65 raise NotImplementedError() # pragma: no cover666768class BaseQueue:69 """70 A FIFO queue. Abstracts away any asyncio-specific interfaces.71 """
40 unmodified lines
112 hostname: str,113 port: int,114 ssl_context: typing.Optional[ssl.SSLContext],115 timeout: TimeoutConfig,121 ) -> typing.Tuple[BaseReader, BaseWriter, str]:116 ) -> BaseStream:117 raise NotImplementedError() # pragma: no cover118119 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:120 raise NotImplementedError() # pragma: no cover
57 unmodified lines
modified:httpx/dispatch/connection.py+6 added-6 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(83 host, port, ssl_context, timeout84 )82 stream = await self.backend.connect(host, port, ssl_context, timeout)83 http_version = stream.get_http_version()8485 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:97 return None9899 # Run the SSL loading in a threadpool, since it may makes disk accesses.99 # Run the SSL loading in a threadpool, since it may make disk accesses.100 return await self.backend.run_in_threadpool(101 ssl.load_ssl_context, self.http_versions102 )103
24 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+8 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 ) -> BaseStream:24 self.server = MockHTTP2Server(self.app)25 return self.server, self.server, "HTTP/2"25 return self.server262728class 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 def get_http_version(self) -> str:40 return "HTTP/2"4142 async def read(self, n, timeout, flag=None) -> bytes:43 await asyncio.sleep(0)44 send, self.buffer = self.buffer[:n], self.buffer[n:]45 return send4648 # BaseWriter interface4947 def write_no_block(self, data: bytes) -> None:48 events = self.conn.receive_data(data)49 self.buffer += self.conn.data_to_send()50 for event in events:
62 unmodified lines