Skip to content

Commit d316d0e

Browse files
authored
fix(client): Create separate httpx per client when none configured (#1358)
Closes #1349 ## Issue if `httpx` object was not provided in `ClientConfig` when creating `ClientFactory()`, the default one was created and was shared **across clients** ## Fix If `httpx` object is not provided, the default one is created when **creating new client**. Thus, closing connection on one client doesen't affect the other clients ## Note If `httpx` is provided, all client created by factory keep the reference and it is expected behaviour ## Tests Added one tests which check if: - Clients from the same `ClientFacotry` have different httpx objects (providing config was empty) - Closing connection twice throws `A2AClientError` - Closing can't be done from sdk-scope (only http author can close its connection)
1 parent a2dbedd commit d316d0e

12 files changed

Lines changed: 174 additions & 29 deletions

File tree

‎src/a2a/client/client_factory.py‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -77,23 +77,35 @@ class ClientFactory:
7777
7878
The client can be used consistently regardless of the transport. This
7979
aligns the client configuration with the server's capabilities.
80+
81+
Each created client gets its own `httpx.AsyncClient` and closes it on
82+
`close()`, unless `ClientConfig.httpx_client` is set.
8083
"""
8184

8285
def __init__(
8386
self,
8487
config: ClientConfig | None = None,
8588
):
8689
config = config or ClientConfig()
87-
httpx_client = config.httpx_client or httpx.AsyncClient()
88-
httpx_client.headers.setdefault(
89-
VERSION_HEADER, PROTOCOL_VERSION_CURRENT
90-
)
90+
if config.httpx_client:
91+
config.httpx_client.headers.setdefault(
92+
VERSION_HEADER, PROTOCOL_VERSION_CURRENT
93+
)
9194

9295
self._config = config
93-
self._httpx_client = httpx_client
9496
self._registry: dict[str, TransportProducer] = {}
9597
self._register_defaults(config.supported_protocol_bindings)
9698

99+
def _resolve_http_client(self) -> tuple[httpx.AsyncClient, bool]:
100+
"""Returns an HTTP client and whether it is shared across clients."""
101+
if self._config.httpx_client:
102+
return self._config.httpx_client, True
103+
httpx_client = httpx.AsyncClient()
104+
httpx_client.headers.setdefault(
105+
VERSION_HEADER, PROTOCOL_VERSION_CURRENT
106+
)
107+
return httpx_client, False
108+
97109
def _register_defaults(self, supported: list[str]) -> None:
98110
# Empty support list implies JSON-RPC only.
99111

@@ -115,21 +127,25 @@ def jsonrpc_transport_producer(
115127
else PROTOCOL_VERSION_CURRENT
116128
)
117129

130+
httpx_client, is_shared_httpx = self._resolve_http_client()
131+
118132
if is_legacy_version(version):
119133
from a2a.compat.v0_3.jsonrpc_transport import ( # noqa: PLC0415
120134
CompatJsonRpcTransport,
121135
)
122136

123137
return CompatJsonRpcTransport(
124-
self._httpx_client,
138+
httpx_client,
125139
card,
126140
url,
141+
is_shared_httpx=is_shared_httpx,
127142
)
128143

129144
return JsonRpcTransport(
130-
self._httpx_client,
145+
httpx_client,
131146
card,
132147
url,
148+
is_shared_httpx=is_shared_httpx,
133149
)
134150

135151
self.register(
@@ -154,21 +170,25 @@ def rest_transport_producer(
154170
else PROTOCOL_VERSION_CURRENT
155171
)
156172

173+
httpx_client, is_shared_httpx = self._resolve_http_client()
174+
157175
if is_legacy_version(version):
158176
from a2a.compat.v0_3.rest_transport import ( # noqa: PLC0415
159177
CompatRestTransport,
160178
)
161179

162180
return CompatRestTransport(
163-
self._httpx_client,
181+
httpx_client,
164182
card,
165183
url,
184+
is_shared_httpx=is_shared_httpx,
166185
)
167186

168187
return RestTransport(
169-
self._httpx_client,
188+
httpx_client,
170189
card,
171190
url,
191+
is_shared_httpx=is_shared_httpx,
172192
)
173193

174194
self.register(
@@ -273,8 +293,9 @@ async def create_from_url(
273293
) -> Client:
274294
"""Create a `Client` by resolving an `AgentCard` from a URL.
275295
276-
Resolves the agent card from the given URL using the factory's
277-
configured httpx client, then creates a client via `create`.
296+
Resolves the agent card from the given URL, then creates a client
297+
via `create`. The card is fetched with `ClientConfig.httpx_client`
298+
when one is set, otherwise with a temporary client.
278299
279300
If the agent card is already available, use `create` directly
280301
instead.
@@ -295,12 +316,17 @@ async def create_from_url(
295316
Returns:
296317
A `Client` object.
297318
"""
298-
resolver = A2ACardResolver(self._httpx_client, url)
299-
card = await resolver.get_agent_card(
300-
relative_card_path=relative_card_path,
301-
http_kwargs=resolver_http_kwargs,
302-
signature_verifier=signature_verifier,
303-
)
319+
httpx_client, is_shared_httpx = self._resolve_http_client()
320+
try:
321+
resolver = A2ACardResolver(httpx_client, url)
322+
card = await resolver.get_agent_card(
323+
relative_card_path=relative_card_path,
324+
http_kwargs=resolver_http_kwargs,
325+
signature_verifier=signature_verifier,
326+
)
327+
finally:
328+
if not is_shared_httpx:
329+
await httpx_client.aclose()
304330
return self.create(card, interceptors)
305331

306332
def register(self, label: str, generator: TransportProducer) -> None:

‎src/a2a/client/transports/http_helpers.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ async def send_http_request(
5757
| None = None,
5858
) -> dict[str, Any]:
5959
"""Sends an HTTP request and parses the JSON response, handling common exceptions."""
60+
if httpx_client.is_closed:
61+
raise A2AClientError('HTTP client is closed')
6062
with handle_http_exceptions(status_error_handler):
6163
response = await httpx_client.send(request)
6264
response.raise_for_status()
@@ -125,6 +127,8 @@ async def send_http_stream_request(
125127
Should raise an appropriate domain-specific exception.
126128
**kwargs: Additional keyword arguments forwarded to ``aconnect_sse``.
127129
"""
130+
if httpx_client.is_closed:
131+
raise A2AClientError('HTTP client is closed')
128132
with handle_http_exceptions(status_error_handler):
129133
async with _SSEEventSource(
130134
httpx_client, method, url, **kwargs

‎src/a2a/client/transports/jsonrpc.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,13 @@ def __init__(
5656
httpx_client: httpx.AsyncClient,
5757
agent_card: AgentCard,
5858
url: str,
59+
is_shared_httpx: bool = False,
5960
):
6061
"""Initializes the JsonRpcTransport."""
6162
self.url = url
6263
self.httpx_client = httpx_client
6364
self.agent_card = agent_card
65+
self.is_shared_httpx = is_shared_httpx
6466

6567
async def send_message(
6668
self,
@@ -312,8 +314,19 @@ async def get_extended_agent_card(
312314
return response
313315

314316
async def close(self) -> None:
315-
"""Closes the httpx client."""
316-
await self.httpx_client.aclose()
317+
"""Closes the httpx client unless it is shared."""
318+
if self.is_shared_httpx:
319+
logger.debug(
320+
'Cannot close a shared httpx client; only the provider '
321+
'that supplied it via ClientConfig.httpx_client can close it.'
322+
)
323+
return
324+
if self.httpx_client.is_closed:
325+
raise A2AClientError('HTTP client is already closed')
326+
try:
327+
await self.httpx_client.aclose()
328+
except Exception as e:
329+
raise A2AClientError(f'Failed to close HTTP client: {e}') from e
317330

318331
def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception:
319332
"""Creates the appropriate A2AError from a JSON-RPC error dictionary."""

‎src/a2a/client/transports/rest.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,13 @@ def __init__(
9797
httpx_client: httpx.AsyncClient,
9898
agent_card: AgentCard,
9999
url: str,
100+
is_shared_httpx: bool = False,
100101
):
101102
"""Initializes the RestTransport."""
102103
self.url = url.removesuffix('/')
103104
self.httpx_client = httpx_client
104105
self.agent_card = agent_card
106+
self.is_shared_httpx = is_shared_httpx
105107

106108
async def send_message(
107109
self,
@@ -330,8 +332,19 @@ async def get_extended_agent_card(
330332
return ParseDict(response_data, AgentCard())
331333

332334
async def close(self) -> None:
333-
"""Closes the httpx client."""
334-
await self.httpx_client.aclose()
335+
"""Closes the httpx client unless it is shared."""
336+
if self.is_shared_httpx:
337+
logger.debug(
338+
'Cannot close a shared httpx client; only the provider '
339+
'that supplied it via ClientConfig.httpx_client can close it.'
340+
)
341+
return
342+
if self.httpx_client.is_closed:
343+
raise A2AClientError('HTTP client is already closed')
344+
try:
345+
await self.httpx_client.aclose()
346+
except Exception as e:
347+
raise A2AClientError(f'Failed to close HTTP client: {e}') from e
335348

336349
def _get_path(self, base_path: str, tenant: str) -> str:
337350
"""Returns the full path, prepending the tenant if provided."""

‎src/a2a/compat/v0_3/jsonrpc_transport.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,14 @@ def __init__(
5959
httpx_client: httpx.AsyncClient,
6060
agent_card: AgentCard | None,
6161
url: str,
62+
*,
63+
is_shared_httpx: bool = False,
6264
):
6365
"""Initializes the CompatJsonRpcTransport."""
6466
self.url = url
6567
self.httpx_client = httpx_client
6668
self.agent_card = agent_card
69+
self.is_shared_httpx = is_shared_httpx
6770

6871
async def send_message(
6972
self,
@@ -395,8 +398,19 @@ async def get_extended_agent_card(
395398
return card
396399

397400
async def close(self) -> None:
398-
"""Closes the httpx client."""
399-
await self.httpx_client.aclose()
401+
"""Closes the httpx client unless it is shared."""
402+
if self.is_shared_httpx:
403+
logger.debug(
404+
'Cannot close a shared httpx client; only the provider '
405+
'that supplied it via ClientConfig.httpx_client can close it.'
406+
)
407+
return
408+
if self.httpx_client.is_closed:
409+
raise A2AClientError('HTTP client is already closed')
410+
try:
411+
await self.httpx_client.aclose()
412+
except Exception as e:
413+
raise A2AClientError(f'Failed to close HTTP client: {e}') from e
400414

401415
def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception:
402416
"""Raises a specific error based on jsonrpc error code."""

‎src/a2a/compat/v0_3/rest_transport.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,14 @@ def __init__(
6666
agent_card: AgentCard | None,
6767
url: str,
6868
subscribe_method_override: str | None = None,
69+
*,
70+
is_shared_httpx: bool = False,
6971
):
7072
"""Initializes the CompatRestTransport."""
7173
self.url = url.removesuffix('/')
7274
self.httpx_client = httpx_client
7375
self.agent_card = agent_card
76+
self.is_shared_httpx = is_shared_httpx
7477
self._subscribe_method_override = subscribe_method_override
7578
self._subscribe_auto_method_override = subscribe_method_override is None
7679

@@ -338,8 +341,19 @@ async def get_extended_agent_card(
338341
return card
339342

340343
async def close(self) -> None:
341-
"""Closes the httpx client."""
342-
await self.httpx_client.aclose()
344+
"""Closes the httpx client unless it is shared."""
345+
if self.is_shared_httpx:
346+
logger.debug(
347+
'Cannot close a shared httpx client; only the provider '
348+
'that supplied it via ClientConfig.httpx_client can close it.'
349+
)
350+
return
351+
if self.httpx_client.is_closed:
352+
raise A2AClientError('HTTP client is already closed')
353+
try:
354+
await self.httpx_client.aclose()
355+
except Exception as e:
356+
raise A2AClientError(f'Failed to close HTTP client: {e}') from e
343357

344358
def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn:
345359
"""Handles HTTP status errors and raises the appropriate A2AError."""

‎tests/client/test_client_factory.py‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from a2a.client import ClientConfig, ClientFactory, create_client
1111
from a2a.client.client_factory import TransportProducer
12+
from a2a.client.errors import A2AClientError
1213
from a2a.client.transports import (
1314
JsonRpcTransport,
1415
RestTransport,
@@ -19,7 +20,9 @@
1920
AgentCard,
2021
AgentInterface,
2122
)
22-
from a2a.utils.constants import TransportProtocol
23+
from a2a.utils.constants import (
24+
TransportProtocol,
25+
)
2326

2427

2528
@pytest.fixture
@@ -407,3 +410,51 @@ async def test_create_client_with_url_and_config(base_agent_card: AgentCard):
407410
mock_resolver.assert_called_once_with(
408411
mock_httpx_client, 'http://example.com'
409412
)
413+
414+
415+
@pytest.mark.asyncio
416+
async def test_client_factory_creates_a_client_per_created_client(
417+
base_agent_card: AgentCard,
418+
):
419+
"""Verify each created client gets its own httpx client by default."""
420+
factory = ClientFactory()
421+
422+
client_a = factory.create(base_agent_card)
423+
client_b = factory.create(base_agent_card)
424+
425+
assert (
426+
client_a._transport.httpx_client # type: ignore[attr-defined]
427+
is not client_b._transport.httpx_client # type: ignore[attr-defined]
428+
)
429+
430+
431+
@pytest.mark.asyncio
432+
async def test_client_close_does_not_close_shared_httpx_client(
433+
base_agent_card: AgentCard,
434+
):
435+
"""Verify closing a client does not close a shared httpx_client from config."""
436+
shared_httpx_client = httpx.AsyncClient()
437+
try:
438+
factory = ClientFactory(ClientConfig(httpx_client=shared_httpx_client))
439+
client = factory.create(base_agent_card)
440+
441+
await client.close()
442+
443+
assert not shared_httpx_client.is_closed
444+
finally:
445+
await shared_httpx_client.aclose()
446+
447+
448+
@pytest.mark.asyncio
449+
async def test_client_second_close_raises_a2a_client_error(
450+
base_agent_card: AgentCard,
451+
):
452+
"""Verify closing an already closed client raises A2AClientError."""
453+
factory = ClientFactory()
454+
client = factory.create(base_agent_card)
455+
456+
await client.close()
457+
assert client._transport.httpx_client.is_closed # type: ignore[attr-defined]
458+
459+
with pytest.raises(A2AClientError, match='HTTP client is already closed'):
460+
await client.close()

‎tests/client/transports/test_jsonrpc_client.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ async def async_iterable_from_list(
4646
def mock_httpx_client():
4747
"""Creates a mock httpx.AsyncClient."""
4848
client = AsyncMock(spec=httpx.AsyncClient)
49+
client.is_closed = False
4950
client.headers = httpx.Headers()
5051
client.timeout = httpx.Timeout(30.0)
5152
return client

‎tests/client/transports/test_rest_client.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@
3333

3434
@pytest.fixture
3535
def mock_httpx_client() -> AsyncMock:
36-
return AsyncMock(spec=httpx.AsyncClient)
36+
client = AsyncMock(spec=httpx.AsyncClient)
37+
client.is_closed = False
38+
return client
3739

3840

3941
@pytest.fixture

‎tests/compat/v0_3/test_jsonrpc_transport.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@
3131

3232
@pytest.fixture
3333
def mock_httpx_client():
34-
return AsyncMock(spec=httpx.AsyncClient)
34+
client = AsyncMock(spec=httpx.AsyncClient)
35+
client.is_closed = False
36+
return client
3537

3638

3739
@pytest.fixture

0 commit comments

Comments
 (0)