diff --git a/src/functions_framework/aio/__init__.py b/src/functions_framework/aio/__init__.py index a56fe942..ad0e17d3 100644 --- a/src/functions_framework/aio/__init__.py +++ b/src/functions_framework/aio/__init__.py @@ -181,8 +181,16 @@ async def __call__(self, scope, receive, send): await self.app(scope, receive, send) return + response_started = False + + async def send_with_state(message): + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + await send(message) + try: - await self.app(scope, receive, send) + await self.app(scope, receive, send_with_state) except Exception as exc: logger = logging.getLogger() tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__) @@ -194,6 +202,14 @@ async def __call__(self, scope, receive, send): logger.error(error_msg) + if response_started: + # The status line is already on the wire, so the only thing we could + # still send is a body. Sending another response start here is an + # invalid ASGI message sequence and the server rejects it, which + # replaces the traceback above with a confusing protocol error. Let + # the connection end instead; the client sees a truncated response. + return + headers = [ [b"content-type", b"text/plain"], [_FUNCTION_STATUS_HEADER_FIELD.encode(), _CRASH.encode()], diff --git a/tests/test_aio.py b/tests/test_aio.py index e7533b1d..10f69e04 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging import pathlib import re import sys @@ -26,6 +27,7 @@ from functions_framework import exceptions from functions_framework.aio import ( + ExceptionHandlerMiddleware, LazyASGIApp, _cloudevent_func_wrapper, _http_func_wrapper, @@ -169,3 +171,58 @@ def sync_cloud_event(event): assert called_with_event is not None assert called_with_event["type"] == "test.event" assert called_with_event["source"] == "test-source" + + +@pytest.mark.asyncio +async def test_exception_handler_middleware_returns_crash_response(caplog): + async def failing_app(scope, receive, send): + raise ValueError("boom") + + middleware = ExceptionHandlerMiddleware(failing_app) + sent = [] + + async def send(message): + sent.append(message) + + with caplog.at_level(logging.ERROR): + await middleware( + {"type": "http", "method": "GET", "path": "/"}, AsyncMock(), send + ) + + assert [message["type"] for message in sent] == [ + "http.response.start", + "http.response.body", + ] + assert sent[0]["status"] == 500 + assert [b"X-Google-Status", b"crash"] in sent[0]["headers"] + assert "boom" in caplog.text + + +@pytest.mark.asyncio +async def test_exception_handler_middleware_after_response_started(caplog): + async def failing_stream(scope, receive, send): + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send( + {"type": "http.response.body", "body": b"first chunk", "more_body": True} + ) + raise ValueError("boom mid-stream") + + middleware = ExceptionHandlerMiddleware(failing_stream) + sent = [] + + async def send(message): + sent.append(message) + + with caplog.at_level(logging.ERROR): + await middleware( + {"type": "http", "method": "GET", "path": "/"}, AsyncMock(), send + ) + + # The response start was already sent, so there is nothing left to send: an + # extra response start would be an invalid ASGI message sequence. + assert [message["type"] for message in sent] == [ + "http.response.start", + "http.response.body", + ] + assert sent[0]["status"] == 200 + assert "boom mid-stream" in caplog.text