Significantly reduce websocket api connection auth phase latency (#108564)

* Significantly reduce websocket api connection auth phase latancy

Since the auth phase has exclusive control over the websocket
until ActiveConnection is created, we can bypass the queue and
send messages right away. This reduces the latancy and reconnect
time since we do not have to wait for the background processing
of the queue to send the auth ok message.

* only start the writer queue after auth is successful
This commit is contained in:
J. Nick Koston 2024-01-21 17:33:31 -10:00 committed by GitHub
parent da1d530889
commit dbb5645e63
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 47 additions and 38 deletions

View file

@ -1,14 +1,13 @@
"""Handle the auth of a connection."""
from __future__ import annotations
from collections.abc import Callable
from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any, Final
from aiohttp.web import Request
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.auth.models import RefreshToken, User
from homeassistant.components.http.ban import process_success_login, process_wrong_login
from homeassistant.const import __version__
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
@ -41,9 +40,9 @@ AUTH_REQUIRED_MESSAGE = json_bytes(
)
def auth_invalid_message(message: str) -> dict[str, str]:
def auth_invalid_message(message: str) -> bytes:
"""Return an auth_invalid message."""
return {"type": TYPE_AUTH_INVALID, "message": message}
return json_bytes({"type": TYPE_AUTH_INVALID, "message": message})
class AuthPhase:
@ -56,13 +55,17 @@ class AuthPhase:
send_message: Callable[[bytes | str | dict[str, Any]], None],
cancel_ws: CALLBACK_TYPE,
request: Request,
send_bytes_text: Callable[[bytes], Coroutine[Any, Any, None]],
) -> None:
"""Initialize the authentiated connection."""
"""Initialize the authenticated connection."""
self._hass = hass
# send_message will send a message to the client via the queue.
self._send_message = send_message
self._cancel_ws = cancel_ws
self._logger = logger
self._request = request
# send_bytes_text will directly send a message to the client.
self._send_bytes_text = send_bytes_text
async def async_handle(self, msg: JsonValueType) -> ActiveConnection:
"""Handle authentication."""
@ -73,7 +76,7 @@ class AuthPhase:
f"Auth message incorrectly formatted: {humanize_error(msg, err)}"
)
self._logger.warning(error_msg)
self._send_message(auth_invalid_message(error_msg))
await self._send_bytes_text(auth_invalid_message(error_msg))
raise Disconnect from err
if (access_token := valid_msg.get("access_token")) and (
@ -81,26 +84,25 @@ class AuthPhase:
access_token
)
):
conn = await self._async_finish_auth(refresh_token.user, refresh_token)
conn = ActiveConnection(
self._logger,
self._hass,
self._send_message,
refresh_token.user,
refresh_token,
)
conn.subscriptions[
"auth"
] = self._hass.auth.async_register_revoke_token_callback(
refresh_token.id, self._cancel_ws
)
await self._send_bytes_text(AUTH_OK_MESSAGE)
self._logger.debug("Auth OK")
process_success_login(self._request)
return conn
self._send_message(auth_invalid_message("Invalid access token or password"))
await self._send_bytes_text(
auth_invalid_message("Invalid access token or password")
)
await process_wrong_login(self._request)
raise Disconnect
async def _async_finish_auth(
self, user: User, refresh_token: RefreshToken
) -> ActiveConnection:
"""Create an active connection."""
self._logger.debug("Auth OK")
process_success_login(self._request)
self._send_message(AUTH_OK_MESSAGE)
return ActiveConnection(
self._logger, self._hass, self._send_message, user, refresh_token
)