Files
hermes-agent/gateway/platforms/_http_client_limits.py
ahisblessed bf6dbcfca7 fix(gateway): honor HERMES_GATEWAY_HTTPX_MAX_KEEPALIVE=0 as "keepalive off"
_positive_env() rejected every non-positive value, so the documented
override HERMES_GATEWAY_HTTPX_MAX_KEEPALIVE=0 was silently discarded and
platform_httpx_limits() kept the default of 10 idle connections — there
was no way to disable keepalive when debugging connection reuse.

httpx accepts max_keepalive_connections=0 (keep no idle connections), so
the max-keepalive knob now parses non-negative values (a new
_non_negative_env) and only negatives fall back to the default. The
keepalive_expiry knob keeps its strictly-positive contract, since a zero
expiry would expire every idle connection immediately.

Fixes #126052
2026-11-10 13:28:59 -08:00

49 lines
1.8 KiB
Python

"""Shared HTTP client factory for long-lived platform adapters.
httpx's default ``keepalive_expiry`` (5s) lets peer-initiated FIN sit in
``CLOSE_WAIT`` behind transparent proxies (macOS + Cloudflare Warp); across 7
adapters plus LLM/MCP clients that walks into the default 256 fd limit.
``platform_httpx_limits()`` returns tighter ``httpx.Limits``: 10 keepalive
connections (platform APIs rarely parallelise beyond this), 2.0s expiry.
Override via ``HERMES_GATEWAY_HTTPX_KEEPALIVE_EXPIRY`` / ``HERMES_GATEWAY_HTTPX_MAX_KEEPALIVE``;
``HERMES_GATEWAY_HTTPX_MAX_KEEPALIVE=0`` disables keepalive (httpx keeps no idle connections).
"""
from __future__ import annotations
import os
try:
import httpx
except ImportError: # pragma: no cover — optional dep
httpx = None # type: ignore[assignment]
_DEFAULT_KEEPALIVE_EXPIRY_S = 2.0
_DEFAULT_MAX_KEEPALIVE = 10
def _positive_env(name: str, default, cast, *, allow_zero: bool = False):
"""``cast(env)`` when set, parseable and > 0 (>= 0 with *allow_zero*); else *default*."""
raw = os.environ.get(name, "").strip()
if not raw:
return default
try:
val = cast(raw)
except (TypeError, ValueError):
return default
return val if val > 0 or (allow_zero and val == 0) else default
def platform_httpx_limits() -> httpx.Limits | None:
"""``httpx.Limits`` tuned for persistent platform-adapter clients; ``None`` without httpx."""
if httpx is None:
return None
# max_connections stays at the httpx default (100) — plenty of headroom.
return httpx.Limits(
max_keepalive_connections=_positive_env(
"HERMES_GATEWAY_HTTPX_MAX_KEEPALIVE", _DEFAULT_MAX_KEEPALIVE, int, allow_zero=True),
keepalive_expiry=_positive_env(
"HERMES_GATEWAY_HTTPX_KEEPALIVE_EXPIRY", _DEFAULT_KEEPALIVE_EXPIRY_S, float),
)