diff --git a/sdk/python/src/agent_mesh/httpx_transport.py b/sdk/python/src/agent_mesh/httpx_transport.py index 286adf8ae..5401e3a19 100644 --- a/sdk/python/src/agent_mesh/httpx_transport.py +++ b/sdk/python/src/agent_mesh/httpx_transport.py @@ -28,9 +28,11 @@ from __future__ import annotations +import math from typing import TYPE_CHECKING, AsyncIterator import httpx +import trio from .libp2p_http import MESH_PATH_PREFIX, StreamedResponse, open_http_request @@ -56,11 +58,23 @@ def split_mesh_url(url: httpx.URL) -> tuple[str, str, str]: class _BodyStream(httpx.AsyncByteStream): - def __init__(self, response: StreamedResponse) -> None: + def __init__(self, response: StreamedResponse, request: httpx.Request) -> None: self._response = response + self._request = request + timeout_options = request.extensions.get("timeout") + timeout = timeout_options.get("read") if isinstance(timeout_options, dict) else None + self._read_timeout = math.inf if timeout is None else timeout async def __aiter__(self) -> AsyncIterator[bytes]: - async for chunk in self._response.iter_body(): + body = self._response.iter_body() + while True: + try: + with trio.fail_after(self._read_timeout): + chunk = await anext(body) + except StopAsyncIteration: + return + except trio.TooSlowError as err: + raise httpx.ReadTimeout("timed out reading the mesh response body", request=self._request) from err yield chunk async def aclose(self) -> None: @@ -92,7 +106,7 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: body=body, timeout=self._timeout, ) - return httpx.Response(response.status, headers=list(response.headers.items()), stream=_BodyStream(response), request=request) + return httpx.Response(response.status, headers=response.raw_headers, stream=_BodyStream(response, request), request=request) __all__ = ("MESH_PATH_PREFIX", "MeshTransport", "split_mesh_url") diff --git a/sdk/python/src/agent_mesh/libp2p_http.py b/sdk/python/src/agent_mesh/libp2p_http.py index 68a483b3b..c21507dc1 100644 --- a/sdk/python/src/agent_mesh/libp2p_http.py +++ b/sdk/python/src/agent_mesh/libp2p_http.py @@ -435,12 +435,16 @@ class StreamedResponse: headers are in; `iter_body` yields the body as the peer sends it, which is what an SSE stream (A2A `message/stream`) needs. Close it when done.""" - def __init__(self, stream: INetStream, conn: h11.Connection, status: int, headers: dict[str, str], peer_id: ID) -> None: + def __init__( + self, stream: INetStream, conn: h11.Connection, status: int, headers: dict[str, str], peer_id: ID, + *, raw_headers: tuple[tuple[bytes, bytes], ...] | None = None, + ) -> None: self._stream = stream self._conn = conn self._peer_id = peer_id self.status = status self.headers = headers + self.raw_headers = raw_headers if raw_headers is not None else _encode_headers(headers) async def iter_body(self) -> AsyncIterator[bytes]: while True: @@ -469,6 +473,7 @@ class _BufferedResponse(StreamedResponse): def __init__(self, status: int, headers: dict[str, str], body: bytes) -> None: self.status = status self.headers = headers + self.raw_headers = _encode_headers(headers) self._payload = body async def iter_body(self) -> AsyncIterator[bytes]: @@ -478,6 +483,10 @@ async def aclose(self) -> None: return None +def _encode_headers(headers: Mapping[str, str]) -> tuple[tuple[bytes, bytes], ...]: + return tuple((name.encode("latin-1"), value.encode("latin-1")) for name, value in headers.items()) + + async def open_http_request( host: IHost, peer_id: ID, @@ -565,12 +574,16 @@ async def _open_http_request( continue if isinstance(event, h11.Response): resp_headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in event.headers} - return StreamedResponse(stream, conn, event.status_code, resp_headers, peer_id) + return StreamedResponse(stream, conn, event.status_code, resp_headers, peer_id, raw_headers=tuple(event.headers)) if isinstance(event, h11.InformationalResponse): continue raise ConnectionError(f"peer {peer_id} closed the stream before answering") except BaseException: - await stream.close() + with trio.move_on_after(1, shield=True): + try: + await stream.close() + except Exception: + logger.debug("failed to close HTTP stream to %s", peer_id, exc_info=True) raise diff --git a/sdk/python/tests/test_http_stream_cancel.py b/sdk/python/tests/test_http_stream_cancel.py new file mode 100644 index 000000000..21e67a39f --- /dev/null +++ b/sdk/python/tests/test_http_stream_cancel.py @@ -0,0 +1,53 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +import trio + +from agent_mesh import libp2p_http + + +@pytest.mark.parametrize("cancel", [False, True]) +def test_http_request_closes_stream_on_failure(monkeypatch, cancel): + closed = [] + + class Stream: + async def write(self, data): + await trio.lowlevel.checkpoint() + raise OSError("write failed") + + async def close(self): + await trio.lowlevel.checkpoint() + closed.append(True) + + async def open_stream(*args): + return Stream() + + monkeypatch.setattr(libp2p_http, "open_stream", open_stream) + + async def request(): + await libp2p_http.open_http_request(None, "peer", b"fixture", "GET", "/a2a/example/message") + + async def run(): + if cancel: + with trio.CancelScope() as scope: + scope.cancel() + await request() + assert scope.cancelled_caught + else: + with pytest.raises(OSError, match="write failed"): + await request() + assert closed == [True] + + trio.run(run) diff --git a/sdk/python/tests/test_httpx_read_timeout.py b/sdk/python/tests/test_httpx_read_timeout.py new file mode 100644 index 000000000..626c67b13 --- /dev/null +++ b/sdk/python/tests/test_httpx_read_timeout.py @@ -0,0 +1,62 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from types import SimpleNamespace + +import httpx +import pytest +import trio +from trio.testing import MockClock + +from agent_mesh import httpx_transport +from agent_mesh.httpx_transport import MeshTransport + + +def test_mesh_transport_applies_httpx_read_timeout_to_body(monkeypatch): + closed = [] + + class Response: + status = 200 + headers = {} + raw_headers = () + + async def iter_body(self): + yield b"first" + await trio.sleep(2) + yield b"second" + + async def aclose(self): + closed.append(True) + + async def open_request(*args, **kwargs): + return Response() + + async def egress_peer(peer, service): + return peer + + monkeypatch.setattr(httpx_transport, "open_http_request", open_request) + session = SimpleNamespace(host=None, biscuit=b"fixture", _egress_peer=egress_peer) + + async def run(): + path = "http://mesh/mesh/peer/a2a/example" + async with httpx.AsyncClient(transport=MeshTransport(session)) as client: + assert (await client.get(path, timeout=None)).content == b"firstsecond" + request = httpx.Request("GET", path, extensions={"timeout": None}) + assert (await client.send(request)).content == b"firstsecond" + with pytest.raises(httpx.ReadTimeout) as caught: + await client.get(path, timeout=httpx.Timeout(10, read=1)) + assert str(caught.value.request.url) == path + assert closed == [True, True, True] + + trio.run(run, clock=MockClock(autojump_threshold=0)) diff --git a/sdk/python/tests/test_httpx_response_headers.py b/sdk/python/tests/test_httpx_response_headers.py new file mode 100644 index 000000000..4a1d0d1fd --- /dev/null +++ b/sdk/python/tests/test_httpx_response_headers.py @@ -0,0 +1,55 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from types import SimpleNamespace + +import httpx +import trio + +from agent_mesh import libp2p_http +from agent_mesh.httpx_transport import MeshTransport + + +def test_mesh_transport_keeps_multiple_set_cookie_fields(monkeypatch): + class Stream: + async def write(self, data): + pass + + async def read(self, size): + return ( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n" + b"Set-Cookie: one=1\r\nSet-Cookie: two=2\r\n\r\nok" + ) + + async def close(self): + pass + + async def open_stream(*args): + return Stream() + + async def egress_peer(peer, service): + return peer + + monkeypatch.setattr(libp2p_http, "open_stream", open_stream) + session = SimpleNamespace(host=None, biscuit=b"fixture", _egress_peer=egress_peer) + + async def run(): + async with httpx.AsyncClient(transport=MeshTransport(session)) as client: + response = await client.get("http://mesh/mesh/peer/a2a/example/message") + assert response.text == "ok" + assert response.headers.get_list("set-cookie") == ["one=1", "two=2"] + assert client.cookies.get("one") == "1" + assert client.cookies.get("two") == "2" + + trio.run(run)