Use an event filter for event triggers (#89339)

We avoid the overhead of call_soon and event loop
scheduling if the event does not match the schema
This commit is contained in:
J. Nick Koston 2023-03-08 05:23:13 -10:00 committed by GitHub
parent 4ce36366c3
commit 614a1b03c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -80,11 +80,11 @@ async def async_attach_trigger(
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
job = HassJob(action) job = HassJob(action, f"event trigger {trigger_info}")
@callback @callback
def handle_event(event: Event) -> None: def filter_event(event: Event) -> bool:
"""Listen for events and calls the action when data matches.""" """Filter events."""
try: try:
# Check that the event data and context match the configured # Check that the event data and context match the configured
# schema if one was provided # schema if one was provided
@ -94,8 +94,12 @@ async def async_attach_trigger(
event_context_schema(event.context.as_dict()) event_context_schema(event.context.as_dict())
except vol.Invalid: except vol.Invalid:
# If event doesn't match, skip event # If event doesn't match, skip event
return return False
return True
@callback
def handle_event(event: Event) -> None:
"""Listen for events and calls the action when data matches."""
hass.async_run_hass_job( hass.async_run_hass_job(
job, job,
{ {
@ -110,7 +114,8 @@ async def async_attach_trigger(
) )
removes = [ removes = [
hass.bus.async_listen(event_type, handle_event) for event_type in event_types hass.bus.async_listen(event_type, handle_event, event_filter=filter_event)
for event_type in event_types
] ]
@callback @callback