Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import json
import re
import ssl
from typing import Optional, Union
from urllib.request import getproxies

import {{httpxModule}}

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import re
import ssl
from typing import Optional, Union
from urllib.request import getproxies

import httpx

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import re
import ssl
from typing import Optional, Union
from urllib.request import getproxies

import httpx

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: With retries enabled, each connect attempt gets the full timeout, so an unreachable host can block for up to (retries + 1) × timeout plus backoff. That breaks the total-timeout contract documented in request(). Document this behavior, or enforce an overall deadline.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py, line 207:

<comment>With retries enabled, each connect attempt gets the full timeout, so an unreachable host can block for up to (retries + 1) × timeout plus backoff. That breaks the total-timeout contract documented in `request()`. Document this behavior, or enforce an overall deadline.</comment>

<file context>
@@ -193,6 +195,22 @@ def _create_pool_manager(self) -> httpx.AsyncClient:
+                verify=self.ssl_context,
+                limits=limits,
+                proxy=proxy,
+                retries=self.retries,
+            )
+            return httpx.AsyncClient(
</file context>

)
return httpx.AsyncClient(
transport=transport,
trust_env=True
)

return httpx.AsyncClient(
limits=limits,
proxy=proxy,
Expand Down
104 changes: 104 additions & 0 deletions samples/openapi3/client/petstore/python-httpx/tests/test_retries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Configuration.retries is passed to httpx's transport retries, for direct connections."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Several added lines exceed this sample’s configured 99-character flake8 limit, causing lint failures when flake8 runs. Wrap the helper, patch, assertion, and context-manager lines to keep each line within the configured limit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx/tests/test_retries.py, line 48:

<comment>Several added lines exceed this sample’s configured 99-character flake8 limit, causing lint failures when flake8 runs. Wrap the helper, patch, assertion, and context-manager lines to keep each line within the configured limit.</comment>

<file context>
@@ -26,13 +37,23 @@ async def counting_connect_tcp(*args, **kwargs):
         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, \
</file context>

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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This helper releases the selected port before the request starts, creating a race with other processes that can make the retry-count assertions flaky. Keep the reservation lifecycle through the connection attempt or use a deterministic local failure mechanism.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx/tests/test_retries.py, line 15:

<comment>This helper releases the selected port before the request starts, creating a race with other processes that can make the retry-count assertions flaky. Keep the reservation lifecycle through the connection attempt or use a deterministic local failure mechanism.</comment>

<file context>
@@ -1,24 +1,57 @@
+def closed_port():
+    with socket.socket() as sock:
+        sock.bind(("127.0.0.1", 0))
+        return sock.getsockname()[1]
+
+
</file context>



@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)
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading