Fix Throttle cooldown restarting on refused no_throttle calls (#187647)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raman Gupta
2026-10-20 22:32:33 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 17652e4760
commit 16446e1328
2 changed files with 33 additions and 6 deletions
+9 -6
View File
@@ -148,9 +148,6 @@ class Throttle:
def throttled_value() -> None: # type: ignore[misc]
"""Stand-in function for when real func is being throttled."""
if self.limit_no_throttle is not None:
method = Throttle(self.limit_no_throttle)(method)
# Different methods that can be passed in:
# - a function
# - an unbound function on a class
@@ -189,11 +186,17 @@ class Throttle:
if not throttle[0].acquire(False):
return throttled_value()
# Check if method is never called or no_throttle is given
force = kwargs.pop("no_throttle", False) or not throttle[1]
no_throttle = kwargs.pop("no_throttle", False)
try:
if force or utcnow() - throttle[1] > self.min_time:
# limit_no_throttle always applies, min_time only without no_throttle
if not throttle[1] or (
(no_throttle or utcnow() - throttle[1] > self.min_time)
and (
self.limit_no_throttle is None
or utcnow() - throttle[1] > self.limit_no_throttle
)
):
result = method(*args, **kwargs)
throttle[1] = utcnow()
return result # type: ignore[no-any-return]
+24
View File
@@ -146,6 +146,30 @@ def test_throttle() -> None:
assert len(calls2) == 2
def test_throttle_refused_no_throttle_call_keeps_cooldown() -> None:
"""Test a no_throttle call refused by limit_no_throttle keeps the cooldown."""
calls = []
@util.Throttle(timedelta(seconds=10), timedelta(seconds=5))
def test_throttle():
calls.append(1)
return True
now = dt_util.utcnow()
with patch("homeassistant.util.utcnow", return_value=now):
assert test_throttle() is True
# Refused by limit_no_throttle, must not restart the min_time cooldown
with patch("homeassistant.util.utcnow", return_value=now + timedelta(seconds=2)):
assert test_throttle(no_throttle=True) is None
with patch("homeassistant.util.utcnow", return_value=now + timedelta(seconds=11)):
assert test_throttle() is True
assert len(calls) == 2
def test_throttle_per_instance() -> None:
"""Test that the throttle method is done per instance of a class."""