Reduce event loop overhead for listeners that already queue (#71364)

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
J. Nick Koston 2022-05-05 23:09:10 -04:00 committed by GitHub
parent 07706fa62a
commit d612b9e0b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 61 additions and 16 deletions

View file

@ -105,17 +105,21 @@ def handle_subscribe_events(
):
return
connection.send_message(messages.cached_event_message(msg["id"], event))
connection.send_message(
lambda: messages.cached_event_message(msg["id"], event)
)
else:
@callback
def forward_events(event: Event) -> None:
"""Forward events to websocket."""
connection.send_message(messages.cached_event_message(msg["id"], event))
connection.send_message(
lambda: messages.cached_event_message(msg["id"], event)
)
connection.subscriptions[msg["id"]] = hass.bus.async_listen(
event_type, forward_events
event_type, forward_events, run_immediately=True
)
connection.send_result(msg["id"])
@ -286,14 +290,16 @@ def handle_subscribe_entities(
if entity_ids and event.data["entity_id"] not in entity_ids:
return
connection.send_message(messages.cached_state_diff_message(msg["id"], event))
connection.send_message(
lambda: messages.cached_state_diff_message(msg["id"], event)
)
# 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)
connection.subscriptions[msg["id"]] = hass.bus.async_listen(
"state_changed", forward_entity_changes
EVENT_STATE_CHANGED, forward_entity_changes, run_immediately=True
)
connection.send_result(msg["id"])
data: dict[str, dict[str, dict]] = {