Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11132): handle ClientDisconnect in raw-request logging middleware (#6659)
Aaron Perez595164f9b2ba
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.pyindex 955f7592f..f51635344 100644--- a/skyvern/forge/api_app.py+++ b/skyvern/forge/api_app.py@@ -21,7 +21,7 @@ from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.openapi.utils import get_openapifrom fastapi.responses import JSONResponsefrom fastapi.routing import APIRoute-from starlette.requests import HTTPConnection, Request+from starlette.requests import ClientDisconnect, HTTPConnection, Requestfrom starlette_context.middleware import RawContextMiddlewarefrom starlette_context.plugins.base import Plugin@@ -391,6 +391,13 @@ def create_api_app() -> FastAPI:content={"detail": detail},)+ @fastapi_app.exception_handler(ClientDisconnect)+ async def handle_client_disconnect(request: Request, exc: ClientDisconnect) -> Response:+ # Client closed the connection mid-request (e.g. while a route reads the body).+ # There is no one to respond to, so return a quiet 499 instead of letting it+ # fall through to the 500 handler and pollute error tracking.+ return Response(status_code=499)+@fastapi_app.exception_handler(Exception)async def unexpected_exception(request: Request, exc: Exception) -> JSONResponse:LOG.exception("Unexpected error in agent server.", exc_info=exc)diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.pyindex d81896ed4..f96db6a60 100644--- a/skyvern/forge/request_logging.py+++ b/skyvern/forge/request_logging.py@@ -6,13 +6,14 @@ import typingimport structlogfrom starlette.concurrency import iterate_in_threadpool+from starlette.requests import ClientDisconnect+from starlette.responses import Responsefrom skyvern.config import settingsif typing.TYPE_CHECKING: # pragma: no cover - import only for type hintsfrom typing import Awaitable, Callable- from fastapi import Responsefrom starlette.requests import RequestLOG = structlog.get_logger()@@ -174,7 +175,15 @@ async def log_raw_request_middleware(request: Request, call_next: Callable[[Requreturn await call_next(request)start_time = time.monotonic()- body_bytes = await request.body()+ try:+ body_bytes = await request.body()+ except ClientDisconnect:+ # The client closed the connection before the body finished streaming, so no+ # response will reach it. Short-circuit with a benign 499 instead of letting+ # the disconnect escape this BaseHTTPMiddleware (which wraps it in an+ # ExceptionGroup) and surface as an unhandled error in tracking.+ LOG.info("api.client_disconnect", method=request.method, path=request.url.path)+ return Response(status_code=499)# ensure downstream handlers can access body againtry:request._body = body_bytes # type: ignore[attr-defined]diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.pyindex 692373920..2f57bb27b 100644--- a/tests/unit/test_request_logging.py+++ b/tests/unit/test_request_logging.py@@ -1,11 +1,12 @@from __future__ import annotationsimport json-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytestfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClient+from starlette.requests import ClientDisconnectfrom skyvern.forge import request_loggingfrom skyvern.forge.request_logging import (@@ -458,3 +459,37 @@ class TestMiddlewareLogVolume:client = TestClient(_make_app())client.post("/tasks")log_mock.info.assert_not_called()+++class TestClientDisconnectDuringBodyRead:+ """A client closing the connection mid-body must not surface as an unhandled error."""++ @pytest.mark.asyncio+ async def test_disconnect_short_circuits_without_error_log(self, log_mock: MagicMock) -> None:+ request = MagicMock()+ request.method = "POST"+ request.url.path = "/v1/tasks"+ request.body = AsyncMock(side_effect=ClientDisconnect())+ call_next = AsyncMock()++ response = await log_raw_request_middleware(request, call_next)++ assert response.status_code == 499+ call_next.assert_not_awaited()+ log_mock.error.assert_not_called()+ log_mock.exception.assert_not_called()++ @pytest.mark.asyncio+ async def test_disconnect_when_logging_disabled_still_calls_downstream(+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(request_logging.settings, "LOG_RAW_API_REQUESTS", False)+ request = MagicMock()+ request.body = AsyncMock(side_effect=ClientDisconnect())+ sentinel = MagicMock()+ call_next = AsyncMock(return_value=sentinel)++ response = await log_raw_request_middleware(request, call_next)++ assert response is sentinel+ request.body.assert_not_awaited()