Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
222 changes: 185 additions & 37 deletions homeassistant_api/asyncwebsocket.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import contextlib
import json
import logging
Expand Down Expand Up @@ -43,17 +44,32 @@

if TYPE_CHECKING:
from collections.abc import AsyncGenerator
from collections.abc import Generator
from datetime import datetime
from types import TracebackType

from urllib3.contrib.webextensions._async.protocol import AsyncExtensionFromHTTP

logger = logging.getLogger(__name__)

# What the reader task can hand to a waiting recv(): a response, or the error to raise.
_Inbound = ResultResponse | EventResponse | PingResponse | BaseException

# Commands whose id keeps receiving events after its result, until unsubscribed.
_STREAMING_COMMANDS = frozenset(
{
"config_entries/subscribe",
"render_template",
"subscribe_events",
"subscribe_trigger",
},
)


class AsyncWebsocketClient(BaseWebsocketClient):
_session: AsyncSession
_ws: AsyncExtensionFromHTTP
_reader_task: asyncio.Task[None]

def __init__(
self,
Expand All @@ -65,17 +81,32 @@ def __init__(
) -> None:
super().__init__(api_url, token, max_size=max_size)
self._session = session if session is not None else AsyncSession()
# One inbox per pending request id. The reader task puts each response
# (or the error for it) in its owner's inbox, so a message only wakes
# the task waiting on that id.
self._inboxes: dict[int, asyncio.Queue[_Inbound]] = {}
self._streaming_ids: set[int] = set()
self._ping_starts: dict[int, int] = {}
self._fatal_error: BaseException | None = None

async def __aenter__(self) -> Self:
# Start clean if this instance is re-entered after an earlier connection.
self._inboxes.clear()
self._streaming_ids.clear()
self._ping_starts.clear()
self._fatal_error = None
await self._session.__aenter__()
resp = await self._session.get(self.api_url)
resp.raise_for_status()
if resp.extension is None:
msg = "Server did not upgrade to WebSocket"
raise ReceivingError(msg)
self._ws = resp.extension
# Authenticate before starting the reader task: these messages have no "id"
# and aren't dispatched through it, so nothing else may read the socket yet.
okay = await self.authentication_phase()
logger.info("Authenticated with Home Assistant (%s)", okay.ha_version)
self._reader_task = asyncio.create_task(self._reader_loop())
await self.supported_features_phase()
return self

Expand All @@ -85,10 +116,106 @@ async def __aexit__(
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
self._reader_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._reader_task
if self._fatal_error is None:
# Nothing will be read any more: wake every pending recv() instead of
# leaving it waiting forever.
self._fail_all(ReceivingError("WebSocket client closed"))
await self._ws.close()
del self._ws
await self._session.__aexit__(exc_type, exc_value, traceback)

async def _reader_loop(self) -> None:
"""
Continuously read messages off the socket and dispatch them by id.

This is the only task allowed to touch the socket directly, so reads can
never interleave or starve a waiting `recv()` call.
"""
while True:
try:
data = await self._async_recv()
except Exception as e: # noqa: BLE001
# No message id is available yet, so there's no single owner to
# blame this on: the connection is dead for every pending recv().
self._fail_all(e)
return
self._dispatch(data)
if self._fatal_error is not None:
return # a protocol error in that message: the connection is unusable

def _dispatch(self, data: dict[str, Any]) -> None:
"""Hand a received message to `handle_recv`, routing any failure to its owner."""
try:
self.handle_recv(data)
except Exception as e: # noqa: BLE001
data_id = data.get("id")
if not isinstance(data_id, int):
self._fail_all(e)
elif (inbox := self._inboxes.get(data_id)) is not None:
# The message carried its own id, so only the caller waiting
# on that id needs to see the failure.
inbox.put_nowait(e)
else:
logger.warning(
"Dropping error for unknown message id %s: %s",
data_id,
e,
)

def _fail_all(self, error: BaseException) -> None:
"""Fail every pending recv(), and every later one, with a connection-level error."""
self._fatal_error = error
for inbox in self._inboxes.values():
inbox.put_nowait(error)

def _deliver(self, msg_id: int, item: _Inbound) -> None:
"""Put a response in the inbox of the request it answers."""
inbox = self._inboxes.get(msg_id)
if inbox is None:
# e.g. an event still in flight when its subscription was cancelled
logger.debug("Dropping message for id %s with no pending request", msg_id)
return
inbox.put_nowait(item)

def _forget(self, msg_id: int) -> None:
"""Release everything held for a request that will get no more responses."""
self._inboxes.pop(msg_id, None)
self._streaming_ids.discard(msg_id)
self._ping_starts.pop(msg_id, None)

@contextlib.contextmanager
def _released_on_error(self, subscription_id: int) -> Generator[None, None, None]:
"""
Release a subscription's state if the ``listen_*`` body raises or is cancelled.

Unsubscribing is skipped then, since the connection may be the problem;
events still in flight for the id are dropped.
"""
try:
yield
except BaseException:
self._forget(subscription_id)
raise

def _store_result(self, msg_id: int, response: ResultResponse) -> None:
self._deliver(msg_id, response)

def _store_event(self, msg_id: int, response: EventResponse) -> None:
self._deliver(msg_id, response)

def _store_pong(self, msg_id: int, end_ns: int) -> None:
start = self._ping_starts.pop(msg_id, None)
if start is None:
logger.debug("Dropping pong for unknown ping id %s", msg_id)
return
self._deliver(
msg_id,
PingResponse(start=start, end=end_ns, id=msg_id, type="pong"),
)

async def _async_send(self, data: dict[str, Any]) -> None:
"""Send a message to the websocket server."""
if data.get("type") != "auth":
Expand Down Expand Up @@ -124,43 +251,61 @@ async def send(self, msg_type: str, *, include_id: bool = True, **data: Any) ->
data["id"] = self._request_id()

data["type"] = msg_type
await self._async_send(data)
if "id" not in data:
await self._async_send(data)
return -1 # non-command messages don't have an id

if "id" in data:
if not isinstance(data["id"], int):
msg = f"Expected int for message id, got {type(data['id'])}"
raise TypeError(msg)
if data["type"] == "ping":
self._ping_responses[data["id"]] = PingResponse(
start=time.perf_counter_ns(),
id=data["id"],
type="pong",
)
else:
self._event_responses[data["id"]] = []
self._result_responses[data["id"]] = None
return data["id"]
return -1 # non-command messages don't have an id
msg_id = data["id"]
if not isinstance(msg_id, int):
msg = f"Expected int for message id, got {type(msg_id)}"
raise TypeError(msg)
# Register before sending: the reader task can dispatch the reply
# before send_payload() returns.
self._inboxes[msg_id] = asyncio.Queue()
if msg_type in _STREAMING_COMMANDS:
self._streaming_ids.add(msg_id)
if msg_type == "ping":
self._ping_starts[msg_id] = time.perf_counter_ns()
try:
await self._async_send(data)
except BaseException:
self._forget(msg_id)
raise
return msg_id

async def recv(
self,
msg_id: int,
) -> EventResponse | ResultResponse | PingResponse | None:
"""Receive a response to a message from the websocket server."""
while True:
## have we received a message with the id we're looking for?
if self._result_responses.get(msg_id) is not None:
return self._result_responses.pop(msg_id)
if self._event_responses.get(msg_id, []):
return self._event_responses[msg_id].pop(0)
if (
self._ping_responses.get(msg_id) is not None
and self._ping_responses[msg_id].end is not None
):
return self._ping_responses.pop(msg_id)
inbox = self._inboxes.get(msg_id)
if inbox is None:
if self._fatal_error is not None:
raise self._fatal_error
msg = f"No pending request with id {msg_id}"
raise ReceivingError(msg)
if inbox.empty() and self._fatal_error is not None:
raise self._fatal_error

## if not, keep receiving messages until we do
self.handle_recv(await self._async_recv())
try:
item = await inbox.get()
except asyncio.CancelledError:
# e.g. a timeout around ping_latency(): nobody will read this reply.
# Subscriptions are released by unsubscribing instead.
if msg_id not in self._streaming_ids:
self._forget(msg_id)
raise
streaming = msg_id in self._streaming_ids
if isinstance(item, BaseException):
# A failed result ends the request; a bad event doesn't end a subscription.
if item is not self._fatal_error and (
not streaming or isinstance(item, ResponseError)
):
self._forget(msg_id)
raise item
if not streaming and isinstance(item, ResultResponse | PingResponse):
self._forget(msg_id) # single-shot request: nothing else will arrive
return item

async def recv_result(self, msg_id: int) -> ResultResponse:
"""Receive a ResultResponse, raising TypeError if the response is not a ResultResponse."""
Expand Down Expand Up @@ -481,7 +626,8 @@ async def listen_events(
print(event)
"""
subscription = await self._async_subscribe_events(event_type)
yield self._async_wait_for(subscription)
with self._released_on_error(subscription):
yield self._async_wait_for(subscription)
await self._async_unsubscribe(subscription)

async def _async_subscribe_events(self, event_type: str | None) -> int:
Expand Down Expand Up @@ -531,11 +677,12 @@ async def listen_trigger(
Woohoo! We can now listen to triggers in Python code!
"""
subscription = await self._async_subscribe_trigger(trigger, **trigger_fields)
yield (
fired_trigger.variables
async for fired_trigger in self._async_wait_for(subscription)
if isinstance(fired_trigger, FiredTrigger)
)
with self._released_on_error(subscription):
yield (
fired_trigger.variables
async for fired_trigger in self._async_wait_for(subscription)
if isinstance(fired_trigger, FiredTrigger)
)
await self._async_unsubscribe(subscription)

async def _async_subscribe_trigger(
Expand Down Expand Up @@ -584,7 +731,7 @@ async def _async_unsubscribe(self, subcription_id: int) -> None:
msg = "Expected None result for unsubscribe"
raise ValueError(msg)
finally:
self._event_responses.pop(subcription_id, None)
self._forget(subcription_id)

async def get_config_entries(self) -> tuple[ConfigEntry, ...]:
"""
Expand Down Expand Up @@ -751,7 +898,8 @@ async def listen_config_entries(
subscription = (
await self.recv_result(await self.send("config_entries/subscribe"))
).id
yield self._async_wait_for_config_entries(subscription)
with self._released_on_error(subscription):
yield self._async_wait_for_config_entries(subscription)
await self._async_unsubscribe(subscription)

async def _async_wait_for_config_entries(
Expand Down
26 changes: 16 additions & 10 deletions homeassistant_api/basewebsocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from homeassistant_api.errors import ResponseError
from homeassistant_api.models.websocket import ErrorResponse
from homeassistant_api.models.websocket import EventResponse
from homeassistant_api.models.websocket import PingResponse
from homeassistant_api.models.websocket import ResultResponse

logger = logging.getLogger(__name__)
Expand All @@ -21,9 +20,6 @@ class BaseWebsocketClient:
token: str
max_size: int
_id_counter: int
_result_responses: dict[int, ResultResponse | None]
_event_responses: dict[int, list[EventResponse]]
_ping_responses: dict[int, PingResponse]

def __init__(self, api_url: str, token: str, *, max_size: int = 2**24) -> None:
parsed = urlparse.urlparse(api_url)
Expand All @@ -38,9 +34,6 @@ def __init__(self, api_url: str, token: str, *, max_size: int = 2**24) -> None:
self.max_size = max_size

self._id_counter = 0
self._result_responses = {} # id -> response
self._event_responses = {} # id -> [response, ...]
self._ping_responses = {} # id -> (sent, received)

def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.api_url!r})"
Expand All @@ -58,21 +51,34 @@ def handle_recv(self, data: dict[str, Any]) -> None:
self.parse_response(data)

def parse_response(self, data: dict[str, Any]) -> None:
"""Parse a received message by type and hand it to the matching storage hook."""
data_id = cast("int", data["id"])
if data.get("type") == "pong":
logger.info("Received pong message")
self._ping_responses[data_id].end = time.perf_counter_ns()
self._store_pong(data_id, time.perf_counter_ns())
elif data.get("type") == "result":
logger.info("Received result message")
if data.get("success"):
self._result_responses[data_id] = ResultResponse.model_validate(data)
self._store_result(data_id, ResultResponse.model_validate(data))
else:
error_resp = ErrorResponse.model_validate(data)
msg = f"[{error_resp.error.code}] {error_resp.error.message}"
raise ResponseError(msg)
elif data.get("type") == "event":
logger.info("Received event message %s", data["event"])
self._event_responses[data_id].append(EventResponse.model_validate(data))
self._store_event(data_id, EventResponse.model_validate(data))
else:
msg = f"Received unexpected message type: {data}"
raise ReceivingError(msg)

def _store_result(self, msg_id: int, response: ResultResponse) -> None:
"""Make a successful result available to whoever waits on ``msg_id``."""
raise NotImplementedError

def _store_event(self, msg_id: int, response: EventResponse) -> None:
"""Make an event available to whoever waits on subscription ``msg_id``."""
raise NotImplementedError

def _store_pong(self, msg_id: int, end_ns: int) -> None:
"""Complete the ping ``msg_id``, which the pong arrived for at ``end_ns``."""
raise NotImplementedError
Loading
Loading