Handle WebSocket client disconnect during prepare (#124173)

This commit is contained in:
J. Nick Koston 2024-08-19 15:28:05 -05:00 committed by GitHub
parent fc767ee562
commit 108a54a4a8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 27 additions and 2 deletions

View File

@ -306,6 +306,13 @@ class WebSocketHandler:
try:
async with asyncio.timeout(10):
await wsock.prepare(request)
except ConnectionResetError:
# Likely the client disconnected before we prepared the websocket
logger.debug(
"%s: Connection reset by peer while preparing WebSocket",
self.description,
)
return wsock
except TimeoutError:
logger.warning("Timeout preparing request from %s", request.remote)
return wsock

View File

@ -363,12 +363,12 @@ async def test_non_json_message(
assert "bad=<object" in caplog.text
async def test_prepare_fail(
async def test_prepare_fail_timeout(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test failing to prepare."""
"""Test failing to prepare due to timeout."""
with (
patch(
"homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
@ -381,6 +381,24 @@ async def test_prepare_fail(
assert "Timeout preparing request" in caplog.text
async def test_prepare_fail_connection_reset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test failing to prepare due to connection reset."""
with (
patch(
"homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
side_effect=(ConnectionResetError, web.WebSocketResponse.prepare),
),
pytest.raises(WSServerHandshakeError),
):
await hass_ws_client(hass)
assert "Connection reset by peer while preparing WebSocket" in caplog.text
async def test_enable_coalesce(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,