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
5 changes: 5 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,11 @@ name)` raises `AmbiguousChildError` for a shared name, and `client.find_child` r
`client.serves(card, method)` says whether a card serves a data-plane method by its declared
`operations`, None for a card that declares none.

The client enables TCP keepalive on direct `data/add`, `data/get`, and `data/reset` connections so
they can stay open while the environment prepares a reply. Where supported, probes start after
30 seconds of inactivity. Each socket uses the keepalive settings its kernel accepts. These calls use
HTTPX's usual proxy and TLS settings.

Extensions are invoked from what the card advertises. `client.find_extension_method(card, uri,
method)` returns one advertised method, whose `endpoint` is the method's own or else the
extension's, and `client.invoke_extension(base_url, card, uri, params, method=...)` calls it with
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""HTTP client for data-plane RPCs that may wait a long time for response headers."""

import socket
from contextlib import suppress

import httpx
from httpx._utils import get_environment_proxies


class _DirectTransport(httpx.AsyncHTTPTransport):
_KEEPALIVE_IDLE_SECONDS = 30
_KEEPALIVE_PROBE_INTERVAL_SECONDS = 10
_KEEPALIVE_PROBE_COUNT = 3

def _enable_keepalive(self, sock: socket.socket) -> None:
options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
idle = getattr(socket, "TCP_KEEPIDLE", getattr(socket, "TCP_KEEPALIVE", None))
if idle is not None:
options.append((socket.IPPROTO_TCP, idle, self._KEEPALIVE_IDLE_SECONDS))
for name, value in (
("TCP_KEEPINTVL", self._KEEPALIVE_PROBE_INTERVAL_SECONDS),
("TCP_KEEPCNT", self._KEEPALIVE_PROBE_COUNT),
):
option = getattr(socket, name, None)
if option is not None:
options.append((socket.IPPROTO_TCP, option, value))
for level, option, value in options:
with suppress(OSError):
sock.setsockopt(level, option, value)

async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
extensions = request.extensions
previous = extensions.get("trace")

async def trace(event, info):
if event == "connection.connect_tcp.complete":
sock = info["return_value"].get_extra_info("socket")
if sock is not None:
self._enable_keepalive(sock)
if previous is not None:
await previous(event, info)

# Scope tuning to the direct hop. HTTPX can reuse the original request's extensions on a redirect.
request.extensions = {**extensions, "trace": trace}
try:
return await super().handle_async_request(request)
finally:
request.extensions = extensions


def rpc_client(verify: bool) -> httpx.AsyncClient:
# A custom default transport disables HTTPX's environment proxy discovery.
# Its NO_PROXY entries map to None, which selects our direct transport.
mounts = {
pattern: httpx.AsyncHTTPTransport(proxy=proxy, verify=verify) if proxy is not None else None
for pattern, proxy in get_environment_proxies().items()
}
direct = _DirectTransport(verify=verify)
return httpx.AsyncClient(transport=direct, mounts=mounts)
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import httpx

from ._rpc_transport import rpc_client
from .manifest import INTERFACE_MANIFEST_PATH
from .transfers import WriteNamespaceGrant
from .types import CONTROL_TOKEN_HEADER, INTAKE_EXTENSION_URI, MCP_PATH, MCP_TRANSPORT, METHOD_ADD, METHOD_GET, METHOD_RESET, RPC_PATH, WELL_KNOWN_PATH, AddDataResponse, GetDataResponse, Part, ResetDataResponse
Expand Down Expand Up @@ -105,7 +106,7 @@ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: b
headers: dict[str, str] | None) -> dict:
request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
url = f"{base_url.rstrip('/')}{RPC_PATH}"
async with httpx.AsyncClient(verify=verify) as client:
async with rpc_client(verify) as client:
response = await client.post(url, json=request, timeout=timeout, headers=request_headers(url, headers))
response.raise_for_status()
body = response.json()
Expand Down
84 changes: 84 additions & 0 deletions packages/agentenv-protocol/tests/test_rpc_keepalive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Exercise RPC routing through HTTPX down to the TCP and TLS handshakes."""

import errno
import socket
import ssl

import httpcore
import pytest
from httpcore._backends.auto import AutoBackend

from agentenv_protocol import client


@pytest.mark.asyncio
@pytest.mark.parametrize("scheme,proxies,via_proxy,refuse_interval", [
("http", {}, False, False),
("https", {}, False, False),
("https", {}, False, True),
("http", {"HTTP_PROXY": "http://proxy.test:8080"}, True, False),
("https", {"HTTPS_PROXY": "http://proxy.test:8080"}, True, False),
("http", {"ALL_PROXY": "http://proxy.test:8080"}, True, False),
("https", {"HTTPS_PROXY": "http://proxy.test:8080", "NO_PROXY": ".env.test"}, False, False),
("http", {"ALL_PROXY": "http://proxy.test:8080", "NO_PROXY": "*"}, False, False),
])
@pytest.mark.parametrize("verify", [True, False])
async def test_rpc_socket_options_and_routing(monkeypatch, scheme, proxies, via_proxy, refuse_interval, verify):
for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "REQUEST_METHOD"):
monkeypatch.delenv(name, raising=False)
monkeypatch.delenv(name.lower(), raising=False)
monkeypatch.setenv("NO_PROXY", "unused.test")
for name, value in proxies.items():
monkeypatch.setenv(name, value)

connections = []
handshakes = []
options = []
interval = getattr(socket, "TCP_KEEPINTVL", 12345)
if refuse_interval:
monkeypatch.setattr(socket, "TCP_KEEPINTVL", interval, raising=False)

class Socket:
def setsockopt(self, level, option, value):
options.append((level, option, value))
if refuse_interval and option == interval:
raise OSError(errno.ENOPROTOOPT, "interval unavailable")

raw = Socket()
body = b'{"jsonrpc":"2.0","id":1,"result":{}}'
responses = [b"HTTP/1.1 200 OK\r\nContent-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body]
if via_proxy and scheme == "https":
responses.insert(0, b"HTTP/1.1 200 Connection established\r\n\r\n")

class Stream(httpcore.AsyncMockStream):
def get_extra_info(self, info):
return raw if info == "socket" else super().get_extra_info(info)

async def start_tls(self, ssl_context, server_hostname=None, timeout=None):
handshakes.append((server_hostname, ssl_context.verify_mode))
return self

async def connect_tcp(self, host, port, socket_options, **kwargs):
connections.append((host, port))
for option in socket_options or ():
raw.setsockopt(*option)
return Stream(responses)

monkeypatch.setattr(AutoBackend, "connect_tcp", connect_tcp)
await client.add_data(f"{scheme}://worker.env.test", [], verify=verify)

(host, port), = connections
if via_proxy:
assert (host, port) == ("proxy.test", 8080)
assert options == []
else:
assert (host, port) == ("worker.env.test", 443 if scheme == "https" else 80)
assert (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) in options
idle = getattr(socket, "TCP_KEEPIDLE", getattr(socket, "TCP_KEEPALIVE", None))
if idle is not None:
assert (socket.IPPROTO_TCP, idle, 30) in options
for name, value in (("TCP_KEEPINTVL", 10), ("TCP_KEEPCNT", 3)):
if hasattr(socket, name):
assert (socket.IPPROTO_TCP, getattr(socket, name), value) in options
expected = ssl.CERT_REQUIRED if verify else ssl.CERT_NONE
assert handshakes == ([("worker.env.test", expected)] if scheme == "https" else [])
Loading