Skip to content

Commit

Permalink
rapu: catch aiohttp.ClientError with a 503 response status
Browse files Browse the repository at this point in the history
  • Loading branch information
nosahama committed Jun 7, 2024
1 parent a189931 commit 47aff6f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
4 changes: 2 additions & 2 deletions karapace/rapu.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,11 +393,11 @@ async def _handle_request(
)
headers = {"Content-Type": "application/json"}
resp = aiohttp.web.Response(body=body, status=status.value, headers=headers)
except ConnectionError as connection_error:
except (ConnectionError, aiohttp.ClientError) as connection_error:
# TCP level connection errors, e.g. TCP reset, client closes connection.
self.log.debug("Connection error.", exc_info=connection_error)
# No response can be returned and written to client, aiohttp expects some response here.
resp = aiohttp.web.Response(text="Connection error", status=HTTPStatus.INTERNAL_SERVER_ERROR.value)
resp = aiohttp.web.Response(text="Connection error", status=HTTPStatus.SERVICE_UNAVAILABLE.value)
except asyncio.CancelledError:
self.log.debug("Client closed connection")
raise
Expand Down
10 changes: 7 additions & 3 deletions tests/unit/test_rapu.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
Copyright (c) 2023 Aiven Ltd
See LICENSE for details
"""
from aiohttp.client_exceptions import ClientConnectionError
from aiohttp.web import Request
from karapace.config import DEFAULTS
from karapace.karapace import KarapaceBase
from karapace.rapu import HTTPRequest, REST_ACCEPT_RE, REST_CONTENT_TYPE_RE
from unittest.mock import Mock

import pytest


async def test_header_get():
req = HTTPRequest(url="", query="", headers={}, path_for_stats="", method="GET")
Expand Down Expand Up @@ -160,9 +163,10 @@ def test_content_type_re():
}


async def test_raise_connection_error_handling() -> None:
@pytest.mark.parametrize("connection_error", (ConnectionError(), ClientConnectionError()))
async def test_raise_connection_error_handling(connection_error: BaseException) -> None:
request_mock = Mock(spec=Request)
request_mock.read.side_effect = ConnectionError("Connection error test.")
request_mock.read.side_effect = connection_error
callback_mock = Mock()

app = KarapaceBase(config=DEFAULTS)
Expand All @@ -173,6 +177,6 @@ async def test_raise_connection_error_handling() -> None:
callback=callback_mock,
)

assert response.status == 500
assert response.status == 503
request_mock.read.assert_has_calls([])
callback_mock.assert_not_called()

0 comments on commit 47aff6f

Please sign in to comment.