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
20 changes: 17 additions & 3 deletions sdk/python/src/agent_mesh/httpx_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Comment on lines +61 to 78

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.

medium

There are two opportunities for improvement here:

  1. Defensive Programming / Robustness: If request.extensions.get("timeout") is explicitly set to None (rather than being absent), calling .get("read") on it will raise an AttributeError. We should safely check if the timeout extension is a dictionary before calling .get() on it.
  2. Performance / Efficiency: Wrapping every single chunk read in a trio.fail_after context manager when there is no timeout (i.e., self._read_timeout is math.inf) adds unnecessary overhead. We can bypass trio.fail_after entirely when the timeout is infinite.
    def __init__(self, response: StreamedResponse, request: httpx.Request) -> None:
        self._response = response
        self._request = request
        timeout_ext = request.extensions.get("timeout")
        timeout = timeout_ext.get("read") if isinstance(timeout_ext, dict) else None
        self._read_timeout = math.inf if timeout is None else timeout

    async def __aiter__(self) -> AsyncIterator[bytes]:
        body = self._response.iter_body()
        while True:
            try:
                if self._read_timeout == math.inf:
                    chunk = await anext(body)
                else:
                    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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The first point is already in the PR: 211253d (pushed a minute after this review) reads the read value only when the timeout extension is a dict, and test_httpx_read_timeout.py covers an explicitly unset extension.

I'd rather not take the second. trio.fail_after(math.inf) opens a cancel scope with an infinite deadline; trio does not put an infinite deadline in its deadline queue, so entering it costs a few attribute writes, which is nothing next to awaiting a chunk from a libp2p stream. A separate branch for the infinite case would give the loop two read paths to keep in step, for no measurable gain.


async def aclose(self) -> None:
Expand Down Expand Up @@ -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")
19 changes: 16 additions & 3 deletions sdk/python/src/agent_mesh/libp2p_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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]:
Expand All @@ -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,
Expand Down Expand Up @@ -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


Expand Down
53 changes: 53 additions & 0 deletions sdk/python/tests/test_http_stream_cancel.py
Original file line number Diff line number Diff line change
@@ -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)
62 changes: 62 additions & 0 deletions sdk/python/tests/test_httpx_read_timeout.py
Original file line number Diff line number Diff line change
@@ -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))
55 changes: 55 additions & 0 deletions sdk/python/tests/test_httpx_response_headers.py
Original file line number Diff line number Diff line change
@@ -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)
Loading