diff --git a/CHANGELOG.md b/CHANGELOG.md index 502c99b..376fe77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- Fixed the HTTP server stalling while RaaS answers slowly: the `/token` credential + check and the per-request RaaS login and RPC in the dispatcher are synchronous + (`httpx.Client`) but ran inside async handlers, so one slow RaaS call blocked the + whole event loop (health probes, `/mcp`, other `/token` calls). A rejected login + took ~30 s on a loaded RaaS and, with the Helm chart's default liveness probe + (1 s timeout, 3 failures), got the pod restarted. They now run in worker threads + (`asyncio.to_thread`); the stdio transport's shared client is unchanged. + - Migrated to the `mcp` python-sdk 2.x line (`mcp>=2.3.0,<3`, closes #9): tool handlers are now passed to the `Server` constructor (`on_list_tools` / `on_call_tool`), bearer-auth types are imported from diff --git a/raas_mcp/auth/token_endpoint.py b/raas_mcp/auth/token_endpoint.py index 246e550..6e280c7 100644 --- a/raas_mcp/auth/token_endpoint.py +++ b/raas_mcp/auth/token_endpoint.py @@ -13,6 +13,7 @@ from __future__ import annotations +import asyncio import base64 import logging from typing import Any @@ -105,7 +106,11 @@ async def token_handler(request: Request) -> Response: ) raas_user, raas_password = creds - valid = _validate_raas_credentials( + # The RaaS login is synchronous (httpx.Client) and can take tens of seconds + # (a rejected login is slow on a loaded RaaS). Run it in a worker thread so the + # event loop keeps serving /health/*, /mcp and other /token requests meanwhile. + valid = await asyncio.to_thread( + _validate_raas_credentials, raas_url, raas_user, raas_password, diff --git a/raas_mcp/dispatcher.py b/raas_mcp/dispatcher.py index 520192b..c82f247 100644 --- a/raas_mcp/dispatcher.py +++ b/raas_mcp/dispatcher.py @@ -24,6 +24,7 @@ from __future__ import annotations +import asyncio from typing import Any from mcp import types as mcp_types @@ -60,7 +61,10 @@ async def dispatch( Returns a list containing exactly one TextContent whose ``.text`` is a JSON object matching ``contracts/mcp-tool-result.schema.json``. """ - # Resolve which client to use + # Resolve which client to use. A per-request client (HTTP transport) is private to this call, + # so its blocking login and RPC run in worker threads and never stall the event loop. The shared + # client of the stdio transport is not thread-safe and is used as before. + per_request_client = client is _SENTINEL if client is _SENTINEL: if vidb_jwt: # VIDB JWT path: forward the JWT as a Bearer token to RaaS @@ -70,13 +74,14 @@ async def dispatch( "HTTP transport (VIDB path): raas_url is required.", ) try: - resolved_client = connect_from_mapping( + resolved_client = await asyncio.to_thread( + connect_from_mapping, { "raas": raas_url, "auth_token": vidb_jwt, "timeout": raas_timeout, "insecure": raas_insecure, - } + }, ) except Exception as exc: return error_result( @@ -92,13 +97,14 @@ async def dispatch( "when no shared client is provided.", ) try: - resolved_client = connect_from_mapping( + resolved_client = await asyncio.to_thread( + connect_from_mapping, { "raas": raas_url, "auth": f"{raas_user}:{raas_password}", "timeout": raas_timeout, "insecure": raas_insecure, - } + }, ) except Exception as exc: return error_result( @@ -147,7 +153,10 @@ async def dispatch( try: resource_obj = getattr(resolved_client.api, entry.resource) method_fn = getattr(resource_obj, entry.method) - ret = method_fn(**arguments) + if per_request_client: + ret = await asyncio.to_thread(method_fn, **arguments) + else: + ret = method_fn(**arguments) return success_result(entry.resource, entry.method, ret) except (ConnectionError, OSError) as exc: return error_result( diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index c93b93c..4420363 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_dispatcher.py @@ -312,3 +312,48 @@ async def test_vidb_path_requires_raas_url(): data = json.loads(result[0].text) assert data["ok"] is False assert data["error"]["code"] == "RAAS_RPC_ERROR" + + +# --------------------------------------------------------------------------- +# Per-request (HTTP) clients: blocking login and RPC must not block the event loop +# --------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_http_path_does_not_block_event_loop(): + import asyncio + import time + + def slow_connect(_mapping): + time.sleep(0.5) # blocking RaaS login + client = MagicMock() + + def slow_rpc(**_kw): + time.sleep(0.5) # blocking RaaS RPC + return {"ret": ["m1"]} + + client.api.ret.get_minions.side_effect = slow_rpc + return client + + ticks: list[float] = [] + + async def ticker(): + while True: + ticks.append(time.monotonic()) + await asyncio.sleep(0.05) + + task = asyncio.create_task(ticker()) + try: + with patch("raas_mcp.dispatcher.connect_from_mapping", side_effect=slow_connect): + result = await dispatch( + "ret_get_minions", {}, + catalog_entries=_catalog(_entry()), + approval_gate=[], + ctx=None, + raas_user="u", raas_password="p", raas_url="http://raas.test", + ) + finally: + task.cancel() + assert json.loads(result[0].text)["ok"] is True + # The call took ~1 s; a blocked loop would leave a gap of ~0.5 s between ticks. + gaps = [b - a for a, b in zip(ticks, ticks[1:], strict=False)] + assert len(ticks) > 10 and max(gaps) < 0.25, (len(ticks), max(gaps, default=None)) diff --git a/tests/test_token_endpoint.py b/tests/test_token_endpoint.py index 2691295..99f508c 100644 --- a/tests/test_token_endpoint.py +++ b/tests/test_token_endpoint.py @@ -119,3 +119,48 @@ def test_two_requests_produce_distinct_tokens(): r1 = client.post("/token", headers={"Authorization": _basic_header("alice", "pw")}) r2 = client.post("/token", headers={"Authorization": _basic_header("alice", "pw")}) assert r1.json()["access_token"] != r2.json()["access_token"] + + +# ----------------------------------------------------------------------- +# A slow RaaS login must not block the event loop (health checks, other requests) +# ----------------------------------------------------------------------- + +async def test_slow_credential_check_does_not_block_event_loop(): + import asyncio + import time + + import httpx + + def slow_validate(*_args, **_kwargs): + time.sleep(0.8) # a blocking RaaS login + return True + + store = TokenStore(token_ttl_seconds=60) + handler = build_token_handler(store, raas_url="http://raas.test", raas_insecure=False) + + async def token_route(request): + return await handler(request) + + app = Starlette(routes=[Route("/token", token_route, methods=["POST"])]) + transport = httpx.ASGITransport(app=app) + + ticks: list[float] = [] + + async def ticker(): # stands in for /health/live, /mcp and other requests sharing the loop + while True: + ticks.append(time.monotonic()) + await asyncio.sleep(0.05) + + ticker_task = asyncio.create_task(ticker()) + try: + target = "raas_mcp.auth.token_endpoint._validate_raas_credentials" + with patch(target, side_effect=slow_validate): + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + auth = {"Authorization": _basic_header("u", "p")} + resp = await client.post("/token", headers=auth) + finally: + ticker_task.cancel() + assert resp.status_code == 200 + # The login took ~0.8 s; with the call on the event loop there is one ~0.8 s gap between ticks. + gaps = [b - a for a, b in zip(ticks, ticks[1:], strict=False)] + assert len(ticks) > 8 and max(gaps) < 0.3, (len(ticks), max(gaps, default=None))