Add support for unix domain sockets (#511)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add and implement open_uds_stream in concurrency backends * Add uds arg to BaseClient and select tcp or uds in HttpConnection * Make open stream methods in backends more explicit * Close sentence Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Refactor uds concurrency test * Remove redundant uds test assertions
authored by Jonas Lundberg · committed by Florimond Manca · parent a5f9983 · Browse files · 10 files·+135 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+135 added−6 removed
- tests:+60 added−4 removed
- other:+75 added−2 removed
Provenance
- Commit
7a96a2c- Tree
70d2048- Author
Jonas Lundberg <jonas@5monkeys.se>- Committer
Florimond Manca <florimond.manca@gmail.com>- Parent
a5f9983
10 files changed+135 added−6 removed
modified:httpx/concurrency/asyncio.py+23 added
273 unmodified lines274 return SocketStream(275 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout276 )277 278+ async def open_uds_stream(279+ self,280+ path: str,281+ hostname: typing.Optional[str],282+ ssl_context: typing.Optional[ssl.SSLContext],283+ timeout: TimeoutConfig,284+ ) -> SocketStream:285+ server_hostname = hostname if ssl_context else None286+287+ try:288+ stream_reader, stream_writer = await asyncio.wait_for( # type: ignore289+ asyncio.open_unix_connection(290+ path, ssl=ssl_context, server_hostname=server_hostname291+ ),292+ timeout.connect_timeout,293+ )294+ except asyncio.TimeoutError:295+ raise ConnectTimeout()296+297+ return SocketStream(298+ stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout299+ )300+301 async def run_in_threadpool(302 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any303 ) -> typing.Any:304 if kwargs:49 unmodified linesmodified:httpx/concurrency/base.py+9 added
122 unmodified lines123 timeout: TimeoutConfig,124 ) -> BaseSocketStream:125 raise NotImplementedError() # pragma: no cover126 127+ async def open_uds_stream(128+ self,129+ path: str,130+ hostname: typing.Optional[str],131+ ssl_context: typing.Optional[ssl.SSLContext],132+ timeout: TimeoutConfig,133+ ) -> BaseSocketStream:134+ raise NotImplementedError() # pragma: no cover135+136 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:137 raise NotImplementedError() # pragma: no cover138 139 async def run_in_threadpool(62 unmodified linesmodified:httpx/concurrency/trio.py+20 added
189 unmodified lines190 raise ConnectTimeout()191 192 return SocketStream(stream=stream, timeout=timeout)193 194+ async def open_uds_stream(195+ self,196+ path: str,197+ hostname: typing.Optional[str],198+ ssl_context: typing.Optional[ssl.SSLContext],199+ timeout: TimeoutConfig,200+ ) -> SocketStream:201+ connect_timeout = _or_inf(timeout.connect_timeout)202+203+ with trio.move_on_after(connect_timeout) as cancel_scope:204+ stream: trio.SocketStream = await trio.open_unix_socket(path)205+ if ssl_context is not None:206+ stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)207+ await stream.do_handshake()208+209+ if cancel_scope.cancelled_caught:210+ raise ConnectTimeout()211+212+ return SocketStream(stream=stream, timeout=timeout)213+214 async def run_in_threadpool(215 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any216 ) -> typing.Any:217 return await trio.to_thread.run_sync(75 unmodified linesmodified:httpx/dispatch/connection_pool.py+3 added
87 unmodified lines88 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,89 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,90 http_versions: HTTPVersionTypes = None,91 backend: ConcurrencyBackend = None,92+ uds: typing.Optional[str] = None,93 ):94 self.verify = verify95 self.cert = cert96 self.timeout = timeout97 self.pool_limits = pool_limits98 self.http_versions = http_versions99 self.is_closed = False100 self.trust_env = trust_env101+ self.uds = uds102 103 self.keepalive_connections = ConnectionStore()104 self.active_connections = ConnectionStore()105 37 unmodified lines143 http_versions=self.http_versions,144 backend=self.backend,145 release_func=self.release_connection,146 trust_env=self.trust_env,147+ uds=self.uds,148 )149 logger.trace(f"new_connection connection={connection!r}")150 else:151 logger.trace(f"reuse_connection connection={connection!r}")38 unmodified linesmodified:httpx/dispatch/connection.py+17 added-2 removed
36 unmodified lines37 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,38 http_versions: HTTPVersionTypes = None,39 backend: ConcurrencyBackend = None,40 release_func: typing.Optional[ReleaseCallback] = None,41+ uds: typing.Optional[str] = None,42 ):43 self.origin = Origin(origin) if isinstance(origin, str) else origin44 self.ssl = SSLConfig(cert=cert, verify=verify, trust_env=trust_env)45 self.timeout = TimeoutConfig(timeout)46 self.http_versions = HTTPVersionConfig(http_versions)47 self.backend = AsyncioBackend() if backend is None else backend48 self.release_func = release_func49+ self.uds = uds50 self.h11_connection = None # type: typing.Optional[HTTP11Connection]51 self.h2_connection = None # type: typing.Optional[HTTP2Connection]52 53 async def send(31 unmodified lines85 on_release = None86 else:87 on_release = functools.partial(self.release_func, self)88 87- logger.trace(f"start_connect host={host!r} port={port!r} timeout={timeout!r}")88- stream = await self.backend.open_tcp_stream(host, port, ssl_context, timeout)89+ if self.uds is None:90+ logger.trace(91+ f"start_connect tcp host={host!r} port={port!r} timeout={timeout!r}"92+ )93+ stream = await self.backend.open_tcp_stream(94+ host, port, ssl_context, timeout95+ )96+ else:97+ logger.trace(98+ f"start_connect uds path={self.uds!r} host={host!r} timeout={timeout!r}"99+ )100+ stream = await self.backend.open_uds_stream(101+ self.uds, host, ssl_context, timeout102+ )103+104 http_version = stream.get_http_version()105 logger.trace(f"connected http_version={http_version!r}")106 107 if http_version == "HTTP/2":47 unmodified linesmodified:httpx/client.py+3 added
72 unmodified lines73 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,74 app: typing.Callable = None,75 backend: ConcurrencyBackend = None,76 trust_env: bool = True,77+ uds: str = None,78 ):79 if backend is None:80 backend = AsyncioBackend()81 17 unmodified lines99 http_versions=http_versions,100 pool_limits=pool_limits,101 backend=backend,102 trust_env=self.trust_env,103+ uds=uds,104 )105 elif isinstance(dispatch, Dispatcher):106 async_dispatch = ThreadedDispatcher(dispatch, backend)107 else:614 unmodified lines722 * **backend** - *(optional)* A concurrency backend to use when issuing723 async requests.724 * **trust_env** - *(optional)* Enables or disables usage of environment725 variables for configuration.726+ * **uds** - *(optional)* A path to a Unix domain socket to connect through.727 """728 729 def check_concurrency_backend(self, backend: ConcurrencyBackend) -> None:730 # Iterating over response content allocates an async environment on each step.518 unmodified linesmodified:tests/client/test_async_client.py+11 added
144 unmodified lines145 )146 147 assert response.status_code == 200148 assert response.content == data149+150+151+async def test_uds(uds_server, backend):152+ url = uds_server.url153+ uds = uds_server.config.uds154+ assert uds is not None155+ async with httpx.AsyncClient(backend=backend, uds=uds) as client:156+ response = await client.get(url)157+ assert response.status_code == 200158+ assert response.text == "Hello, world!"159+ assert response.encoding == "iso-8859-1"modified:tests/client/test_client.py+11 added
136 unmodified lines137 assert response.status_code == 200138 assert response.url == base_url139 140 141+def test_uds(uds_server):142+ url = uds_server.url143+ uds = uds_server.config.uds144+ assert uds is not None145+ with httpx.Client(uds=uds) as http:146+ response = http.get(url)147+ assert response.status_code == 200148+ assert response.text == "Hello, world!"149+ assert response.encoding == "iso-8859-1"150+151+152 def test_merge_url():153 client = httpx.Client(base_url="https://www.paypal.com/")154 url = client.merge_url("http://www.paypal.com")155 34 unmodified linesmodified:tests/conftest.py+25 added
287 unmodified lines288 yield from serve_in_thread(server)289 290 291 @pytest.fixture(scope=SERVER_SCOPE)292+def uds_server():293+ uds = "test_server.sock"294+ config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)295+ server = TestServer(config=config)296+ yield from serve_in_thread(server)297+ os.remove(uds)298+299+300+@pytest.fixture(scope=SERVER_SCOPE)301 def https_server(cert_pem_file, cert_private_key_file):302 config = Config(303 app=app,304 lifespan="off",4 unmodified lines309 loop="asyncio",310 )311 server = TestServer(config=config)312 yield from serve_in_thread(server)313+314+315+@pytest.fixture(scope=SERVER_SCOPE)316+def https_uds_server(cert_pem_file, cert_private_key_file):317+ uds = "https_test_server.sock"318+ config = Config(319+ app=app,320+ lifespan="off",321+ ssl_certfile=cert_pem_file,322+ ssl_keyfile=cert_private_key_file,323+ uds=uds,324+ loop="asyncio",325+ )326+ server = TestServer(config=config)327+ yield from serve_in_thread(server)328+ os.remove(uds)modified:tests/test_concurrency.py+13 added-4 removed
22 unmodified lines23 marks=pytest.mark.trio,24 ),25 ],26 )27+@pytest.mark.parametrize("use_uds", (False, True))27-async def test_start_tls_on_socket_stream(https_server, backend, get_cipher):28+async def test_start_tls_on_socket_stream(29+ https_server, https_uds_server, backend, get_cipher, use_uds30+):31 """32 See that the concurrency backend can make a connection without TLS then33 start TLS on an existing connection.34 """35 ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())36 timeout = TimeoutConfig(5)37 38+ if use_uds:39+ assert https_uds_server.config.uds is not None40+ stream = await backend.open_uds_stream(41+ https_uds_server.config.uds, https_uds_server.url.host, None, timeout42+ )43+ else:35- stream = await backend.open_tcp_stream(36- https_server.url.host, https_server.url.port, None, timeout37- )44+ stream = await backend.open_tcp_stream(45+ https_server.url.host, https_server.url.port, None, timeout46+ )47 48 try:49 assert stream.is_connection_dropped() is False50 assert get_cipher(stream) is None24 unmodified lines