Skip to content
Myr

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

10 files+135 added−6 removed

modified:httpx/concurrency/asyncio.py+23 added
273 unmodified lines
274 return SocketStream(275 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout276 )277278 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 None286287 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()296297 return SocketStream(298 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout299 )300301 async def run_in_threadpool(302 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any303 ) -> typing.Any:304 if kwargs:
49 unmodified lines
modified:httpx/concurrency/base.py+9 added
122 unmodified lines
123 timeout: TimeoutConfig,124 ) -> BaseSocketStream:125 raise NotImplementedError() # pragma: no cover126127 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 cover135136 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:137 raise NotImplementedError() # pragma: no cover138139 async def run_in_threadpool(
62 unmodified lines
modified:httpx/concurrency/trio.py+20 added
189 unmodified lines
190 raise ConnectTimeout()191192 return SocketStream(stream=stream, timeout=timeout)193194 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)202203 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()208209 if cancel_scope.cancelled_caught:210 raise ConnectTimeout()211212 return SocketStream(stream=stream, timeout=timeout)213214 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 lines
modified:httpx/dispatch/connection_pool.py+3 added
87 unmodified lines
88 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 = uds102103 self.keepalive_connections = ConnectionStore()104 self.active_connections = ConnectionStore()105
37 unmodified lines
143 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 lines
modified:httpx/dispatch/connection.py+17 added-2 removed
36 unmodified lines
37 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]5253 async def send(
31 unmodified lines
85 on_release = None86 else:87 on_release = functools.partial(self.release_func, self)8887 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 )103104 http_version = stream.get_http_version()105 logger.trace(f"connected http_version={http_version!r}")106107 if http_version == "HTTP/2":
47 unmodified lines
modified:httpx/client.py+3 added
72 unmodified lines
73 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 lines
99 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 lines
722 * **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 """728729 def check_concurrency_backend(self, backend: ConcurrencyBackend) -> None:730 # Iterating over response content allocates an async environment on each step.
518 unmodified lines
modified:tests/client/test_async_client.py+11 added
144 unmodified lines
145 )146147 assert response.status_code == 200148 assert response.content == data149150151async 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 lines
137 assert response.status_code == 200138 assert response.url == base_url139140141def 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"150151152def 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 lines
modified:tests/conftest.py+25 added
287 unmodified lines
288 yield from serve_in_thread(server)289290291@pytest.fixture(scope=SERVER_SCOPE)292def 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)298299300@pytest.fixture(scope=SERVER_SCOPE)301def https_server(cert_pem_file, cert_private_key_file):302 config = Config(303 app=app,304 lifespan="off",
4 unmodified lines
309 loop="asyncio",310 )311 server = TestServer(config=config)312 yield from serve_in_thread(server)313314315@pytest.fixture(scope=SERVER_SCOPE)316def 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 lines
23 marks=pytest.mark.trio,24 ),25 ],26)27@pytest.mark.parametrize("use_uds", (False, True))27async def test_start_tls_on_socket_stream(https_server, backend, get_cipher):28async 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)3738 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 )4748 try:49 assert stream.is_connection_dropped() is False50 assert get_cipher(stream) is None
24 unmodified lines