Draft
[WIP]P8-1: opt in to the local single-AgentServer worker trial #486
yutaoJustinBieber1223Add on 2 days ago
[WIP]P8-1: opt in to the local single-AgentServer worker trial #486
Draft
Total: 17 files changed+1949-24
| @@ -329,6 +329,9 @@ def main() -> None: | |||
| 329 | metavar="<path>", | 329 | metavar="<path>", |
| 330 | help="Load environment from .env file (processed at startup, not used here).", | 330 | help="Load environment from .env file (processed at startup, not used here).", |
| 331 | ) | 331 | ) |
| 332 | + parser.add_argument("--mode", choices=("single", "multiprocess"), default="single", | ||
| 333 | + help="Run the single Gateway or opt in to the personal loopback Worker trial.") | ||
| 334 | + parser.add_argument("--workers", type=int, help="Fixed Worker count in multiprocess mode (default: 2).") | ||
| 332 | parser.add_argument( | 335 | parser.add_argument( |
| 333 | "--require-adx-router", | 336 | "--require-adx-router", |
| 334 | # Accept previously generated service units; validation itself is generic. | 337 | # Accept previously generated service units; validation itself is generic. |
| @@ -336,6 +339,8 @@ def main() -> None: | |||
| 336 | help=argparse.SUPPRESS, | 339 | help=argparse.SUPPRESS, |
| 337 | ) | 340 | ) |
| 338 | args = parser.parse_args() | 341 | args = parser.parse_args() |
| 342 | + if args.workers is not None and args.mode != "multiprocess": | ||
| 343 | + parser.error("--workers requires --mode multiprocess") | ||
| 339 | 344 | ||
| 340 | # Handle --name: check if bootstrap .env was loaded successfully | 345 | # Handle --name: check if bootstrap .env was loaded successfully |
| 341 | # (parse_dotenv_early() already processed it, this is just a fallback check) | 346 | # (parse_dotenv_early() already processed it, this is just a fallback check) |
| @@ -365,7 +370,9 @@ def main() -> None: | |||
| 365 | or f"ws://{default_host}:{default_port}" | 370 | or f"ws://{default_host}:{default_port}" |
| 366 | ) | 371 | ) |
| 367 | web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1") | 372 | web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1") |
| 368 | - web_port = args.port or int(os.getenv("WEB_PORT", "19000")) | 373 | + web_port = args.port if args.mode == "multiprocess" and args.port is not None else ( |
| 374 | + args.port or int(os.getenv("WEB_PORT", "19000")) | ||
| 375 | + ) | ||
| 369 | web_path = args.web_path or os.getenv("WEB_PATH", "/ws") | 376 | web_path = args.web_path or os.getenv("WEB_PATH", "/ws") |
| 370 | # ws permessage-deflate compresses every frame with zlib; on loopback/LAN | 377 | # ws permessage-deflate compresses every frame with zlib; on loopback/LAN |
| 371 | # the CPU cost outweighs the bandwidth saving, so it stays off by default. | 378 | # the CPU cost outweighs the bandwidth saving, so it stays off by default. |
| @@ -377,6 +384,28 @@ def main() -> None: | |||
| 377 | "on", | 384 | "on", |
| 378 | ) | 385 | ) |
| 379 | 386 | ||
| 387 | + if args.mode == "multiprocess": | ||
| 388 | + from agent_gateway.application.multiprocess import MultiprocessOptions, run_multiprocess | ||
| 389 | + from agent_gateway.startup.lifecycle import gateway_workspace_lock, run_with_shutdown_signals | ||
| 390 | + | ||
| 391 | + try: | ||
| 392 | + options = MultiprocessOptions.from_cli( | ||
| 393 | + workers=args.workers, web_host=web_host, web_port=web_port, | ||
| 394 | + web_path=web_path, web_ws_deflate=web_ws_deflate, | ||
| 395 | + required_client_type=args.required_client_type, | ||
| 396 | + ) | ||
| 397 | + | ||
| 398 | + async def run_multiprocess_until_shutdown(shutdown_event: asyncio.Event) -> None: | ||
| 399 | + await run_multiprocess(options, agent_server_url, shutdown_event) | ||
| 400 | + | ||
| 401 | + install_crash_exit_handler("gateway") | ||
| 402 | + install_async_dump_handler("gateway") | ||
| 403 | + with gateway_workspace_lock(get_user_workspace_dir()): | ||
| 404 | + asyncio.run(run_with_shutdown_signals(run_multiprocess_until_shutdown, shutdown_gateway_telemetry)) | ||
| 405 | + except ValueError as error: | ||
| 406 | + parser.error(str(error)) | ||
| 407 | + return | ||
| 408 | + | ||
| 380 | install_crash_exit_handler("gateway") | 409 | install_crash_exit_handler("gateway") |
| 381 | install_async_dump_handler("gateway") | 410 | install_async_dump_handler("gateway") |
| 382 | 411 | ||
| @@ -0,0 +1,137 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Opt-in, personal loopback trial using the fixed Worker group.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +from dataclasses import dataclass | ||
| 8 | +import json | ||
| 9 | +import logging | ||
| 10 | +import os | ||
| 11 | +from pathlib import Path | ||
| 12 | +import socket | ||
| 13 | + | ||
| 14 | +from agent_gateway.application.worker_group import WorkerGroup | ||
| 15 | +from agent_gateway.common.agentos_runtime import is_agentos_runtime | ||
| 16 | +from agent_gateway.enterprise import is_enterprise | ||
| 17 | +from agent_gateway.processes.capabilities import management_preflight | ||
| 18 | + | ||
| 19 | +DEFAULT_WORKERS = 2 | ||
| 20 | +logger = logging.getLogger("gateway") | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +@dataclass(frozen=True) | ||
| 24 | +class MultiprocessOptions: | ||
| 25 | + workers: int | ||
| 26 | + web_port: int | ||
| 27 | + protocol_port: int | ||
| 28 | + | ||
| 29 | + @classmethod | ||
| 30 | + def from_cli(cls, *, workers: int | None, web_host: str, web_port: int, | ||
| 31 | + web_path: str, web_ws_deflate: bool, | ||
| 32 | + required_client_type: str | tuple[str, ...] | None) -> MultiprocessOptions: | ||
| 33 | + count = DEFAULT_WORKERS if workers is None else workers | ||
| 34 | + if not 1 <= count <= 32: | ||
| 35 | + raise ValueError("--workers must be between 1 and 32") | ||
| 36 | + if is_enterprise() or is_agentos_runtime() or required_client_type is not None: | ||
| 37 | + raise ValueError("multiprocess requires a personal deployment") | ||
| 38 | + if web_host not in {"127.0.0.1", "localhost"} or os.getenv( | ||
| 39 | + "GATEWAY_HOST", "127.0.0.1", | ||
| 40 | + ) not in {"127.0.0.1", "localhost"}: | ||
| 41 | + raise ValueError("multiprocess requires loopback listeners (127.0.0.1)") | ||
| 42 | + if web_path != "/ws" or web_ws_deflate: | ||
| 43 | + raise ValueError("multiprocess requires /ws without WebSocket compression") | ||
| 44 | + if os.getenv("A2A_SERVER_ENABLED", "").strip().lower() in {"1", "true", "yes", "on"}: | ||
| 45 | + raise ValueError("A2A is unavailable in multiprocess mode") | ||
| 46 | + if not management_preflight().supported or not all(( | ||
| 47 | + hasattr(socket, "SCM_RIGHTS"), hasattr(socket.socket, "sendmsg"), | ||
| 48 | + hasattr(socket.socket, "recvmsg"), | ||
| 49 | + )): | ||
| 50 | + raise ValueError("multiprocess requires Linux or macOS with fd passing") | ||
| 51 | + protocol_port = int(os.getenv("GATEWAY_PORT", "19001")) | ||
| 52 | + if not 0 <= web_port <= 65535 or not 0 <= protocol_port <= 65535: | ||
| 53 | + raise ValueError("listen ports must be between 0 and 65535") | ||
| 54 | + if web_port == protocol_port != 0: | ||
| 55 | + raise ValueError("Web and TUI/ACP must use distinct ports") | ||
| 56 | + return cls(count, web_port, protocol_port) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _channel_enabled(config: object) -> bool: | ||
| 60 | + if not isinstance(config, dict) or not config: | ||
| 61 | + return bool(config) | ||
| 62 | + if "enabled" in config: | ||
| 63 | + return bool(config["enabled"]) | ||
| 64 | + if "apps" in config: | ||
| 65 | + return any(_channel_enabled(app) for app in (config["apps"] or ())) | ||
| 66 | + return True | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _has_enabled_cron_jobs(path: Path) -> bool: | ||
| 70 | + # Read the atomic snapshot without invoking the store's lazy migration. | ||
| 71 | + try: | ||
| 72 | + data = json.loads(path.read_text(encoding="utf-8")) | ||
| 73 | + except FileNotFoundError: | ||
| 74 | + return False | ||
| 75 | + except (OSError, ValueError) as error: | ||
| 76 | + raise ValueError("cannot read the Cron job snapshot; use single mode") from error | ||
| 77 | + jobs = data.get("jobs", []) if isinstance(data, dict) else None | ||
| 78 | + if not isinstance(jobs, list) or not all(isinstance(job, dict) for job in jobs): | ||
| 79 | + raise ValueError("invalid Cron job snapshot; use single mode") | ||
| 80 | + return any(job.get("enabled") for job in jobs) | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +async def validate_workspace() -> None: | ||
| 84 | + from agent_gateway.common.config import get_config | ||
| 85 | + from agent_gateway.common.cron_settings import load_cron_store_settings | ||
| 86 | + | ||
| 87 | + config = await asyncio.to_thread(get_config) | ||
| 88 | + gateway = config.get("gateway") or {} | ||
| 89 | + client_type = (gateway.get("agent_client") or {}).get("type") or "websocket" | ||
| 90 | + if client_type != "websocket": | ||
| 91 | + raise ValueError("multiprocess requires the direct WebSocket AgentServer client") | ||
| 92 | + for name, channel in (config.get("channels") or {}).items(): | ||
| 93 | + if name == "web": | ||
| 94 | + continue | ||
| 95 | + enabled = (any(_channel_enabled(bot) for bot in channel.values()) | ||
| 96 | + if name == "feishu_enterprise" and isinstance(channel, dict) | ||
| 97 | + else _channel_enabled(channel)) | ||
| 98 | + if enabled: | ||
| 99 | + raise ValueError("multiprocess requires optional channels to be disabled") | ||
| 100 | + if (config.get("proactive_recommendation") or {}).get("enabled"): | ||
| 101 | + raise ValueError("proactive recommendations are unavailable in multiprocess mode") | ||
| 102 | + settings = load_cron_store_settings(config) | ||
| 103 | + if settings.backend != "file" or await asyncio.to_thread(_has_enabled_cron_jobs, settings.file_path): | ||
| 104 | + raise ValueError("Cron is not supported by this trial; use single mode") | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +async def run_multiprocess(options: MultiprocessOptions, agent_server_url: str, | ||
| 108 | + shutdown_event: asyncio.Event) -> None: | ||
| 109 | + await validate_workspace() | ||
| 110 | + if shutdown_event.is_set(): | ||
| 111 | + return | ||
| 112 | + group = WorkerGroup(agent_server_url, workers=options.workers, web_port=options.web_port, | ||
| 113 | + protocol_port=options.protocol_port) | ||
| 114 | + shutdown = asyncio.create_task(shutdown_event.wait()) | ||
| 115 | + startup = asyncio.create_task(group.start()) | ||
| 116 | + tasks = [shutdown, startup] | ||
| 117 | + try: | ||
| 118 | + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) | ||
| 119 | + if startup in done: | ||
| 120 | + await startup | ||
| 121 | + if shutdown.done(): | ||
| 122 | + return | ||
| 123 | + logger.info("[App] multiprocess_ready workers=%d web_port=%d protocol_port=%d worker_pids=%s", | ||
| 124 | + options.workers, group.addresses[0][1], group.addresses[1][1], | ||
| 125 | + ",".join(str(process.pid) for process in group.pool.processes)) | ||
| 126 | + closed = asyncio.create_task(group.wait()) | ||
| 127 | + tasks.append(closed) | ||
| 128 | + done, _ = await asyncio.wait((closed, shutdown), return_when=asyncio.FIRST_COMPLETED) | ||
| 129 | + if closed in done: | ||
| 130 | + await closed | ||
| 131 | + finally: | ||
| 132 | + for task in tasks: | ||
| 133 | + task.cancel() | ||
| 134 | + try: | ||
| 135 | + await asyncio.gather(*tasks, return_exceptions=True) | ||
| 136 | + finally: | ||
| 137 | + await group.stop() | ||
| @@ -0,0 +1,180 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Assemble the existing data handlers for the internal single-AS Worker test host.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +from contextlib import AsyncExitStack, asynccontextmanager | ||
| 7 | +from functools import partial | ||
| 8 | +import json | ||
| 9 | +import logging | ||
| 10 | + | ||
| 11 | +from fastapi import FastAPI, Request, WebSocket | ||
| 12 | +from starlette.responses import PlainTextResponse | ||
| 13 | + | ||
| 14 | +from agent_gateway.application.inbound import ( | ||
| 15 | + MessagePreprocessor, _inject_session_work_mode, _normalize_gateway_message, | ||
| 16 | +) | ||
| 17 | +from agent_gateway.auth.passthrough import MODEL_AUTH_PARAM_KEY | ||
| 18 | +from agent_gateway.common.ingress_identity import LocalIdentityPolicy, resolve_local_identity | ||
| 19 | +from agent_gateway.transport.protocol_connection_runtime import ProtocolConnectionRuntime | ||
| 20 | +from agent_gateway.transport.web_protocol_runtime import WebProtocolRuntime | ||
| 21 | + | ||
| 22 | +logger = logging.getLogger("gateway") | ||
| 23 | +_DATA_METHODS = frozenset({ | ||
| 24 | + "chat.send", "chat.interrupt", "chat.resume", "connection.status", "history.get", | ||
| 25 | +}) | ||
| 26 | +_ACP_METHODS = frozenset({"initialize", "session/new", "session/prompt", "session/cancel"}) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +class _DisabledAccounts: | ||
| 30 | + async def remember(self, session_id, credential_ref, model_name): | ||
| 31 | + raise RuntimeError("account bindings are not enabled in the Worker") | ||
| 32 | + | ||
| 33 | + async def lookup(self, session_id): | ||
| 34 | + return None | ||
| 35 | + | ||
| 36 | + async def model_auth_for_binding(self, binding): | ||
| 37 | + return None | ||
| 38 | + | ||
| 39 | + async def request_model_auth(self, auth_session, model_name): | ||
| 40 | + return None | ||
| 41 | + | ||
| 42 | + async def credential_update_for_ref(self, credential_ref): | ||
| 43 | + return None | ||
| 44 | + | ||
| 45 | + async def credential_ref_for_login_session(self, auth_session): | ||
| 46 | + return None | ||
| 47 | + | ||
| 48 | + async def model_auth_for_ref(self, credential_ref): | ||
| 49 | + return None | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def is_data_frame(raw: str | bytes, *, acp: bool = False) -> bool: | ||
| 53 | + """Keep unadapted login, configuration and Cron out of this Worker host.""" | ||
| 54 | + try: | ||
| 55 | + frame = json.loads(raw) | ||
| 56 | + except (ValueError, RecursionError): | ||
| 57 | + return False | ||
| 58 | + if not isinstance(frame, dict): | ||
| 59 | + return False | ||
| 60 | + method = frame.get("method") | ||
| 61 | + methods = _ACP_METHODS if acp and frame.get("jsonrpc") == "2.0" else _DATA_METHODS | ||
| 62 | + if not isinstance(method, str) or method not in methods: | ||
| 63 | + return False | ||
| 64 | + params = frame.get("params") | ||
| 65 | + if not isinstance(params, dict): | ||
| 66 | + return True | ||
| 67 | + return not ( | ||
| 68 | + any(key in params for key in (MODEL_AUTH_PARAM_KEY, "credential_ref", "_jiuwen_auth_session")) | ||
| 69 | + or any(params.get(key) == "huawei-maas-login" for key in ("source", "model_source")) | ||
| 70 | + ) | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def _build_web_app(channel): | ||
| 74 | + from agent_gateway.channel_manager.web import web_channel_app | ||
| 75 | + from agent_gateway.common.ingress_identity import IngressIdentityError | ||
| 76 | + | ||
| 77 | + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False) | ||
| 78 | + policy = LocalIdentityPolicy() | ||
| 79 | + | ||
| 80 | + @app.middleware("http") | ||
| 81 | + async def bind_http_identity(request: Request, call_next): | ||
| 82 | + try: | ||
| 83 | + identity = resolve_local_identity(request.scope["query_string"], request.scope["headers"], | ||
| 84 | + entry="http", policy=policy) | ||
| 85 | + except IngressIdentityError: | ||
| 86 | + return PlainTextResponse("invalid user identity", status_code=400) | ||
| 87 | + request.state.agentos_user_id = identity.business_user_id | ||
| 88 | + return await call_next(request) | ||
| 89 | + | ||
| 90 | + @app.get("/healthz") | ||
| 91 | + async def health() -> dict[str, str]: | ||
| 92 | + return {"status": "ok"} | ||
| 93 | + | ||
| 94 | + @app.websocket("/ws") | ||
| 95 | + async def web(websocket: WebSocket) -> None: | ||
| 96 | + try: | ||
| 97 | + identity = resolve_local_identity(websocket.scope["query_string"], websocket.scope["headers"], | ||
| 98 | + entry="web", policy=policy) | ||
| 99 | + except IngressIdentityError: | ||
| 100 | + await websocket.close(code=1008) | ||
| 101 | + return | ||
| 102 | + await web_channel_app._serve_channel_websocket( | ||
| 103 | + channel, websocket, local_user_id=identity.business_user_id or "", | ||
| 104 | + frame_allowed=is_data_frame, | ||
| 105 | + ) | ||
| 106 | + | ||
| 107 | + return app | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +async def _reject_config(*args, **kwargs) -> None: | ||
| 111 | + raise RuntimeError("configuration changes are not enabled in the Worker") | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +async def _no_refresh(_message) -> None: | ||
| 115 | + pass | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +@asynccontextmanager | ||
| 119 | +async def data_worker(agent_server_url: str): | ||
| 120 | + from agent_gateway.application.preparation import callback_framework | ||
| 121 | + from agent_gateway.application.tui_acp import assemble_tui_acp | ||
| 122 | + from agent_gateway.application.web import assemble_web | ||
| 123 | + from agent_gateway.channel_manager.channel_manager import ChannelManager | ||
| 124 | + from agent_gateway.extensions.registry import ExtensionRegistry | ||
| 125 | + from agent_gateway.message_handler.message_handler import MessageHandler | ||
| 126 | + from agent_gateway.routing.third_agent import get_unsupported_third_agent | ||
| 127 | + from agent_gateway.southbound.orchestration.client import assemble_client | ||
| 128 | + | ||
| 129 | + async with AsyncExitStack() as cleanup: | ||
| 130 | + registry = ExtensionRegistry.create_instance( | ||
| 131 | + callback_framework=None, callback_framework_factory=callback_framework, config={}, logger=logger, | ||
| 132 | + ) | ||
| 133 | + cleanup.callback(ExtensionRegistry.reset_instance) | ||
| 134 | + client = assemble_client(None, mode="websocket", enterprise=False, uri=agent_server_url) | ||
| 135 | + cleanup.push_async_callback(client.disconnect) | ||
| 136 | + await client.connect(agent_server_url) | ||
| 137 | + accounts = _DisabledAccounts() | ||
| 138 | + handler = MessageHandler(client, session_login_bindings=accounts) | ||
| 139 | + handler.set_credential_access(accounts) | ||
| 140 | + manager = ChannelManager(handler, config={}) | ||
| 141 | + handler.set_channel_manager(manager) | ||
| 142 | + cleanup.push_async_callback(handler.stop_forwarding) | ||
| 143 | + await handler.start_forwarding() | ||
| 144 | + cleanup.push_async_callback(manager.stop_dispatch) | ||
| 145 | + await manager.start_dispatch() | ||
| 146 | + preprocessor = MessagePreprocessor( | ||
| 147 | + _no_refresh, partial(_normalize_gateway_message, apply_model_auth=False), _inject_session_work_mode, | ||
| 148 | + ) | ||
| 149 | + web, _ = assemble_web( | ||
| 150 | + agent_client=client, message_handler=handler, channel_manager=manager, | ||
| 151 | + extension_registry=registry, on_config_saved=_reject_config, heartbeat_service=None, | ||
| 152 | + cron_controller=None, heartbeat_controller=None, updater_service=None, | ||
| 153 | + host="127.0.0.1", port=0, path="/ws", ws_permessage_deflate=False, | ||
| 154 | + preprocessor=preprocessor, log_stage=lambda _stage: None, | ||
| 155 | + ) | ||
| 156 | + cleanup.push_async_callback(web.stop) | ||
| 157 | + tui = await assemble_tui_acp( | ||
| 158 | + agent_client=client, message_handler=handler, channel_manager=manager, | ||
| 159 | + third_agent=get_unsupported_third_agent(), on_config_saved=_reject_config, | ||
| 160 | + cron_controller=None, heartbeat_controller=None, preprocessor=preprocessor, | ||
| 161 | + log_stage=lambda _stage: None, | ||
| 162 | + ) | ||
| 163 | + cleanup.push_async_callback(tui.stop) | ||
| 164 | + await tui.tui_channel.start() | ||
| 165 | + web_app = _build_web_app(web) | ||
| 166 | + web_runtime = WebProtocolRuntime(web_app, ws_per_message_deflate=False, single_request_http=True) | ||
| 167 | + cleanup.push_async_callback(web_runtime.stop) | ||
| 168 | + await web_runtime.start() | ||
| 169 | + protocol = ProtocolConnectionRuntime(tui.protocol_runtime, frame_allowed=is_data_frame) | ||
| 170 | + cleanup.push_async_callback(protocol.stop) | ||
| 171 | + await protocol.start() | ||
| 172 | + yield {"web-http": web_runtime, "web-ws": _WebSocketAdopter(web_runtime), "protocol": protocol}, web_runtime | ||
| 173 | + | ||
| 174 | + | ||
| 175 | +class _WebSocketAdopter: | ||
| 176 | + def __init__(self, runtime: WebProtocolRuntime) -> None: | ||
| 177 | + self._runtime = runtime | ||
| 178 | + | ||
| 179 | + async def adopt(self, sock, prefix: bytes) -> None: | ||
| 180 | + await self._runtime.adopt(sock, prefix, protocol="websocket") | ||
| @@ -0,0 +1,106 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Internal integration host for the fixed Worker pool and loopback listeners.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +import math | ||
| 8 | +import socket | ||
| 9 | +from urllib.parse import urlsplit | ||
| 10 | + | ||
| 11 | +from agent_gateway.common.ingress_identity import LocalIdentityPolicy | ||
| 12 | +from agent_gateway.common.worker_affinity import FixedUserHash, WorkerManifest | ||
| 13 | +from agent_gateway.enterprise import is_enterprise | ||
| 14 | +from agent_gateway.processes.pool import WorkerPool | ||
| 15 | +from agent_gateway.transport.connection_acceptor import ConnectionAcceptor | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class WorkerGroup: | ||
| 19 | + """No CLI wiring. The parent owns admission and supervises one fixed generation.""" | ||
| 20 | + | ||
| 21 | + def __init__( | ||
| 22 | + self, agent_server_url: str, *, workers: int, web_port: int = 19000, | ||
| 23 | + protocol_port: int = 19001, handoff_timeout: float = 2, | ||
| 24 | + ) -> None: | ||
| 25 | + url = urlsplit(agent_server_url) | ||
| 26 | + if (is_enterprise() or url.scheme != "ws" or not url.port | ||
| 27 | + or url.netloc != f"127.0.0.1:{url.port}" or url.query or url.fragment): | ||
| 28 | + raise ValueError("the Worker group only supports personal loopback with a single local AgentServer") | ||
| 29 | + if not math.isfinite(handoff_timeout) or handoff_timeout <= 0: | ||
| 30 | + raise ValueError("handoff timeout must be finite and positive") | ||
| 31 | + self.pool = WorkerPool(agent_server_url, workers) | ||
| 32 | + self._ports = (web_port, protocol_port) | ||
| 33 | + self._handoff_timeout = handoff_timeout | ||
| 34 | + self._acceptors: list[ConnectionAcceptor] = [] | ||
| 35 | + self._monitor: asyncio.Task | None = None | ||
| 36 | + self._started = False | ||
| 37 | + self._close_task: asyncio.Task | None = None | ||
| 38 | + self.addresses: tuple[tuple[str, int], ...] = () | ||
| 39 | + | ||
| 40 | + async def start(self) -> None: | ||
| 41 | + if self._close_task is not None or self._started: | ||
| 42 | + raise RuntimeError("Worker group is single-use") | ||
| 43 | + self._started = True | ||
| 44 | + try: | ||
| 45 | + await self.pool.start() | ||
| 46 | + if self._close_task is not None: | ||
| 47 | + raise RuntimeError("Worker group stopped during startup") | ||
| 48 | + affinity = FixedUserHash(WorkerManifest(self.pool.slots), LocalIdentityPolicy()) | ||
| 49 | + addresses = [] | ||
| 50 | + for index, port in enumerate(self._ports): | ||
| 51 | + listener = socket.socket() | ||
| 52 | + try: | ||
| 53 | + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| 54 | + listener.bind(("127.0.0.1", port)) | ||
| 55 | + listener.listen() | ||
| 56 | + listener.setblocking(False) | ||
| 57 | + addresses.append(listener.getsockname()) | ||
| 58 | + self._acceptors.append(ConnectionAcceptor( | ||
| 59 | + listener, protocol_port=index == 1, affinity=affinity, handoff=self.pool.handoff, | ||
| 60 | + handoff_timeout=self._handoff_timeout, | ||
| 61 | + )) | ||
| 62 | + except BaseException: | ||
| 63 | + listener.close() | ||
| 64 | + raise | ||
| 65 | + self.addresses = tuple(addresses) | ||
| 66 | + for acceptor in self._acceptors: | ||
| 67 | + acceptor.start() | ||
| 68 | + self._monitor = asyncio.create_task(self._watch(), name="gateway-watch-worker-group") | ||
| 69 | + except BaseException: | ||
| 70 | + await self.stop() | ||
| 71 | + raise | ||
| 72 | + | ||
| 73 | + async def _watch(self) -> Exception | None: | ||
| 74 | + tasks = [asyncio.create_task(wait()) for wait in | ||
| 75 | + (self.pool.wait, *(acceptor.wait for acceptor in self._acceptors))] | ||
| 76 | + try: | ||
| 77 | + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) | ||
| 78 | + for task in done: | ||
| 79 | + if not task.cancelled(): | ||
| 80 | + task.result() | ||
| 81 | + except Exception as error: | ||
| 82 | + return error | ||
| 83 | + finally: | ||
| 84 | + for task in tasks: | ||
| 85 | + task.cancel() | ||
| 86 | + await asyncio.gather(*tasks, return_exceptions=True) | ||
| 87 | + await self.stop() | ||
| 88 | + return None | ||
| 89 | + | ||
| 90 | + async def wait(self) -> None: | ||
| 91 | + if self._monitor is None: | ||
| 92 | + raise RuntimeError("Worker group was not started") | ||
| 93 | + error = await asyncio.shield(self._monitor) | ||
| 94 | + if error is not None: | ||
| 95 | + raise error | ||
| 96 | + | ||
| 97 | + async def stop(self) -> None: | ||
| 98 | + if self._close_task is None: | ||
| 99 | + self._close_task = asyncio.create_task(self._close(), name="gateway-stop-worker-group") | ||
| 100 | + await asyncio.shield(self._close_task) | ||
| 101 | + | ||
| 102 | + async def _close(self) -> None: | ||
| 103 | + try: | ||
| 104 | + await asyncio.gather(*(acceptor.stop() for acceptor in self._acceptors)) | ||
| 105 | + finally: | ||
| 106 | + await self.pool.stop() | ||
| @@ -5,6 +5,7 @@ | |||
| 5 | from __future__ import annotations | 5 | from __future__ import annotations |
| 6 | 6 | ||
| 7 | import logging | 7 | import logging |
| 8 | +from collections.abc import Callable | ||
| 8 | from typing import TYPE_CHECKING, Any | 9 | from typing import TYPE_CHECKING, Any |
| 9 | 10 | ||
| 10 | from fastapi import FastAPI, WebSocket | 11 | from fastapi import FastAPI, WebSocket |
| @@ -185,15 +186,24 @@ def register_http_routes(app: FastAPI, channel: WebChannel) -> None: | |||
| 185 | attach_ag_ui_routes(app, channel) | 186 | attach_ag_ui_routes(app, channel) |
| 186 | 187 | ||
| 187 | 188 | ||
| 188 | -async def _serve_channel_websocket(channel: WebChannel, websocket: WebSocket) -> None: | 189 | +async def _serve_channel_websocket( |
| 190 | + channel: WebChannel, websocket: WebSocket, *, local_user_id: str | None = None, | ||
| 191 | + frame_allowed: Callable[[str | bytes], bool] | None = None, | ||
| 192 | +) -> None: | ||
| 189 | if await _reject_disallowed_origin(websocket): | 193 | if await _reject_disallowed_origin(websocket): |
| 190 | return | 194 | return |
| 191 | denied, authenticated_user_id, verified_user_id = await _reject_unauthorized_handshake(channel, websocket) | 195 | denied, authenticated_user_id, verified_user_id = await _reject_unauthorized_handshake(channel, websocket) |
| 192 | if denied: | 196 | if denied: |
| 193 | return | 197 | return |
| 194 | 198 | ||
| 199 | + if local_user_id is not None: | ||
| 200 | + if verified_user_id is not None and verified_user_id != local_user_id: | ||
| 201 | + await websocket.close(code=1008) | ||
| 202 | + return | ||
| 203 | + verified_user_id = local_user_id | ||
| 195 | adapter = StarletteWsAdapter( | 204 | adapter = StarletteWsAdapter( |
| 196 | websocket, authenticated_user_id=authenticated_user_id, verified_user_id=verified_user_id, | 205 | websocket, authenticated_user_id=authenticated_user_id, verified_user_id=verified_user_id, |
| 206 | + frame_allowed=frame_allowed, | ||
| 197 | ) | 207 | ) |
| 198 | await adapter.accept() | 208 | await adapter.accept() |
| 199 | try: | 209 | try: |
| @@ -4,6 +4,7 @@ | |||
| 4 | 4 | ||
| 5 | from __future__ import annotations | 5 | from __future__ import annotations |
| 6 | 6 | ||
| 7 | +from collections.abc import Callable | ||
| 7 | from typing import Any | 8 | from typing import Any |
| 8 | 9 | ||
| 9 | from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState | 10 | from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState |
| @@ -23,8 +24,10 @@ class StarletteWsAdapter: | |||
| 23 | *, | 24 | *, |
| 24 | authenticated_user_id: str | None = None, | 25 | authenticated_user_id: str | None = None, |
| 25 | verified_user_id: str | None = None, | 26 | verified_user_id: str | None = None, |
| 27 | + frame_allowed: Callable[[str | bytes], bool] | None = None, | ||
| 26 | ) -> None: | 28 | ) -> None: |
| 27 | self._ws = websocket | 29 | self._ws = websocket |
| 30 | + self._frame_allowed = frame_allowed | ||
| 28 | self.authenticated_user_id = authenticated_user_id | 31 | self.authenticated_user_id = authenticated_user_id |
| 29 | # The declared user the handshake bound to the token ("" when none was | 32 | # The declared user the handshake bound to the token ("" when none was |
| 30 | # declared); None when no check ran. WebChannel uses it as the identity. | 33 | # declared); None when no check ran. WebChannel uses it as the identity. |
| @@ -99,10 +102,14 @@ class StarletteWsAdapter: | |||
| 99 | if msg_type == "websocket.disconnect": | 102 | if msg_type == "websocket.disconnect": |
| 100 | self._mark_closed(message.get("code", 1006), message.get("reason", "")) | 103 | self._mark_closed(message.get("code", 1006), message.get("reason", "")) |
| 101 | raise self._closed_exc() | 104 | raise self._closed_exc() |
| 102 | - if "text" in message and message["text"] is not None: | 105 | + data = message.get("text") |
| 103 | - return message["text"] | 106 | + if data is None: |
| 104 | - if "bytes" in message and message["bytes"] is not None: | 107 | + data = message.get("bytes") |
| 105 | - return message["bytes"] | 108 | + if data is not None: |
| 109 | + if self._frame_allowed is not None and not self._frame_allowed(data): | ||
| 110 | + await self.close(code=1008, reason="unsupported Worker request") | ||
| 111 | + raise self._closed_exc() | ||
| 112 | + return data | ||
| 106 | self._mark_closed(1006, "empty websocket frame") | 113 | self._mark_closed(1006, "empty websocket frame") |
| 107 | raise self._closed_exc() | 114 | raise self._closed_exc() |
| 108 | 115 | ||
| @@ -0,0 +1,230 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Manage a fixed generation of data Workers. A lost slot stops the group.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +from dataclasses import dataclass, field | ||
| 8 | +import socket | ||
| 9 | +import sys | ||
| 10 | +import uuid | ||
| 11 | + | ||
| 12 | +from agent_gateway.processes.capabilities import management_preflight | ||
| 13 | +from agent_gateway.processes.channel import ManagementChannel | ||
| 14 | +from agent_gateway.processes.management_protocol import PROTOCOL_VERSION, validate_message | ||
| 15 | +from agent_gateway.transport.handoff import HandoffRejected, HandoffSender | ||
| 16 | +from agent_gateway.transport.handoff_channel import HandoffChannel | ||
| 17 | +from agent_gateway.transport.handoff_protocol import HandoffIdentity | ||
| 18 | + | ||
| 19 | +RUNTIME_IDS = ("web-http", "web-ws", "protocol") | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def management_frame(kind: str, identity: HandoffIdentity, **fields) -> dict: | ||
| 23 | + return dict(type=kind, protocol_version=PROTOCOL_VERSION, group_id=identity.group_id, | ||
| 24 | + slot_id=identity.slot_id, generation=identity.generation, **fields) | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +@dataclass | ||
| 28 | +class _Worker: | ||
| 29 | + process: asyncio.subprocess.Process | ||
| 30 | + management: ManagementChannel | ||
| 31 | + sender: HandoffSender | ||
| 32 | + adopted: int = 0 | ||
| 33 | + watcher: asyncio.Task | None = None | ||
| 34 | + handoff_waiters: int = 0 | ||
| 35 | + handoff_lock: asyncio.Lock = field(default_factory=asyncio.Lock) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class WorkerPool: | ||
| 39 | + def __init__(self, agent_server_url: str, count: int, *, startup_timeout: float = 30) -> None: | ||
| 40 | + if type(count) is not int or not 1 <= count <= 32: | ||
| 41 | + raise ValueError("number of Workers must be between 1 and 32") | ||
| 42 | + self.slots = tuple(range(count)) | ||
| 43 | + self._agent_server_url = agent_server_url | ||
| 44 | + self._startup_timeout = startup_timeout | ||
| 45 | + self._group_id = uuid.uuid4().hex | ||
| 46 | + self._workers: list[_Worker] = [] | ||
| 47 | + self._failure = asyncio.get_running_loop().create_future() | ||
| 48 | + self._startup: asyncio.Task | None = None | ||
| 49 | + self._stop_task: asyncio.Task | None = None | ||
| 50 | + self._started = False | ||
| 51 | + self._ready = False | ||
| 52 | + | ||
| 53 | + @property | ||
| 54 | + def processes(self) -> tuple[asyncio.subprocess.Process, ...]: | ||
| 55 | + return tuple(worker.process for worker in self._workers) | ||
| 56 | + | ||
| 57 | + @property | ||
| 58 | + def adopted_counts(self) -> tuple[int, ...]: | ||
| 59 | + return tuple(worker.adopted for worker in self._workers) | ||
| 60 | + | ||
| 61 | + async def start(self) -> None: | ||
| 62 | + if self._started or self._stop_task is not None: | ||
| 63 | + raise RuntimeError("Worker pool is single-use") | ||
| 64 | + preflight = management_preflight() | ||
| 65 | + if not preflight.supported or not hasattr(socket, "SCM_RIGHTS"): | ||
| 66 | + raise RuntimeError(f"Worker pool platform unsupported: {preflight.reasons}") | ||
| 67 | + self._started = True | ||
| 68 | + startup = self._startup = asyncio.create_task(self._start(), name="gateway-start-workers") | ||
| 69 | + try: | ||
| 70 | + await asyncio.shield(startup) | ||
| 71 | + if self._stop_task is not None: | ||
| 72 | + raise RuntimeError("Worker pool stopped during startup") | ||
| 73 | + self._ready = True | ||
| 74 | + except BaseException: | ||
| 75 | + await self.stop() | ||
| 76 | + raise | ||
| 77 | + finally: | ||
| 78 | + self._startup = None | ||
| 79 | + | ||
| 80 | + async def _start(self) -> None: | ||
| 81 | + for slot in self.slots: | ||
| 82 | + await self._spawn(slot) | ||
| 83 | + async with asyncio.timeout(self._startup_timeout): | ||
| 84 | + await self._wait_ready() | ||
| 85 | + | ||
| 86 | + async def _spawn(self, slot: int) -> None: | ||
| 87 | + identity = HandoffIdentity(self._group_id, slot, 1) | ||
| 88 | + manager, child_manager = socket.socketpair() | ||
| 89 | + try: | ||
| 90 | + transfer, child_transfer = socket.socketpair() | ||
| 91 | + try: | ||
| 92 | + # Keep the spawn task owned if start is cancelled during fork/exec. | ||
| 93 | + spawn = asyncio.create_task(asyncio.create_subprocess_exec( | ||
| 94 | + sys.executable, "-m", "agent_gateway.processes.worker", | ||
| 95 | + str(child_manager.fileno()), str(child_transfer.fileno()), self._agent_server_url, | ||
| 96 | + pass_fds=(child_manager.fileno(), child_transfer.fileno()), | ||
| 97 | + stdin=asyncio.subprocess.DEVNULL, | ||
| 98 | + )) | ||
| 99 | + try: | ||
| 100 | + process = await asyncio.shield(spawn) | ||
| 101 | + except asyncio.CancelledError: | ||
| 102 | + process = await spawn | ||
| 103 | + self._register(process, manager, transfer, identity) | ||
| 104 | + raise | ||
| 105 | + self._register(process, manager, transfer, identity) | ||
| 106 | + except BaseException: | ||
| 107 | + if len(self._workers) == slot: | ||
| 108 | + transfer.close() | ||
| 109 | + raise | ||
| 110 | + finally: | ||
| 111 | + child_transfer.close() | ||
| 112 | + except BaseException: | ||
| 113 | + if len(self._workers) == slot: | ||
| 114 | + manager.close() | ||
| 115 | + raise | ||
| 116 | + finally: | ||
| 117 | + child_manager.close() | ||
| 118 | + | ||
| 119 | + def _register(self, process, manager, transfer, identity) -> None: | ||
| 120 | + self._workers.append(_Worker( | ||
| 121 | + process, ManagementChannel(manager), HandoffSender(HandoffChannel(transfer), identity), | ||
| 122 | + )) | ||
| 123 | + | ||
| 124 | + async def _wait_ready(self) -> None: | ||
| 125 | + async with asyncio.TaskGroup() as tasks: | ||
| 126 | + for worker in self._workers: | ||
| 127 | + tasks.create_task(self._initialize(worker)) | ||
| 128 | + for worker in self._workers: | ||
| 129 | + worker.watcher = asyncio.create_task(self._watch(worker), name="gateway-watch-worker") | ||
| 130 | + | ||
| 131 | + async def _initialize(self, worker: _Worker) -> None: | ||
| 132 | + await worker.management.send(management_frame("INIT", worker.sender.identity)) | ||
| 133 | + await self._expect(worker, "READY") | ||
| 134 | + frame = await self._expect(worker, "RUNTIME_READY") | ||
| 135 | + if set(frame["runtime_ids"]) != set(RUNTIME_IDS): | ||
| 136 | + raise RuntimeError("Worker runtime manifest does not match") | ||
| 137 | + | ||
| 138 | + async def _expect(self, worker: _Worker, kind: str) -> dict: | ||
| 139 | + frame = validate_message(await worker.management.receive(), expected=vars(worker.sender.identity)) | ||
| 140 | + if frame["type"] != kind or frame["pid"] != worker.process.pid: | ||
| 141 | + slot = worker.sender.identity.slot_id | ||
| 142 | + raise RuntimeError(f"Worker {slot}: expected {kind}, received {frame['type']}") | ||
| 143 | + return frame | ||
| 144 | + | ||
| 145 | + async def _watch(self, worker: _Worker) -> None: | ||
| 146 | + slot = worker.sender.identity.slot_id | ||
| 147 | + try: | ||
| 148 | + await self._expect(worker, "STOPPED") | ||
| 149 | + except Exception as error: | ||
| 150 | + if self._stop_task is None: | ||
| 151 | + self._fail(RuntimeError(f"Worker {slot} management channel failed: {type(error).__name__}")) | ||
| 152 | + return | ||
| 153 | + if self._stop_task is None: | ||
| 154 | + self._fail(RuntimeError(f"Worker {slot} stopped unexpectedly")) | ||
| 155 | + | ||
| 156 | + def _fail(self, error: RuntimeError) -> None: | ||
| 157 | + if not self._failure.done(): | ||
| 158 | + self._ready = False | ||
| 159 | + self._failure.set_result(error) | ||
| 160 | + | ||
| 161 | + async def wait(self) -> None: | ||
| 162 | + failure = await asyncio.shield(self._failure) | ||
| 163 | + if failure is not None: | ||
| 164 | + raise failure | ||
| 165 | + | ||
| 166 | + async def handoff(self, slot: int, client: socket.socket, runtime: str, prefix: bytes, *, timeout: float) -> None: | ||
| 167 | + worker = self._workers[slot] | ||
| 168 | + if not self._ready or worker.handoff_waiters >= 16 or worker.process.returncode is not None: | ||
| 169 | + raise HandoffRejected("Worker not available for handoff") | ||
| 170 | + worker.handoff_waiters += 1 | ||
| 171 | + try: | ||
| 172 | + async with asyncio.timeout(timeout): | ||
| 173 | + async with worker.handoff_lock: | ||
| 174 | + if not self._ready: | ||
| 175 | + raise HandoffRejected("Worker pool stopped admission") | ||
| 176 | + await worker.sender.handoff(client, runtime, prefix, timeout=timeout) | ||
| 177 | + worker.adopted += 1 | ||
| 178 | + finally: | ||
| 179 | + worker.handoff_waiters -= 1 | ||
| 180 | + if worker.sender.channel.closed and self._stop_task is None: | ||
| 181 | + self._fail(RuntimeError(f"Worker {slot} handoff channel closed")) | ||
| 182 | + | ||
| 183 | + async def stop(self) -> None: | ||
| 184 | + if self._stop_task is None: | ||
| 185 | + self._ready = False | ||
| 186 | + self._stop_task = asyncio.create_task(self._stop(), name="gateway-stop-workers") | ||
| 187 | + await asyncio.shield(self._stop_task) | ||
| 188 | + | ||
| 189 | + async def _stop(self) -> None: | ||
| 190 | + try: | ||
| 191 | + startup = self._startup | ||
| 192 | + if startup is not None and not startup.done(): | ||
| 193 | + startup.cancel() | ||
| 194 | + await asyncio.gather(startup, return_exceptions=True) | ||
| 195 | + await asyncio.gather(*(self._stop_worker(worker) for worker in self._workers)) | ||
| 196 | + finally: | ||
| 197 | + if not self._failure.done(): | ||
| 198 | + self._failure.set_result(None) | ||
| 199 | + | ||
| 200 | + async def _stop_worker(self, worker: _Worker) -> None: | ||
| 201 | + process = worker.process | ||
| 202 | + watcher = worker.watcher | ||
| 203 | + try: | ||
| 204 | + if process.returncode is None: | ||
| 205 | + try: | ||
| 206 | + async with asyncio.timeout(12): | ||
| 207 | + await worker.management.send(management_frame("STOP", worker.sender.identity)) | ||
| 208 | + if watcher is not None: | ||
| 209 | + await asyncio.shield(watcher) | ||
| 210 | + await process.wait() | ||
| 211 | + except (ConnectionError, OSError, TimeoutError): | ||
| 212 | + pass | ||
| 213 | + finally: | ||
| 214 | + worker.management.close() | ||
| 215 | + worker.sender.channel.close() | ||
| 216 | + if process.returncode is None: | ||
| 217 | + try: | ||
| 218 | + process.terminate() | ||
| 219 | + except ProcessLookupError: | ||
| 220 | + pass | ||
| 221 | + try: | ||
| 222 | + await asyncio.wait_for(process.wait(), 2) | ||
| 223 | + except TimeoutError: | ||
| 224 | + try: | ||
| 225 | + process.kill() | ||
| 226 | + except ProcessLookupError: | ||
| 227 | + pass | ||
| 228 | + await process.wait() | ||
| 229 | + if watcher is not None: | ||
| 230 | + await asyncio.gather(watcher, return_exceptions=True) | ||
| @@ -0,0 +1,79 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Private subprocess entry point for one data Worker.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +import logging | ||
| 8 | +import os | ||
| 9 | +import socket | ||
| 10 | +import sys | ||
| 11 | + | ||
| 12 | +from agent_gateway.processes.channel import ManagementChannel | ||
| 13 | +from agent_gateway.processes.management_protocol import validate_message | ||
| 14 | +from agent_gateway.processes.pool import management_frame | ||
| 15 | +from agent_gateway.transport.handoff import HandoffReceiver | ||
| 16 | +from agent_gateway.transport.handoff_channel import HandoffChannel | ||
| 17 | +from agent_gateway.transport.handoff_protocol import HandoffIdentity | ||
| 18 | + | ||
| 19 | +logger = logging.getLogger("gateway") | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +async def _run(management_fd: int, transfer_fd: int, agent_server_url: str) -> None: | ||
| 23 | + from agent_gateway.application.worker_data import data_worker | ||
| 24 | + | ||
| 25 | + management = ManagementChannel(socket.socket(fileno=management_fd)) | ||
| 26 | + transfer = HandoffChannel(socket.socket(fileno=transfer_fd)) | ||
| 27 | + identity = None | ||
| 28 | + try: | ||
| 29 | + init = await management.receive(timeout=10) | ||
| 30 | + if init["type"] != "INIT": | ||
| 31 | + raise RuntimeError("expected Worker INIT") | ||
| 32 | + identity = HandoffIdentity(init["group_id"], init["slot_id"], init["generation"]) | ||
| 33 | + await management.send(management_frame("READY", identity, pid=os.getpid(), stage="management_ready")) | ||
| 34 | + stop = asyncio.create_task(management.receive(), name="gateway-worker-stop-frame") | ||
| 35 | + try: | ||
| 36 | + async with data_worker(agent_server_url) as (runtimes, web_runtime): | ||
| 37 | + await management.send(management_frame("RUNTIME_READY", identity, pid=os.getpid(), | ||
| 38 | + runtime_ids=list(runtimes))) | ||
| 39 | + receiver = HandoffReceiver(transfer, identity, runtimes) | ||
| 40 | + | ||
| 41 | + async def receive_connections() -> None: | ||
| 42 | + while True: | ||
| 43 | + await receiver.receive_one() | ||
| 44 | + | ||
| 45 | + handoff = asyncio.create_task(receive_connections(), name="gateway-worker-handoff") | ||
| 46 | + web_closed = asyncio.create_task(web_runtime.wait_closed(), name="gateway-worker-web-runtime") | ||
| 47 | + try: | ||
| 48 | + done, _ = await asyncio.wait((stop, handoff, web_closed), return_when=asyncio.FIRST_COMPLETED) | ||
| 49 | + if stop not in done: | ||
| 50 | + for task in done: | ||
| 51 | + task.result() | ||
| 52 | + raise RuntimeError("Worker runtime closed unexpectedly") | ||
| 53 | + frame = validate_message(stop.result(), expected=vars(identity)) | ||
| 54 | + if frame["type"] != "STOP": | ||
| 55 | + raise RuntimeError("expected Worker STOP") | ||
| 56 | + finally: | ||
| 57 | + handoff.cancel() | ||
| 58 | + web_closed.cancel() | ||
| 59 | + await asyncio.gather(handoff, web_closed, return_exceptions=True) | ||
| 60 | + finally: | ||
| 61 | + stop.cancel() | ||
| 62 | + await asyncio.gather(stop, return_exceptions=True) | ||
| 63 | + await management.send(management_frame("STOPPED", identity, pid=os.getpid()), timeout=2) | ||
| 64 | + except Exception: | ||
| 65 | + logger.exception("Gateway Worker failed") | ||
| 66 | + if identity is not None: | ||
| 67 | + try: | ||
| 68 | + await management.send(management_frame("FAILED", identity, pid=os.getpid(), | ||
| 69 | + error_code="WORKER_FAILURE"), timeout=2) | ||
| 70 | + except (ConnectionError, OSError, TimeoutError): | ||
| 71 | + pass | ||
| 72 | + raise | ||
| 73 | + finally: | ||
| 74 | + management.close() | ||
| 75 | + transfer.close() | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +if __name__ == "__main__": | ||
| 79 | + asyncio.run(_run(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3])) | ||
| @@ -0,0 +1,110 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Read only the first request head and give one selected Worker the socket.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +from collections.abc import Awaitable, Callable | ||
| 8 | +import logging | ||
| 9 | +from http import HTTPStatus | ||
| 10 | +import socket | ||
| 11 | + | ||
| 12 | +from agent_gateway.common.ingress_identity import IngressIdentityError, resolve_local_identity | ||
| 13 | +from agent_gateway.common.worker_affinity import FixedUserHash | ||
| 14 | +from agent_gateway.transport.acceptor_http import HeadRejected, read_request_head | ||
| 15 | +from agent_gateway.transport.handoff import HandoffRejected | ||
| 16 | + | ||
| 17 | +logger = logging.getLogger("gateway") | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +class ConnectionAcceptor: | ||
| 21 | + def __init__( | ||
| 22 | + self, listener: socket.socket, *, protocol_port: bool, affinity: FixedUserHash, | ||
| 23 | + handoff: Callable[..., Awaitable[None]], handoff_timeout: float, head_timeout: float = 5, | ||
| 24 | + ) -> None: | ||
| 25 | + self._listener = listener | ||
| 26 | + self._protocol_port = protocol_port | ||
| 27 | + self._affinity = affinity | ||
| 28 | + self._handoff = handoff | ||
| 29 | + self._handoff_timeout = handoff_timeout | ||
| 30 | + self._head_timeout = head_timeout | ||
| 31 | + self._inflight = asyncio.Semaphore(128) | ||
| 32 | + self._clients: dict[asyncio.Task, socket.socket] = {} | ||
| 33 | + self._task: asyncio.Task | None = None | ||
| 34 | + | ||
| 35 | + def start(self) -> None: | ||
| 36 | + self._task = asyncio.create_task(self._accept(), name="gateway-accept-loop") | ||
| 37 | + | ||
| 38 | + async def wait(self) -> None: | ||
| 39 | + await asyncio.shield(self._task) | ||
| 40 | + | ||
| 41 | + async def stop(self) -> None: | ||
| 42 | + if self._task is not None: | ||
| 43 | + self._task.cancel() | ||
| 44 | + await asyncio.gather(self._task, return_exceptions=True) | ||
| 45 | + self._listener.close() | ||
| 46 | + for task in self._clients: | ||
| 47 | + task.cancel() | ||
| 48 | + await asyncio.gather(*self._clients, return_exceptions=True) | ||
| 49 | + | ||
| 50 | + async def _accept(self) -> None: | ||
| 51 | + loop = asyncio.get_running_loop() | ||
| 52 | + while True: | ||
| 53 | + await self._inflight.acquire() | ||
| 54 | + try: | ||
| 55 | + client, _ = await loop.sock_accept(self._listener) | ||
| 56 | + except BaseException: | ||
| 57 | + self._inflight.release() | ||
| 58 | + raise | ||
| 59 | + client.setblocking(False) | ||
| 60 | + task = asyncio.create_task(self._dispatch(client), name="gateway-classify-connection") | ||
| 61 | + self._clients[task] = client | ||
| 62 | + task.add_done_callback(self._finish) | ||
| 63 | + | ||
| 64 | + def _finish(self, task: asyncio.Task) -> None: | ||
| 65 | + # Also handles cancellation before the coroutine begins. | ||
| 66 | + self._clients.pop(task).close() | ||
| 67 | + self._inflight.release() | ||
| 68 | + if not task.cancelled() and (error := task.exception()) is not None: | ||
| 69 | + logger.error("Connection admission failed", exc_info=error) | ||
| 70 | + | ||
| 71 | + async def _dispatch(self, client: socket.socket) -> None: | ||
| 72 | + try: | ||
| 73 | + request = await read_request_head(client, timeout=self._head_timeout) | ||
| 74 | + if self._protocol_port: | ||
| 75 | + if request.protocol != "websocket" or request.path not in {"/tui", "/acp"}: | ||
| 76 | + raise HeadRejected(404) | ||
| 77 | + entry = request.path[1:] | ||
| 78 | + runtime = "protocol" | ||
| 79 | + elif request.protocol == "websocket" and request.path == "/ws": | ||
| 80 | + entry, runtime = "web", "web-ws" | ||
| 81 | + elif request.protocol == "http": | ||
| 82 | + entry, runtime = "http", "web-http" | ||
| 83 | + else: | ||
| 84 | + raise HeadRejected(404) | ||
| 85 | + try: | ||
| 86 | + identity = resolve_local_identity( | ||
| 87 | + request.query, request.headers, entry=entry, policy=self._affinity.identity_policy, | ||
| 88 | + ) | ||
| 89 | + except IngressIdentityError: | ||
| 90 | + raise HeadRejected(400) from None | ||
| 91 | + selection = self._affinity.select(identity) | ||
| 92 | + except HeadRejected as error: | ||
| 93 | + status = HTTPStatus(error.status) | ||
| 94 | + try: | ||
| 95 | + async with asyncio.timeout(0.25): | ||
| 96 | + await asyncio.get_running_loop().sock_sendall( | ||
| 97 | + client, f"HTTP/1.1 {status.value} {status.phrase}\r\nConnection: close\r\n" | ||
| 98 | + "Content-Length: 0\r\n\r\n".encode("ascii"), | ||
| 99 | + ) | ||
| 100 | + except (OSError, TimeoutError): | ||
| 101 | + pass | ||
| 102 | + return | ||
| 103 | + except OSError: | ||
| 104 | + return | ||
| 105 | + | ||
| 106 | + try: | ||
| 107 | + await self._handoff(selection, client, runtime, request.prefix, timeout=self._handoff_timeout) | ||
| 108 | + except (HandoffRejected, ConnectionError, OSError, TimeoutError): | ||
| 109 | + # No response or retry after offering the fd: the Worker may own it. | ||
| 110 | + return | ||
| @@ -0,0 +1,356 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import asyncio | ||
| 6 | +from collections.abc import Callable, Sequence | ||
| 7 | +import socket | ||
| 8 | +from typing import Any | ||
| 9 | + | ||
| 10 | +from agent_gateway.routing.protocol_runtime import ProtocolRuntime | ||
| 11 | +from websockets.extensions.permessage_deflate import enable_server_permessage_deflate | ||
| 12 | +from websockets.legacy.server import WebSocketServer, WebSocketServerProtocol | ||
| 13 | +from websockets.protocol import State | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +class _NoSocketServer: | ||
| 17 | + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: | ||
| 18 | + self._loop = loop | ||
| 19 | + self._serving = False | ||
| 20 | + self._closed = asyncio.Event() | ||
| 21 | + | ||
| 22 | + @property | ||
| 23 | + def sockets(self) -> tuple[(), ...]: | ||
| 24 | + return () | ||
| 25 | + | ||
| 26 | + def get_loop(self) -> asyncio.AbstractEventLoop: | ||
| 27 | + return self._loop | ||
| 28 | + | ||
| 29 | + def is_serving(self) -> bool: | ||
| 30 | + return self._serving | ||
| 31 | + | ||
| 32 | + def start_serving(self) -> None: | ||
| 33 | + self._serving = True | ||
| 34 | + | ||
| 35 | + def close(self) -> None: | ||
| 36 | + self._serving = False | ||
| 37 | + self._closed.set() | ||
| 38 | + | ||
| 39 | + async def wait_closed(self) -> None: | ||
| 40 | + await self._closed.wait() | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +class ProtocolConnectionRuntime: | ||
| 44 | + def __init__( | ||
| 45 | + self, runtime: ProtocolRuntime, *, frame_allowed: Callable[..., bool], stop_timeout: float = 10.0, | ||
| 46 | + ) -> None: | ||
| 47 | + self._runtime = runtime | ||
| 48 | + self._frame_allowed = frame_allowed | ||
| 49 | + self._stop_timeout = stop_timeout | ||
| 50 | + self._ready = asyncio.Event() | ||
| 51 | + self._closed = asyncio.Event() | ||
| 52 | + self._closed.set() | ||
| 53 | + self._server: WebSocketServer | None = None | ||
| 54 | + self._socket_server: _NoSocketServer | None = None | ||
| 55 | + self._extensions = tuple(enable_server_permessage_deflate(None)) | ||
| 56 | + self._adoptions: set[asyncio.Task[WebSocketServerProtocol]] = set() | ||
| 57 | + self._stop_task: asyncio.Task[None] | None = None | ||
| 58 | + self._stop_requested = False | ||
| 59 | + self._startup_error: BaseException | None = None | ||
| 60 | + self._stop_error: BaseException | None = None | ||
| 61 | + | ||
| 62 | + @property | ||
| 63 | + def bound_addresses(self) -> tuple[(), ...]: | ||
| 64 | + return () | ||
| 65 | + | ||
| 66 | + async def start(self) -> None: | ||
| 67 | + if self._stop_requested: | ||
| 68 | + self._startup_error = self._startup_error or RuntimeError( | ||
| 69 | + "Protocol connection runtime stopped before startup" | ||
| 70 | + ) | ||
| 71 | + self._ready.set() | ||
| 72 | + raise RuntimeError("Protocol connection runtime is stopped") | ||
| 73 | + if self._server is not None: | ||
| 74 | + return | ||
| 75 | + try: | ||
| 76 | + loop = asyncio.get_running_loop() | ||
| 77 | + socket_server = _NoSocketServer(loop) | ||
| 78 | + server = WebSocketServer() | ||
| 79 | + server.wrap(socket_server) | ||
| 80 | + socket_server.start_serving() | ||
| 81 | + except BaseException as error: | ||
| 82 | + self._startup_error = error | ||
| 83 | + self._stop_error = error | ||
| 84 | + self._ready.set() | ||
| 85 | + self._closed.set() | ||
| 86 | + raise | ||
| 87 | + self._socket_server = socket_server | ||
| 88 | + self._server = server | ||
| 89 | + self._closed.clear() | ||
| 90 | + self._ready.set() | ||
| 91 | + self._runtime._running = True | ||
| 92 | + | ||
| 93 | + async def wait_ready(self) -> None: | ||
| 94 | + await self._ready.wait() | ||
| 95 | + if self._startup_error is not None: | ||
| 96 | + raise self._startup_error | ||
| 97 | + self._require_serving() | ||
| 98 | + | ||
| 99 | + async def adopt(self, sock: socket.socket, prefix: bytes) -> WebSocketServerProtocol: | ||
| 100 | + try: | ||
| 101 | + self._require_serving() | ||
| 102 | + except BaseException: | ||
| 103 | + _close_socket_quietly(sock) | ||
| 104 | + raise | ||
| 105 | + adoption = asyncio.create_task(self._adopt_connection(sock, prefix)) | ||
| 106 | + self._adoptions.add(adoption) | ||
| 107 | + adoption.add_done_callback(self._finish_adoption) | ||
| 108 | + try: | ||
| 109 | + return await asyncio.shield(adoption) | ||
| 110 | + except asyncio.CancelledError: | ||
| 111 | + _close_socket_quietly(sock) | ||
| 112 | + _cancel_task(adoption) | ||
| 113 | + deadline = asyncio.get_running_loop().time() + self._stop_timeout * 2 | ||
| 114 | + await _wait_tasks_until((adoption,), deadline, ignore_cancelled=True) | ||
| 115 | + if not adoption.cancelled(): | ||
| 116 | + await self._discard_protocol(adoption.result()) | ||
| 117 | + raise | ||
| 118 | + | ||
| 119 | + async def _adopt_connection( | ||
| 120 | + self, | ||
| 121 | + sock: socket.socket, | ||
| 122 | + prefix: bytes, | ||
| 123 | + ) -> WebSocketServerProtocol: | ||
| 124 | + protocol: WebSocketServerProtocol | None = None | ||
| 125 | + | ||
| 126 | + def protocol_factory() -> WebSocketServerProtocol: | ||
| 127 | + nonlocal protocol | ||
| 128 | + protocol = self._protocol_factory() | ||
| 129 | + return protocol | ||
| 130 | + | ||
| 131 | + try: | ||
| 132 | + from agent_gateway.transport.accepted_socket import adopt_connection | ||
| 133 | + | ||
| 134 | + self._require_serving() | ||
| 135 | + _transport, adopted_protocol = await adopt_connection( | ||
| 136 | + sock, | ||
| 137 | + prefix, | ||
| 138 | + protocol_factory, | ||
| 139 | + ) | ||
| 140 | + self._require_serving() | ||
| 141 | + except BaseException: | ||
| 142 | + _close_socket_quietly(sock) | ||
| 143 | + if protocol is not None: | ||
| 144 | + await self._discard_protocol(protocol) | ||
| 145 | + raise | ||
| 146 | + return adopted_protocol | ||
| 147 | + | ||
| 148 | + def _finish_adoption(self, adoption: asyncio.Task[WebSocketServerProtocol]) -> None: | ||
| 149 | + self._adoptions.discard(adoption) | ||
| 150 | + _consume_task_result(adoption) | ||
| 151 | + | ||
| 152 | + async def stop(self) -> None: | ||
| 153 | + self._stop_requested = True | ||
| 154 | + self._ready.set() | ||
| 155 | + if self._stop_task is None: | ||
| 156 | + self._closed.clear() | ||
| 157 | + if self._socket_server is not None: | ||
| 158 | + self._socket_server.close() | ||
| 159 | + if self._server is None: | ||
| 160 | + self._startup_error = self._startup_error or RuntimeError( | ||
| 161 | + "Protocol connection runtime stopped before startup" | ||
| 162 | + ) | ||
| 163 | + self._stop_task = asyncio.create_task(self._stop_before_started()) | ||
| 164 | + else: | ||
| 165 | + self._stop_task = asyncio.create_task(self._stop_running_server()) | ||
| 166 | + self._stop_task.add_done_callback(_consume_task_result) | ||
| 167 | + await asyncio.shield(self._stop_task) | ||
| 168 | + | ||
| 169 | + async def wait_closed(self) -> None: | ||
| 170 | + await self._closed.wait() | ||
| 171 | + if self._stop_error is not None: | ||
| 172 | + raise self._stop_error | ||
| 173 | + | ||
| 174 | + def is_serving(self) -> bool: | ||
| 175 | + if self._server is None or self._stop_requested: | ||
| 176 | + return False | ||
| 177 | + return self._server.is_serving() | ||
| 178 | + | ||
| 179 | + def _require_serving(self) -> None: | ||
| 180 | + if not self.is_serving(): | ||
| 181 | + raise RuntimeError("Protocol connection runtime is not serving or is stopped") | ||
| 182 | + | ||
| 183 | + async def _stop_before_started(self) -> None: | ||
| 184 | + try: | ||
| 185 | + await self._runtime.stop() | ||
| 186 | + except BaseException as error: | ||
| 187 | + self._stop_error = error | ||
| 188 | + raise | ||
| 189 | + finally: | ||
| 190 | + self._clear_runtime_state() | ||
| 191 | + self._closed.set() | ||
| 192 | + | ||
| 193 | + async def _stop_running_server(self) -> None: | ||
| 194 | + server = self._server | ||
| 195 | + if server is None: | ||
| 196 | + return | ||
| 197 | + loop = asyncio.get_running_loop() | ||
| 198 | + deadline = loop.time() + self._stop_timeout | ||
| 199 | + close_tasks: list[asyncio.Task[Any]] = [] | ||
| 200 | + try: | ||
| 201 | + server.close(close_connections=False) | ||
| 202 | + adoptions = tuple(self._adoptions) | ||
| 203 | + for adoption in adoptions: | ||
| 204 | + _cancel_task(adoption) | ||
| 205 | + await _wait_tasks_until(adoptions, deadline, ignore_cancelled=True) | ||
| 206 | + for protocol in list(server.websockets): | ||
| 207 | + if protocol.state is State.OPEN: | ||
| 208 | + close_task = asyncio.create_task(protocol.close(1001)) | ||
| 209 | + close_task.add_done_callback(_consume_task_result) | ||
| 210 | + close_tasks.append(close_task) | ||
| 211 | + await _wait_tasks_until(close_tasks, deadline) | ||
| 212 | + if server.close_task is not None: | ||
| 213 | + await _wait_tasks_until((server.close_task,), deadline) | ||
| 214 | + await self._runtime.stop() | ||
| 215 | + except BaseException as error: | ||
| 216 | + self._stop_error = error | ||
| 217 | + try: | ||
| 218 | + await self._force_close_protocols(server, close_tasks) | ||
| 219 | + except BaseException as cleanup_error: | ||
| 220 | + error.add_note(f"Forced protocol cleanup failed: {cleanup_error!r}") | ||
| 221 | + raise | ||
| 222 | + finally: | ||
| 223 | + self._clear_runtime_state() | ||
| 224 | + self._closed.set() | ||
| 225 | + | ||
| 226 | + async def _discard_protocol(self, protocol: WebSocketServerProtocol) -> None: | ||
| 227 | + tasks = self._abort_protocol(protocol) | ||
| 228 | + try: | ||
| 229 | + deadline = asyncio.get_running_loop().time() + self._stop_timeout | ||
| 230 | + await _wait_tasks_until(tasks, deadline, ignore_cancelled=True) | ||
| 231 | + finally: | ||
| 232 | + self._clear_connection_state(protocol) | ||
| 233 | + handler = getattr(protocol, "handler_task", None) | ||
| 234 | + if ( | ||
| 235 | + self._server is not None | ||
| 236 | + and protocol in self._server.websockets | ||
| 237 | + and (handler is None or handler.done()) | ||
| 238 | + ): | ||
| 239 | + self._server.unregister(protocol) | ||
| 240 | + | ||
| 241 | + async def _force_close_protocols( | ||
| 242 | + self, | ||
| 243 | + server: WebSocketServer, | ||
| 244 | + close_tasks: Sequence[asyncio.Task[Any]], | ||
| 245 | + ) -> None: | ||
| 246 | + tasks = set(close_tasks) | ||
| 247 | + for protocol in list(server.websockets): | ||
| 248 | + tasks.update(self._abort_protocol(protocol)) | ||
| 249 | + tasks.update(self._adoptions) | ||
| 250 | + if server.close_task is not None: | ||
| 251 | + tasks.add(server.close_task) | ||
| 252 | + for task in tasks: | ||
| 253 | + task.add_done_callback(_consume_task_result) | ||
| 254 | + _cancel_task(task) | ||
| 255 | + deadline = asyncio.get_running_loop().time() + self._stop_timeout | ||
| 256 | + await _wait_tasks_until(tuple(tasks), deadline, ignore_cancelled=True) | ||
| 257 | + | ||
| 258 | + def _abort_protocol(self, protocol: WebSocketServerProtocol) -> list[asyncio.Task[Any]]: | ||
| 259 | + transport = getattr(protocol, "transport", None) | ||
| 260 | + if transport is not None: | ||
| 261 | + transport.abort() | ||
| 262 | + tasks = [] | ||
| 263 | + for name in ("handler_task", "transfer_data_task", "keepalive_ping_task", "close_connection_task"): | ||
| 264 | + task = getattr(protocol, name, None) | ||
| 265 | + if task is not None: | ||
| 266 | + task.add_done_callback(_consume_task_result) | ||
| 267 | + if name != "close_connection_task": | ||
| 268 | + _cancel_task(task) | ||
| 269 | + tasks.append(task) | ||
| 270 | + return tasks | ||
| 271 | + | ||
| 272 | + def _clear_connection_state(self, protocol: WebSocketServerProtocol) -> None: | ||
| 273 | + self._runtime._clients.discard(protocol) | ||
| 274 | + for table in ( | ||
| 275 | + self._runtime._request_to_client, | ||
| 276 | + self._runtime._session_to_client, | ||
| 277 | + self._runtime._pending_session_clients, | ||
| 278 | + ): | ||
| 279 | + for key, client in list(table.items()): | ||
| 280 | + if client is protocol: | ||
| 281 | + table.pop(key, None) | ||
| 282 | + | ||
| 283 | + def _clear_runtime_state(self) -> None: | ||
| 284 | + self._runtime._running = False | ||
| 285 | + self._runtime._clients.clear() | ||
| 286 | + self._runtime._request_to_client.clear() | ||
| 287 | + self._runtime._session_to_client.clear() | ||
| 288 | + self._runtime._pending_session_clients.clear() | ||
| 289 | + | ||
| 290 | + def _protocol_factory(self) -> WebSocketServerProtocol: | ||
| 291 | + self._require_serving() | ||
| 292 | + frame_allowed = self._frame_allowed | ||
| 293 | + | ||
| 294 | + class DataProtocol(WebSocketServerProtocol): | ||
| 295 | + async def recv(self) -> str | bytes: | ||
| 296 | + raw = await super().recv() | ||
| 297 | + if not frame_allowed(raw, acp=self.path.partition("?")[0] == "/acp"): | ||
| 298 | + await self.close(code=1008, reason="unsupported Worker request") | ||
| 299 | + await self.ensure_open() # Raise the normal ConnectionClosed error. | ||
| 300 | + return raw | ||
| 301 | + | ||
| 302 | + return DataProtocol( | ||
| 303 | + self._runtime._connection_handler, | ||
| 304 | + self._server, | ||
| 305 | + extensions=self._extensions, | ||
| 306 | + process_request=self._runtime._process_request, | ||
| 307 | + ping_interval=20, | ||
| 308 | + ping_timeout=600, | ||
| 309 | + max_size=8 * 2**20, | ||
| 310 | + ) | ||
| 311 | + | ||
| 312 | + | ||
| 313 | +def _close_socket_quietly(sock: object) -> None: | ||
| 314 | + close = getattr(sock, "close", None) | ||
| 315 | + if close is None: | ||
| 316 | + return | ||
| 317 | + try: | ||
| 318 | + close() | ||
| 319 | + except OSError: | ||
| 320 | + return | ||
| 321 | + | ||
| 322 | + | ||
| 323 | +def _cancel_task(task: asyncio.Task[Any]) -> None: | ||
| 324 | + if not task.done() and not task.cancelling(): | ||
| 325 | + task.cancel() | ||
| 326 | + | ||
| 327 | + | ||
| 328 | +def _consume_task_result(task: asyncio.Task[Any]) -> None: | ||
| 329 | + if not task.cancelled(): | ||
| 330 | + task.exception() | ||
| 331 | + | ||
| 332 | + | ||
| 333 | +async def _wait_tasks_until( | ||
| 334 | + tasks: Sequence[asyncio.Task[Any]], | ||
| 335 | + deadline: float, | ||
| 336 | + *, | ||
| 337 | + ignore_cancelled: bool = False, | ||
| 338 | +) -> None: | ||
| 339 | + if not tasks: | ||
| 340 | + return | ||
| 341 | + loop = asyncio.get_running_loop() | ||
| 342 | + remaining = max(0.0, deadline - loop.time()) | ||
| 343 | + done, pending = await asyncio.wait(tasks, timeout=remaining) | ||
| 344 | + failure: BaseException | None = None | ||
| 345 | + for task in done: | ||
| 346 | + if ignore_cancelled and task.cancelled(): | ||
| 347 | + continue | ||
| 348 | + try: | ||
| 349 | + task.result() | ||
| 350 | + except BaseException as error: | ||
| 351 | + if failure is None: | ||
| 352 | + failure = error | ||
| 353 | + if failure is not None: | ||
| 354 | + raise failure | ||
| 355 | + if pending: | ||
| 356 | + raise asyncio.TimeoutError(f"{len(pending)} protocol task(s) did not finish before the deadline") | ||
| @@ -18,6 +18,32 @@ _CANCEL_TIMEOUT_SECONDS = 1.0 | |||
| 18 | _logger = logging.getLogger("gateway") | 18 | _logger = logging.getLogger("gateway") |
| 19 | 19 | ||
| 20 | 20 | ||
| 21 | +def web_protocol_config( | ||
| 22 | + app: ASGIApp, *, host: str = "127.0.0.1", port: int = 0, ws_per_message_deflate: bool, | ||
| 23 | +) -> uvicorn.Config: | ||
| 24 | + """Use the same protocol settings for listening and adopted sockets.""" | ||
| 25 | + from agent_gateway.channel_manager.web.transport_stall_guard import ( | ||
| 26 | + guarded_http_protocol, | ||
| 27 | + guarded_websockets_protocol, | ||
| 28 | + ) | ||
| 29 | + from agent_gateway.common.ws_limits import WEB_WS_MAX_MESSAGE_BYTES | ||
| 30 | + | ||
| 31 | + return uvicorn.Config( | ||
| 32 | + app, | ||
| 33 | + host=host, | ||
| 34 | + port=port, | ||
| 35 | + log_level="info", | ||
| 36 | + access_log=False, | ||
| 37 | + ws_max_size=WEB_WS_MAX_MESSAGE_BYTES, | ||
| 38 | + ws_ping_interval=20.0, | ||
| 39 | + ws_ping_timeout=60.0, | ||
| 40 | + timeout_graceful_shutdown=_GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS, | ||
| 41 | + http=guarded_http_protocol(), | ||
| 42 | + ws=guarded_websockets_protocol(), | ||
| 43 | + ws_per_message_deflate=ws_per_message_deflate, | ||
| 44 | + ) | ||
| 45 | + | ||
| 46 | + | ||
| 21 | class _EmbeddedServer(uvicorn.Server): | 47 | class _EmbeddedServer(uvicorn.Server): |
| 22 | """Leave process signals with the Gateway and publish actual readiness.""" | 48 | """Leave process signals with the Gateway and publish actual readiness.""" |
| 23 | 49 | ||
| @@ -152,24 +178,8 @@ class UvicornListener: | |||
| 152 | 178 | ||
| 153 | async def _serve(self) -> None: | 179 | async def _serve(self) -> None: |
| 154 | try: | 180 | try: |
| 155 | - from agent_gateway.channel_manager.web.transport_stall_guard import ( | 181 | + config = web_protocol_config( |
| 156 | - guarded_http_protocol, | 182 | + self._app, host=self._host, port=self._port, |
| 157 | - guarded_websockets_protocol, | ||
| 158 | - ) | ||
| 159 | - from agent_gateway.common.ws_limits import WEB_WS_MAX_MESSAGE_BYTES | ||
| 160 | - | ||
| 161 | - config = uvicorn.Config( | ||
| 162 | - self._app, | ||
| 163 | - host=self._host, | ||
| 164 | - port=self._port, | ||
| 165 | - log_level="info", | ||
| 166 | - access_log=False, | ||
| 167 | - ws_max_size=WEB_WS_MAX_MESSAGE_BYTES, | ||
| 168 | - ws_ping_interval=20.0, | ||
| 169 | - ws_ping_timeout=60.0, | ||
| 170 | - timeout_graceful_shutdown=_GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS, | ||
| 171 | - http=guarded_http_protocol(), | ||
| 172 | - ws=guarded_websockets_protocol(), | ||
| 173 | ws_per_message_deflate=self._ws_per_message_deflate, | 183 | ws_per_message_deflate=self._ws_per_message_deflate, |
| 174 | ) | 184 | ) |
| 175 | self._server = _EmbeddedServer(config, self._ready) | 185 | self._server = _EmbeddedServer(config, self._ready) |
| @@ -0,0 +1,346 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | + | ||
| 3 | +"""Run the existing Web ASGI protocols without creating a listener.""" | ||
| 4 | + | ||
| 5 | +from __future__ import annotations | ||
| 6 | + | ||
| 7 | +import asyncio | ||
| 8 | +import socket | ||
| 9 | +from typing import Literal | ||
| 10 | +import weakref | ||
| 11 | + | ||
| 12 | +from starlette.types import ASGIApp | ||
| 13 | +import uvicorn | ||
| 14 | +from uvicorn.lifespan.on import LifespanOn | ||
| 15 | +from websockets.protocol import State | ||
| 16 | + | ||
| 17 | +from agent_gateway.transport.accepted_socket import adopt_connection | ||
| 18 | +from agent_gateway.transport.uvicorn_listener import web_protocol_config | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class _ConnectionSet(set): | ||
| 22 | + def __init__(self, shared: set) -> None: | ||
| 23 | + super().__init__() | ||
| 24 | + self.shared = shared | ||
| 25 | + self.seen = weakref.WeakSet() | ||
| 26 | + | ||
| 27 | + def add(self, item) -> None: | ||
| 28 | + super().add(item) | ||
| 29 | + self.shared.add(item) | ||
| 30 | + self.seen.add(item) | ||
| 31 | + | ||
| 32 | + def discard(self, item) -> None: | ||
| 33 | + super().discard(item) | ||
| 34 | + self.shared.discard(item) | ||
| 35 | + | ||
| 36 | + def remove(self, item) -> None: | ||
| 37 | + super().remove(item) | ||
| 38 | + self.shared.discard(item) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +class _ConnectionState: | ||
| 42 | + def __init__(self, shared: uvicorn.server.ServerState) -> None: | ||
| 43 | + self.shared = shared | ||
| 44 | + self.connections = _ConnectionSet(shared.connections) | ||
| 45 | + self.tasks = _ConnectionSet(shared.tasks) | ||
| 46 | + | ||
| 47 | + @property | ||
| 48 | + def total_requests(self): | ||
| 49 | + return self.shared.total_requests | ||
| 50 | + | ||
| 51 | + @total_requests.setter | ||
| 52 | + def total_requests(self, value): | ||
| 53 | + self.shared.total_requests = value | ||
| 54 | + | ||
| 55 | + @property | ||
| 56 | + def default_headers(self): | ||
| 57 | + return self.shared.default_headers | ||
| 58 | + | ||
| 59 | + async def abort(self, timeout: float) -> None: | ||
| 60 | + tasks = set(self.tasks) | ||
| 61 | + for connection in tuple(self.connections.seen): | ||
| 62 | + transport = getattr(connection, "transport", None) | ||
| 63 | + if transport is not None: | ||
| 64 | + transport.abort() | ||
| 65 | + handler = getattr(connection, "handler_task", None) | ||
| 66 | + if handler is not None: | ||
| 67 | + tasks.add(handler) | ||
| 68 | + for task in tasks: | ||
| 69 | + task.cancel() | ||
| 70 | + if tasks: | ||
| 71 | + _done, pending = await asyncio.wait(tasks, timeout=timeout) | ||
| 72 | + if pending: | ||
| 73 | + raise RuntimeError("Adopted Web connection tasks did not stop") | ||
| 74 | + await asyncio.sleep(0) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +class _TrackedLifespan(LifespanOn): | ||
| 78 | + main_task: asyncio.Task | None = None | ||
| 79 | + | ||
| 80 | + async def main(self) -> None: | ||
| 81 | + self.main_task = asyncio.current_task() | ||
| 82 | + await super().main() | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def _single_request_http_protocol(protocol_class: type[asyncio.Protocol]) -> type[asyncio.Protocol]: | ||
| 86 | + def single_request_app(app: ASGIApp) -> ASGIApp: | ||
| 87 | + async def bounded_app(scope, receive, send) -> None: | ||
| 88 | + async def bounded_send(message) -> None: | ||
| 89 | + if message["type"] == "http.response.start": | ||
| 90 | + headers = [ | ||
| 91 | + (name, value) | ||
| 92 | + for name, value in message.get("headers", []) | ||
| 93 | + if name.lower() != b"connection" | ||
| 94 | + ] | ||
| 95 | + message = {**message, "headers": headers + [(b"connection", b"close")]} | ||
| 96 | + await send(message) | ||
| 97 | + | ||
| 98 | + await app(scope, receive, bounded_send) | ||
| 99 | + | ||
| 100 | + return bounded_app | ||
| 101 | + | ||
| 102 | + class SingleRequestHTTPProtocol(protocol_class): | ||
| 103 | + def __init__(self, *, config, server_state, app_state, _loop=None) -> None: | ||
| 104 | + super().__init__(config=config, server_state=server_state, app_state=app_state, _loop=_loop) | ||
| 105 | + self.app = single_request_app(self.app) | ||
| 106 | + | ||
| 107 | + def on_response_complete(self) -> None: | ||
| 108 | + # Closing before the base callback prevents uvicorn from starting | ||
| 109 | + # an already-parsed pipelined request. asyncio still flushes writes. | ||
| 110 | + self.transport.close() | ||
| 111 | + super().on_response_complete() | ||
| 112 | + | ||
| 113 | + return SingleRequestHTTPProtocol | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +class WebProtocolRuntime: | ||
| 117 | + """Own adopted HTTP/WS connections and one bounded ASGI lifecycle.""" | ||
| 118 | + | ||
| 119 | + def __init__( | ||
| 120 | + self, | ||
| 121 | + app: ASGIApp, | ||
| 122 | + *, | ||
| 123 | + ws_per_message_deflate: bool, | ||
| 124 | + single_request_http: bool = False, | ||
| 125 | + lifecycle_timeout: float = 5.0, | ||
| 126 | + ) -> None: | ||
| 127 | + if lifecycle_timeout <= 0: | ||
| 128 | + raise ValueError("lifecycle_timeout must be positive") | ||
| 129 | + self._app = app | ||
| 130 | + self._deflate = ws_per_message_deflate | ||
| 131 | + self._single_request_http = single_request_http | ||
| 132 | + self._timeout = lifecycle_timeout | ||
| 133 | + self._ready = asyncio.Event() | ||
| 134 | + self._task: asyncio.Task | None = None | ||
| 135 | + self._server: uvicorn.Server | None = None | ||
| 136 | + self._lifespan: _TrackedLifespan | None = None | ||
| 137 | + self._adoptions: set[asyncio.Task] = set() | ||
| 138 | + self._states: set[_ConnectionState] = set() | ||
| 139 | + self._close_tasks: set[asyncio.Task] = set() | ||
| 140 | + self._stopping = False | ||
| 141 | + self._error: BaseException | None = None | ||
| 142 | + self._shutdown_error: BaseException | None = None | ||
| 143 | + | ||
| 144 | + @property | ||
| 145 | + def bound_addresses(self) -> tuple[tuple[str, int], ...]: | ||
| 146 | + return () | ||
| 147 | + | ||
| 148 | + async def start(self) -> None: | ||
| 149 | + if self._stopping: | ||
| 150 | + raise RuntimeError("Web protocol runtime is closed") | ||
| 151 | + if self._task is None: | ||
| 152 | + self._task = asyncio.create_task(self._run(), name="gateway-web-protocol-runtime") | ||
| 153 | + try: | ||
| 154 | + await self.wait_ready() | ||
| 155 | + except asyncio.CancelledError: | ||
| 156 | + await self.stop() | ||
| 157 | + raise | ||
| 158 | + | ||
| 159 | + async def wait_ready(self) -> None: | ||
| 160 | + await self._ready.wait() | ||
| 161 | + if self._error is not None: | ||
| 162 | + raise self._error | ||
| 163 | + if self._stopping or self._server is None or not self._server.started: | ||
| 164 | + raise RuntimeError("Web protocol runtime stopped before ready") | ||
| 165 | + | ||
| 166 | + async def adopt( | ||
| 167 | + self, | ||
| 168 | + sock: socket.socket, | ||
| 169 | + prefix: bytes, | ||
| 170 | + *, | ||
| 171 | + protocol: Literal["http", "websocket"] = "http", | ||
| 172 | + ) -> None: | ||
| 173 | + server = self._server | ||
| 174 | + if self._stopping or server is None or not server.started or self._error is not None: | ||
| 175 | + sock.close() | ||
| 176 | + raise RuntimeError("Web protocol runtime is not ready") | ||
| 177 | + if protocol not in ("http", "websocket"): | ||
| 178 | + sock.close() | ||
| 179 | + raise ValueError("unsupported Web protocol") | ||
| 180 | + task = asyncio.current_task() | ||
| 181 | + self._adoptions.add(task) | ||
| 182 | + state = _ConnectionState(server.server_state) | ||
| 183 | + try: | ||
| 184 | + protocol_class = ( | ||
| 185 | + server.config.http_protocol_class if protocol == "http" else server.config.ws_protocol_class | ||
| 186 | + ) | ||
| 187 | + await adopt_connection( | ||
| 188 | + sock, | ||
| 189 | + prefix, | ||
| 190 | + lambda: protocol_class( | ||
| 191 | + config=server.config, | ||
| 192 | + server_state=state, | ||
| 193 | + app_state=self._lifespan.state, | ||
| 194 | + ), | ||
| 195 | + ) | ||
| 196 | + self._states.add(state) | ||
| 197 | + except BaseException: | ||
| 198 | + await state.abort(self._timeout) | ||
| 199 | + raise | ||
| 200 | + finally: | ||
| 201 | + self._adoptions.discard(task) | ||
| 202 | + | ||
| 203 | + async def stop(self) -> None: | ||
| 204 | + self._stopping = True | ||
| 205 | + if self._server is not None: | ||
| 206 | + self._server.should_exit = True | ||
| 207 | + if self._task is not None: | ||
| 208 | + await asyncio.shield(self._task) | ||
| 209 | + self._ready.set() | ||
| 210 | + if self._shutdown_error is not None: | ||
| 211 | + raise self._shutdown_error | ||
| 212 | + | ||
| 213 | + async def wait_closed(self) -> None: | ||
| 214 | + if self._task is not None: | ||
| 215 | + await asyncio.shield(self._task) | ||
| 216 | + if self._error is not None: | ||
| 217 | + raise self._error | ||
| 218 | + | ||
| 219 | + async def _run(self) -> None: | ||
| 220 | + try: | ||
| 221 | + config = web_protocol_config(self._app, ws_per_message_deflate=self._deflate) | ||
| 222 | + config.load() | ||
| 223 | + if self._single_request_http: | ||
| 224 | + config.http_protocol_class = _single_request_http_protocol(config.http_protocol_class) | ||
| 225 | + self._server = uvicorn.Server(config) | ||
| 226 | + self._server.servers = [] | ||
| 227 | + self._lifespan = _TrackedLifespan(config) | ||
| 228 | + self._server.lifespan = self._lifespan | ||
| 229 | + await asyncio.wait_for(self._lifespan.startup(), self._timeout) | ||
| 230 | + if self._lifespan.should_exit: | ||
| 231 | + raise RuntimeError("Web ASGI lifespan startup failed") | ||
| 232 | + await self._server.on_tick(0) | ||
| 233 | + self._server.started = True | ||
| 234 | + self._server.should_exit = self._stopping | ||
| 235 | + self._ready.set() | ||
| 236 | + counter = 0 | ||
| 237 | + while not self._server.should_exit: | ||
| 238 | + await asyncio.sleep(0.1) | ||
| 239 | + counter = (counter + 1) % 864000 | ||
| 240 | + self._server.should_exit = await self._server.on_tick(counter) | ||
| 241 | + self._states = { | ||
| 242 | + state for state in self._states | ||
| 243 | + if state.connections or state.tasks or self._state_handlers(state) | ||
| 244 | + } | ||
| 245 | + except BaseException as error: | ||
| 246 | + self._error = error | ||
| 247 | + finally: | ||
| 248 | + self._stopping = True | ||
| 249 | + try: | ||
| 250 | + await self._shutdown() | ||
| 251 | + except BaseException as error: | ||
| 252 | + self._shutdown_error = error | ||
| 253 | + if self._error is None: | ||
| 254 | + self._error = error | ||
| 255 | + self._ready.set() | ||
| 256 | + | ||
| 257 | + async def _shutdown(self) -> None: | ||
| 258 | + error = None | ||
| 259 | + try: | ||
| 260 | + await asyncio.wait_for(self._drain(), self._timeout) | ||
| 261 | + except BaseException as failure: | ||
| 262 | + error = failure | ||
| 263 | + try: | ||
| 264 | + await self._abort_connections() | ||
| 265 | + except BaseException as failure: | ||
| 266 | + error = failure | ||
| 267 | + lifespan = self._lifespan | ||
| 268 | + if lifespan is not None: | ||
| 269 | + try: | ||
| 270 | + if self._server is not None and self._server.started: | ||
| 271 | + await asyncio.wait_for(lifespan.shutdown(), self._timeout) | ||
| 272 | + if lifespan.shutdown_failed: | ||
| 273 | + raise RuntimeError("Web ASGI lifespan shutdown failed") | ||
| 274 | + except BaseException as failure: | ||
| 275 | + if error is None: | ||
| 276 | + error = failure | ||
| 277 | + finally: | ||
| 278 | + task = lifespan.main_task | ||
| 279 | + if task is not None and not task.done(): | ||
| 280 | + task.cancel() | ||
| 281 | + await asyncio.wait({task}, timeout=self._timeout) | ||
| 282 | + if not task.done() and error is None: | ||
| 283 | + error = RuntimeError("Web ASGI lifespan did not stop") | ||
| 284 | + if error is not None: | ||
| 285 | + raise error | ||
| 286 | + | ||
| 287 | + async def _drain(self) -> None: | ||
| 288 | + while self._adoptions: | ||
| 289 | + await asyncio.sleep(0.01) | ||
| 290 | + server = self._server | ||
| 291 | + if server is None: | ||
| 292 | + return | ||
| 293 | + for connection in tuple(server.server_state.connections): | ||
| 294 | + if isinstance(connection, server.config.ws_protocol_class): | ||
| 295 | + if connection.state in (State.OPEN, State.CLOSING): | ||
| 296 | + task = asyncio.create_task(connection.close(code=1001)) | ||
| 297 | + self._close_tasks.add(task) | ||
| 298 | + else: | ||
| 299 | + connection.transport.abort() | ||
| 300 | + else: | ||
| 301 | + connection.shutdown() | ||
| 302 | + while ( | ||
| 303 | + server.server_state.connections or server.server_state.tasks | ||
| 304 | + or self._handler_tasks() or any(not task.done() for task in self._close_tasks) | ||
| 305 | + ): | ||
| 306 | + await asyncio.sleep(0.01) | ||
| 307 | + for task in self._close_tasks: | ||
| 308 | + task.result() | ||
| 309 | + self._close_tasks.clear() | ||
| 310 | + self._states.clear() | ||
| 311 | + | ||
| 312 | + async def _abort_connections(self) -> None: | ||
| 313 | + tasks = set(self._adoptions) | ||
| 314 | + if self._server is not None: | ||
| 315 | + for connection in tuple(self._server.server_state.connections): | ||
| 316 | + connection.transport.abort() | ||
| 317 | + tasks.update(self._server.server_state.tasks) | ||
| 318 | + tasks.update(self._handler_tasks()) | ||
| 319 | + tasks.update(self._close_tasks) | ||
| 320 | + for task in tasks: | ||
| 321 | + task.cancel() | ||
| 322 | + if tasks: | ||
| 323 | + _done, pending = await asyncio.wait(tasks, timeout=self._timeout) | ||
| 324 | + if pending: | ||
| 325 | + raise RuntimeError("Web protocol tasks did not stop") | ||
| 326 | + for task in self._close_tasks: | ||
| 327 | + if not task.cancelled(): | ||
| 328 | + task.exception() | ||
| 329 | + self._close_tasks.clear() | ||
| 330 | + self._states.clear() | ||
| 331 | + await asyncio.sleep(0) | ||
| 332 | + | ||
| 333 | + def _handler_tasks(self) -> set[asyncio.Task]: | ||
| 334 | + return { | ||
| 335 | + task | ||
| 336 | + for state in self._states | ||
| 337 | + for task in self._state_handlers(state) | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + @staticmethod | ||
| 341 | + def _state_handlers(state: _ConnectionState) -> set[asyncio.Task]: | ||
| 342 | + return { | ||
| 343 | + connection.handler_task | ||
| 344 | + for connection in state.connections.seen | ||
| 345 | + if hasattr(connection, "handler_task") and not connection.handler_task.done() | ||
| 346 | + } | ||
| @@ -16,6 +16,10 @@ Entry points: `agent-gateway` (gateway + channels) and `agent-gateway-acp` (ACP | |||
| 16 | | `--dotenv <path>` | none | Load environment variables from the given `.env` at startup (startup phase only) | | 16 | | `--dotenv <path>` | none | Load environment variables from the given `.env` at startup (startup phase only) | |
| 17 | | `-h, --help` | none | Show help and exit | | 17 | | `-h, --help` | none | Show help and exit | |
| 18 | 18 | ||
| 19 | +### Local multiprocess trial | ||
| 20 | + | ||
| 21 | +Use `--mode multiprocess --workers 2` to start two Workers on loopback in the personal edition. The default remains single-process. The trial serves Web `/ws`, health probes and data operations over TUI/ACP, and connects to a single `ws://127.0.0.1:<port>` AgentServer. Keep using single mode for account management, Cron and optional channels. | ||
| 22 | + | ||
| 19 | ## Environment variables | 23 | ## Environment variables |
| 20 | 24 | ||
| 21 | ### Downstream AgentServer | 25 | ### Downstream AgentServer |
| @@ -16,6 +16,10 @@ | |||
| 16 | | `--dotenv <path>` | 无 | 启动时从指定 `.env` 加载环境变量(仅启动阶段生效) | | 16 | | `--dotenv <path>` | 无 | 启动时从指定 `.env` 加载环境变量(仅启动阶段生效) | |
| 17 | | `-h, --help` | 无 | 显示帮助并退出 | | 17 | | `-h, --help` | 无 | 显示帮助并退出 | |
| 18 | 18 | ||
| 19 | +### 本地多进程试点 | ||
| 20 | + | ||
| 21 | +仅用于个人版 IPv4 回环部署。显式使用 `--mode multiprocess --workers 2` 启动两个 Worker;省略 `--mode` 仍走原单进程。北向仅开放试点支持的 Web `/ws`、健康探针和 TUI/ACP 数据操作;南向连接单个 `ws://127.0.0.1:<端口>`。账号管理、Cron 和可选渠道请继续使用单进程。 | ||
| 22 | + | ||
| 19 | ## 环境变量 | 23 | ## 环境变量 |
| 20 | 24 | ||
| 21 | ### 下游 AgentServer | 25 | ### 下游 AgentServer |
| @@ -0,0 +1,75 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | + | ||
| 3 | +import asyncio | ||
| 4 | +from contextlib import closing | ||
| 5 | +import os | ||
| 6 | +import re | ||
| 7 | +import socket | ||
| 8 | +import sys | ||
| 9 | + | ||
| 10 | +import httpx | ||
| 11 | +import pytest | ||
| 12 | + | ||
| 13 | +from agent_gateway.processes.capabilities import management_preflight | ||
| 14 | +from testcases_gateway.stub_agent_server import StubAgentServer | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +@pytest.mark.skipif(not management_preflight().supported, reason="requires Linux/macOS fd passing") | ||
| 18 | +async def test_cli_starts_two_workers_and_releases_listeners_on_sigterm(tmp_path): | ||
| 19 | + env = { | ||
| 20 | + **os.environ, | ||
| 21 | + "HOME": str(tmp_path), | ||
| 22 | + "AGENT_GATEWAY_HOME": str(tmp_path), | ||
| 23 | + "AGENT_GATEWAY_DATA_DIR": str(tmp_path / "data"), | ||
| 24 | + "JIUWENSWARM_DATA_DIR": str(tmp_path / "data"), | ||
| 25 | + "JIUWENSWARM_HOME": str(tmp_path), | ||
| 26 | + "JIUWENSWARM_EDITION": "personal", | ||
| 27 | + "GATEWAY_HOST": "127.0.0.1", | ||
| 28 | + "GATEWAY_PORT": "0", | ||
| 29 | + "WEB_WS_PERMESSAGE_DEFLATE": "0", | ||
| 30 | + } | ||
| 31 | + stub = StubAgentServer().start() | ||
| 32 | + proc = None | ||
| 33 | + try: | ||
| 34 | + proc = await asyncio.create_subprocess_exec( | ||
| 35 | + sys.executable, "-m", "agent_gateway.app_gateway", "--mode", "multiprocess", | ||
| 36 | + "--workers", "2", "--host", "127.0.0.1", "--port", "0", "--web-path", "/ws", | ||
| 37 | + "--agent-server-url", stub.url, | ||
| 38 | + env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, | ||
| 39 | + ) | ||
| 40 | + lines = [] | ||
| 41 | + async with asyncio.timeout(40): | ||
| 42 | + while line := await proc.stdout.readline(): | ||
| 43 | + lines.append(line.decode(errors="replace")) | ||
| 44 | + ready = re.search(r"multiprocess_ready workers=2 web_port=(\d+) protocol_port=(\d+) " | ||
| 45 | + r"worker_pids=(\d+),(\d+)", lines[-1]) | ||
| 46 | + if ready: | ||
| 47 | + break | ||
| 48 | + else: | ||
| 49 | + pytest.fail("Gateway failed to become ready:\n" + "".join(lines[-25:])) | ||
| 50 | + web_port, protocol_port, *worker_pids = map(int, ready.groups()) | ||
| 51 | + async with httpx.AsyncClient(trust_env=False) as client: | ||
| 52 | + response = await client.get(f"http://127.0.0.1:{web_port}/healthz") | ||
| 53 | + assert response.json() == {"status": "ok"} | ||
| 54 | + assert response.headers["connection"] == "close" | ||
| 55 | + proc.terminate() | ||
| 56 | + await asyncio.wait_for(proc.communicate(), 15) | ||
| 57 | + assert proc.returncode == 0 | ||
| 58 | + for pid in worker_pids: | ||
| 59 | + with pytest.raises(ProcessLookupError): | ||
| 60 | + os.kill(pid, 0) | ||
| 61 | + for port in (web_port, protocol_port): | ||
| 62 | + with closing(socket.socket()) as listener: | ||
| 63 | + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| 64 | + listener.bind(("127.0.0.1", port)) | ||
| 65 | + finally: | ||
| 66 | + try: | ||
| 67 | + if proc is not None and proc.returncode is None: | ||
| 68 | + proc.terminate() | ||
| 69 | + try: | ||
| 70 | + await asyncio.wait_for(proc.communicate(), 15) | ||
| 71 | + except TimeoutError: | ||
| 72 | + proc.kill() | ||
| 73 | + await proc.wait() | ||
| 74 | + finally: | ||
| 75 | + await asyncio.to_thread(stub.stop) | ||
| @@ -0,0 +1,199 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Black-box tests of real child processes and the existing northbound handlers.""" | ||
| 3 | + | ||
| 4 | +import asyncio | ||
| 5 | +from contextlib import closing | ||
| 6 | +import json | ||
| 7 | +import os | ||
| 8 | +import signal | ||
| 9 | +import socket | ||
| 10 | + | ||
| 11 | +import httpx | ||
| 12 | +import pytest | ||
| 13 | +from websockets.asyncio.client import connect | ||
| 14 | +from websockets.exceptions import InvalidStatus | ||
| 15 | + | ||
| 16 | +from agent_gateway.application.worker_group import WorkerGroup | ||
| 17 | +from agent_gateway.common.ingress_identity import LocalIdentityPolicy, resolve_local_identity | ||
| 18 | +from agent_gateway.common.worker_affinity import FixedUserHash, WorkerManifest | ||
| 19 | +from agent_gateway.processes.capabilities import management_preflight | ||
| 20 | +from testcases_gateway.stub_agent_server import StubAgentServer | ||
| 21 | + | ||
| 22 | +pytestmark = pytest.mark.skipif(not management_preflight().supported, reason="requires Linux/macOS fd passing") | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +@pytest.fixture | ||
| 26 | +async def group(tmp_path, monkeypatch): | ||
| 27 | + for name, directory in (("HOME", "home"), ("JIUWENSWARM_HOME", "home"), | ||
| 28 | + ("JIUWENSWARM_DATA_DIR", "data"), ("AGENT_GATEWAY_DATA_DIR", "data"), | ||
| 29 | + ("AGENTOS_GATEWAY_LOG_DIR", "logs")): | ||
| 30 | + path = tmp_path / directory | ||
| 31 | + path.mkdir(exist_ok=True) | ||
| 32 | + monkeypatch.setenv(name, str(path)) | ||
| 33 | + monkeypatch.setenv("JIUWENSWARM_EDITION", "personal") | ||
| 34 | + stub = StubAgentServer().start() | ||
| 35 | + group = WorkerGroup(stub.url, workers=2, web_port=0, protocol_port=0, handoff_timeout=2) | ||
| 36 | + try: | ||
| 37 | + await group.start() | ||
| 38 | + yield group | ||
| 39 | + finally: | ||
| 40 | + try: | ||
| 41 | + await group.stop() | ||
| 42 | + finally: | ||
| 43 | + await asyncio.to_thread(stub.stop) | ||
| 44 | + assert all(process.returncode is not None for process in group.pool.processes) | ||
| 45 | + for address in group.addresses: | ||
| 46 | + with closing(socket.socket()) as listener: | ||
| 47 | + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
| 48 | + listener.bind(address) | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +async def test_web_stream_and_tui_acp_user_affinity(group): | ||
| 52 | + web_addr, protocol_addr = (f"{host}:{port}" for host, port in group.addresses) | ||
| 53 | + async with ( | ||
| 54 | + connect(f"ws://{web_addr}/ws?user_id=alice") as web, | ||
| 55 | + connect(f"ws://{protocol_addr}/tui", additional_headers={"X-User-Id": "alice"}) as tui, | ||
| 56 | + connect(f"ws://{protocol_addr}/acp?user_id=alice", additional_headers={"X-User-Id": "alice"}) as acp, | ||
| 57 | + ): | ||
| 58 | + assert json.loads(await asyncio.wait_for(acp.recv(), 5))["event"] == "connection.ack" | ||
| 59 | + await acp.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize"})) | ||
| 60 | + assert "result" in json.loads(await asyncio.wait_for(acp.recv(), 5)) | ||
| 61 | + await tui.send(json.dumps({"type": "req", "id": "tui-history", "method": "history.get", | ||
| 62 | + "params": {"session_id": "test-session"}})) | ||
| 63 | + async with asyncio.timeout(5): | ||
| 64 | + while True: | ||
| 65 | + frame = json.loads(await tui.recv()) | ||
| 66 | + if frame.get("id") == "tui-history": | ||
| 67 | + assert frame["ok"], frame | ||
| 68 | + break | ||
| 69 | + await web.send(json.dumps({"type": "req", "id": "web-stream", "method": "chat.send", "is_stream": True, | ||
| 70 | + "params": {"session_id": "test-session", "content": "hello"}})) | ||
| 71 | + events = [] | ||
| 72 | + async with asyncio.timeout(5): | ||
| 73 | + while "chat.final" not in events: | ||
| 74 | + events.append(json.loads(await web.recv()).get("event")) | ||
| 75 | + assert "chat.delta" in events | ||
| 76 | + assert sorted(group.pool.adopted_counts) == [0, 3] | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +async def test_http_connection_is_not_reused_and_conflicting_identity_is_rejected(group): | ||
| 80 | + web_addr, protocol_addr = (f"{host}:{port}" for host, port in group.addresses) | ||
| 81 | + async with httpx.AsyncClient(trust_env=False) as client: | ||
| 82 | + response = await client.get(f"http://{web_addr}/healthz?user_id=alice") | ||
| 83 | + assert response.status_code == 200 | ||
| 84 | + assert response.headers["connection"] == "close" | ||
| 85 | + assert response.headers["content-type"].startswith("application/json") | ||
| 86 | + assert response.json() == {"status": "ok"} | ||
| 87 | + rejected = await client.get(f"http://{web_addr}/healthz?user_id=bob", | ||
| 88 | + headers={"X-User-Id": "alice"}) | ||
| 89 | + assert rejected.status_code == 400 | ||
| 90 | + with pytest.raises(InvalidStatus) as error: | ||
| 91 | + async with connect(f"ws://{protocol_addr}/acp?user_id=bob", additional_headers={"X-User-Id": "alice"}): | ||
| 92 | + pytest.fail("conflicting identity is not admissible") | ||
| 93 | + assert error.value.response.status_code == 400 | ||
| 94 | + assert sum(group.pool.adopted_counts) == 1 | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +async def test_pipelined_http_finishes_only_the_first_response(group): | ||
| 98 | + reader, writer = await asyncio.open_connection(*group.addresses[0]) | ||
| 99 | + try: | ||
| 100 | + for user in (b"alice", b"bob"): | ||
| 101 | + writer.write(b"GET /healthz?user_id=" + user + b" HTTP/1.1\r\nHost: localhost\r\n\r\n") | ||
| 102 | + await writer.drain() | ||
| 103 | + output = await asyncio.wait_for(reader.read(), 5) | ||
| 104 | + headers, body = output.split(b"\r\n\r\n", 1) | ||
| 105 | + assert headers.startswith(b"HTTP/1.1 200 OK") | ||
| 106 | + assert b"connection: close" in headers.lower() | ||
| 107 | + assert json.loads(body) == {"status": "ok"} | ||
| 108 | + finally: | ||
| 109 | + writer.close() | ||
| 110 | + await writer.wait_closed() | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +async def test_user_burst_stays_on_owner_and_both_slots_are_reachable(group): | ||
| 114 | + host, port = group.addresses[0] | ||
| 115 | + policy = LocalIdentityPolicy() | ||
| 116 | + affinity = FixedUserHash(WorkerManifest(group.pool.slots), policy) | ||
| 117 | + users = {} | ||
| 118 | + for index in range(50): | ||
| 119 | + user = f"user-{index}" | ||
| 120 | + identity = resolve_local_identity(f"user_id={user}".encode(), (), entry="web", policy=policy) | ||
| 121 | + users.setdefault(affinity.select(identity), user) | ||
| 122 | + assert set(users) == {0, 1} | ||
| 123 | + | ||
| 124 | + async def open_and_confirm(user): | ||
| 125 | + async with connect(f"ws://{host}:{port}/ws?user_id={user}", proxy=None, open_timeout=5) as ws: | ||
| 126 | + assert json.loads(await asyncio.wait_for(ws.recv(), 5))["event"] == "connection.ack" | ||
| 127 | + | ||
| 128 | + await asyncio.gather(*(open_and_confirm(users[0]) for _ in range(8)), open_and_confirm(users[1])) | ||
| 129 | + assert group.pool.adopted_counts == (8, 1) | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +async def test_stopping_during_spawn_reaps_the_child(tmp_path, monkeypatch): | ||
| 133 | + spawned = asyncio.Event() | ||
| 134 | + hold_spawn = asyncio.Event() | ||
| 135 | + real_spawn = asyncio.create_subprocess_exec | ||
| 136 | + | ||
| 137 | + async def delayed_spawn(*args, **kwargs): | ||
| 138 | + process = await real_spawn(*args, **kwargs) | ||
| 139 | + spawned.set() | ||
| 140 | + await hold_spawn.wait() | ||
| 141 | + return process | ||
| 142 | + | ||
| 143 | + monkeypatch.setattr(asyncio, "create_subprocess_exec", delayed_spawn) | ||
| 144 | + monkeypatch.setenv("HOME", str(tmp_path)) | ||
| 145 | + group = WorkerGroup("ws://127.0.0.1:1", workers=2, web_port=0, protocol_port=0) | ||
| 146 | + start = asyncio.create_task(group.start()) | ||
| 147 | + stop = None | ||
| 148 | + try: | ||
| 149 | + await asyncio.wait_for(spawned.wait(), 5) | ||
| 150 | + stop = asyncio.create_task(group.stop()) | ||
| 151 | + await asyncio.sleep(0) | ||
| 152 | + await asyncio.sleep(0) | ||
| 153 | + finally: | ||
| 154 | + hold_spawn.set() | ||
| 155 | + if stop is not None: | ||
| 156 | + await asyncio.wait_for(stop, 20) | ||
| 157 | + else: | ||
| 158 | + await group.stop() | ||
| 159 | + result, = await asyncio.gather(start, return_exceptions=True) | ||
| 160 | + assert isinstance(result, asyncio.CancelledError) | ||
| 161 | + assert len(group.pool.processes) == 1 | ||
| 162 | + assert group.pool.processes[0].returncode is not None | ||
| 163 | + assert not group.addresses | ||
| 164 | + | ||
| 165 | + | ||
| 166 | +async def test_missing_ack_stops_group_and_does_not_retry_another_slot(group): | ||
| 167 | + policy = LocalIdentityPolicy() | ||
| 168 | + affinity = FixedUserHash(WorkerManifest(group.pool.slots), policy) | ||
| 169 | + identity = resolve_local_identity(b"user_id=alice", (), entry="http", policy=policy) | ||
| 170 | + worker = group.pool.processes[affinity.select(identity)] | ||
| 171 | + worker.send_signal(signal.SIGSTOP) | ||
| 172 | + reader, writer = await asyncio.open_connection(*group.addresses[0]) | ||
| 173 | + try: | ||
| 174 | + writer.write(b"GET /healthz?user_id=alice HTTP/1.1\r\nHost: localhost\r\n\r\n") | ||
| 175 | + await writer.drain() | ||
| 176 | + # Pool failure initiates shutdown. Resume only after the ACK deadline so | ||
| 177 | + # the test process can be reaped without waiting for the kill fallback. | ||
| 178 | + with pytest.raises(RuntimeError, match="handoff channel closed"): | ||
| 179 | + await asyncio.wait_for(group.pool.wait(), 5) | ||
| 180 | + finally: | ||
| 181 | + if worker.returncode is None: | ||
| 182 | + worker.send_signal(signal.SIGCONT) | ||
| 183 | + writer.close() | ||
| 184 | + await writer.wait_closed() | ||
| 185 | + with pytest.raises(RuntimeError, match="handoff channel closed"): | ||
| 186 | + await asyncio.wait_for(group.wait(), 10) | ||
| 187 | + assert reader.at_eof() | ||
| 188 | + assert group.pool.adopted_counts == (0, 0) | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +async def test_client_eof_and_worker_exit_release_listeners_and_workers(group): | ||
| 192 | + _, writer = await asyncio.open_connection(*group.addresses[0]) | ||
| 193 | + writer.write(b"GET /ws HTTP/1.1\r\n") | ||
| 194 | + await writer.drain() | ||
| 195 | + writer.close() | ||
| 196 | + await writer.wait_closed() | ||
| 197 | + os.kill(group.pool.processes[0].pid, signal.SIGKILL) | ||
| 198 | + with pytest.raises(RuntimeError, match="Worker 0"): | ||
| 199 | + await asyncio.wait_for(group.wait(), 10) | ||
| @@ -0,0 +1,43 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | +import sys | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +@pytest.mark.parametrize( | ||
| 10 | + "arguments,expected", | ||
| 11 | + [ | ||
| 12 | + (["--workers", "2"], "--workers requires --mode multiprocess"), | ||
| 13 | + (["--mode", "multiprocess", "--workers", "0"], "--workers must be between 1 and 32"), | ||
| 14 | + (["--mode", "multiprocess", "--host", "0.0.0.0"], "loopback"), | ||
| 15 | + ], | ||
| 16 | +) | ||
| 17 | +def test_rejects_unsupported_cli_options(monkeypatch, capsys, arguments, expected): | ||
| 18 | + from agent_gateway import app_gateway | ||
| 19 | + | ||
| 20 | + monkeypatch.setattr(sys, "argv", ["agent-gateway", *arguments]) | ||
| 21 | + with pytest.raises(SystemExit) as error: | ||
| 22 | + app_gateway.main() | ||
| 23 | + assert error.value.code == 2 | ||
| 24 | + assert expected in capsys.readouterr().err | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +@pytest.mark.parametrize("jobs,blocked", [([], False), ([{"enabled": True}], True), ([None], True)]) | ||
| 28 | +async def test_trial_never_consumes_or_migrates_existing_cron_jobs(tmp_path, monkeypatch, jobs, blocked): | ||
| 29 | + from agent_gateway.application.multiprocess import validate_workspace | ||
| 30 | + from agent_gateway.common import config, cron_settings | ||
| 31 | + | ||
| 32 | + store = tmp_path / "cron_jobs.json" | ||
| 33 | + original = json.dumps({"jobs": jobs}) | ||
| 34 | + store.write_text(original, encoding="utf-8") | ||
| 35 | + monkeypatch.setattr(config, "get_config", dict) | ||
| 36 | + monkeypatch.setattr(cron_settings, "get_cron_jobs_path", lambda: store) | ||
| 37 | + if blocked: | ||
| 38 | + with pytest.raises(ValueError, match="Cron"): | ||
| 39 | + await validate_workspace() | ||
| 40 | + else: | ||
| 41 | + await validate_workspace() | ||
| 42 | + assert store.read_text(encoding="utf-8") == original | ||
| 43 | + assert sorted(tmp_path.iterdir()) == [store] | ||