Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Significantly speed up single use callback dispatchers #117934

Merged
merged 5 commits into from
May 24, 2024
Merged
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
22 changes: 19 additions & 3 deletions homeassistant/helpers/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@

from homeassistant.core import (
HassJob,
HassJobType,
HomeAssistant,
callback,
get_hassjob_callable_job_type,
)
from homeassistant.loader import bind_hass
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util.logging import catch_log_exception
from homeassistant.util.logging import catch_log_exception, log_exception

# Explicit reexport of 'SignalType' for backwards compatibility
from homeassistant.util.signal_type import SignalType as SignalType # noqa: PLC0414
Expand Down Expand Up @@ -167,11 +168,17 @@ def _generate_job[*_Ts](
) -> HassJob[..., None | Coroutine[Any, Any, None]]:
"""Generate a HassJob for a signal and target."""
job_type = get_hassjob_callable_job_type(target)
name = f"dispatcher {signal}"
if job_type is HassJobType.Callback:
# We will catch exceptions in the callback to avoid
# wrapping the callback since calling wraps() is more
# expensive than the whole dispatcher_send process
return HassJob(target, name, job_type=job_type)
return HassJob(
catch_log_exception(
target, partial(_format_err, signal, target), job_type=job_type
),
f"dispatcher {signal}",
name,
job_type=job_type,
)

Expand Down Expand Up @@ -236,4 +243,13 @@ def async_dispatcher_send_internal[*_Ts](
if job is None:
job = _generate_job(signal, target)
target_list[target] = job
hass.async_run_hass_job(job, *args)
# We do not wrap Callback jobs in catch_log_exception since
# single use dispatchers spend more time wrapping the callback
# than the actual callback takes to run in many cases.
if job.job_type is HassJobType.Callback:
bdraco marked this conversation as resolved.
Show resolved Hide resolved
bdraco marked this conversation as resolved.
Show resolved Hide resolved
try:
job.target(*args)
except Exception: # noqa: BLE001
log_exception(partial(_format_err, signal, target), *args) # type: ignore[arg-type]
else:
hass.async_run_hass_job(job, *args)