init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
"""WebSocket based API for Home Assistant."""
from __future__ import annotations
from typing import Final, cast
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType, VolSchemaType
from homeassistant.loader import bind_hass
from . import commands, connection, const, decorators, http, messages # noqa: F401
from .connection import ActiveConnection, current_connection # noqa: F401
from .const import ( # noqa: F401
ERR_HOME_ASSISTANT_ERROR,
ERR_INVALID_FORMAT,
ERR_NOT_ALLOWED,
ERR_NOT_FOUND,
ERR_NOT_SUPPORTED,
ERR_SERVICE_VALIDATION_ERROR,
ERR_TEMPLATE_ERROR,
ERR_TIMEOUT,
ERR_UNAUTHORIZED,
ERR_UNKNOWN_COMMAND,
ERR_UNKNOWN_ERROR,
TYPE_RESULT,
AsyncWebSocketCommandHandler,
WebSocketCommandHandler,
)
from .decorators import ( # noqa: F401
async_response,
require_admin,
websocket_command,
ws_require_user,
)
from .messages import ( # noqa: F401
BASE_COMMAND_MESSAGE_SCHEMA,
error_message,
event_message,
result_message,
)
DOMAIN: Final = const.DOMAIN
DEPENDENCIES: Final[tuple[str]] = ("http",)
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
@bind_hass
@callback
def async_register_command(
hass: HomeAssistant,
command_or_handler: str | const.WebSocketCommandHandler,
handler: const.WebSocketCommandHandler | None = None,
schema: VolSchemaType | None = None,
) -> None:
"""Register a websocket command."""
if handler is None:
handler = cast(const.WebSocketCommandHandler, command_or_handler)
command = handler._ws_command # type: ignore[attr-defined] # noqa: SLF001
schema = handler._ws_schema # type: ignore[attr-defined] # noqa: SLF001
else:
command = command_or_handler
if (handlers := hass.data.get(DOMAIN)) is None:
handlers = hass.data[DOMAIN] = {}
handlers[command] = (handler, schema)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Initialize the websocket API."""
hass.http.register_view(http.WebsocketAPIView())
commands.async_register_commands(hass, async_register_command)
return True

View File

@@ -0,0 +1,107 @@
"""Handle the auth of a connection."""
from __future__ import annotations
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.components.http.ban import process_success_login, process_wrong_login
from homeassistant.const import __version__
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers.json import json_bytes
from homeassistant.util.json import JsonValueType
from .connection import ActiveConnection
from .error import Disconnect
if TYPE_CHECKING:
from .http import WebSocketAdapter
TYPE_AUTH: Final = "auth"
TYPE_AUTH_INVALID: Final = "auth_invalid"
TYPE_AUTH_OK: Final = "auth_ok"
TYPE_AUTH_REQUIRED: Final = "auth_required"
AUTH_MESSAGE_SCHEMA: Final = vol.Schema(
{
vol.Required("type"): TYPE_AUTH,
vol.Exclusive("api_password", "auth"): str,
vol.Exclusive("access_token", "auth"): str,
}
)
AUTH_OK_MESSAGE = json_bytes({"type": TYPE_AUTH_OK, "ha_version": __version__})
AUTH_REQUIRED_MESSAGE = json_bytes(
{"type": TYPE_AUTH_REQUIRED, "ha_version": __version__}
)
def auth_invalid_message(message: str) -> bytes:
"""Return an auth_invalid message."""
return json_bytes({"type": TYPE_AUTH_INVALID, "message": message})
class AuthPhase:
"""Connection that requires client to authenticate first."""
def __init__(
self,
logger: WebSocketAdapter,
hass: HomeAssistant,
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 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."""
try:
valid_msg = AUTH_MESSAGE_SCHEMA(msg)
except vol.Invalid as err:
error_msg = (
f"Auth message incorrectly formatted: {humanize_error(msg, err)}"
)
self._logger.warning(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 (
refresh_token := self._hass.auth.async_validate_access_token(access_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
await self._send_bytes_text(
auth_invalid_message("Invalid access token or password")
)
await process_wrong_login(self._request)
raise Disconnect

View File

@@ -0,0 +1,925 @@
"""Commands part of Websocket API."""
from __future__ import annotations
from collections.abc import Callable
from functools import lru_cache, partial
import json
import logging
from typing import Any, cast
import voluptuous as vol
from homeassistant.auth.models import User
from homeassistant.auth.permissions.const import POLICY_READ
from homeassistant.auth.permissions.events import SUBSCRIBE_ALLOWLIST
from homeassistant.const import (
EVENT_STATE_CHANGED,
MATCH_ALL,
SIGNAL_BOOTSTRAP_INTEGRATIONS,
)
from homeassistant.core import (
Context,
Event,
EventStateChangedData,
HomeAssistant,
ServiceResponse,
State,
callback,
)
from homeassistant.exceptions import (
HomeAssistantError,
ServiceNotFound,
ServiceValidationError,
TemplateError,
Unauthorized,
)
from homeassistant.helpers import config_validation as cv, entity, template
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entityfilter import (
INCLUDE_EXCLUDE_BASE_FILTER_SCHEMA,
convert_include_exclude_filter,
)
from homeassistant.helpers.event import (
TrackTemplate,
TrackTemplateResult,
async_track_template_result,
)
from homeassistant.helpers.json import (
JSON_DUMP,
ExtendedJSONEncoder,
find_paths_unserializable_data,
json_bytes,
json_fragment,
)
from homeassistant.helpers.service import async_get_all_descriptions
from homeassistant.loader import (
IntegrationNotFound,
async_get_integration,
async_get_integration_descriptions,
async_get_integrations,
)
from homeassistant.setup import async_get_loaded_integrations, async_get_setup_timings
from homeassistant.util.json import format_unserializable_data
from . import const, decorators, messages
from .connection import ActiveConnection
from .messages import construct_result_message
ALL_SERVICE_DESCRIPTIONS_JSON_CACHE = "websocket_api_all_service_descriptions_json"
_LOGGER = logging.getLogger(__name__)
@callback
def async_register_commands(
hass: HomeAssistant,
async_reg: Callable[[HomeAssistant, const.WebSocketCommandHandler], None],
) -> None:
"""Register commands."""
async_reg(hass, handle_call_service)
async_reg(hass, handle_entity_source)
async_reg(hass, handle_execute_script)
async_reg(hass, handle_fire_event)
async_reg(hass, handle_get_config)
async_reg(hass, handle_get_services)
async_reg(hass, handle_get_states)
async_reg(hass, handle_manifest_get)
async_reg(hass, handle_integration_setup_info)
async_reg(hass, handle_manifest_list)
async_reg(hass, handle_ping)
async_reg(hass, handle_render_template)
async_reg(hass, handle_subscribe_bootstrap_integrations)
async_reg(hass, handle_subscribe_events)
async_reg(hass, handle_subscribe_trigger)
async_reg(hass, handle_test_condition)
async_reg(hass, handle_unsubscribe_events)
async_reg(hass, handle_validate_config)
async_reg(hass, handle_subscribe_entities)
async_reg(hass, handle_supported_features)
async_reg(hass, handle_integration_descriptions)
def pong_message(iden: int) -> dict[str, Any]:
"""Return a pong message."""
return {"id": iden, "type": "pong"}
@callback
def _forward_events_check_permissions(
send_message: Callable[[bytes | str | dict[str, Any]], None],
user: User,
message_id_as_bytes: bytes,
event: Event,
) -> None:
"""Forward state changed events to websocket."""
# We have to lookup the permissions again because the user might have
# changed since the subscription was created.
permissions = user.permissions
if (
not user.is_admin
and not permissions.access_all_entities(POLICY_READ)
and not permissions.check_entity(event.data["entity_id"], POLICY_READ)
):
return
send_message(messages.cached_event_message(message_id_as_bytes, event))
@callback
def _forward_events_unconditional(
send_message: Callable[[bytes | str | dict[str, Any]], None],
message_id_as_bytes: bytes,
event: Event,
) -> None:
"""Forward events to websocket."""
send_message(messages.cached_event_message(message_id_as_bytes, event))
@callback
@decorators.websocket_command(
{
vol.Required("type"): "subscribe_events",
vol.Optional("event_type", default=MATCH_ALL): str,
}
)
def handle_subscribe_events(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle subscribe events command."""
event_type = msg["event_type"]
if event_type not in SUBSCRIBE_ALLOWLIST and not connection.user.is_admin:
_LOGGER.error(
"Refusing to allow %s to subscribe to event %s",
connection.user.name,
event_type,
)
raise Unauthorized(user_id=connection.user.id)
message_id_as_bytes = str(msg["id"]).encode()
if event_type == EVENT_STATE_CHANGED:
forward_events = partial(
_forward_events_check_permissions,
connection.send_message,
connection.user,
message_id_as_bytes,
)
else:
forward_events = partial(
_forward_events_unconditional, connection.send_message, message_id_as_bytes
)
connection.subscriptions[msg["id"]] = hass.bus.async_listen(
event_type, forward_events
)
connection.send_result(msg["id"])
@callback
@decorators.websocket_command(
{
vol.Required("type"): "subscribe_bootstrap_integrations",
}
)
def handle_subscribe_bootstrap_integrations(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle subscribe bootstrap integrations command."""
@callback
def forward_bootstrap_integrations(message: dict[str, Any]) -> None:
"""Forward bootstrap integrations to websocket."""
connection.send_message(messages.event_message(msg["id"], message))
connection.subscriptions[msg["id"]] = async_dispatcher_connect(
hass, SIGNAL_BOOTSTRAP_INTEGRATIONS, forward_bootstrap_integrations
)
connection.send_result(msg["id"])
@callback
@decorators.websocket_command(
{
vol.Required("type"): "unsubscribe_events",
vol.Required("subscription"): cv.positive_int,
}
)
def handle_unsubscribe_events(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle unsubscribe events command."""
subscription = msg["subscription"]
if subscription in connection.subscriptions:
connection.subscriptions.pop(subscription)()
connection.send_result(msg["id"])
else:
connection.send_error(msg["id"], const.ERR_NOT_FOUND, "Subscription not found.")
@decorators.websocket_command(
{
vol.Required("type"): "call_service",
vol.Required("domain"): str,
vol.Required("service"): str,
vol.Optional("target"): cv.ENTITY_SERVICE_FIELDS,
vol.Optional("service_data"): dict,
vol.Optional("return_response", default=False): bool,
}
)
@decorators.async_response
async def handle_call_service(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle call service command."""
# We do not support templates.
target = msg.get("target")
if template.is_complex(target):
raise vol.Invalid("Templates are not supported here")
try:
context = connection.context(msg)
response = await hass.services.async_call(
domain=msg["domain"],
service=msg["service"],
service_data=msg.get("service_data"),
blocking=True,
context=context,
target=target,
return_response=msg["return_response"],
)
result: dict[str, Context | ServiceResponse] = {"context": context}
if msg["return_response"]:
result["response"] = response
connection.send_result(msg["id"], result)
except ServiceNotFound as err:
if err.domain == msg["domain"] and err.service == msg["service"]:
connection.send_error(
msg["id"],
const.ERR_NOT_FOUND,
f"Service {err.domain}.{err.service} not found.",
translation_domain=err.translation_domain,
translation_key=err.translation_key,
translation_placeholders=err.translation_placeholders,
)
else:
# The called service called another service which does not exist
connection.send_error(
msg["id"],
const.ERR_HOME_ASSISTANT_ERROR,
f"Service {err.domain}.{err.service} called service "
f"{msg['domain']}.{msg['service']} which was not found.",
translation_domain=const.DOMAIN,
translation_key="child_service_not_found",
translation_placeholders={
"domain": err.domain,
"service": err.service,
"child_domain": msg["domain"],
"child_service": msg["service"],
},
)
except vol.Invalid as err:
connection.send_error(msg["id"], const.ERR_INVALID_FORMAT, str(err))
except ServiceValidationError as err:
connection.logger.error(err)
connection.logger.debug("", exc_info=err)
connection.send_error(
msg["id"],
const.ERR_SERVICE_VALIDATION_ERROR,
f"Validation error: {err}",
translation_domain=err.translation_domain,
translation_key=err.translation_key,
translation_placeholders=err.translation_placeholders,
)
except HomeAssistantError as err:
connection.logger.exception("Unexpected exception")
connection.send_error(
msg["id"],
const.ERR_HOME_ASSISTANT_ERROR,
str(err),
translation_domain=err.translation_domain,
translation_key=err.translation_key,
translation_placeholders=err.translation_placeholders,
)
except Exception as err:
connection.logger.exception("Unexpected exception")
connection.send_error(msg["id"], const.ERR_UNKNOWN_ERROR, str(err))
@callback
def _async_get_allowed_states(
hass: HomeAssistant, connection: ActiveConnection
) -> list[State]:
user = connection.user
if user.is_admin or user.permissions.access_all_entities(POLICY_READ):
return hass.states.async_all()
entity_perm = connection.user.permissions.check_entity
return [
state
for state in hass.states.async_all()
if entity_perm(state.entity_id, POLICY_READ)
]
@callback
@decorators.websocket_command({vol.Required("type"): "get_states"})
def handle_get_states(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle get states command."""
states = _async_get_allowed_states(hass, connection)
try:
serialized_states = [state.as_dict_json for state in states]
except (ValueError, TypeError):
pass
else:
_send_handle_get_states_response(connection, msg["id"], serialized_states)
return
# If we can't serialize, we'll filter out unserializable states
serialized_states = []
for state in states:
try:
serialized_states.append(state.as_dict_json)
except (ValueError, TypeError):
connection.logger.error(
"Unable to serialize to JSON. Bad data found at %s",
format_unserializable_data(
find_paths_unserializable_data(state, dump=JSON_DUMP)
),
)
_send_handle_get_states_response(connection, msg["id"], serialized_states)
def _send_handle_get_states_response(
connection: ActiveConnection, msg_id: int, serialized_states: list[bytes]
) -> None:
"""Send handle get states response."""
connection.send_message(
construct_result_message(
msg_id, b"".join((b"[", b",".join(serialized_states), b"]"))
)
)
@callback
def _forward_entity_changes(
send_message: Callable[[str | bytes | dict[str, Any]], None],
entity_ids: set[str] | None,
entity_filter: Callable[[str], bool] | None,
user: User,
message_id_as_bytes: bytes,
event: Event[EventStateChangedData],
) -> None:
"""Forward entity state changed events to websocket."""
entity_id = event.data["entity_id"]
if (entity_ids and entity_id not in entity_ids) or (
entity_filter and not entity_filter(entity_id)
):
return
# We have to lookup the permissions again because the user might have
# changed since the subscription was created.
permissions = user.permissions
if (
not user.is_admin
and not permissions.access_all_entities(POLICY_READ)
and not permissions.check_entity(entity_id, POLICY_READ)
):
return
send_message(messages.cached_state_diff_message(message_id_as_bytes, event))
@callback
@decorators.websocket_command(
{
vol.Required("type"): "subscribe_entities",
vol.Optional("entity_ids"): cv.entity_ids,
**INCLUDE_EXCLUDE_BASE_FILTER_SCHEMA.schema,
}
)
def handle_subscribe_entities(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle subscribe entities command."""
entity_ids = set(msg.get("entity_ids", [])) or None
_filter = convert_include_exclude_filter(msg)
entity_filter = None if _filter.empty_filter else _filter.get_filter()
# We must never await between sending the states and listening for
# state changed events or we will introduce a race condition
# where some states are missed
states = _async_get_allowed_states(hass, connection)
msg_id = msg["id"]
message_id_as_bytes = str(msg_id).encode()
connection.subscriptions[msg_id] = hass.bus.async_listen(
EVENT_STATE_CHANGED,
partial(
_forward_entity_changes,
connection.send_message,
entity_ids,
entity_filter,
connection.user,
message_id_as_bytes,
),
)
connection.send_result(msg_id)
# JSON serialize here so we can recover if it blows up due to the
# state machine containing unserializable data. This command is required
# to succeed for the UI to show.
try:
if entity_ids or entity_filter:
serialized_states = [
state.as_compressed_state_json
for state in states
if (not entity_ids or state.entity_id in entity_ids)
and (not entity_filter or entity_filter(state.entity_id))
]
else:
# Fast path when not filtering
serialized_states = [state.as_compressed_state_json for state in states]
except (ValueError, TypeError):
pass
else:
_send_handle_entities_init_response(
connection, message_id_as_bytes, serialized_states
)
return
serialized_states = []
for state in states:
try:
serialized_states.append(state.as_compressed_state_json)
except (ValueError, TypeError):
connection.logger.error(
"Unable to serialize to JSON. Bad data found at %s",
format_unserializable_data(
find_paths_unserializable_data(state, dump=JSON_DUMP)
),
)
_send_handle_entities_init_response(
connection, message_id_as_bytes, serialized_states
)
def _send_handle_entities_init_response(
connection: ActiveConnection,
message_id_as_bytes: bytes,
serialized_states: list[bytes],
) -> None:
"""Send handle entities init response."""
connection.send_message(
b"".join(
(
b'{"id":',
message_id_as_bytes,
b',"type":"event","event":{"a":{',
b",".join(serialized_states),
b"}}}",
)
)
)
async def _async_get_all_descriptions_json(hass: HomeAssistant) -> bytes:
"""Return JSON of descriptions (i.e. user documentation) for all service calls."""
descriptions = await async_get_all_descriptions(hass)
if ALL_SERVICE_DESCRIPTIONS_JSON_CACHE in hass.data:
cached_descriptions, cached_json_payload = hass.data[
ALL_SERVICE_DESCRIPTIONS_JSON_CACHE
]
# If the descriptions are the same, return the cached JSON payload
if cached_descriptions is descriptions:
return cast(bytes, cached_json_payload)
json_payload = json_bytes(descriptions)
hass.data[ALL_SERVICE_DESCRIPTIONS_JSON_CACHE] = (descriptions, json_payload)
return json_payload
@decorators.websocket_command({vol.Required("type"): "get_services"})
@decorators.async_response
async def handle_get_services(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle get services command."""
payload = await _async_get_all_descriptions_json(hass)
connection.send_message(construct_result_message(msg["id"], payload))
@callback
@decorators.websocket_command({vol.Required("type"): "get_config"})
def handle_get_config(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle get config command."""
connection.send_result(msg["id"], hass.config.as_dict())
@decorators.websocket_command(
{vol.Required("type"): "manifest/list", vol.Optional("integrations"): [str]}
)
@decorators.async_response
async def handle_manifest_list(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle integrations command."""
ints_or_excs = await async_get_integrations(
hass, msg.get("integrations") or async_get_loaded_integrations(hass)
)
manifest_json_fragments: list[json_fragment] = []
for int_or_exc in ints_or_excs.values():
if isinstance(int_or_exc, Exception):
raise int_or_exc
manifest_json_fragments.append(int_or_exc.manifest_json_fragment)
connection.send_result(msg["id"], manifest_json_fragments)
@decorators.websocket_command(
{vol.Required("type"): "manifest/get", vol.Required("integration"): str}
)
@decorators.async_response
async def handle_manifest_get(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle integrations command."""
try:
integration = await async_get_integration(hass, msg["integration"])
except IntegrationNotFound:
connection.send_error(msg["id"], const.ERR_NOT_FOUND, "Integration not found")
else:
connection.send_result(msg["id"], integration.manifest_json_fragment)
@callback
@decorators.websocket_command({vol.Required("type"): "integration/setup_info"})
def handle_integration_setup_info(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle integrations command."""
connection.send_result(
msg["id"],
[
{"domain": integration, "seconds": seconds}
for integration, seconds in async_get_setup_timings(hass).items()
],
)
@callback
@decorators.websocket_command({vol.Required("type"): "ping"})
def handle_ping(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle ping command."""
connection.send_message(pong_message(msg["id"]))
@lru_cache
def _cached_template(template_str: str, hass: HomeAssistant) -> template.Template:
"""Return a cached template."""
return template.Template(template_str, hass)
@decorators.websocket_command(
{
vol.Required("type"): "render_template",
vol.Required("template"): str,
vol.Optional("entity_ids"): cv.entity_ids,
vol.Optional("variables"): dict,
vol.Optional("timeout"): vol.Coerce(float),
vol.Optional("strict", default=False): bool,
vol.Optional("report_errors", default=False): bool,
}
)
@decorators.async_response
async def handle_render_template(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle render_template command."""
template_str = msg["template"]
report_errors: bool = msg["report_errors"]
if report_errors:
template_obj = template.Template(template_str, hass)
else:
template_obj = _cached_template(template_str, hass)
variables = msg.get("variables")
timeout = msg.get("timeout")
@callback
def _error_listener(level: int, template_error: str) -> None:
connection.send_message(
messages.event_message(
msg["id"],
{"error": template_error, "level": logging.getLevelName(level)},
)
)
@callback
def _thread_safe_error_listener(level: int, template_error: str) -> None:
hass.loop.call_soon_threadsafe(_error_listener, level, template_error)
if timeout:
try:
log_fn = _thread_safe_error_listener if report_errors else None
timed_out = await template_obj.async_render_will_timeout(
timeout, variables, strict=msg["strict"], log_fn=log_fn
)
except TemplateError:
timed_out = False
if timed_out:
connection.send_error(
msg["id"],
const.ERR_TEMPLATE_ERROR,
f"Exceeded maximum execution time of {timeout}s",
)
return
@callback
def _template_listener(
event: Event[EventStateChangedData] | None,
updates: list[TrackTemplateResult],
) -> None:
track_template_result = updates.pop()
result = track_template_result.result
if isinstance(result, TemplateError):
if not report_errors:
return
connection.send_message(
messages.event_message(
msg["id"], {"error": str(result), "level": "ERROR"}
)
)
return
connection.send_message(
messages.event_message(
msg["id"], {"result": result, "listeners": info.listeners}
)
)
try:
log_fn = _error_listener if report_errors else None
info = async_track_template_result(
hass,
[TrackTemplate(template_obj, variables)],
_template_listener,
strict=msg["strict"],
log_fn=log_fn,
)
except TemplateError as ex:
connection.send_error(msg["id"], const.ERR_TEMPLATE_ERROR, str(ex))
return
connection.subscriptions[msg["id"]] = info.async_remove
connection.send_result(msg["id"])
hass.loop.call_soon_threadsafe(info.async_refresh)
def _serialize_entity_sources(
entity_infos: dict[str, entity.EntityInfo],
) -> dict[str, Any]:
"""Prepare a websocket response from a dict of entity sources."""
return {
entity_id: {"domain": entity_info["domain"]}
for entity_id, entity_info in entity_infos.items()
}
@callback
@decorators.websocket_command({vol.Required("type"): "entity/source"})
def handle_entity_source(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle entity source command."""
all_entity_sources = entity.entity_sources(hass)
entity_perm = connection.user.permissions.check_entity
if connection.user.permissions.access_all_entities(POLICY_READ):
entity_sources = all_entity_sources
else:
entity_sources = {
entity_id: source
for entity_id, source in all_entity_sources.items()
if entity_perm(entity_id, POLICY_READ)
}
connection.send_result(msg["id"], _serialize_entity_sources(entity_sources))
@decorators.websocket_command(
{
vol.Required("type"): "subscribe_trigger",
vol.Required("trigger"): cv.TRIGGER_SCHEMA,
vol.Optional("variables"): dict,
}
)
@decorators.require_admin
@decorators.async_response
async def handle_subscribe_trigger(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle subscribe trigger command."""
# Circular dep
# pylint: disable-next=import-outside-toplevel
from homeassistant.helpers import trigger
trigger_config = await trigger.async_validate_trigger_config(hass, msg["trigger"])
@callback
def forward_triggers(
variables: dict[str, Any], context: Context | None = None
) -> None:
"""Forward events to websocket."""
message = messages.event_message(
msg["id"], {"variables": variables, "context": context}
)
connection.send_message(
json.dumps(
message, cls=ExtendedJSONEncoder, allow_nan=False, separators=(",", ":")
)
)
connection.subscriptions[msg["id"]] = (
await trigger.async_initialize_triggers(
hass,
trigger_config,
forward_triggers,
const.DOMAIN,
const.DOMAIN,
connection.logger.log,
variables=msg.get("variables"),
)
) or (
# Some triggers won't return an unsub function. Since the caller expects
# a subscription, we're going to fake one.
lambda: None
)
connection.send_result(msg["id"])
@decorators.websocket_command(
{
vol.Required("type"): "test_condition",
vol.Required("condition"): cv.CONDITION_SCHEMA,
vol.Optional("variables"): dict,
}
)
@decorators.require_admin
@decorators.async_response
async def handle_test_condition(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle test condition command."""
# Circular dep
# pylint: disable-next=import-outside-toplevel
from homeassistant.helpers import condition
# Do static + dynamic validation of the condition
config = await condition.async_validate_condition_config(hass, msg["condition"])
# Test the condition
check_condition = await condition.async_from_config(hass, config)
connection.send_result(
msg["id"], {"result": check_condition(hass, msg.get("variables"))}
)
@decorators.websocket_command(
{
vol.Required("type"): "execute_script",
vol.Required("sequence"): cv.SCRIPT_SCHEMA,
vol.Optional("variables"): dict,
}
)
@decorators.require_admin
@decorators.async_response
async def handle_execute_script(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle execute script command."""
# Circular dep
# pylint: disable-next=import-outside-toplevel
from homeassistant.helpers.script import Script, async_validate_actions_config
script_config = await async_validate_actions_config(hass, msg["sequence"])
context = connection.context(msg)
script_obj = Script(hass, script_config, f"{const.DOMAIN} script", const.DOMAIN)
try:
script_result = await script_obj.async_run(
msg.get("variables"), context=context
)
except ServiceValidationError as err:
connection.logger.error(err)
connection.logger.debug("", exc_info=err)
connection.send_error(
msg["id"],
const.ERR_SERVICE_VALIDATION_ERROR,
str(err),
translation_domain=err.translation_domain,
translation_key=err.translation_key,
translation_placeholders=err.translation_placeholders,
)
return
connection.send_result(
msg["id"],
{
"context": context,
"response": script_result.service_response if script_result else None,
},
)
@callback
@decorators.websocket_command(
{
vol.Required("type"): "fire_event",
vol.Required("event_type"): str,
vol.Optional("event_data"): dict,
}
)
@decorators.require_admin
def handle_fire_event(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle fire event command."""
context = connection.context(msg)
hass.bus.async_fire(msg["event_type"], msg.get("event_data"), context=context)
connection.send_result(msg["id"], {"context": context})
@decorators.websocket_command(
{
vol.Required("type"): "validate_config",
vol.Optional("triggers"): cv.match_all,
vol.Optional("conditions"): cv.match_all,
vol.Optional("actions"): cv.match_all,
}
)
@decorators.async_response
async def handle_validate_config(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle validate config command."""
# Circular dep
# pylint: disable-next=import-outside-toplevel
from homeassistant.helpers import condition, script, trigger
result = {}
for key, schema, validator in (
("triggers", cv.TRIGGER_SCHEMA, trigger.async_validate_trigger_config),
(
"conditions",
cv.CONDITIONS_SCHEMA,
condition.async_validate_conditions_config,
),
("actions", cv.SCRIPT_SCHEMA, script.async_validate_actions_config),
):
if key not in msg:
continue
try:
await validator(hass, schema(msg[key]))
except (
vol.Invalid,
HomeAssistantError,
) as err:
result[key] = {"valid": False, "error": str(err)}
else:
result[key] = {"valid": True, "error": None}
connection.send_result(msg["id"], result)
@callback
@decorators.websocket_command(
{
vol.Required("type"): "supported_features",
vol.Required("features"): {str: int},
}
)
def handle_supported_features(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle setting supported features."""
connection.set_supported_features(msg["features"])
connection.send_result(msg["id"])
@decorators.require_admin
@decorators.websocket_command({"type": "integration/descriptions"})
@decorators.async_response
async def handle_integration_descriptions(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Get metadata for all brands and integrations."""
connection.send_result(msg["id"], await async_get_integration_descriptions(hass))

View File

@@ -0,0 +1,315 @@
"""Connection session."""
from __future__ import annotations
from collections.abc import Callable, Hashable
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Literal
from aiohttp import web
import voluptuous as vol
from homeassistant.auth.models import RefreshToken, User
from homeassistant.core import Context, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError, Unauthorized
from homeassistant.helpers.http import current_request
from homeassistant.util.json import JsonValueType
from . import const, messages
from .messages import (
error_message,
event_message,
message_to_json_bytes,
result_message,
)
from .util import describe_request
if TYPE_CHECKING:
from .http import WebSocketAdapter
current_connection = ContextVar["ActiveConnection | None"](
"current_connection", default=None
)
type MessageHandler = Callable[[HomeAssistant, ActiveConnection, dict[str, Any]], None]
type BinaryHandler = Callable[[HomeAssistant, ActiveConnection, bytes], None]
class ActiveConnection:
"""Handle an active websocket client connection."""
__slots__ = (
"logger",
"hass",
"send_message",
"user",
"refresh_token_id",
"subscriptions",
"last_id",
"can_coalesce",
"supported_features",
"handlers",
"binary_handlers",
)
def __init__(
self,
logger: WebSocketAdapter,
hass: HomeAssistant,
send_message: Callable[[bytes | str | dict[str, Any]], None],
user: User,
refresh_token: RefreshToken,
) -> None:
"""Initialize an active connection."""
self.logger = logger
self.hass = hass
self.send_message = send_message
self.user = user
self.refresh_token_id = refresh_token.id
self.subscriptions: dict[Hashable, Callable[[], Any]] = {}
self.last_id = 0
self.can_coalesce = False
self.supported_features: dict[str, float] = {}
self.handlers: dict[str, tuple[MessageHandler, vol.Schema | Literal[False]]] = (
self.hass.data[const.DOMAIN]
)
self.binary_handlers: list[BinaryHandler | None] = []
current_connection.set(self)
def __repr__(self) -> str:
"""Return the representation."""
return f"<ActiveConnection {self.get_description(None)}>"
def set_supported_features(self, features: dict[str, float]) -> None:
"""Set supported features."""
self.supported_features = features
self.can_coalesce = const.FEATURE_COALESCE_MESSAGES in features
def get_description(self, request: web.Request | None) -> str:
"""Return a description of the connection."""
description = self.user.name or ""
if request:
description += " " + describe_request(request)
return description
def context(self, msg: dict[str, Any]) -> Context:
"""Return a context."""
return Context(user_id=self.user.id)
@callback
def async_register_binary_handler(
self, handler: BinaryHandler
) -> tuple[int, Callable[[], None]]:
"""Register a temporary binary handler for this connection.
Returns a binary handler_id (1 byte) and a callback to unregister the handler.
"""
if len(self.binary_handlers) < 255:
index = len(self.binary_handlers)
self.binary_handlers.append(None)
else:
# Once the list is full, we search for a None entry to reuse.
index = None
for idx, existing in enumerate(self.binary_handlers):
if existing is None:
index = idx
break
if index is None:
raise RuntimeError("Too many binary handlers registered")
self.binary_handlers[index] = handler
@callback
def unsub() -> None:
"""Unregister the handler."""
assert index is not None
self.binary_handlers[index] = None
return index + 1, unsub
@callback
def send_result(self, msg_id: int, result: Any | None = None) -> None:
"""Send a result message."""
self.send_message(message_to_json_bytes(result_message(msg_id, result)))
@callback
def send_event(self, msg_id: int, event: Any | None = None) -> None:
"""Send a event message."""
self.send_message(message_to_json_bytes(event_message(msg_id, event)))
@callback
def send_error(
self,
msg_id: int,
code: str,
message: str,
translation_key: str | None = None,
translation_domain: str | None = None,
translation_placeholders: dict[str, Any] | None = None,
) -> None:
"""Send an error message."""
self.send_message(
message_to_json_bytes(
error_message(
msg_id,
code,
message,
translation_key=translation_key,
translation_domain=translation_domain,
translation_placeholders=translation_placeholders,
)
)
)
@callback
def async_handle_binary(self, handler_id: int, payload: bytes) -> None:
"""Handle a single incoming binary message."""
index = handler_id - 1
if (
index < 0
or index >= len(self.binary_handlers)
or (handler := self.binary_handlers[index]) is None
):
self.logger.error(
"Received binary message for non-existing handler %s", handler_id
)
return
try:
handler(self.hass, self, payload)
except Exception:
self.logger.exception("Error handling binary message")
self.binary_handlers[index] = None
@callback
def async_handle(self, msg: JsonValueType) -> None:
"""Handle a single incoming message."""
if (
# Not using isinstance as we don't care about children
# as these are always coming from JSON
type(msg) is not dict # noqa: E721
or (
not (cur_id := msg.get("id"))
or type(cur_id) is not int # noqa: E721
or cur_id < 0
or not (type_ := msg.get("type"))
or type(type_) is not str # noqa: E721
)
):
self.logger.error("Received invalid command: %s", msg)
id_ = msg.get("id") if isinstance(msg, dict) else 0
self.send_message(
messages.error_message(
id_, # type: ignore[arg-type]
const.ERR_INVALID_FORMAT,
"Message incorrectly formatted.",
)
)
return
if cur_id <= self.last_id:
self.send_message(
messages.error_message(
cur_id, const.ERR_ID_REUSE, "Identifier values have to increase."
)
)
return
if not (handler_schema := self.handlers.get(type_)):
self.logger.info("Received unknown command: %s", type_)
self.send_message(
messages.error_message(
cur_id, const.ERR_UNKNOWN_COMMAND, "Unknown command."
)
)
return
handler, schema = handler_schema
try:
if schema is False:
if len(msg) > 2:
raise vol.Invalid("extra keys not allowed") # noqa: TRY301
handler(self.hass, self, msg)
else:
handler(self.hass, self, schema(msg))
except Exception as err: # noqa: BLE001
self.async_handle_exception(msg, err)
self.last_id = cur_id
@callback
def async_handle_close(self) -> None:
"""Handle closing down connection."""
for unsub in self.subscriptions.values():
try:
unsub()
except Exception:
# If one fails, make sure we still try the rest
self.logger.exception(
"Error unsubscribing from subscription: %s", unsub
)
self.subscriptions.clear()
self.send_message = self._connect_closed_error
current_request.set(None)
current_connection.set(None)
@callback
def _connect_closed_error(
self, msg: bytes | str | dict[str, Any] | Callable[[], str]
) -> None:
"""Send a message when the connection is closed."""
self.logger.debug("Tried to send message %s on closed connection", msg)
@callback
def async_handle_exception(self, msg: dict[str, Any], err: Exception) -> None:
"""Handle an exception while processing a handler."""
log_handler = self.logger.error
code = const.ERR_UNKNOWN_ERROR
err_message: str | None = None
translation_domain: str | None = None
translation_key: str | None = None
translation_placeholders: dict[str, Any] | None = None
if isinstance(err, Unauthorized):
code = const.ERR_UNAUTHORIZED
err_message = "Unauthorized"
elif isinstance(err, vol.Invalid):
code = const.ERR_INVALID_FORMAT
err_message = vol.humanize.humanize_error(msg, err)
elif isinstance(err, TimeoutError):
code = const.ERR_TIMEOUT
err_message = "Timeout"
elif isinstance(err, HomeAssistantError):
err_message = str(err)
code = const.ERR_HOME_ASSISTANT_ERROR
translation_domain = err.translation_domain
translation_key = err.translation_key
translation_placeholders = err.translation_placeholders
# This if-check matches all other errors but also matches errors which
# result in an empty message. In that case we will also log the stack
# trace so it can be fixed.
if not err_message:
err_message = "Unknown error"
log_handler = self.logger.exception
self.send_message(
messages.error_message(
msg["id"],
code,
err_message,
translation_domain=translation_domain,
translation_key=translation_key,
translation_placeholders=translation_placeholders,
)
)
if code:
err_message += f" ({code})"
err_message += " " + self.get_description(current_request.get())
log_handler("Error handling message: %s", err_message)

View File

@@ -0,0 +1,60 @@
"""Websocket constants."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any, Final
from homeassistant.core import HomeAssistant
if TYPE_CHECKING:
from .connection import ActiveConnection
type WebSocketCommandHandler = Callable[
[HomeAssistant, ActiveConnection, dict[str, Any]], None
]
type AsyncWebSocketCommandHandler = Callable[
[HomeAssistant, ActiveConnection, dict[str, Any]], Awaitable[None]
]
DOMAIN: Final = "websocket_api"
URL: Final = "/api/websocket"
PENDING_MSG_PEAK: Final = 1024
PENDING_MSG_PEAK_TIME: Final = 5
# Maximum number of messages that can be pending at any given time.
# This is effectively the upper limit of the number of entities
# that can fire state changes within ~1 second.
# Ideally we would use homeassistant.const.MAX_EXPECTED_ENTITY_IDS
# but since chrome will lock up with too many messages we need to
# limit it to a lower number.
MAX_PENDING_MSG: Final = 4096
# Maximum number of messages that are pending before we force
# resolve the ready future.
PENDING_MSG_MAX_FORCE_READY: Final = 256
ERR_ID_REUSE: Final = "id_reuse"
ERR_INVALID_FORMAT: Final = "invalid_format"
ERR_NOT_ALLOWED: Final = "not_allowed"
ERR_NOT_FOUND: Final = "not_found"
ERR_NOT_SUPPORTED: Final = "not_supported"
ERR_HOME_ASSISTANT_ERROR: Final = "home_assistant_error"
ERR_SERVICE_VALIDATION_ERROR: Final = "service_validation_error"
ERR_UNKNOWN_COMMAND: Final = "unknown_command"
ERR_UNKNOWN_ERROR: Final = "unknown_error"
ERR_UNAUTHORIZED: Final = "unauthorized"
ERR_TIMEOUT: Final = "timeout"
ERR_TEMPLATE_ERROR: Final = "template_error"
TYPE_RESULT: Final = "result"
# Event types
SIGNAL_WEBSOCKET_CONNECTED: Final = "websocket_connected"
SIGNAL_WEBSOCKET_DISCONNECTED: Final = "websocket_disconnected"
# Data used to store the current connection list
DATA_CONNECTIONS: Final = f"{DOMAIN}.connections"
FEATURE_COALESCE_MESSAGES = "coalesce_messages"

View File

@@ -0,0 +1,165 @@
"""Decorators for the Websocket API."""
from __future__ import annotations
from collections.abc import Callable
from functools import wraps
from typing import TYPE_CHECKING, Any
import voluptuous as vol
from homeassistant.const import HASSIO_USER_NAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import Unauthorized
from homeassistant.helpers.typing import VolDictType
from . import const, messages
from .connection import ActiveConnection
async def _handle_async_response(
func: const.AsyncWebSocketCommandHandler,
hass: HomeAssistant,
connection: ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Create a response and handle exception."""
try:
await func(hass, connection, msg)
except Exception as err: # noqa: BLE001
connection.async_handle_exception(msg, err)
def async_response(
func: const.AsyncWebSocketCommandHandler,
) -> const.WebSocketCommandHandler:
"""Decorate an async function to handle WebSocket API messages."""
task_name = f"websocket_api.async:{func.__name__}"
@callback
@wraps(func)
def schedule_handler(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Schedule the handler."""
# As the webserver is now started before the start
# event we do not want to block for websocket responders
hass.async_create_background_task(
_handle_async_response(func, hass, connection, msg),
task_name,
eager_start=True,
)
return schedule_handler
def require_admin(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler:
"""Websocket decorator to require user to be an admin."""
@wraps(func)
def with_admin(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Check admin and call function."""
user = connection.user
if user is None or not user.is_admin:
raise Unauthorized
func(hass, connection, msg)
return with_admin
def ws_require_user(
only_owner: bool = False,
only_system_user: bool = False,
allow_system_user: bool = True,
only_active_user: bool = True,
only_inactive_user: bool = False,
only_supervisor: bool = False,
) -> Callable[[const.WebSocketCommandHandler], const.WebSocketCommandHandler]:
"""Decorate function validating login user exist in current WS connection.
Will write out error message if not authenticated.
"""
def validator(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler:
"""Decorate func."""
@wraps(func)
def check_current_user(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Check current user."""
def output_error(message_id: str, message: str) -> None:
"""Output error message."""
connection.send_message(
messages.error_message(msg["id"], message_id, message)
)
if only_owner and not connection.user.is_owner:
output_error("only_owner", "Only allowed as owner")
return None
if only_system_user and not connection.user.system_generated:
output_error("only_system_user", "Only allowed as system user")
return None
if not allow_system_user and connection.user.system_generated:
output_error("not_system_user", "Not allowed as system user")
return None
if only_active_user and not connection.user.is_active:
output_error("only_active_user", "Only allowed as active user")
return None
if only_inactive_user and connection.user.is_active:
output_error("only_inactive_user", "Not allowed as active user")
return None
if only_supervisor and connection.user.name != HASSIO_USER_NAME:
output_error("only_supervisor", "Only allowed as Supervisor")
return None
return func(hass, connection, msg)
return check_current_user
return validator
def websocket_command(
schema: VolDictType | vol.All,
) -> Callable[[const.WebSocketCommandHandler], const.WebSocketCommandHandler]:
"""Tag a function as a websocket command.
The schema must be either a dictionary where the keys are voluptuous markers, or
a voluptuous.All schema where the first item is a voluptuous Mapping schema.
"""
if is_dict := isinstance(schema, dict):
command = schema["type"]
else:
command = schema.validators[0].schema["type"]
def decorate(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler:
"""Decorate ws command function."""
if is_dict and len(schema) == 1: # type: ignore[arg-type] # type only empty schema
func._ws_schema = False # type: ignore[attr-defined] # noqa: SLF001
elif is_dict:
func._ws_schema = messages.BASE_COMMAND_MESSAGE_SCHEMA.extend(schema) # type: ignore[attr-defined] # noqa: SLF001
else:
if TYPE_CHECKING:
assert not isinstance(schema, dict)
extended_schema = vol.All(
schema.validators[0].extend(
messages.BASE_COMMAND_MESSAGE_SCHEMA.schema
),
*schema.validators[1:],
)
func._ws_schema = extended_schema # type: ignore[attr-defined] # noqa: SLF001
func._ws_command = command # type: ignore[attr-defined] # noqa: SLF001
return func
return decorate

View File

@@ -0,0 +1,7 @@
"""WebSocket API related errors."""
from homeassistant.exceptions import HomeAssistantError
class Disconnect(HomeAssistantError):
"""Disconnect the current session."""

View File

@@ -0,0 +1,539 @@
"""View to accept incoming websocket connection."""
from __future__ import annotations
import asyncio
from collections import deque
from collections.abc import Callable, Coroutine
import datetime as dt
from functools import partial
import logging
from typing import TYPE_CHECKING, Any, Final
from aiohttp import WSMsgType, web
from aiohttp.http_websocket import WebSocketWriter
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later
from homeassistant.util.async_ import create_eager_task
from homeassistant.util.json import json_loads
from .auth import AUTH_REQUIRED_MESSAGE, AuthPhase
from .const import (
DATA_CONNECTIONS,
MAX_PENDING_MSG,
PENDING_MSG_MAX_FORCE_READY,
PENDING_MSG_PEAK,
PENDING_MSG_PEAK_TIME,
SIGNAL_WEBSOCKET_CONNECTED,
SIGNAL_WEBSOCKET_DISCONNECTED,
URL,
)
from .error import Disconnect
from .messages import message_to_json_bytes
from .util import describe_request
CLOSE_MSG_TYPES = {WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING}
if TYPE_CHECKING:
from .connection import ActiveConnection
_WS_LOGGER: Final = logging.getLogger(f"{__name__}.connection")
class WebsocketAPIView(HomeAssistantView):
"""View to serve a websockets endpoint."""
name: str = "websocketapi"
url: str = URL
requires_auth: bool = False
async def get(self, request: web.Request) -> web.WebSocketResponse:
"""Handle an incoming websocket connection."""
return await WebSocketHandler(request.app[KEY_HASS], request).async_handle()
class WebSocketAdapter(logging.LoggerAdapter):
"""Add connection id to websocket messages."""
def process(self, msg: str, kwargs: Any) -> tuple[str, Any]:
"""Add connid to websocket log messages."""
assert self.extra is not None
return f'[{self.extra["connid"]}] {msg}', kwargs
class WebSocketHandler:
"""Handle an active websocket client connection."""
__slots__ = (
"_hass",
"_loop",
"_request",
"_wsock",
"_handle_task",
"_writer_task",
"_closing",
"_authenticated",
"_logger",
"_peak_checker_unsub",
"_connection",
"_message_queue",
"_ready_future",
"_release_ready_queue_size",
)
def __init__(self, hass: HomeAssistant, request: web.Request) -> None:
"""Initialize an active connection."""
self._hass = hass
self._loop = hass.loop
self._request: web.Request = request
self._wsock = web.WebSocketResponse(heartbeat=55)
self._handle_task: asyncio.Task | None = None
self._writer_task: asyncio.Task | None = None
self._closing: bool = False
self._authenticated: bool = False
self._logger = WebSocketAdapter(_WS_LOGGER, {"connid": id(self)})
self._peak_checker_unsub: Callable[[], None] | None = None
self._connection: ActiveConnection | None = None
# The WebSocketHandler has a single consumer and path
# to where messages are queued. This allows the implementation
# to use a deque and an asyncio.Future to avoid the overhead of
# an asyncio.Queue.
self._message_queue: deque[bytes] = deque()
self._ready_future: asyncio.Future[int] | None = None
self._release_ready_queue_size: int = 0
def __repr__(self) -> str:
"""Return the representation."""
return (
"<WebSocketHandler "
f"closing={self._closing} "
f"authenticated={self._authenticated} "
f"description={self.description}>"
)
@property
def description(self) -> str:
"""Return a description of the connection."""
if connection := self._connection:
return connection.get_description(self._request)
if request := self._request:
return describe_request(request)
return "finished connection"
async def _writer(
self,
connection: ActiveConnection,
send_bytes_text: Callable[[bytes], Coroutine[Any, Any, None]],
) -> None:
"""Write outgoing messages."""
# Variables are set locally to avoid lookups in the loop
message_queue = self._message_queue
logger = self._logger
wsock = self._wsock
loop = self._loop
is_debug_log_enabled = partial(logger.isEnabledFor, logging.DEBUG)
debug = logger.debug
can_coalesce = connection.can_coalesce
ready_message_count = len(message_queue)
# Exceptions if Socket disconnected or cancelled by connection handler
try:
while not wsock.closed:
if not message_queue:
self._ready_future = loop.create_future()
ready_message_count = await self._ready_future
if self._closing:
return
if not can_coalesce:
# coalesce may be enabled later in the connection
can_coalesce = connection.can_coalesce
if not can_coalesce or ready_message_count == 1:
message = message_queue.popleft()
if is_debug_log_enabled():
debug("%s: Sending %s", self.description, message)
await send_bytes_text(message)
continue
coalesced_messages = b"".join((b"[", b",".join(message_queue), b"]"))
message_queue.clear()
if is_debug_log_enabled():
debug("%s: Sending %s", self.description, coalesced_messages)
await send_bytes_text(coalesced_messages)
except asyncio.CancelledError:
debug("%s: Writer cancelled", self.description)
raise
except (RuntimeError, ConnectionResetError) as ex:
debug("%s: Unexpected error in writer: %s", self.description, ex)
finally:
debug("%s: Writer done", self.description)
# Clean up the peak checker when we shut down the writer
self._cancel_peak_checker()
@callback
def _cancel_peak_checker(self) -> None:
"""Cancel the peak checker."""
if self._peak_checker_unsub is not None:
self._peak_checker_unsub()
self._peak_checker_unsub = None
@callback
def _send_message(self, message: str | bytes | dict[str, Any]) -> None:
"""Queue sending a message to the client.
Closes connection if the client is not reading the messages.
Async friendly.
"""
if self._closing:
# Connection is cancelled, don't flood logs about exceeding
# max pending messages.
return
if type(message) is not bytes: # noqa: E721
if isinstance(message, dict):
message = message_to_json_bytes(message)
elif isinstance(message, str):
message = message.encode("utf-8")
message_queue = self._message_queue
message_queue.append(message)
if (queue_size_after_add := len(message_queue)) >= MAX_PENDING_MSG:
self._logger.error(
(
"%s: Client unable to keep up with pending messages. Reached %s pending"
" messages. The system's load is too high or an integration is"
" misbehaving; Last message was: %s"
),
self.description,
MAX_PENDING_MSG,
message,
)
self._cancel()
return
if self._release_ready_queue_size == 0:
# Try to coalesce more messages to reduce the number of writes
self._release_ready_queue_size = queue_size_after_add
self._loop.call_soon(self._release_ready_future_or_reschedule)
peak_checker_active = self._peak_checker_unsub is not None
if queue_size_after_add <= PENDING_MSG_PEAK:
if peak_checker_active:
self._cancel_peak_checker()
return
if not peak_checker_active:
self._peak_checker_unsub = async_call_later(
self._hass, PENDING_MSG_PEAK_TIME, self._check_write_peak
)
@callback
def _release_ready_future_or_reschedule(self) -> None:
"""Release the ready future or reschedule.
We will release the ready future if the queue did not grow since the
last time we tried to release the ready future.
If we reach PENDING_MSG_MAX_FORCE_READY, we will release the ready future
immediately so avoid the coalesced messages from growing too large.
"""
if not (ready_future := self._ready_future) or not (
queue_size := len(self._message_queue)
):
self._release_ready_queue_size = 0
return
# If we are below the max pending to force ready, and there are new messages
# in the queue since the last time we tried to release the ready future, we
# try again later so we can coalesce more messages.
if queue_size > self._release_ready_queue_size < PENDING_MSG_MAX_FORCE_READY:
self._release_ready_queue_size = queue_size
self._loop.call_soon(self._release_ready_future_or_reschedule)
return
self._release_ready_queue_size = 0
if not ready_future.done():
ready_future.set_result(queue_size)
@callback
def _check_write_peak(self, _utc_time: dt.datetime) -> None:
"""Check that we are no longer above the write peak."""
self._peak_checker_unsub = None
if len(self._message_queue) < PENDING_MSG_PEAK:
return
self._logger.error(
(
"%s: Client unable to keep up with pending messages. Stayed over %s for %s"
" seconds. The system's load is too high or an integration is"
" misbehaving; Last message was: %s"
),
self.description,
PENDING_MSG_PEAK,
PENDING_MSG_PEAK_TIME,
self._message_queue[-1],
)
self._cancel()
@callback
def _cancel(self) -> None:
"""Cancel the connection."""
self._closing = True
self._cancel_peak_checker()
if self._handle_task is not None:
self._handle_task.cancel()
if self._writer_task is not None:
self._writer_task.cancel()
@callback
def _async_handle_hass_stop(self, event: Event) -> None:
"""Cancel this connection."""
self._cancel()
async def async_handle(self) -> web.WebSocketResponse:
"""Handle a websocket response."""
request = self._request
wsock = self._wsock
logger = self._logger
hass = self._hass
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
logger.debug("%s: Connected from %s", self.description, request.remote)
self._handle_task = asyncio.current_task()
unsub_stop = hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP, self._async_handle_hass_stop
)
writer = wsock._writer # noqa: SLF001
if TYPE_CHECKING:
assert writer is not None
send_bytes_text = partial(writer.send_frame, opcode=WSMsgType.TEXT)
auth = AuthPhase(
logger, hass, self._send_message, self._cancel, request, send_bytes_text
)
connection: ActiveConnection | None = None
disconnect_warn: str | None = None
try:
connection = await self._async_handle_auth_phase(auth, send_bytes_text)
self._async_increase_writer_limit(writer)
await self._async_websocket_command_phase(connection)
except asyncio.CancelledError:
logger.debug("%s: Connection cancelled", self.description)
raise
except Disconnect as ex:
if disconnect_msg := str(ex):
disconnect_warn = disconnect_msg
logger.debug("%s: Connection closed by client: %s", self.description, ex)
except Exception:
logger.exception(
"%s: Unexpected error inside websocket API", self.description
)
finally:
unsub_stop()
self._cancel_peak_checker()
if connection is not None:
connection.async_handle_close()
self._closing = True
if self._ready_future and not self._ready_future.done():
self._ready_future.set_result(len(self._message_queue))
await self._async_cleanup_writer_and_close(disconnect_warn, connection)
return wsock
async def _async_handle_auth_phase(
self,
auth: AuthPhase,
send_bytes_text: Callable[[bytes], Coroutine[Any, Any, None]],
) -> ActiveConnection:
"""Handle the auth phase of the websocket connection."""
await send_bytes_text(AUTH_REQUIRED_MESSAGE)
# Auth Phase
try:
msg = await self._wsock.receive(10)
except TimeoutError as err:
raise Disconnect("Did not receive auth message within 10 seconds") from err
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING):
raise Disconnect("Received close message during auth phase")
if msg.type is not WSMsgType.TEXT:
raise Disconnect("Received non-Text message during auth phase")
try:
auth_msg_data = json_loads(msg.data)
except ValueError as err:
raise Disconnect("Received invalid JSON during auth phase") from err
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.debug("%s: Received %s", self.description, auth_msg_data)
connection = await auth.async_handle(auth_msg_data)
# As the webserver is now started before the start
# event we do not want to block for websocket responses
#
# We only start the writer queue after the auth phase is completed
# since there is no need to queue messages before the auth phase
self._connection = connection
self._writer_task = create_eager_task(self._writer(connection, send_bytes_text))
self._hass.data[DATA_CONNECTIONS] = self._hass.data.get(DATA_CONNECTIONS, 0) + 1
async_dispatcher_send(self._hass, SIGNAL_WEBSOCKET_CONNECTED)
self._authenticated = True
return connection
@callback
def _async_increase_writer_limit(self, writer: WebSocketWriter) -> None:
#
#
# Our websocket implementation is backed by a deque
#
# As back-pressure builds, the queue will back up and use more memory
# until we disconnect the client when the queue size reaches
# MAX_PENDING_MSG. When we are generating a high volume of websocket messages,
# we hit a bottleneck in aiohttp where it will wait for
# the buffer to drain before sending the next message and messages
# start backing up in the queue.
#
# https://github.com/aio-libs/aiohttp/issues/1367 added drains
# to the websocket writer to handle malicious clients and network issues.
# The drain causes multiple problems for us since the buffer cannot be
# drained fast enough when we deliver a high volume or large messages:
#
# - We end up disconnecting the client. The client will then reconnect,
# and the cycle repeats itself, which results in a significant amount of
# CPU usage.
#
# - Messages latency increases because messages cannot be moved into
# the TCP buffer because it is blocked waiting for the drain to happen because
# of the low default limit of 16KiB. By increasing the limit, we instead
# rely on the underlying TCP buffer and stack to deliver the messages which
# can typically happen much faster.
#
# After the auth phase is completed, and we are not concerned about
# the user being a malicious client, we set the limit to force a drain
# to 1MiB. 1MiB is the maximum expected size of the serialized entity
# registry, which is the largest message we usually send.
#
# https://github.com/aio-libs/aiohttp/commit/b3c80ee3f7d5d8f0b8bc27afe52e4d46621eaf99
# added a way to set the limit, but there is no way to actually
# reach the code to set the limit, so we have to set it directly.
#
writer._limit = 2**20 # noqa: SLF001
async def _async_websocket_command_phase(
self, connection: ActiveConnection
) -> None:
"""Handle the command phase of the websocket connection."""
wsock = self._wsock
async_handle_str = connection.async_handle
async_handle_binary = connection.async_handle_binary
_debug_enabled = partial(self._logger.isEnabledFor, logging.DEBUG)
# Command phase
while not wsock.closed:
msg = await wsock.receive()
msg_type = msg.type
msg_data = msg.data
if msg_type in CLOSE_MSG_TYPES:
break
if msg_type is WSMsgType.BINARY:
if len(msg_data) < 1:
raise Disconnect("Received invalid binary message.")
handler = msg_data[0]
payload = msg_data[1:]
async_handle_binary(handler, payload)
continue
if msg_type is not WSMsgType.TEXT:
raise Disconnect("Received non-Text message.")
try:
command_msg_data = json_loads(msg_data)
except ValueError as ex:
raise Disconnect("Received invalid JSON.") from ex
if _debug_enabled():
self._logger.debug(
"%s: Received %s", self.description, command_msg_data
)
# command_msg_data is always deserialized from JSON as a list
if type(command_msg_data) is not list: # noqa: E721
async_handle_str(command_msg_data)
continue
for split_msg in command_msg_data:
async_handle_str(split_msg)
async def _async_cleanup_writer_and_close(
self, disconnect_warn: str | None, connection: ActiveConnection | None
) -> None:
"""Cleanup the writer and close the websocket."""
# If the writer gets canceled we still need to close the websocket
# so we have another finally block to make sure we close the websocket
# if the writer gets canceled.
wsock = self._wsock
hass = self._hass
logger = self._logger
try:
if self._writer_task:
await self._writer_task
finally:
try:
# Make sure all error messages are written before closing
await wsock.close()
finally:
if disconnect_warn is None:
logger.debug("%s: Disconnected", self.description)
else:
logger.warning(
"%s: Disconnected: %s", self.description, disconnect_warn
)
if connection is not None:
hass.data[DATA_CONNECTIONS] -= 1
self._connection = None
async_dispatcher_send(hass, SIGNAL_WEBSOCKET_DISCONNECTED)
# Break reference cycles to make sure GC can happen sooner
self._wsock = None # type: ignore[assignment]
self._request = None # type: ignore[assignment]
self._hass = None # type: ignore[assignment]
self._logger = None # type: ignore[assignment]
self._message_queue = None # type: ignore[assignment]
self._handle_task = None
self._writer_task = None
self._ready_future = None

View File

@@ -0,0 +1,9 @@
{
"domain": "websocket_api",
"name": "Home Assistant WebSocket API",
"codeowners": ["@home-assistant/core"],
"dependencies": ["http"],
"documentation": "https://www.home-assistant.io/integrations/websocket_api",
"integration_type": "system",
"quality_scale": "internal"
}

View File

@@ -0,0 +1,261 @@
"""Message templates for websocket commands."""
from __future__ import annotations
from functools import lru_cache
import logging
from typing import Any, Final
import voluptuous as vol
from homeassistant.const import (
COMPRESSED_STATE_ATTRIBUTES,
COMPRESSED_STATE_CONTEXT,
COMPRESSED_STATE_LAST_CHANGED,
COMPRESSED_STATE_LAST_UPDATED,
COMPRESSED_STATE_STATE,
)
from homeassistant.core import CompressedState, Event, EventStateChangedData
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.json import (
JSON_DUMP,
find_paths_unserializable_data,
json_bytes,
)
from homeassistant.util.json import format_unserializable_data
from . import const
_LOGGER: Final = logging.getLogger(__name__)
# Minimal requirements of a message
MINIMAL_MESSAGE_SCHEMA: Final = vol.Schema(
{vol.Required("id"): cv.positive_int, vol.Required("type"): cv.string},
extra=vol.ALLOW_EXTRA,
)
# Base schema to extend by message handlers
BASE_COMMAND_MESSAGE_SCHEMA: Final = vol.Schema({vol.Required("id"): cv.positive_int})
STATE_DIFF_ADDITIONS = "+"
STATE_DIFF_REMOVALS = "-"
ENTITY_EVENT_ADD = "a"
ENTITY_EVENT_REMOVE = "r"
ENTITY_EVENT_CHANGE = "c"
BASE_ERROR_MESSAGE = {
"type": const.TYPE_RESULT,
"success": False,
}
INVALID_JSON_PARTIAL_MESSAGE = json_bytes(
{
**BASE_ERROR_MESSAGE,
"error": {
"code": const.ERR_UNKNOWN_ERROR,
"message": "Invalid JSON in response",
},
}
)
def result_message(iden: int, result: Any = None) -> dict[str, Any]:
"""Return a success result message."""
return {"id": iden, "type": const.TYPE_RESULT, "success": True, "result": result}
def construct_result_message(iden: int, payload: bytes) -> bytes:
"""Construct a success result message JSON."""
return b"".join(
(
b'{"id":',
str(iden).encode(),
b',"type":"result","success":true,"result":',
payload,
b"}",
)
)
def error_message(
iden: int | None,
code: str,
message: str,
translation_key: str | None = None,
translation_domain: str | None = None,
translation_placeholders: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Return an error result message."""
error_payload: dict[str, Any] = {
"code": code,
"message": message,
}
# In case `translation_key` is `None` we do not set it, nor the
# `translation`_placeholders` and `translation_domain`.
if translation_key is not None:
error_payload["translation_key"] = translation_key
error_payload["translation_placeholders"] = translation_placeholders
error_payload["translation_domain"] = translation_domain
return {
"id": iden,
**BASE_ERROR_MESSAGE,
"error": error_payload,
}
def event_message(iden: int, event: Any) -> dict[str, Any]:
"""Return an event message."""
return {"id": iden, "type": "event", "event": event}
def cached_event_message(message_id_as_bytes: bytes, event: Event) -> bytes:
"""Return an event message.
Serialize to json once per message.
Since we can have many clients connected that are
all getting many of the same events (mostly state changed)
we can avoid serializing the same data for each connection.
"""
return b"".join(
(
_partial_cached_event_message(event)[:-1],
b',"id":',
message_id_as_bytes,
b"}",
)
)
@lru_cache(maxsize=128)
def _partial_cached_event_message(event: Event) -> bytes:
"""Cache and serialize the event to json.
The message is constructed without the id which appended
in cached_event_message.
"""
return (
_message_to_json_bytes_or_none({"type": "event", "event": event.json_fragment})
or INVALID_JSON_PARTIAL_MESSAGE
)
def cached_state_diff_message(
message_id_as_bytes: bytes, event: Event[EventStateChangedData]
) -> bytes:
"""Return an event message.
Serialize to json once per message.
Since we can have many clients connected that are
all getting many of the same events (mostly state changed)
we can avoid serializing the same data for each connection.
"""
return b"".join(
(
_partial_cached_state_diff_message(event)[:-1],
b',"id":',
message_id_as_bytes,
b"}",
)
)
@lru_cache(maxsize=128)
def _partial_cached_state_diff_message(event: Event[EventStateChangedData]) -> bytes:
"""Cache and serialize the event to json.
The message is constructed without the id which
will be appended in cached_state_diff_message
"""
return (
_message_to_json_bytes_or_none(
{"type": "event", "event": _state_diff_event(event)}
)
or INVALID_JSON_PARTIAL_MESSAGE
)
def _state_diff_event(
event: Event[EventStateChangedData],
) -> dict[
str,
list[str]
| dict[str, CompressedState]
| dict[str, dict[str, dict[str, str | list[str]]]],
]:
"""Convert a state_changed event to the minimal version.
State update example
{
"a": {entity_id: compressed_state,…}
"c": {entity_id: diff,…}
"r": [entity_id,…]
}
"""
if (new_state := event.data["new_state"]) is None:
return {ENTITY_EVENT_REMOVE: [event.data["entity_id"]]}
if (old_state := event.data["old_state"]) is None:
return {ENTITY_EVENT_ADD: {new_state.entity_id: new_state.as_compressed_state}}
additions: dict[str, Any] = {}
diff: dict[str, dict[str, Any]] = {STATE_DIFF_ADDITIONS: additions}
new_state_context = new_state.context
old_state_context = old_state.context
if old_state.state != new_state.state:
additions[COMPRESSED_STATE_STATE] = new_state.state
if old_state.last_changed != new_state.last_changed:
additions[COMPRESSED_STATE_LAST_CHANGED] = new_state.last_changed_timestamp
elif old_state.last_updated != new_state.last_updated:
additions[COMPRESSED_STATE_LAST_UPDATED] = new_state.last_updated_timestamp
if old_state_context.parent_id != new_state_context.parent_id:
additions[COMPRESSED_STATE_CONTEXT] = {"parent_id": new_state_context.parent_id}
if old_state_context.user_id != new_state_context.user_id:
if COMPRESSED_STATE_CONTEXT in additions:
additions[COMPRESSED_STATE_CONTEXT]["user_id"] = new_state_context.user_id
else:
additions[COMPRESSED_STATE_CONTEXT] = {"user_id": new_state_context.user_id}
if old_state_context.id != new_state_context.id:
if COMPRESSED_STATE_CONTEXT in additions:
additions[COMPRESSED_STATE_CONTEXT]["id"] = new_state_context.id
else:
additions[COMPRESSED_STATE_CONTEXT] = new_state_context.id
if (old_attributes := old_state.attributes) != (
new_attributes := new_state.attributes
):
if added := {
key: value
for key, value in new_attributes.items()
if key not in old_attributes or old_attributes[key] != value
}:
additions[COMPRESSED_STATE_ATTRIBUTES] = added
if removed := old_attributes.keys() - new_attributes:
# sets are not JSON serializable by default so we convert to list
# here if there are any values to avoid jumping into the json_encoder_default
# for every state diff with a removed attribute
diff[STATE_DIFF_REMOVALS] = {COMPRESSED_STATE_ATTRIBUTES: list(removed)}
return {ENTITY_EVENT_CHANGE: {new_state.entity_id: diff}}
def _message_to_json_bytes_or_none(message: dict[str, Any]) -> bytes | None:
"""Serialize a websocket message to json or return None."""
try:
return json_bytes(message)
except (ValueError, TypeError):
_LOGGER.error(
"Unable to serialize to JSON. Bad data found at %s",
format_unserializable_data(
find_paths_unserializable_data(message, dump=JSON_DUMP)
),
)
return None
def message_to_json_bytes(message: dict[str, Any]) -> bytes:
"""Serialize a websocket message to json or return an error."""
return _message_to_json_bytes_or_none(message) or json_bytes(
error_message(
message["id"], const.ERR_UNKNOWN_ERROR, "Invalid JSON in response"
)
)

View File

@@ -0,0 +1,56 @@
"""Entity to track connections to websocket API."""
from __future__ import annotations
from homeassistant.components.sensor import SensorEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import (
DATA_CONNECTIONS,
SIGNAL_WEBSOCKET_CONNECTED,
SIGNAL_WEBSOCKET_DISCONNECTED,
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the API streams platform."""
entity = APICount()
async_add_entities([entity])
class APICount(SensorEntity):
"""Entity to represent how many people are connected to the stream API."""
_attr_name = "Connected clients"
_attr_native_unit_of_measurement = "clients"
def __init__(self) -> None:
"""Initialize the API count."""
self._attr_native_value = 0
async def async_added_to_hass(self) -> None:
"""Handle addition to hass."""
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_WEBSOCKET_CONNECTED, self._update_count
)
)
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_WEBSOCKET_DISCONNECTED, self._update_count
)
)
@callback
def _update_count(self) -> None:
self._attr_native_value = self.hass.data.get(DATA_CONNECTIONS, 0)
self.async_write_ha_state()

View File

@@ -0,0 +1,7 @@
{
"exceptions": {
"child_service_not_found": {
"message": "Action {domain}.{service} uses action {child_domain}.{child_service} which was not found."
}
}
}

View File

@@ -0,0 +1,13 @@
"""Websocket API util.""."""
from __future__ import annotations
from aiohttp import web
def describe_request(request: web.Request) -> str:
"""Describe a request."""
description = f"from {request.remote}"
if user_agent := request.headers.get("user-agent"):
description += f" ({user_agent})"
return description