Limit the websocket close to 0.25 s while Home Assistant stops (#195585)

Co-authored-by: Luuk Visser <3588293+luukvisser@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Luuk Visser
2026-12-01 18:17:37 +00:00
committed by GitHub
co-authored by Luuk Visser Claude Opus 5.5
parent 173f504b28
commit 0ead9a8e25
2 changed files with 146 additions and 3 deletions
+10 -1
View File
@@ -3,6 +3,7 @@
import asyncio
from collections import deque
from collections.abc import Callable, Coroutine
import contextlib
import datetime as dt
from functools import partial
import logging
@@ -45,6 +46,7 @@ if TYPE_CHECKING:
CLOSE_MSG_TYPES = {WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING}
AUTH_MESSAGE_TIMEOUT = 10 # seconds
CLOSE_TIMEOUT_AT_STOP = 0.25 # seconds
_WS_LOGGER: Final = logging.getLogger(f"{__name__}.connection")
@@ -567,7 +569,14 @@ class WebSocketHandler:
finally:
try:
# Make sure all error messages are written before closing
await wsock.close()
if not hass.is_stopping:
await wsock.close()
else:
# Once the HTTP server shuts down, aiohttp reads no more
# data, so the answer may never be seen; don't wait 10 s
with contextlib.suppress(TimeoutError):
async with asyncio.timeout(CLOSE_TIMEOUT_AT_STOP):
await wsock.close()
finally:
if disconnect_warn is None:
logger.debug("%s: Disconnected", self.description)
+136 -2
View File
@@ -1,13 +1,21 @@
"""Test Websocket API http module."""
import asyncio
from collections.abc import Generator
from datetime import timedelta
import logging
from typing import Any, cast
from unittest.mock import patch
from aiohttp import ClientConnectionResetError, ServerDisconnectedError, WSMsgType, web
from aiohttp import (
ClientConnectionResetError,
ServerDisconnectedError,
WSCloseCode,
WSMsgType,
web,
)
from aiohttp.http import WebSocketWriter
from aiohttp.http_writer import StreamWriter
import pytest
from pytest_homeassistant.common import (
async_call_logger_set_level,
@@ -31,7 +39,8 @@ from homeassistant.components.websocket_api.auth import (
AUTH_REQUIRED_MESSAGE,
)
from homeassistant.components.websocket_api.connection import ActiveConnection
from homeassistant.core import HomeAssistant, callback
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import CoreState, HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.redact import REDACTED
from homeassistant.setup import async_setup_component
@@ -52,6 +61,33 @@ def mock_low_peak():
yield
@pytest.fixture
def server_closes() -> Generator[asyncio.Queue[web.WebSocketResponse]]:
"""Queue each server-side websocket when its close starts."""
closes: asyncio.Queue[web.WebSocketResponse] = asyncio.Queue()
close = web.WebSocketResponse.close
async def queue_and_close(self: web.WebSocketResponse, **kwargs: Any) -> bool:
closes.put_nowait(self)
return await close(self, **kwargs)
with patch.object(web.WebSocketResponse, "close", queue_and_close):
yield closes
@pytest.fixture
def disconnected(hass: HomeAssistant) -> asyncio.Event:
"""Set when the server has finished closing a websocket."""
event = asyncio.Event()
@callback
def set_event() -> None:
event.set()
async_dispatcher_connect(hass, const.SIGNAL_WEBSOCKET_DISCONNECTED, set_event)
return event
async def test_pending_msg_overflow(
hass: HomeAssistant, mock_low_queue, websocket_client: MockHAClientWebSocket
) -> None:
@@ -705,3 +741,101 @@ async def test_received_secrets_are_redacted_in_debug_log(
assert "nested-secret" not in received
assert "batched" not in received
assert received.count(REDACTED) == 3
@pytest.mark.parametrize(
("state", "close_code"),
[
pytest.param(CoreState.not_running, WSCloseCode.OK, id="not_running"),
pytest.param(CoreState.running, WSCloseCode.OK, id="running"),
pytest.param(CoreState.stopping, WSCloseCode.ABNORMAL_CLOSURE, id="stopping"),
pytest.param(
CoreState.final_write, WSCloseCode.ABNORMAL_CLOSURE, id="final_write"
),
],
)
async def test_close_waits_for_late_answer_unless_stopping(
hass: HomeAssistant,
websocket_client: MockHAClientWebSocket,
server_closes: asyncio.Queue[web.WebSocketResponse],
disconnected: asyncio.Event,
state: CoreState,
close_code: WSCloseCode,
) -> None:
"""Test the server stops waiting for the close answer only while stopping."""
hass.set_state(state)
await websocket_client.send_str("[--INVALID-JSON--]")
server_wsock = await server_closes.get()
# The client answers the close frame only after the stop timeout passed
async_fire_time_changed(hass, utcnow() + timedelta(seconds=2))
assert (await websocket_client.receive()).type is WSMsgType.CLOSE
await disconnected.wait()
assert server_wsock.close_code == close_code
@pytest.mark.parametrize(
("stop_timeout", "answer_after", "close_code"),
[
# A timeout real time cannot reach, so the answer always comes first
pytest.param(10, timedelta(0), WSCloseCode.OK, id="answers_at_once"),
pytest.param(
1, timedelta(seconds=2), WSCloseCode.ABNORMAL_CLOSURE, id="answers_late"
),
],
)
async def test_stop_does_not_wait_for_close_answer(
hass: HomeAssistant,
websocket_client: MockHAClientWebSocket,
server_closes: asyncio.Queue[web.WebSocketResponse],
disconnected: asyncio.Event,
caplog: pytest.LogCaptureFixture,
stop_timeout: float,
answer_after: timedelta,
close_code: WSCloseCode,
) -> None:
"""Test the stop closes websockets without waiting long for the answer."""
hass.set_state(CoreState.stopping)
with patch(
"homeassistant.components.websocket_api.http.CLOSE_TIMEOUT_AT_STOP",
stop_timeout,
):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
server_wsock = await server_closes.get()
async_fire_time_changed(hass, utcnow() + answer_after)
assert (await websocket_client.receive()).type is WSMsgType.CLOSE
await disconnected.wait()
assert websocket_client.close_code == WSCloseCode.OK
assert server_wsock.close_code == close_code
assert not [
record for record in caplog.records if record.levelno >= logging.WARNING
]
@pytest.mark.usefixtures("websocket_client")
async def test_stop_does_not_wait_for_stalled_drain(
hass: HomeAssistant,
server_closes: asyncio.Queue[web.WebSocketResponse],
disconnected: asyncio.Event,
) -> None:
"""Test the stop does not wait for a close whose drain never ends."""
stall: asyncio.Future[None] = hass.loop.create_future()
async def stalled_drain(self: StreamWriter) -> None:
await asyncio.shield(stall)
hass.set_state(CoreState.stopping)
try:
with patch.object(StreamWriter, "drain", stalled_drain):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
server_wsock = await server_closes.get()
async_fire_time_changed(hass, utcnow() + timedelta(seconds=2))
async with asyncio.timeout(3):
await disconnected.wait()
finally:
stall.cancel()
assert server_wsock.close_code == WSCloseCode.ABNORMAL_CLOSURE