diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 8e15817..f69d8ac 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -57,15 +57,18 @@ def _parse_block_seconds(content: bytes) -> Optional[int]: return int(match.group(1)) -def _rate_limit_wait_seconds(content: bytes) -> int: - """Effective wait for a 429: parsed duration + 1s margin, else 5s.""" +# Ariston answers "Requests are blocked" without a duration once an account +# exceeds its request budget. Retrying keeps the block alive, so every request +# of the instance pauses instead, doubling the pause while the block persists. +RATE_LIMIT_BACKOFF_START_SECONDS = 15 * 60 +RATE_LIMIT_BACKOFF_MAX_SECONDS = 2 * 60 * 60 + + +def _rate_limit_wait_seconds(content: bytes) -> Optional[int]: + """Effective wait for a 429: parsed duration + 1s margin, else None.""" parsed = _parse_block_seconds(content) if parsed is None: - _LOGGER.warning( - "Rate limited (429) without parsable block duration; " - "falling back to 5s wait" - ) - return 5 + return None _LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1) return parsed + 1 @@ -98,6 +101,8 @@ def __init__( # API URLs must not silence each other; the three coordinators for # one account still share one API instance. self._blocked_until = 0.0 + # Current pause for 429s without a block duration; 0 after a success. + self._rate_limit_backoff_seconds = 0 # Sync (requests) R2 web-app session; created lazily on first use. self.__r2_requests_session: Optional[requests.Session] = None @@ -566,9 +571,12 @@ def __request( params: Optional[dict[str, Any]] = None, body: Any = None, is_retry: bool = False, + waited_out_block: bool = False, ) -> Optional[dict[str, Any]]: """Request with requests""" - if not is_retry and time.time() < self._blocked_until: + # Retries are checked too: a 405/5xx retry must not slip through a + # pause that another in-flight response started meanwhile. + if not waited_out_block and time.time() < self._blocked_until: raise ConnectionException( 429, "Rate limited; skipping request until the block window ends", @@ -607,6 +615,7 @@ def __request( return self.__request(method, path, params, body, True) raise ConnectionException(response.status_code) + self._reset_rate_limit_backoff() if len(response.content) > 0: json = response.json() _LOGGER.debug("Response %s", json) @@ -618,6 +627,45 @@ def _post(self, path: str, body: Any) -> Any: """POST request""" return self.__request("POST", path, None, body) + def _start_rate_limit_backoff(self) -> None: + """Pause all requests of this instance after a 429 without a duration.""" + if self._rate_limit_backoff_seconds and time.time() < self._blocked_until: + # Sent before the current pause started: same block, keep the pause. + return + self._rate_limit_backoff_seconds = ( + min(self._rate_limit_backoff_seconds * 2, RATE_LIMIT_BACKOFF_MAX_SECONDS) + if self._rate_limit_backoff_seconds + else RATE_LIMIT_BACKOFF_START_SECONDS + ) + self._blocked_until = max( + self._blocked_until, time.time() + self._rate_limit_backoff_seconds + ) + _LOGGER.warning( + "Rate limited (429) without block duration; pausing requests for %s seconds", + self._rate_limit_backoff_seconds, + ) + + def _reset_rate_limit_backoff(self) -> None: + """Forget the backoff after a success, unless a pause is still active. + + A success that was in flight when a pause started does not prove the + block is over, so it must not reset the doubling. + """ + if time.time() >= self._blocked_until: + self._rate_limit_backoff_seconds = 0 + + def _start_rate_limit_wait(self, wait_seconds: int) -> Optional[float]: + """Block until a parsed 429 window ends, without shortening a longer pause. + + Returns the end of the window to wait out, or None when a longer pause + is already active and the request must not be retried. + """ + until = time.time() + wait_seconds + if self._blocked_until > until: + return None + self._blocked_until = until + return until + def __handle_rate_limit( self, response, @@ -627,13 +675,18 @@ def __handle_rate_limit( params: Optional[dict[str, Any]], body: Any, ) -> Optional[dict[str, Any]]: - """Sleep out the 429 block window, retry once, per-instance deadline.""" + """Sleep out a short 429 block window and retry once; back off otherwise.""" content = response.content wait_seconds = _rate_limit_wait_seconds(content) - self._blocked_until = time.time() + wait_seconds - if not is_retry: + if wait_seconds is None: + self._start_rate_limit_backoff() + raise ConnectionException(response.status_code, content.decode()) + until = self._start_rate_limit_wait(wait_seconds) + if until is not None and not is_retry: time.sleep(wait_seconds) - return self.__request(method, path, params, body, True) + # Retry only if no longer pause started while waiting. + if self._blocked_until <= until: + return self.__request(method, path, params, body, True, True) raise ConnectionException(response.status_code, content.decode()) def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: @@ -1506,9 +1559,12 @@ async def __async_request( body: Any = None, is_retry: bool = False, timeout_seconds: int = 30, + waited_out_block: bool = False, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" - if not is_retry and time.time() < self._blocked_until: + # Retries are checked too: a 405/5xx retry must not slip through a + # pause that another in-flight response started meanwhile. + if not waited_out_block and time.time() < self._blocked_until: raise ConnectionException( 429, "Rate limited; skipping request until the block window ends", @@ -1558,6 +1614,7 @@ async def __async_request( ) raise ConnectionException(response.status) + self._reset_rate_limit_backoff() if response.content_length and response.content_length > 0: json = await response.json() _LOGGER.debug("Response %s", json) @@ -1583,15 +1640,20 @@ async def __async_handle_rate_limit( body: Any, timeout_seconds: int, ) -> Optional[dict[str, Any]]: - """Sleep out the 429 block window, retry once, share the deadline.""" + """Sleep out a short 429 block window and retry once; back off otherwise.""" content = await response.content.read() wait_seconds = _rate_limit_wait_seconds(content) - self._blocked_until = time.time() + wait_seconds - if not is_retry: + if wait_seconds is None: + self._start_rate_limit_backoff() + raise ConnectionException(response.status, content) + until = self._start_rate_limit_wait(wait_seconds) + if until is not None and not is_retry: await asyncio.sleep(wait_seconds) - return await self.__async_request( - method, path, params, body, True, timeout_seconds - ) + # Retry only if no longer pause started while waiting. + if self._blocked_until <= until: + return await self.__async_request( + method, path, params, body, True, timeout_seconds, True + ) raise ConnectionException(response.status, content) async def _async_get( diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index 7b11ea6..44bd929 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -5,6 +5,7 @@ import logging import math +import time from datetime import date from typing import Any, Optional @@ -29,6 +30,15 @@ ) from .device import AristonDevice +# Hybrid and heat pump menu items cost up to four extra requests per refresh +# (more when the per-item fallback runs). Refreshing them on every poll exhausts +# Ariston's per-account request budget, so they are refreshed less often and the +# last values are kept in between. +HYBRID_MENU_ITEMS_REFRESH_SECONDS = 30 * 60 +HYBRID_MENU_ITEM_IDS = frozenset( + item.value for group in MenuItemNames.hybrid_groups() for item in group +) + _LOGGER = logging.getLogger(__name__) _MENU_ITEM_UNAVAILABLE_VALUES = frozenset({3276.0, 3276.7, -3276.8, -3277.0}) _CH_RETURN_TEMP_UNAVAILABLE_VALUES = _MENU_ITEM_UNAVAILABLE_VALUES | {0.0} @@ -50,6 +60,8 @@ def __init__( self.consumptions_settings: dict[str, Any] = {} self.energy_account: dict[str, Any] = {} self.menu_items: list[dict[str, Any]] = [] + # When the hybrid menu items were last fetched successfully. + self._hybrid_menu_items_fetched_at: Optional[float] = None @property def consumption_type(self) -> str: @@ -121,6 +133,35 @@ def _should_include_hybrid_menu_items(self) -> bool: or self.features.get(DeviceFeatures.HP_SYS) is True ) + def _hybrid_menu_items_due(self) -> bool: + """Return True if this refresh should request the hybrid menu items.""" + if not self._should_include_hybrid_menu_items(): + return False + last = self._hybrid_menu_items_fetched_at + return last is None or time.monotonic() - last >= HYBRID_MENU_ITEMS_REFRESH_SECONDS + + def _mark_hybrid_menu_items_fetched(self, include_hybrid_items: bool) -> None: + """Start the refresh window only once the hybrid items really arrived. + + A request skipped by a 429 pause or failed by a server error must not + delay the next attempt by a whole window. + """ + if include_hybrid_items: + self._hybrid_menu_items_fetched_at = time.monotonic() + + def _with_cached_hybrid_menu_items( + self, items: list[dict[str, Any]], include_hybrid_items: bool + ) -> list[dict[str, Any]]: + """Keep the last hybrid menu items when this refresh skipped them.""" + if include_hybrid_items or not self._should_include_hybrid_menu_items(): + return items + ids = {item.get("id") for item in items} + return items + [ + item + for item in self.menu_items + if item.get("id") in HYBRID_MENU_ITEM_IDS and item.get("id") not in ids + ] + def update_state(self) -> None: """Update the device states from the cloud""" if len(self.features) == 0: @@ -132,11 +173,15 @@ def update_state(self) -> None: self.language_tag, self.umsys, ) + include_hybrid_items = self._hybrid_menu_items_due() try: - self.menu_items = self.api.get_menu_items( - self.gw, - include_hybrid_items=self._should_include_hybrid_menu_items(), + self.menu_items = self._with_cached_hybrid_menu_items( + self.api.get_menu_items( + self.gw, include_hybrid_items=include_hybrid_items + ), + include_hybrid_items, ) + self._mark_hybrid_menu_items_fetched(include_hybrid_items) except ConnectionException as error: if not self._should_retain_menu_items_after_error(error): raise @@ -147,31 +192,38 @@ async def async_update_state(self) -> None: if len(self.features) == 0: await self.async_get_features() - (self.data, self.menu_items) = await asyncio.gather( + include_hybrid_items = self._hybrid_menu_items_due() + (self.data, (self.menu_items, fetched)) = await asyncio.gather( self.api.async_get_properties( self.gw, self.features, self.language_tag, self.umsys, ), - self._async_get_menu_items( - include_hybrid_items=self._should_include_hybrid_menu_items() - ), + self._async_get_menu_items(include_hybrid_items=include_hybrid_items), ) + # Only once both results are stored: a failed properties request + # discards the menu items, so they must be fetched again. + self._mark_hybrid_menu_items_fetched(include_hybrid_items and fetched) self._update_state() async def _async_get_menu_items( self, include_hybrid_items: bool = False - ) -> list[dict[str, Any]]: - """Get menu items while retaining the last values for server errors.""" + ) -> tuple[list[dict[str, Any]], bool]: + """Get menu items while retaining the last values for server errors. + + Returns the items and whether they were fetched (False when the last + values were retained after a server error). + """ try: - return await self.api.async_get_menu_items( + items = await self.api.async_get_menu_items( self.gw, include_hybrid_items=include_hybrid_items ) except ConnectionException as error: if not self._should_retain_menu_items_after_error(error): raise - return self.menu_items + return self.menu_items, False + return self._with_cached_hybrid_menu_items(items, include_hybrid_items), True def _should_retain_menu_items_after_error( self, error: ConnectionException diff --git a/tests/test_galevo_device.py b/tests/test_galevo_device.py index e36b5e7..d547b5f 100644 --- a/tests/test_galevo_device.py +++ b/tests/test_galevo_device.py @@ -114,6 +114,109 @@ def test_async_update_requests_hybrid_menu_items_only_for_hybrid_devices(self): "gw-1", include_hybrid_items=False ) + def test_async_update_throttles_hybrid_menu_items_and_keeps_last_values(self): + device = self.make_device() + device.features = {DeviceFeatures.HP_SYS: True} + device.api.async_get_properties = AsyncMock(return_value=self.make_data()) + core = {"id": MenuItemNames.SIGNAL_STRENGTH.value, PropertyType.VALUE: 80} + hybrid = {"id": MenuItemNames.HP_OUTSIDE_AIR_TEMP.value, PropertyType.VALUE: 12.0} + device.api.async_get_menu_items = AsyncMock(return_value=[core, hybrid]) + + with patch("ariston.galevo_device.time.monotonic", return_value=1000.0): + asyncio.run(device.async_update_state()) + device.api.async_get_menu_items.assert_awaited_once_with( + "gw-1", include_hybrid_items=True + ) + + # A refresh inside the window asks for core items only and keeps the + # last hybrid values. + device.api.async_get_menu_items = AsyncMock(return_value=[core]) + with patch("ariston.galevo_device.time.monotonic", return_value=2000.0): + asyncio.run(device.async_update_state()) + device.api.async_get_menu_items.assert_awaited_once_with( + "gw-1", include_hybrid_items=False + ) + self.assertEqual(device.hp_outside_air_temp_value, 12.0) + + # Once the window has passed, hybrid items are requested again. + device.api.async_get_menu_items = AsyncMock(return_value=[core, hybrid]) + with patch("ariston.galevo_device.time.monotonic", return_value=2800.0): + asyncio.run(device.async_update_state()) + device.api.async_get_menu_items.assert_awaited_once_with( + "gw-1", include_hybrid_items=True + ) + + def _hybrid_poll_setup(self): + device = self.make_device() + device.features = {DeviceFeatures.HP_SYS: True} + device.api.async_get_properties = AsyncMock(return_value=self.make_data()) + core = {"id": MenuItemNames.SIGNAL_STRENGTH.value, PropertyType.VALUE: 80} + hybrid = {"id": MenuItemNames.HP_OUTSIDE_AIR_TEMP.value, PropertyType.VALUE: 12.0} + return device, core, hybrid + + def _assert_hybrid_fetched_on_next_poll(self, device, core, hybrid): + """A poll one minute later must still ask for the hybrid items.""" + device.api.async_get_properties = AsyncMock(return_value=self.make_data()) + device.api.async_get_menu_items = AsyncMock(return_value=[core, hybrid]) + with patch("ariston.galevo_device.time.monotonic", return_value=1060.0): + asyncio.run(device.async_update_state()) + device.api.async_get_menu_items.assert_awaited_once_with( + "gw-1", include_hybrid_items=True + ) + self.assertEqual(device.hp_outside_air_temp_value, 12.0) + + def test_async_hybrid_items_fetched_on_first_poll_after_429_pause(self): + """Regression: a poll skipped by a 429 pause must not start the 30 min window.""" + device, core, hybrid = self._hybrid_poll_setup() + device.api.async_get_menu_items = AsyncMock( + side_effect=ConnectionException( + 429, "Rate limited; skipping request until the block window ends" + ) + ) + with patch("ariston.galevo_device.time.monotonic", return_value=1000.0): + with self.assertRaises(ConnectionException): + asyncio.run(device.async_update_state()) + + self._assert_hybrid_fetched_on_next_poll(device, core, hybrid) + + def test_async_hybrid_items_fetched_after_retained_server_error(self): + device, core, hybrid = self._hybrid_poll_setup() + device.api.async_get_menu_items = AsyncMock(side_effect=ConnectionException(500)) + with patch("ariston.galevo_device.time.monotonic", return_value=1000.0): + asyncio.run(device.async_update_state()) # keeps the last values + + self._assert_hybrid_fetched_on_next_poll(device, core, hybrid) + + def test_async_hybrid_items_fetched_again_when_properties_fail(self): + """Menu items discarded with a failed properties request are not 'fetched'.""" + device, core, hybrid = self._hybrid_poll_setup() + device.api.async_get_properties = AsyncMock(side_effect=ConnectionException(429)) + device.api.async_get_menu_items = AsyncMock(return_value=[core, hybrid]) + with patch("ariston.galevo_device.time.monotonic", return_value=1000.0): + with self.assertRaises(ConnectionException): + asyncio.run(device.async_update_state()) + + self._assert_hybrid_fetched_on_next_poll(device, core, hybrid) + + def test_sync_hybrid_items_fetched_on_first_poll_after_429_pause(self): + device, core, hybrid = self._hybrid_poll_setup() + device.api.get_properties.return_value = self.make_data() + device.api.get_menu_items.side_effect = ConnectionException( + 429, "Rate limited; skipping request until the block window ends" + ) + with patch("ariston.galevo_device.time.monotonic", return_value=1000.0): + with self.assertRaises(ConnectionException): + device.update_state() + + device.api.get_menu_items.reset_mock(side_effect=True) + device.api.get_menu_items.return_value = [core, hybrid] + with patch("ariston.galevo_device.time.monotonic", return_value=1060.0): + device.update_state() + device.api.get_menu_items.assert_called_once_with( + "gw-1", include_hybrid_items=True + ) + self.assertEqual(device.hp_outside_air_temp_value, 12.0) + def test_sync_update_requests_hybrid_menu_items_from_features(self): device = self.make_device() device.attributes["hybrSys"] = True @@ -817,6 +920,7 @@ def test_heat_pump_menu_items_availability_getters_and_error_handling(self): }, ] device.api.async_get_menu_items = AsyncMock(return_value=updated_hp) + device._hybrid_menu_items_fetched_at = None # next hybrid refresh is due asyncio.run(device.async_update_state()) device.api.async_get_menu_items.assert_awaited_once_with( "gw-1", include_hybrid_items=True diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 951952e..d0a483d 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -4,9 +4,11 @@ import time import unittest from typing import Any, Optional -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch from ariston.ariston_api import ( + RATE_LIMIT_BACKOFF_MAX_SECONDS, + RATE_LIMIT_BACKOFF_START_SECONDS, AristonAPI, ConnectionException, _parse_block_seconds, @@ -67,6 +69,34 @@ async def request(self, *args: Any, **kwargs: Any): return _Session +def _gated_session_cls(responses: list, arrived: list, release: list, calls: list): + """Session whose responses come back only when the test releases them. + + Lets a test keep several requests in flight and decide the order in + which their responses arrive. + """ + + class _Session: + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + async def __aenter__(self) -> "_Session": + return self + + async def __aexit__(self, *exc: Any) -> bool: + return False + + async def request(self, *args: Any, **kwargs: Any): + index = len(calls) + calls.append(index) + if index < len(arrived): + arrived[index].set() + await release[index].wait() + return responses[index] + + return _Session + + class RateLimitTests(unittest.TestCase): """429 handling: parse, sleep-out with a single retry, per-instance window.""" @@ -99,21 +129,19 @@ def test_429_parses_wait_seconds(self): self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin self.assertGreater(api._blocked_until, 0) # block window was set - def test_429_without_parsable_body(self): - responses = [ - _sync_response(429, b"Too many requests"), - _sync_response(200, b"{}", {"ok": True}), - ] - http = MagicMock(side_effect=responses) + def test_429_without_parsable_body_backs_off_without_retry(self): + http = MagicMock(side_effect=[_sync_response(429, b"Requests are blocked")]) sleeps: list[int] = [] + api = _api() with patch("ariston.ariston_api.requests.request", http), patch( "ariston.ariston_api.time.sleep", side_effect=sleeps.append - ): - result = _api()._get("https://example/api") + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + with self.assertRaises(ConnectionException): + api._get("https://example/api") - self.assertEqual(result, {"ok": True}) - self.assertEqual(sleeps, [5]) # documented fallback - self.assertEqual(http.call_count, 2) + self.assertEqual(http.call_count, 1) # no retry while blocked + self.assertEqual(sleeps, []) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) def test_429_twice_raises(self): body = b"Requests are blocked for 10 seconds" @@ -222,5 +250,237 @@ async def run() -> Any: self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 + def test_async_429_without_duration_backs_off_doubles_and_caps(self): + api = _api() + calls: list[int] = [] + sleeps: list[Optional[int]] = [] + waits: list[float] = [] + + async def blocked_request() -> None: + responses = [_FakeAiohttpResponse(429, b"Requests are blocked")] + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + with self.assertRaises(ConnectionException): + await api._async_get("https://example/api") + + for _ in range(5): + api._blocked_until = 0.0 # the previous pause has ended + asyncio.run(blocked_request()) + waits.append(api._blocked_until - 1000.0) + + start = RATE_LIMIT_BACKOFF_START_SECONDS + self.assertEqual(waits, [start, 2 * start, 4 * start, 8 * start, 8 * start]) + self.assertEqual(waits[-1], RATE_LIMIT_BACKOFF_MAX_SECONDS) + self.assertEqual(len(calls), 5) # one request per pause, no retries + self.assertEqual(sleeps, []) + + def test_async_success_resets_backoff(self): + api = _api() + api._rate_limit_backoff_seconds = 4 * RATE_LIMIT_BACKOFF_START_SECONDS + calls: list[int] = [] + + async def run(responses: list) -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + return await api._async_get("https://example/api") + + self.assertEqual( + asyncio.run(run([_FakeAiohttpResponse(200, b"{}", {"ok": True})])), + {"ok": True}, + ) + self.assertEqual(api._rate_limit_backoff_seconds, 0) + + with self.assertRaises(ConnectionException): + asyncio.run(run([_FakeAiohttpResponse(429, b"Requests are blocked")])) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + + # -- a pause in progress must hold for responses that were in flight -- + + def _run_two_in_flight(self, api: AristonAPI, responses: list, sleep: AsyncMock): + """Send two requests, then return the first response before the second. + + Both requests pass the pause check before either response arrives, + like two coordinators polling one account at the same moment. + """ + calls: list[int] = [] + outcomes: list[Any] = [] + + async def run() -> None: + arrived = [asyncio.Event(), asyncio.Event()] + release = [asyncio.Event(), asyncio.Event()] + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _gated_session_cls(responses, arrived, release, calls), + ), patch("ariston.ariston_api.asyncio.sleep", sleep), patch( + "ariston.ariston_api.time.time", return_value=1000.0 + ): + tasks = [ + asyncio.ensure_future(api._async_get("https://example/a")), + asyncio.ensure_future(api._async_get("https://example/b")), + ] + await arrived[0].wait() + await arrived[1].wait() + for gate, task in zip(release, tasks): + gate.set() + try: + outcomes.append(await task) + except ConnectionException as error: + outcomes.append(error) + + asyncio.run(run()) + return calls, outcomes + + def test_async_in_flight_short_429_keeps_active_pause(self): + """A 10 s 429 arriving during a 15 min pause neither shortens it nor retries.""" + api = _api() + sleep = AsyncMock() + calls, outcomes = self._run_two_in_flight( + api, + [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked for 10 seconds"), + ], + sleep, + ) + + self.assertEqual(len(calls), 2) # no retry after the short 429 + sleep.assert_not_awaited() + self.assertIsInstance(outcomes[1], ConnectionException) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + def test_async_in_flight_500_does_not_retry_during_pause(self): + """The 5xx retry is checked against a pause that began while waiting.""" + api = _api() + sleep = AsyncMock() + calls, outcomes = self._run_two_in_flight( + api, + [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(500), + ], + sleep, + ) + + self.assertEqual(len(calls), 2) # the retry never reached the network + sleep.assert_awaited_once_with(5) + self.assertEqual(outcomes[1].args[0], 429) # skipped by the pause + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + def test_async_in_flight_429_without_duration_does_not_double_pause(self): + api = _api() + calls, _ = self._run_two_in_flight( + api, + [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + ], + AsyncMock(), + ) + + self.assertEqual(len(calls), 2) + self.assertEqual(api._rate_limit_backoff_seconds, RATE_LIMIT_BACKOFF_START_SECONDS) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + def test_async_in_flight_success_keeps_pause_and_backoff(self): + """A success sent before the pause began does not prove the block is over.""" + api = _api() + _, outcomes = self._run_two_in_flight( + api, + [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ], + AsyncMock(), + ) + + self.assertEqual(outcomes[1], {"ok": True}) + self.assertEqual(api._rate_limit_backoff_seconds, RATE_LIMIT_BACKOFF_START_SECONDS) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + def test_async_429_wait_is_not_retried_if_a_longer_pause_starts(self): + api = _api() + calls: list[int] = [] + + async def longer_pause_meanwhile(_seconds: int) -> None: + api._start_rate_limit_backoff() # another response blocked the account + + async def run() -> None: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls( + [_FakeAiohttpResponse(429, b"Requests are blocked for 10 seconds")], + calls, + ), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=longer_pause_meanwhile + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + with self.assertRaises(ConnectionException): + await api._async_get("https://example/api") + + asyncio.run(run()) + + self.assertEqual(len(calls), 1) # no retry into the longer pause + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + # -- sync twins: another thread starts the pause meanwhile -- + + def test_sync_500_retry_respects_pause_started_meanwhile(self): + api = _api() + http = MagicMock(side_effect=[_sync_response(500)]) + + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", + side_effect=lambda _seconds: api._start_rate_limit_backoff(), + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + with self.assertRaises(ConnectionException) as raised: + api._get("https://example/api") + + self.assertEqual(http.call_count, 1) + self.assertEqual(raised.exception.args[0], 429) + + def test_sync_short_429_keeps_longer_pause(self): + api = _api() + sleeps: list[int] = [] + + def respond(*_args: Any, **_kwargs: Any): + api._start_rate_limit_backoff() # another thread got blocked meanwhile + return _sync_response(429, b"Requests are blocked for 10 seconds") + + with patch( + "ariston.ariston_api.requests.request", MagicMock(side_effect=respond) + ) as http, patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + + self.assertEqual(http.call_count, 1) + self.assertEqual(sleeps, []) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + def test_sync_429_wait_is_not_retried_if_a_longer_pause_starts(self): + api = _api() + http = MagicMock( + side_effect=[_sync_response(429, b"Requests are blocked for 10 seconds")] + ) + + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", + side_effect=lambda _seconds: api._start_rate_limit_backoff(), + ), patch("ariston.ariston_api.time.time", return_value=1000.0): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + + self.assertEqual(http.call_count, 1) + self.assertEqual(api._blocked_until, 1000.0 + RATE_LIMIT_BACKOFF_START_SECONDS) + + if __name__ == "__main__": unittest.main()