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
Provenance
- Commit
3069227- Tree
b4d7284- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
2e91d8c- Parent 2
fdb1359
7 files changed+75 added−90 removed
modified:httpx/concurrency/asyncio.py+30 added-31 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+ def get_http_version(self) -> str:65+ ssl_object = self.stream_writer.get_extra_info("ssl_object")66+67+ if ssl_object is None:68+ return "HTTP/1.1"69+70+ ident = ssl_object.selected_alpn_protocol()71+ if ident is None:72+ ident = ssl_object.selected_npn_protocol()73+74+ return "HTTP/2" if ident == "h2" else "HTTP/1.1"75+76 async def read(77 self, n: int, timeout: TimeoutConfig = None, flag: TimeoutFlag = None78 ) -> bytes:79 if timeout is None:12 unmodified lines92 raise ReadTimeout() from None93 94 return data95 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-96 def write_no_block(self, data: bytes) -> None:97 self.stream_writer.write(data) # pragma: nocover98 99 async def write(19 unmodified lines119 should_raise = flag is None or flag.raise_on_write_timeout120 if should_raise:121 raise WriteTimeout() from None122 123+ def is_connection_dropped(self) -> bool:124+ return self.stream_reader.at_eof()125+126 async def close(self) -> None:127 self.stream_writer.close()128 129 50 unmodified lines180 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()192 184- 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+ )196 192- 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"195-196- return reader, writer, http_version197-197 async def run_in_threadpool(198 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any199 ) -> typing.Any:200 if kwargs:49 unmodified linesmodified:httpx/concurrency/base.py+11 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+ def get_http_version(self) -> str:48+ raise NotImplementedError() # pragma: no cover49+50 async def read(51 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None52 ) -> bytes:53 raise NotImplementedError() # pragma: no cover54 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-55 def write_no_block(self, data: bytes) -> None:56 raise NotImplementedError() # pragma: no cover57 58 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:1 unmodified line60 61 async def close(self) -> None:62 raise NotImplementedError() # pragma: no cover63 64+ def is_connection_dropped(self) -> bool:65+ raise NotImplementedError() # pragma: no cover66 67+68 class BaseQueue:69 """70 A FIFO queue. Abstracts away any asyncio-specific interfaces.71 """40 unmodified lines112 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 cover118 119 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:120 raise NotImplementedError() # pragma: no cover57 unmodified linesmodified:httpx/dispatch/connection.py+6 added-6 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(83- host, port, ssl_context, timeout84- )82+ stream = await self.backend.connect(host, port, ssl_context, timeout)83+ http_version = stream.get_http_version()84+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:97 return None98 99- # 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 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+8 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+ ) -> BaseStream:24 self.server = MockHTTP2Server(self.app)25- return self.server, self.server, "HTTP/2"25+ return self.server26 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+ def get_http_version(self) -> str:40+ return "HTTP/2"41+42 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 send46 48- # BaseWriter interface49-47 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