Skip to content
Myr

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

4 files+62 added−37 removed

modified:httpx/dispatch/base.py+23 added
56 unmodified lines
57 exc_value: BaseException = None,58 traceback: TracebackType = None,59 ) -> None:60 await self.close()616263class OpenConnection:64 """65 Base class for connection classes that interact with a host via HTTP.66 """6768 @property69 def is_http2(self) -> bool:70 raise NotImplementedError() # pragma: no cover7172 async def send(self, request: Request, timeout: Timeout = None,) -> Response:73 raise NotImplementedError() # pragma: no cover7475 @property76 def is_closed(self) -> bool:77 raise NotImplementedError() # pragma: no cover7879 def is_connection_dropped(self) -> bool:80 raise NotImplementedError() # pragma: no cover8182 async def close(self) -> None:83 raise NotImplementedError() # pragma: no cover
modified:httpx/dispatch/connection.py+27 added-35 removed
2 unmodified lines
3import typing45import h1167from ..concurrency.base import ConcurrencyBackend, lookup_backend7from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, lookup_backend8from ..config import CertTypes, SSLConfig, Timeout, VerifyTypes9from ..models import URL, Origin, Request, Response10from ..utils import get_logger11from .base import Dispatcher11from .base import Dispatcher, OpenConnection12from .http2 import HTTP2Connection13from .http11 import HTTP11Connection1415# Callback signature: async def callback(conn: HTTPConnection) -> None
20 unmodified lines
36 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] = None4142 async def send(43 self,44 request: Request,
2 unmodified lines
47 timeout: Timeout = None,48 ) -> Response:49 timeout = Timeout() if timeout is None else timeout5052 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)5355 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)5657 return response5859 async def connect(
27 unmodified lines
8788 http_version = stream.get_http_version()89 logger.trace(f"connected http_version={http_version!r}")9095 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)9293 async def tunnel_start_tls(94 self,95 origin: Origin,
8 unmodified lines
104 timeout = Timeout() if timeout is None else timeout105106 # 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_PROTOCOL112113 # Store this information here so that we can transfer
26 unmodified lines
140 # 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 pass143144 self.set_open_connection(http_version, socket=socket, on_release=on_release)145146 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)159160 async def get_ssl_context(self, ssl: SSLConfig) -> typing.Optional[ssl.SSLContext]:161 if not self.origin.is_ssl:162 return None
2 unmodified lines
165 return await self.backend.run_in_threadpool(ssl.load_ssl_context, self.http2)166167 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()171172 @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_http2176177 @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_closed181182 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()185186 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 lines
6from ..config import Timeout7from ..exceptions import ConnectionClosed, ProtocolError8from ..models import Request, Response9from ..utils import get_logger10from .base import OpenConnection1112H11Event = typing.Union[13 h11.Request,14 h11.Response,
12 unmodified lines
2728logger = get_logger(__name__)293030class HTTP11Connection:31class HTTP11Connection(OpenConnection):32 READ_NUM_BYTES = 40963334 def __init__(35 self,
3 unmodified lines
39 self.socket = socket40 self.on_release = on_release41 self.h11_state = h11.Connection(our_role=h11.CLIENT)4243 @property44 def is_http2(self) -> bool:45 return False4647 async def send(self, request: Request, timeout: Timeout = None) -> Response:48 timeout = Timeout() if timeout is None else timeout4950 await self._send_request(request, timeout)
154 unmodified lines
modified:httpx/dispatch/http2.py+6 added-1 removed
12 unmodified lines
13from ..config import Timeout14from ..exceptions import ProtocolError15from ..models import Request, Response16from ..utils import get_logger17from .base import OpenConnection1819logger = get_logger(__name__)202121class HTTP2Connection:22class HTTP2Connection(OpenConnection):23 READ_NUM_BYTES = 40962425 def __init__(26 self,
11 unmodified lines
3839 self.init_started = False4041 @property42 def is_http2(self) -> bool:43 return True4445 @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