diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index 920408100449..81663187c39e 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -213,7 +213,12 @@ class Configuration: {{/useIndependentImplicitClients}} {{/asyncio}} {{#httpxLibrary}} - :param retries: int - Retry configuration. + :param retries: int - Number of retries on connection failures + (ConnectError, ConnectTimeout), passed to {{httpxModule}}.AsyncHTTPTransport. + Each attempt gets the full connect timeout, with an exponential backoff + between attempts. Direct connections only: httpx does not retry through + a proxy (encode/httpx#2997), so retries are not applied when a proxy is + set, by the proxy parameter or by environment variables. {{/httpxLibrary}} {{^async}} :param retries: int | urllib3.util.retry.Retry - Retry configuration. diff --git a/modules/openapi-generator/src/main/resources/python/httpx/rest.mustache b/modules/openapi-generator/src/main/resources/python/httpx/rest.mustache index 749b7ffbadbf..2b7654f08620 100644 --- a/modules/openapi-generator/src/main/resources/python/httpx/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/httpx/rest.mustache @@ -8,6 +8,7 @@ import json import re import ssl from typing import Optional, Union +from urllib.request import getproxies import {{httpxModule}} @@ -65,6 +66,8 @@ class RESTClientObject: self.proxy = configuration.proxy self.proxy_headers = configuration.proxy_headers + self.retries = configuration.retries + self.pool_manager: Optional[{{httpxModule}}.AsyncClient] = None async def close(self): @@ -184,6 +187,24 @@ class RESTClientObject: headers=self.proxy_headers ) + # httpx's transport retries only apply to direct connections: it does not + # retry through a proxy (encode/httpx#2997), and a custom transport would + # disable proxies from environment variables. With any proxy, the client + # is built as without retries. getproxies() is what httpx reads as well. + has_proxy = proxy is not None or any( + scheme != "no" for scheme in getproxies() + ) + if self.retries is not None and self.retries > 0 and not has_proxy: + transport = {{httpxModule}}.AsyncHTTPTransport( + verify=self.ssl_context, + limits=limits, + retries=self.retries, + ) + return {{httpxModule}}.AsyncClient( + transport=transport, + trust_env=True + ) + return {{httpxModule}}.AsyncClient( limits=limits, proxy=proxy, diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/configuration.py index cefa6fa3a1f9..952b13d2d126 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/configuration.py @@ -167,7 +167,12 @@ class Configuration: when calling API from https server. :param ssl_ca_cert: str - the path to a file of concatenated CA certificates in PEM format. - :param retries: int - Retry configuration. + :param retries: int - Number of retries on connection failures + (ConnectError, ConnectTimeout), passed to httpx.AsyncHTTPTransport. + Each attempt gets the full connect timeout, with an exponential backoff + between attempts. Direct connections only: httpx does not retry through + a proxy (encode/httpx#2997), so retries are not applied when a proxy is + set, by the proxy parameter or by environment variables. :param ca_cert_data: verify the peer using concatenated CA certificate data in PEM (str) or DER (bytes) format. :param cert_file: the path to a client certificate file, for mTLS. diff --git a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/rest.py b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/rest.py index f28745ec0fe7..2f804f246e72 100644 --- a/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-httpx-sync/petstore_api/rest.py @@ -17,6 +17,7 @@ import re import ssl from typing import Optional, Union +from urllib.request import getproxies import httpx @@ -74,6 +75,8 @@ def __init__(self, configuration) -> None: self.proxy = configuration.proxy self.proxy_headers = configuration.proxy_headers + self.retries = configuration.retries + self.pool_manager: Optional[httpx.AsyncClient] = None async def close(self): @@ -193,6 +196,24 @@ def _create_pool_manager(self) -> httpx.AsyncClient: headers=self.proxy_headers ) + # httpx's transport retries only apply to direct connections: it does not + # retry through a proxy (encode/httpx#2997), and a custom transport would + # disable proxies from environment variables. With any proxy, the client + # is built as without retries. getproxies() is what httpx reads as well. + has_proxy = proxy is not None or any( + scheme != "no" for scheme in getproxies() + ) + if self.retries is not None and self.retries > 0 and not has_proxy: + transport = httpx.AsyncHTTPTransport( + verify=self.ssl_context, + limits=limits, + retries=self.retries, + ) + return httpx.AsyncClient( + transport=transport, + trust_env=True + ) + return httpx.AsyncClient( limits=limits, proxy=proxy, diff --git a/samples/openapi3/client/petstore/python-httpx-sync/tests/test_retries.py b/samples/openapi3/client/petstore/python-httpx-sync/tests/test_retries.py new file mode 100644 index 000000000000..04720ebebf65 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx-sync/tests/test_retries.py @@ -0,0 +1,104 @@ +"""Configuration.retries is passed to httpx's transport retries, for direct connections.""" +import os +import socket +import unittest +from contextlib import contextmanager +from unittest.mock import patch + +import anyio +import httpx +from petstore_api import Configuration +from petstore_api.rest import RESTClientObject + + +def closed_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +@contextmanager +def proxy_environment(**proxies): + """Replace the *_proxy environment variables with the given ones.""" + environ = {k: v for k, v in os.environ.items() if not k.lower().endswith("_proxy")} + environ.update(proxies) + with patch.dict(os.environ, environ, clear=True): + yield + + +class TestRetries(unittest.IsolatedAsyncioTestCase): + async def connection_attempts(self, config): + attempts = [] + connect_tcp = anyio.connect_tcp + + async def counting_connect_tcp(*args, **kwargs): + attempts.append(args) + return await connect_tcp(*args, **kwargs) + + rest = RESTClientObject(config) + try: + with proxy_environment(), patch("anyio.connect_tcp", counting_connect_tcp): + with self.assertRaises(httpx.ConnectError): + await rest.request("GET", "http://127.0.0.1:%d/pet" % closed_port()) + finally: + await rest.close() + return len(attempts) + + def build_client(self, config): + """Return the REST client, the transport kwargs (None if no custom transport) and the client kwargs.""" + rest = RESTClientObject(config) + with patch("petstore_api.rest.httpx.AsyncHTTPTransport", wraps=httpx.AsyncHTTPTransport) as transport, \ + patch("petstore_api.rest.httpx.AsyncClient", wraps=httpx.AsyncClient) as factory: + pool = rest._create_pool_manager() + self.addAsyncCleanup(pool.aclose) + transport_kwargs = transport.call_args.kwargs if transport.called else None + return rest, transport_kwargs, factory.call_args.kwargs + + async def test_connection_failures_are_retried(self): + self.assertEqual(await self.connection_attempts(Configuration(retries=2)), 3) + + async def test_no_retry_by_default(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries): + self.assertEqual(await self.connection_attempts(Configuration(retries=retries)), 1) + + async def test_retry_transport_gets_tls_and_limits(self): + config = Configuration(retries=3) + with proxy_environment(): + rest, transport_kwargs, client_kwargs = self.build_client(config) + self.assertEqual(transport_kwargs["retries"], 3) + self.assertIs(transport_kwargs["verify"], rest.ssl_context) + self.assertEqual(transport_kwargs["limits"].max_connections, config.connection_pool_maxsize) + self.assertIsInstance(client_kwargs["transport"], httpx.AsyncHTTPTransport) + + async def test_no_proxy_alone_keeps_retries(self): + with proxy_environment(NO_PROXY="example.com"): + _, transport_kwargs, _ = self.build_client(Configuration(retries=3)) + self.assertEqual(transport_kwargs["retries"], 3) + + # With any proxy, httpx does not retry (encode/httpx#2997): the client must be + # built exactly as without retries, so that proxies keep working as before. + + async def test_without_retries_the_client_is_built_as_before(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries), proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=retries)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + + async def test_explicit_proxy_keeps_the_client_as_before(self): + config = Configuration(retries=3) + config.proxy = "http://localhost:8080" + config.proxy_headers = {"X-Proxy": "value"} + with proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(config) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + self.assertEqual(client_kwargs["proxy"].headers["X-Proxy"], "value") + + async def test_environment_proxy_keeps_the_client_as_before(self): + for variable in ("HTTP_PROXY", "https_proxy", "ALL_PROXY"): + with self.subTest(variable=variable), proxy_environment(**{variable: "http://localhost:8080"}): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=3)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/configuration.py index cefa6fa3a1f9..952b13d2d126 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/configuration.py @@ -167,7 +167,12 @@ class Configuration: when calling API from https server. :param ssl_ca_cert: str - the path to a file of concatenated CA certificates in PEM format. - :param retries: int - Retry configuration. + :param retries: int - Number of retries on connection failures + (ConnectError, ConnectTimeout), passed to httpx.AsyncHTTPTransport. + Each attempt gets the full connect timeout, with an exponential backoff + between attempts. Direct connections only: httpx does not retry through + a proxy (encode/httpx#2997), so retries are not applied when a proxy is + set, by the proxy parameter or by environment variables. :param ca_cert_data: verify the peer using concatenated CA certificate data in PEM (str) or DER (bytes) format. :param cert_file: the path to a client certificate file, for mTLS. diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py index f28745ec0fe7..2f804f246e72 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py @@ -17,6 +17,7 @@ import re import ssl from typing import Optional, Union +from urllib.request import getproxies import httpx @@ -74,6 +75,8 @@ def __init__(self, configuration) -> None: self.proxy = configuration.proxy self.proxy_headers = configuration.proxy_headers + self.retries = configuration.retries + self.pool_manager: Optional[httpx.AsyncClient] = None async def close(self): @@ -193,6 +196,24 @@ def _create_pool_manager(self) -> httpx.AsyncClient: headers=self.proxy_headers ) + # httpx's transport retries only apply to direct connections: it does not + # retry through a proxy (encode/httpx#2997), and a custom transport would + # disable proxies from environment variables. With any proxy, the client + # is built as without retries. getproxies() is what httpx reads as well. + has_proxy = proxy is not None or any( + scheme != "no" for scheme in getproxies() + ) + if self.retries is not None and self.retries > 0 and not has_proxy: + transport = httpx.AsyncHTTPTransport( + verify=self.ssl_context, + limits=limits, + retries=self.retries, + ) + return httpx.AsyncClient( + transport=transport, + trust_env=True + ) + return httpx.AsyncClient( limits=limits, proxy=proxy, diff --git a/samples/openapi3/client/petstore/python-httpx/tests/test_retries.py b/samples/openapi3/client/petstore/python-httpx/tests/test_retries.py new file mode 100644 index 000000000000..04720ebebf65 --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx/tests/test_retries.py @@ -0,0 +1,104 @@ +"""Configuration.retries is passed to httpx's transport retries, for direct connections.""" +import os +import socket +import unittest +from contextlib import contextmanager +from unittest.mock import patch + +import anyio +import httpx +from petstore_api import Configuration +from petstore_api.rest import RESTClientObject + + +def closed_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +@contextmanager +def proxy_environment(**proxies): + """Replace the *_proxy environment variables with the given ones.""" + environ = {k: v for k, v in os.environ.items() if not k.lower().endswith("_proxy")} + environ.update(proxies) + with patch.dict(os.environ, environ, clear=True): + yield + + +class TestRetries(unittest.IsolatedAsyncioTestCase): + async def connection_attempts(self, config): + attempts = [] + connect_tcp = anyio.connect_tcp + + async def counting_connect_tcp(*args, **kwargs): + attempts.append(args) + return await connect_tcp(*args, **kwargs) + + rest = RESTClientObject(config) + try: + with proxy_environment(), patch("anyio.connect_tcp", counting_connect_tcp): + with self.assertRaises(httpx.ConnectError): + await rest.request("GET", "http://127.0.0.1:%d/pet" % closed_port()) + finally: + await rest.close() + return len(attempts) + + def build_client(self, config): + """Return the REST client, the transport kwargs (None if no custom transport) and the client kwargs.""" + rest = RESTClientObject(config) + with patch("petstore_api.rest.httpx.AsyncHTTPTransport", wraps=httpx.AsyncHTTPTransport) as transport, \ + patch("petstore_api.rest.httpx.AsyncClient", wraps=httpx.AsyncClient) as factory: + pool = rest._create_pool_manager() + self.addAsyncCleanup(pool.aclose) + transport_kwargs = transport.call_args.kwargs if transport.called else None + return rest, transport_kwargs, factory.call_args.kwargs + + async def test_connection_failures_are_retried(self): + self.assertEqual(await self.connection_attempts(Configuration(retries=2)), 3) + + async def test_no_retry_by_default(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries): + self.assertEqual(await self.connection_attempts(Configuration(retries=retries)), 1) + + async def test_retry_transport_gets_tls_and_limits(self): + config = Configuration(retries=3) + with proxy_environment(): + rest, transport_kwargs, client_kwargs = self.build_client(config) + self.assertEqual(transport_kwargs["retries"], 3) + self.assertIs(transport_kwargs["verify"], rest.ssl_context) + self.assertEqual(transport_kwargs["limits"].max_connections, config.connection_pool_maxsize) + self.assertIsInstance(client_kwargs["transport"], httpx.AsyncHTTPTransport) + + async def test_no_proxy_alone_keeps_retries(self): + with proxy_environment(NO_PROXY="example.com"): + _, transport_kwargs, _ = self.build_client(Configuration(retries=3)) + self.assertEqual(transport_kwargs["retries"], 3) + + # With any proxy, httpx does not retry (encode/httpx#2997): the client must be + # built exactly as without retries, so that proxies keep working as before. + + async def test_without_retries_the_client_is_built_as_before(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries), proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=retries)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + + async def test_explicit_proxy_keeps_the_client_as_before(self): + config = Configuration(retries=3) + config.proxy = "http://localhost:8080" + config.proxy_headers = {"X-Proxy": "value"} + with proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(config) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + self.assertEqual(client_kwargs["proxy"].headers["X-Proxy"], "value") + + async def test_environment_proxy_keeps_the_client_as_before(self): + for variable in ("HTTP_PROXY", "https_proxy", "ALL_PROXY"): + with self.subTest(variable=variable), proxy_environment(**{variable: "http://localhost:8080"}): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=3)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/configuration.py index cefa6fa3a1f9..2b5f7c56183f 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/configuration.py @@ -167,7 +167,12 @@ class Configuration: when calling API from https server. :param ssl_ca_cert: str - the path to a file of concatenated CA certificates in PEM format. - :param retries: int - Retry configuration. + :param retries: int - Number of retries on connection failures + (ConnectError, ConnectTimeout), passed to httpx2.AsyncHTTPTransport. + Each attempt gets the full connect timeout, with an exponential backoff + between attempts. Direct connections only: httpx does not retry through + a proxy (encode/httpx#2997), so retries are not applied when a proxy is + set, by the proxy parameter or by environment variables. :param ca_cert_data: verify the peer using concatenated CA certificate data in PEM (str) or DER (bytes) format. :param cert_file: the path to a client certificate file, for mTLS. diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/rest.py b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/rest.py index 22dc7db551e3..68af10bdd4e6 100644 --- a/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-httpx2-sync/petstore_api/rest.py @@ -17,6 +17,7 @@ import re import ssl from typing import Optional, Union +from urllib.request import getproxies import httpx2 @@ -74,6 +75,8 @@ def __init__(self, configuration) -> None: self.proxy = configuration.proxy self.proxy_headers = configuration.proxy_headers + self.retries = configuration.retries + self.pool_manager: Optional[httpx2.AsyncClient] = None async def close(self): @@ -193,6 +196,24 @@ def _create_pool_manager(self) -> httpx2.AsyncClient: headers=self.proxy_headers ) + # httpx's transport retries only apply to direct connections: it does not + # retry through a proxy (encode/httpx#2997), and a custom transport would + # disable proxies from environment variables. With any proxy, the client + # is built as without retries. getproxies() is what httpx reads as well. + has_proxy = proxy is not None or any( + scheme != "no" for scheme in getproxies() + ) + if self.retries is not None and self.retries > 0 and not has_proxy: + transport = httpx2.AsyncHTTPTransport( + verify=self.ssl_context, + limits=limits, + retries=self.retries, + ) + return httpx2.AsyncClient( + transport=transport, + trust_env=True + ) + return httpx2.AsyncClient( limits=limits, proxy=proxy, diff --git a/samples/openapi3/client/petstore/python-httpx2-sync/tests/test_retries.py b/samples/openapi3/client/petstore/python-httpx2-sync/tests/test_retries.py new file mode 100644 index 000000000000..2c764a5f4f7a --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2-sync/tests/test_retries.py @@ -0,0 +1,104 @@ +"""Configuration.retries is passed to httpx2's transport retries, for direct connections.""" +import os +import socket +import unittest +from contextlib import contextmanager +from unittest.mock import patch + +import anyio +import httpx2 +from petstore_api import Configuration +from petstore_api.rest import RESTClientObject + + +def closed_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +@contextmanager +def proxy_environment(**proxies): + """Replace the *_proxy environment variables with the given ones.""" + environ = {k: v for k, v in os.environ.items() if not k.lower().endswith("_proxy")} + environ.update(proxies) + with patch.dict(os.environ, environ, clear=True): + yield + + +class TestRetries(unittest.IsolatedAsyncioTestCase): + async def connection_attempts(self, config): + attempts = [] + connect_tcp = anyio.connect_tcp + + async def counting_connect_tcp(*args, **kwargs): + attempts.append(args) + return await connect_tcp(*args, **kwargs) + + rest = RESTClientObject(config) + try: + with proxy_environment(), patch("anyio.connect_tcp", counting_connect_tcp): + with self.assertRaises(httpx2.ConnectError): + await rest.request("GET", "http://127.0.0.1:%d/pet" % closed_port()) + finally: + await rest.close() + return len(attempts) + + def build_client(self, config): + """Return the REST client, the transport kwargs (None if no custom transport) and the client kwargs.""" + rest = RESTClientObject(config) + with patch("petstore_api.rest.httpx2.AsyncHTTPTransport", wraps=httpx2.AsyncHTTPTransport) as transport, \ + patch("petstore_api.rest.httpx2.AsyncClient", wraps=httpx2.AsyncClient) as factory: + pool = rest._create_pool_manager() + self.addAsyncCleanup(pool.aclose) + transport_kwargs = transport.call_args.kwargs if transport.called else None + return rest, transport_kwargs, factory.call_args.kwargs + + async def test_connection_failures_are_retried(self): + self.assertEqual(await self.connection_attempts(Configuration(retries=2)), 3) + + async def test_no_retry_by_default(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries): + self.assertEqual(await self.connection_attempts(Configuration(retries=retries)), 1) + + async def test_retry_transport_gets_tls_and_limits(self): + config = Configuration(retries=3) + with proxy_environment(): + rest, transport_kwargs, client_kwargs = self.build_client(config) + self.assertEqual(transport_kwargs["retries"], 3) + self.assertIs(transport_kwargs["verify"], rest.ssl_context) + self.assertEqual(transport_kwargs["limits"].max_connections, config.connection_pool_maxsize) + self.assertIsInstance(client_kwargs["transport"], httpx2.AsyncHTTPTransport) + + async def test_no_proxy_alone_keeps_retries(self): + with proxy_environment(NO_PROXY="example.com"): + _, transport_kwargs, _ = self.build_client(Configuration(retries=3)) + self.assertEqual(transport_kwargs["retries"], 3) + + # With any proxy, httpx2 does not retry (encode/httpx2#2997): the client must be + # built exactly as without retries, so that proxies keep working as before. + + async def test_without_retries_the_client_is_built_as_before(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries), proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=retries)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + + async def test_explicit_proxy_keeps_the_client_as_before(self): + config = Configuration(retries=3) + config.proxy = "http://localhost:8080" + config.proxy_headers = {"X-Proxy": "value"} + with proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(config) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + self.assertEqual(client_kwargs["proxy"].headers["X-Proxy"], "value") + + async def test_environment_proxy_keeps_the_client_as_before(self): + for variable in ("HTTP_PROXY", "https_proxy", "ALL_PROXY"): + with self.subTest(variable=variable), proxy_environment(**{variable: "http://localhost:8080"}): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=3)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/configuration.py index cefa6fa3a1f9..2b5f7c56183f 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/configuration.py @@ -167,7 +167,12 @@ class Configuration: when calling API from https server. :param ssl_ca_cert: str - the path to a file of concatenated CA certificates in PEM format. - :param retries: int - Retry configuration. + :param retries: int - Number of retries on connection failures + (ConnectError, ConnectTimeout), passed to httpx2.AsyncHTTPTransport. + Each attempt gets the full connect timeout, with an exponential backoff + between attempts. Direct connections only: httpx does not retry through + a proxy (encode/httpx#2997), so retries are not applied when a proxy is + set, by the proxy parameter or by environment variables. :param ca_cert_data: verify the peer using concatenated CA certificate data in PEM (str) or DER (bytes) format. :param cert_file: the path to a client certificate file, for mTLS. diff --git a/samples/openapi3/client/petstore/python-httpx2/petstore_api/rest.py b/samples/openapi3/client/petstore/python-httpx2/petstore_api/rest.py index 22dc7db551e3..68af10bdd4e6 100644 --- a/samples/openapi3/client/petstore/python-httpx2/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-httpx2/petstore_api/rest.py @@ -17,6 +17,7 @@ import re import ssl from typing import Optional, Union +from urllib.request import getproxies import httpx2 @@ -74,6 +75,8 @@ def __init__(self, configuration) -> None: self.proxy = configuration.proxy self.proxy_headers = configuration.proxy_headers + self.retries = configuration.retries + self.pool_manager: Optional[httpx2.AsyncClient] = None async def close(self): @@ -193,6 +196,24 @@ def _create_pool_manager(self) -> httpx2.AsyncClient: headers=self.proxy_headers ) + # httpx's transport retries only apply to direct connections: it does not + # retry through a proxy (encode/httpx#2997), and a custom transport would + # disable proxies from environment variables. With any proxy, the client + # is built as without retries. getproxies() is what httpx reads as well. + has_proxy = proxy is not None or any( + scheme != "no" for scheme in getproxies() + ) + if self.retries is not None and self.retries > 0 and not has_proxy: + transport = httpx2.AsyncHTTPTransport( + verify=self.ssl_context, + limits=limits, + retries=self.retries, + ) + return httpx2.AsyncClient( + transport=transport, + trust_env=True + ) + return httpx2.AsyncClient( limits=limits, proxy=proxy, diff --git a/samples/openapi3/client/petstore/python-httpx2/tests/test_retries.py b/samples/openapi3/client/petstore/python-httpx2/tests/test_retries.py new file mode 100644 index 000000000000..2c764a5f4f7a --- /dev/null +++ b/samples/openapi3/client/petstore/python-httpx2/tests/test_retries.py @@ -0,0 +1,104 @@ +"""Configuration.retries is passed to httpx2's transport retries, for direct connections.""" +import os +import socket +import unittest +from contextlib import contextmanager +from unittest.mock import patch + +import anyio +import httpx2 +from petstore_api import Configuration +from petstore_api.rest import RESTClientObject + + +def closed_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +@contextmanager +def proxy_environment(**proxies): + """Replace the *_proxy environment variables with the given ones.""" + environ = {k: v for k, v in os.environ.items() if not k.lower().endswith("_proxy")} + environ.update(proxies) + with patch.dict(os.environ, environ, clear=True): + yield + + +class TestRetries(unittest.IsolatedAsyncioTestCase): + async def connection_attempts(self, config): + attempts = [] + connect_tcp = anyio.connect_tcp + + async def counting_connect_tcp(*args, **kwargs): + attempts.append(args) + return await connect_tcp(*args, **kwargs) + + rest = RESTClientObject(config) + try: + with proxy_environment(), patch("anyio.connect_tcp", counting_connect_tcp): + with self.assertRaises(httpx2.ConnectError): + await rest.request("GET", "http://127.0.0.1:%d/pet" % closed_port()) + finally: + await rest.close() + return len(attempts) + + def build_client(self, config): + """Return the REST client, the transport kwargs (None if no custom transport) and the client kwargs.""" + rest = RESTClientObject(config) + with patch("petstore_api.rest.httpx2.AsyncHTTPTransport", wraps=httpx2.AsyncHTTPTransport) as transport, \ + patch("petstore_api.rest.httpx2.AsyncClient", wraps=httpx2.AsyncClient) as factory: + pool = rest._create_pool_manager() + self.addAsyncCleanup(pool.aclose) + transport_kwargs = transport.call_args.kwargs if transport.called else None + return rest, transport_kwargs, factory.call_args.kwargs + + async def test_connection_failures_are_retried(self): + self.assertEqual(await self.connection_attempts(Configuration(retries=2)), 3) + + async def test_no_retry_by_default(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries): + self.assertEqual(await self.connection_attempts(Configuration(retries=retries)), 1) + + async def test_retry_transport_gets_tls_and_limits(self): + config = Configuration(retries=3) + with proxy_environment(): + rest, transport_kwargs, client_kwargs = self.build_client(config) + self.assertEqual(transport_kwargs["retries"], 3) + self.assertIs(transport_kwargs["verify"], rest.ssl_context) + self.assertEqual(transport_kwargs["limits"].max_connections, config.connection_pool_maxsize) + self.assertIsInstance(client_kwargs["transport"], httpx2.AsyncHTTPTransport) + + async def test_no_proxy_alone_keeps_retries(self): + with proxy_environment(NO_PROXY="example.com"): + _, transport_kwargs, _ = self.build_client(Configuration(retries=3)) + self.assertEqual(transport_kwargs["retries"], 3) + + # With any proxy, httpx2 does not retry (encode/httpx2#2997): the client must be + # built exactly as without retries, so that proxies keep working as before. + + async def test_without_retries_the_client_is_built_as_before(self): + for retries in (None, 0, -1): + with self.subTest(retries=retries), proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=retries)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + + async def test_explicit_proxy_keeps_the_client_as_before(self): + config = Configuration(retries=3) + config.proxy = "http://localhost:8080" + config.proxy_headers = {"X-Proxy": "value"} + with proxy_environment(): + _, transport_kwargs, client_kwargs = self.build_client(config) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs) + self.assertEqual(client_kwargs["proxy"].headers["X-Proxy"], "value") + + async def test_environment_proxy_keeps_the_client_as_before(self): + for variable in ("HTTP_PROXY", "https_proxy", "ALL_PROXY"): + with self.subTest(variable=variable), proxy_environment(**{variable: "http://localhost:8080"}): + _, transport_kwargs, client_kwargs = self.build_client(Configuration(retries=3)) + self.assertIsNone(transport_kwargs) + self.assertNotIn("transport", client_kwargs)