JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
gateway分布式场景下提供查询路由的能力
caozhenhua00005972d9de2b72
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.pynew file mode 100644index 0000000000..c81748fe3f--- /dev/null+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py@@ -0,0 +1,216 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Runtime Manager 会话路由客户端:``route`` / ``touch``,不发业务消息。"""++from __future__ import annotations++import logging+from dataclasses import dataclass++import httpx++from jiuwenswarm.common.local_env_config import read_env++logger = logging.getLogger(__name__)++# HLD §3.1:过载可重试;CONFIG_NOT_FOUND 虽是 503 但不可重试。+_RETRYABLE_CODES = frozenset(+ {"SCOPE_QUEUE_FULL", "SCOPE_FULL_TIMEOUT", "NO_POD_AVAILABLE", "TRANSPORT"}+)+_FATAL_CODES = frozenset({"VALIDATION", "CONFIG_NOT_FOUND"})+++@dataclass(frozen=True)+class RouteResult:+ pod_sse_url: str+ pod_id: str+ request_id: str+++class RouteError(Exception):+ def __init__(+ self,+ message: str,+ *,+ code: str,+ retry_after: int | None = None,+ status_code: int | None = None,+ ) -> None:+ super().__init__(message)+ self.code = code+ self.retry_after = retry_after+ self.status_code = status_code+++class RetryableRouteError(RouteError):+ """编排可用同一 ``request_id`` 再调 ``route``。"""+++class FatalRouteError(RouteError):+ """参数错 / 无配置,不要重试。"""+++class RuntimeSessionRouteClient:+ """``POST /api/session/route``、``POST /api/session/touch``。"""++ def __init__(+ self,+ *,+ base_url: str | None = None,+ timeout_seconds: float | None = None,+ http_client: httpx.AsyncClient | None = None,+ ) -> None:+ root = (base_url or read_env("GATEWAY_RUNTIME_MANAGER_URL", "http://127.0.0.1:8091")).strip().rstrip("/")+ if not root:+ root = "http://127.0.0.1:8091"+ self._route_url = f"{root}/api/session/route"+ self._touch_url = f"{root}/api/session/touch"+ if http_client is not None:+ self._http = http_client+ self._owns_http = False+ else:+ timeout = timeout_seconds+ if timeout is None:+ try:+ timeout = float(read_env("GATEWAY_RUNTIME_MANAGER_TIMEOUT", "40"))+ except (TypeError, ValueError):+ timeout = 40.0+ if timeout <= 0:+ timeout = 40.0+ # route 可能排队到 scope_full_timeout(默认 30s),连接超时单独收短+ self._http = httpx.AsyncClient(+ timeout=httpx.Timeout(timeout, connect=min(5.0, timeout)),+ follow_redirects=False,+ trust_env=False,+ )+ self._owns_http = True++ async def aclose(self) -> None:+ if self._owns_http:+ await self._http.aclose()++ async def __aenter__(self) -> "RuntimeSessionRouteClient":+ return self++ async def __aexit__(self, *exc: object) -> None:+ await self.aclose()++ async def route(+ self,+ *,+ session_id: str,+ group_id: str,+ bot_id: str,+ request_id: str,+ user_id: str | None = None,+ ) -> RouteResult:+ session_id = (session_id or "").strip()+ group_id = (group_id or "").strip()+ bot_id = (bot_id or "").strip()+ request_id = (request_id or "").strip()+ user_id = (user_id or "").strip() or None+ if not (session_id and group_id and bot_id and request_id):+ raise FatalRouteError(+ "route requires session_id/group_id/bot_id/request_id",+ code="VALIDATION",+ )++ metadata = {+ "request_id": request_id,+ "session_id": session_id,+ "bot_id": bot_id,+ "extra": {"group_id": group_id},+ }+ if user_id:+ metadata["user_id"] = user_id+ body = await self._post(+ self._route_url,+ {"type": "route", "metadata": metadata, "rawdata": {}},+ )+ rawdata = _rawdata(body)+ pod_sse_url = str(rawdata.get("pod_sse_url") or "").strip()+ pod_id = str(rawdata.get("pod_id") or "").strip()+ if not pod_sse_url or not pod_id:+ raise FatalRouteError(+ "route response missing pod_sse_url/pod_id",+ code="VALIDATION",+ )+ logger.debug(+ "[SessionRoute] routed: session=%s pod=%s url=%s request_id=%s",+ session_id,+ pod_id,+ pod_sse_url,+ request_id,+ )+ return RouteResult(pod_sse_url=pod_sse_url, pod_id=pod_id, request_id=request_id)++ async def touch(self, *, session_id: str, request_id: str) -> bool:+ """保活。返回 False 表示会话已过期,编排应重新 ``route``。"""+ session_id = (session_id or "").strip()+ request_id = (request_id or "").strip()+ if not (session_id and request_id):+ raise FatalRouteError(+ "touch requires session_id/request_id",+ code="VALIDATION",+ )+ body = await self._post(+ self._touch_url,+ {+ "type": "touch",+ "metadata": {"request_id": request_id, "session_id": session_id},+ "rawdata": {},+ },+ )+ rawdata = _rawdata(body)+ touched = bool(rawdata.get("touched"))+ logger.debug("[SessionRoute] touch: session=%s touched=%s", session_id, touched)+ return touched++ async def _post(self, url: str, envelope: dict) -> dict:+ try:+ response = await self._http.post(url, json=envelope)+ except httpx.RequestError as exc:+ logger.warning("[SessionRoute] transport error: url=%s error=%s", url, exc)+ raise RetryableRouteError(f"request failed: {exc}", code="TRANSPORT") from exc+ body = _json_object(response)+ if response.status_code >= 400 or body.get("ok") is False:+ raise _error_from_response(response, body)+ return body+++def _rawdata(body: dict) -> dict:+ raw = body.get("rawdata")+ return raw if isinstance(raw, dict) else body+++def _json_object(response: httpx.Response) -> dict:+ try:+ payload = response.json()+ except ValueError:+ return {}+ return payload if isinstance(payload, dict) else {}+++def _error_from_response(response: httpx.Response, body: dict) -> RouteError:+ code = str(body.get("error_code") or "").strip()+ if not code:+ code = "TRANSPORT" if response.status_code >= 500 else "VALIDATION"+ message = str(body.get("error_message") or body.get("message") or "").strip()+ if not message:+ message = f"request failed: http={response.status_code} code={code}"+ retry_after = body.get("retry_after")+ if retry_after is None:+ retry_after = response.headers.get("Retry-After")+ try:+ retry_after_int = int(retry_after) if retry_after not in (None, "") else None+ except (TypeError, ValueError):+ retry_after_int = None+ if code in _RETRYABLE_CODES:+ cls = RetryableRouteError+ elif code in _FATAL_CODES:+ cls = FatalRouteError+ elif response.status_code >= 500 or response.status_code == 429:+ cls = RetryableRouteError+ else:+ cls = FatalRouteError+ return cls(message, code=code, retry_after=retry_after_int, status_code=response.status_code)diff --git a/tests/unit_tests/gateway/test_session_route.py b/tests/unit_tests/gateway/test_session_route.pynew file mode 100644index 0000000000..5fdf628f11--- /dev/null+++ b/tests/unit_tests/gateway/test_session_route.py@@ -0,0 +1,285 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""RuntimeSessionRouteClient 单测:httpx mock,不启真 Manager。"""++from __future__ import annotations++import json+import sys+from collections.abc import Callable+from pathlib import Path++import httpx+import pytest++_EXT_DIR = (+ Path(__file__).resolve().parents[3]+ / "packages"+ / "jiuwenclaw-ee"+ / "gateway"+ / "extensions"+ / "runtime_management_extension"+)+if str(_EXT_DIR) not in sys.path:+ sys.path.insert(0, str(_EXT_DIR))++from session_route_client import ( # noqa: E402+ FatalRouteError,+ RetryableRouteError,+ RuntimeSessionRouteClient,+)++_ROUTE_KW = {+ "session_id": "sess-1",+ "group_id": "grp-1",+ "bot_id": "bot-1",+ "request_id": "req-1",+ "user_id": "user-1",+}+++def _ok_body() -> dict:+ return {+ "type": "route",+ "metadata": {"request_id": "req-1"},+ "rawdata": {+ "pod_sse_url": "http://10.42.1.23:8080/sse",+ "pod_id": "agentserver-abc",+ },+ "ok": True,+ }+++async def client_factory():+ clients: list = []+ https: list[httpx.AsyncClient] = []++ def factory(+ handler: Callable[[httpx.Request], httpx.Response],+ *,+ base_url: str = "http://runtime-manager:8091",+ ) -> RuntimeSessionRouteClient:+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ https.append(http)+ client = RuntimeSessionRouteClient(base_url=base_url, http_client=http)+ clients.append(client)+ return client++ yield factory+ for client in clients:+ await client.aclose()+ for http in https:+ await http.aclose()+++async def test_route_success(client_factory) -> None:+ captured: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["url"] = str(request.url)+ captured["body"] = json.loads(request.content.decode("utf-8"))+ return httpx.Response(200, json=_ok_body())++ result = await client_factory(handler).route(**_ROUTE_KW)+ assert result.pod_sse_url == "http://10.42.1.23:8080/sse"+ assert result.pod_id == "agentserver-abc"+ assert result.request_id == "req-1"+ assert captured["url"] == "http://runtime-manager:8091/api/session/route"+ assert captured["body"]["type"] == "route"+ assert captured["body"]["rawdata"] == {}+ assert captured["body"]["metadata"]["session_id"] == "sess-1"+ assert captured["body"]["metadata"]["bot_id"] == "bot-1"+ assert captured["body"]["metadata"]["user_id"] == "user-1"+ assert captured["body"]["metadata"]["extra"]["group_id"] == "grp-1"+ assert captured["body"]["metadata"]["request_id"] == "req-1"+++async def test_route_strips_base_url_slash(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ assert str(request.url) == "http://runtime-manager:8091/api/session/route"+ return httpx.Response(200, json=_ok_body())++ await client_factory(handler, base_url="http://runtime-manager:8091/").route(**_ROUTE_KW)+++async def test_route_missing_args_skips_http(client_factory) -> None:+ called = {"n": 0}++ def handler(request: httpx.Request) -> httpx.Response:+ called["n"] += 1+ return httpx.Response(200, json=_ok_body())++ with pytest.raises(FatalRouteError) as exc:+ await client_factory(handler).route(session_id="", group_id="g", bot_id="b", request_id="r")+ assert exc.value.code == "VALIDATION"+ assert called["n"] == 0+++ ("status", "code", "retry_after", "exc_type"),+ [+ (503, "SCOPE_QUEUE_FULL", 2, RetryableRouteError),+ (504, "SCOPE_FULL_TIMEOUT", 1, RetryableRouteError),+ (503, "NO_POD_AVAILABLE", 1, RetryableRouteError),+ (503, "CONFIG_NOT_FOUND", None, FatalRouteError),+ (400, "VALIDATION", None, FatalRouteError),+ ],+)+async def test_route_error_codes(client_factory, status, code, retry_after, exc_type) -> None:+ body: dict = {"ok": False, "error_code": code, "error_message": code}+ if retry_after is not None:+ body["retry_after"] = retry_after++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(status, json=body)++ with pytest.raises(exc_type) as exc:+ await client_factory(handler).route(**_ROUTE_KW)+ assert exc.value.code == code+ assert exc.value.retry_after == retry_after+++async def test_route_connect_error(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ with pytest.raises(RetryableRouteError) as exc:+ await client_factory(handler).route(**_ROUTE_KW)+ assert exc.value.code == "TRANSPORT"+++async def test_route_success_missing_pod_fields(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"ok": True, "rawdata": {}})++ with pytest.raises(FatalRouteError) as exc:+ await client_factory(handler).route(**_ROUTE_KW)+ assert exc.value.code == "VALIDATION"+++async def test_touch_true_and_false(client_factory) -> None:+ captured: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["url"] = str(request.url)+ captured["body"] = json.loads(request.content.decode("utf-8"))+ return httpx.Response(200, json={"ok": True, "rawdata": {"touched": True}})++ client = client_factory(handler)+ assert await client.touch(session_id="sess-1", request_id="req-1") is True+ assert captured["url"] == "http://runtime-manager:8091/api/session/touch"+ assert captured["body"]["type"] == "touch"+ assert captured["body"]["metadata"]["session_id"] == "sess-1"+++async def test_touch_expired_returns_false(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"ok": True, "rawdata": {"touched": False}})++ assert await client_factory(handler).touch(session_id="sess-gone", request_id="req-1") is False+++async def test_touch_missing_args_skips_http(client_factory) -> None:+ called = {"n": 0}++ def handler(request: httpx.Request) -> httpx.Response:+ called["n"] += 1+ return httpx.Response(200, json={"ok": True, "rawdata": {"touched": True}})++ with pytest.raises(FatalRouteError) as exc:+ await client_factory(handler).touch(session_id="", request_id="req-1")+ assert exc.value.code == "VALIDATION"+ assert called["n"] == 0+++async def test_route_accepts_flat_success_body(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={"pod_sse_url": "http://10.0.0.1:8080/sse", "pod_id": "pod-1"},+ )++ result = await client_factory(handler).route(**_ROUTE_KW)+ assert result.pod_sse_url == "http://10.0.0.1:8080/sse"+ assert result.pod_id == "pod-1"+++async def test_route_ok_false_on_200(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={"ok": False, "error_code": "SCOPE_QUEUE_FULL", "retry_after": 2},+ )++ with pytest.raises(RetryableRouteError) as exc:+ await client_factory(handler).route(**_ROUTE_KW)+ assert exc.value.code == "SCOPE_QUEUE_FULL"+ assert exc.value.retry_after == 2+++async def test_route_internal_5xx_is_retryable(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 500,+ json={"ok": False, "error_code": "internal", "error_message": "boom"},+ )++ with pytest.raises(RetryableRouteError) as exc:+ await client_factory(handler).route(**_ROUTE_KW)+ assert exc.value.code == "internal"+++async def test_route_retry_after_header(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 503,+ json={"ok": False, "error_code": "NO_POD_AVAILABLE"},+ headers={"Retry-After": "3"},+ )++ with pytest.raises(RetryableRouteError) as exc:+ await client_factory(handler).route(**_ROUTE_KW)+ assert exc.value.retry_after == 3+++async def test_injected_client_not_closed(client_factory) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=_ok_body())++ client = client_factory(handler)+ await client.route(**_ROUTE_KW)+ await client.aclose()+ assert client._http.is_closed is False+++async def test_reads_url_from_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_URL", "http://rm.example:8091/")+ client = RuntimeSessionRouteClient()+ assert client._route_url == "http://rm.example:8091/api/session/route"+ assert client._touch_url == "http://rm.example:8091/api/session/touch"+ await client.aclose()+++async def test_blank_url_and_bad_timeout_fall_back(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_URL", " ")+ monkeypatch.setenv("GATEWAY_RUNTIME_MANAGER_TIMEOUT", "not-a-number")+ client = RuntimeSessionRouteClient()+ assert client._route_url == "http://127.0.0.1:8091/api/session/route"+ await client.aclose()