diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 60ebbd600..85807ec58 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -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 each `data/add`, `data/get`, and `data/reset` connection, a +proxy's included, so it 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 diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 2fa18a8d8..077a86798 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -5,6 +5,7 @@ import contextlib import logging +import socket from collections.abc import Iterator from contextvars import ContextVar from dataclasses import dataclass, field @@ -106,7 +107,8 @@ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: b 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: - response = await client.post(url, json=request, timeout=timeout, headers=request_headers(url, headers)) + response = await client.post(url, json=request, timeout=timeout, headers=request_headers(url, headers), + extensions={"trace": _keepalive}) response.raise_for_status() body = response.json() if "error" in body: @@ -386,3 +388,24 @@ async def invoke_extension(base_url: str, card: dict, uri: str, params: dict | N if response.status_code >= 400: raise ExtensionCallError(response) return response.json() + + +_KEEPALIVE_IDLE_SECONDS = 30 +_KEEPALIVE_PROBE_INTERVAL_SECONDS = 10 +_KEEPALIVE_PROBE_COUNT = 3 + + +async def _keepalive(event: str, info: dict) -> None: + """Best-effort TCP keepalive on each connection the RPC opens, a proxy's included, so a reply the env takes + minutes to send isn't lost to an idle drop. A setting the socket refuses is skipped.""" + if event != "connection.connect_tcp.complete" or (sock := info["return_value"].get_extra_info("socket")) is None: + return + idle = getattr(socket, "TCP_KEEPIDLE", getattr(socket, "TCP_KEEPALIVE", None)) + tuning = ((idle, _KEEPALIVE_IDLE_SECONDS), + (getattr(socket, "TCP_KEEPINTVL", None), _KEEPALIVE_PROBE_INTERVAL_SECONDS), + (getattr(socket, "TCP_KEEPCNT", None), _KEEPALIVE_PROBE_COUNT)) + options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] + options += [(socket.IPPROTO_TCP, option, value) for option, value in tuning if option is not None] + for level, option, value in options: + with contextlib.suppress(OSError): + sock.setsockopt(level, option, value) diff --git a/packages/agentenv-protocol/tests/test_rpc_keepalive.py b/packages/agentenv-protocol/tests/test_rpc_keepalive.py new file mode 100644 index 000000000..f15ec445a --- /dev/null +++ b/packages/agentenv-protocol/tests/test_rpc_keepalive.py @@ -0,0 +1,81 @@ +"""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 + target = ("proxy.test", 8080) if via_proxy else ("worker.env.test", 443 if scheme == "https" else 80) + assert (host, port) == target + 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 [])