Add OpenConnection base class (#616)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add OpenConnection base class * Move is_http2 property around
authored by Florimond Manca · committed by GitHub · parent eba29da · Browse files · 4 files·+62 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+62 added−37 removed
- other:+62 added−37 removed
Provenance
- Commit
e95111a- Tree
0114964- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
eba29da
4 files changed+62 added−37 removed
modified:httpx/dispatch/base.py+23 added
56 unmodified lines57 exc_value: BaseException = None,58 traceback: TracebackType = None,59 ) -> None:60 await self.close()61+62+63+class OpenConnection:64+ """65+ Base class for connection classes that interact with a host via HTTP.66+ """67+68+ @property69+ def is_http2(self) -> bool:70+ raise NotImplementedError() # pragma: no cover71+72+ async def send(self, request: Request, timeout: Timeout = None,) -> Response:73+ raise NotImplementedError() # pragma: no cover74+75+ @property76+ def is_closed(self) -> bool:77+ raise NotImplementedError() # pragma: no cover78+79+ def is_connection_dropped(self) -> bool:80+ raise NotImplementedError() # pragma: no cover81+82+ async def close(self) -> None:83+ raise NotImplementedError() # pragma: no covermodified:httpx/dispatch/connection.py+27 added-35 removed
2 unmodified lines3 import typing4 5 import h116 7-from ..concurrency.base import ConcurrencyBackend, lookup_backend7+from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, lookup_backend8 from ..config import CertTypes, SSLConfig, Timeout, VerifyTypes9 from ..models import URL, Origin, Request, Response10 from ..utils import get_logger11-from .base import Dispatcher11+from .base import Dispatcher, OpenConnection12 from .http2 import HTTP2Connection13 from .http11 import HTTP11Connection14 15 # Callback signature: async def callback(conn: HTTPConnection) -> None20 unmodified lines36 self.http2 = http237 self.backend = lookup_backend(backend)38 self.release_func = release_func39 self.uds = uds40- self.h11_connection = None # type: typing.Optional[HTTP11Connection]41- self.h2_connection = None # type: typing.Optional[HTTP2Connection]40+ self.open_connection: typing.Optional[OpenConnection] = None41 42 async def send(43 self,44 request: Request,2 unmodified lines47 timeout: Timeout = None,48 ) -> Response:49 timeout = Timeout() if timeout is None else timeout50 52- if self.h11_connection is None and self.h2_connection is None:51+ if self.open_connection is None:52 await self.connect(verify=verify, cert=cert, timeout=timeout)53 55- if self.h2_connection is not None:56- response = await self.h2_connection.send(request, timeout=timeout)57- else:58- assert self.h11_connection is not None59- response = await self.h11_connection.send(request, timeout=timeout)54+ assert self.open_connection is not None55+ response = await self.open_connection.send(request, timeout=timeout)56 57 return response58 59 async def connect(27 unmodified lines87 88 http_version = stream.get_http_version()89 logger.trace(f"connected http_version={http_version!r}")90 95- if http_version == "HTTP/2":96- self.h2_connection = HTTP2Connection(97- stream, backend=self.backend, on_release=on_release98- )99- else:100- assert http_version == "HTTP/1.1"101- self.h11_connection = HTTP11Connection(stream, on_release=on_release)91+ self.set_open_connection(http_version, socket=stream, on_release=on_release)92 93 async def tunnel_start_tls(94 self,95 origin: Origin,8 unmodified lines104 timeout = Timeout() if timeout is None else timeout105 106 # First, check that we are in the correct state to start TLS, i.e. we've107 # just agreed to switch protocols with the server via HTTP/1.1.108+ assert isinstance(self.open_connection, HTTP11Connection)118- h11_connection = self.h11_connection109+ h11_connection = self.open_connection110 assert h11_connection is not None111 assert h11_connection.h11_state.our_state == h11.SWITCHED_PROTOCOL112 113 # Store this information here so that we can transfer26 unmodified lines140 # User requested the use of a tunnel, but they're performing a plain-text141 # HTTP request. Don't try to upgrade to TLS in this case.142 pass143 144+ self.set_open_connection(http_version, socket=socket, on_release=on_release)145+146+ def set_open_connection(147+ self,148+ http_version: str,149+ socket: BaseSocketStream,150+ on_release: typing.Optional[typing.Callable],151+ ) -> None:152 if http_version == "HTTP/2":154- self.h2_connection = HTTP2Connection(153+ self.open_connection = HTTP2Connection(154 socket, self.backend, on_release=on_release155 )156 else:157 assert http_version == "HTTP/1.1"159- self.h11_connection = HTTP11Connection(socket, on_release=on_release)158+ self.open_connection = HTTP11Connection(socket, on_release=on_release)159 160 async def get_ssl_context(self, ssl: SSLConfig) -> typing.Optional[ssl.SSLContext]:161 if not self.origin.is_ssl:162 return None2 unmodified lines165 return await self.backend.run_in_threadpool(ssl.load_ssl_context, self.http2)166 167 async def close(self) -> None:168 logger.trace("close_connection")170- if self.h2_connection is not None:171- await self.h2_connection.close()172- elif self.h11_connection is not None:173- await self.h11_connection.close()169+ if self.open_connection is not None:170+ await self.open_connection.close()171 172 @property173 def is_http2(self) -> bool:177- return self.h2_connection is not None174+ assert self.open_connection is not None175+ return self.open_connection.is_http2176 177 @property178 def is_closed(self) -> bool:181- if self.h2_connection is not None:182- return self.h2_connection.is_closed183- else:184- assert self.h11_connection is not None185- return self.h11_connection.is_closed179+ assert self.open_connection is not None180+ return self.open_connection.is_closed181 182 def is_connection_dropped(self) -> bool:188- if self.h2_connection is not None:189- return self.h2_connection.is_connection_dropped()190- else:191- assert self.h11_connection is not None192- return self.h11_connection.is_connection_dropped()183+ assert self.open_connection is not None184+ return self.open_connection.is_connection_dropped()185 186 def __repr__(self) -> str:187 class_name = self.__class__.__name__188 return f"{class_name}(origin={self.origin!r})"modified:httpx/dispatch/http11.py+6 added-1 removed
5 unmodified lines6 from ..config import Timeout7 from ..exceptions import ConnectionClosed, ProtocolError8 from ..models import Request, Response9 from ..utils import get_logger10+from .base import OpenConnection11 12 H11Event = typing.Union[13 h11.Request,14 h11.Response,12 unmodified lines27 28 logger = get_logger(__name__)29 30 30-class HTTP11Connection:31+class HTTP11Connection(OpenConnection):32 READ_NUM_BYTES = 409633 34 def __init__(35 self,3 unmodified lines39 self.socket = socket40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)42 43+ @property44+ def is_http2(self) -> bool:45+ return False46+47 async def send(self, request: Request, timeout: Timeout = None) -> Response:48 timeout = Timeout() if timeout is None else timeout49 50 await self._send_request(request, timeout)154 unmodified linesmodified:httpx/dispatch/http2.py+6 added-1 removed
12 unmodified lines13 from ..config import Timeout14 from ..exceptions import ProtocolError15 from ..models import Request, Response16 from ..utils import get_logger17+from .base import OpenConnection18 19 logger = get_logger(__name__)20 21 21-class HTTP2Connection:22+class HTTP2Connection(OpenConnection):23 READ_NUM_BYTES = 409624 25 def __init__(26 self,11 unmodified lines38 39 self.init_started = False40 41 @property42+ def is_http2(self) -> bool:43+ return True44+45+ @property46 def init_complete(self) -> BaseEvent:47 # We do this lazily, to make sure backend autodetection always48 # runs within an async context.49 if not hasattr(self, "_initialization_complete"):220 unmodified lines