Skip to content

Agent Mesh

sdk/python: a stream reset mid-response is an error, a close is the end

Antonio Ojeaa69280abc5cb
diff --git a/sdk/python/src/agent_mesh/libp2p_http.py b/sdk/python/src/agent_mesh/libp2p_http.py
index 58d31512..f773bb92 100644
--- a/sdk/python/src/agent_mesh/libp2p_http.py
+++ b/sdk/python/src/agent_mesh/libp2p_http.py
@@ -30,6 +30,7 @@ import httpx
import trio
from libp2p.abc import IHost, INetStream
from libp2p.custom_types import TProtocol
+from libp2p.network.stream.exceptions import StreamEOF
from libp2p.peer.id import ID
from .auth import AUTH_HANDSHAKE_TIMEOUT
@@ -267,6 +268,19 @@ async def _handle_ingress(
return upstream.status_code, out_headers, upstream.content
+async def _read_or_eof(stream: INetStream, peer_id: ID) -> bytes:
+ """One read for the HTTP parser. The peer closing its side is the end of
+ input, which is how a body without a length (server-sent events) ends. A
+ reset or any other failure is not: without a length only the stream can
+ tell a body that ended from one that was cut."""
+ try:
+ return await stream.read(_READ_CHUNK)
+ except StreamEOF:
+ return b""
+ except Exception as err:
+ raise ConnectionError(f"peer {peer_id} broke the stream mid-response: {err}") from err
+
+
def mesh_http_target(target_service: str, path: str = "") -> str:
"""The request target for a service on a peer: /<type>/<name>/<path>."""
scheme, sep, name = target_service.partition("://")
@@ -293,11 +307,7 @@ class StreamedResponse:
while True:
event = self._conn.next_event()
if event is h11.NEED_DATA:
- try:
- chunk = await self._stream.read(_READ_CHUNK)
- except Exception: # noqa: BLE001 - EOF ends the response
- chunk = b""
- self._conn.receive_data(chunk)
+ self._conn.receive_data(await _read_or_eof(self._stream, self._peer_id))
continue
if isinstance(event, h11.Data):
yield bytes(event.data)
@@ -350,11 +360,7 @@ async def open_http_request(
while True:
event = conn.next_event()
if event is h11.NEED_DATA:
- try:
- chunk = await stream.read(_READ_CHUNK)
- except Exception: # noqa: BLE001 - EOF ends the response
- chunk = b""
- conn.receive_data(chunk)
+ conn.receive_data(await _read_or_eof(stream, peer_id))
continue
if isinstance(event, h11.Response):
resp_headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in event.headers}
diff --git a/sdk/python/tests/test_libp2p_http.py b/sdk/python/tests/test_libp2p_http.py
index 36d7e9c5..e0274334 100644
--- a/sdk/python/tests/test_libp2p_http.py
+++ b/sdk/python/tests/test_libp2p_http.py
@@ -253,3 +253,63 @@ def test_mesh_urls_name_a_peer_and_a_service():
assert mesh_http_target("a2a://agent", "card") == "/a2a/agent/card"
with pytest.raises(ValueError):
mesh_http_target("ftp://agent", "/")
+
+
+def test_a_reset_mid_body_is_an_error_and_a_close_is_the_end():
+ """A body that arrives without a length (server-sent events) ends when
+ the peer closes its side. The same body cut by a reset must not pass for
+ one that ended: without a length there is nothing in HTTP to tell them
+ apart, only the stream knows."""
+
+ async def truncating(stream) -> None:
+ # Same framing as `closing`, reset instead of closed.
+ await stream.write(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\ndata: 1\n\n")
+ await stream.reset()
+
+ async def closing(stream) -> None:
+ # No length and no chunking: the close is the end of the body.
+ await stream.write(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\ndata: 1\n\ndata: 2\n\n")
+ await stream.close()
+
+ async def main():
+ async with trio.open_nursery() as nursery:
+ server = libp2p_host(Identity.generate())
+ handlers = {"/a2a/cut": truncating, "/a2a/end": closing}
+
+ async def route(stream) -> None:
+ request = b""
+ while b"\r\n\r\n" not in request:
+ request += await stream.read(1024)
+ path = request.split(b" ", 2)[1].decode()
+ await handlers[path](stream)
+
+ server.set_stream_handler(HTTP_PROTOCOL, route)
+ started = trio.Event()
+ addr_box = []
+
+ async def run():
+ async with server.run(listen_addrs=[multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")]):
+ addr_box.append(multiaddr.Multiaddr(f"{server.get_addrs()[0]}"))
+ started.set()
+ await trio.sleep_forever()
+
+ nursery.start_soon(run)
+ await started.wait()
+ caller = libp2p_host(Identity.generate())
+ async with caller.run(listen_addrs=[]):
+ await caller.connect(info_from_p2p_addr(addr_box[0]))
+ pid = server.get_id()
+ with trio.fail_after(10):
+ ended = await open_http_request(caller, pid, b"x", "GET", "/a2a/end")
+ assert ended.status == 200
+ assert (await ended.read()).decode().count("data:") == 2
+ await ended.aclose()
+
+ cut = await open_http_request(caller, pid, b"x", "GET", "/a2a/cut")
+ assert cut.status == 200
+ with pytest.raises(ConnectionError, match="mid-response"):
+ await cut.read()
+ await cut.aclose()
+ nursery.cancel_scope.cancel()
+
+ trio.run(main)