diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index d383445..888204a 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -49,7 +49,6 @@ _RATE_LIMIT_RE = re.compile(rb"blocked for (\d+) seconds", re.IGNORECASE) _RATE_LIMIT_WAIT_LOG = "Rate limited (429) for %s seconds; waiting it out" -_UNPARSABLE_INITIAL_WAIT_SECONDS = 5 _UNPARSABLE_COOLDOWN_BASE_SECONDS = 60 _UNPARSABLE_COOLDOWN_MAX_SECONDS = 600 _INCOMPLETE_MENU_CACHE_TTL_SECONDS = 3600 @@ -76,20 +75,6 @@ def _parse_retry_after_seconds(headers: Any) -> Optional[int]: return None -def _rate_limit_wait_seconds(content: bytes) -> int: - """Effective wait for a 429: parsed duration + 1s margin, else 5s.""" - parsed = _parse_block_seconds(content) - if parsed is None: - _LOGGER.warning( - "Rate limited (429) without parsable block duration; " - "falling back to %ss wait", - _UNPARSABLE_INITIAL_WAIT_SECONDS, - ) - return _UNPARSABLE_INITIAL_WAIT_SECONDS - _LOGGER.warning(_RATE_LIMIT_WAIT_LOG, parsed + 1) - return parsed + 1 - - def _raise_unless_http_500(error: ConnectionException) -> None: """Re-raise ConnectionException unless its status code is HTTP 500.""" if error.args[:1] != (500,): @@ -147,6 +132,11 @@ def _menu_items_path(api_url: str, gw_id: str, menu_items_query: str) -> str: class ConnectionException(Exception): """When can not connect to Ariston cloud""" + def __init__(self, *args: Any, retry_after: Optional[float] = None) -> None: + """Initialize the connection exception with optional rate-limit delay.""" + super().__init__(*args) + self.retry_after = retry_after + class AristonAPI: """Ariston API class""" @@ -182,8 +172,18 @@ def __init__( # Sync (requests) R2 web-app session; created lazily on first use. self.__r2_requests_session: Optional[requests.Session] = None - def _bump_rate_limit_cooldown(self) -> None: + def _rate_limit_exception(self, payload: Any) -> ConnectionException: + """Build a 429 ConnectionException carrying the remaining block delay.""" + remaining = self._blocked_until - time.time() + return ConnectionException( + 429, + payload, + retry_after=remaining if remaining > 0 else None, + ) + + def _bump_rate_limit_cooldown(self, now: Optional[float] = None) -> None: """Advance unparsable-429 streak and extend the shared block window.""" + current_time = time.time() if now is None else now self._rate_limit_streak += 1 cooldown = min( _UNPARSABLE_COOLDOWN_MAX_SECONDS, @@ -196,7 +196,7 @@ def _bump_rate_limit_cooldown(self) -> None: self._rate_limit_streak, cooldown, ) - self._blocked_until = max(self._blocked_until, time.time() + cooldown) + self._blocked_until = max(self._blocked_until, current_time + cooldown) def _prepare_rate_limit_retry( self, content: bytes, headers: Any, is_retry: bool @@ -207,17 +207,13 @@ def _prepare_rate_limit_retry( if parsed is None: parsed = _parse_retry_after_seconds(headers) - if parsed is not None: - wait_seconds = parsed + 1 - _LOGGER.warning(_RATE_LIMIT_WAIT_LOG, wait_seconds) - elif self._rate_limit_retry_in_flight and not is_retry: - return None - elif is_retry or self._rate_limit_streak: - self._bump_rate_limit_cooldown() + if parsed is None: + if now >= self._blocked_until: + self._bump_rate_limit_cooldown(now) return None - else: - wait_seconds = _rate_limit_wait_seconds(content) + wait_seconds = parsed + 1 + _LOGGER.warning(_RATE_LIMIT_WAIT_LOG, wait_seconds) self._blocked_until = max(self._blocked_until, now + wait_seconds) if is_retry or self._rate_limit_retry_in_flight: return None @@ -259,6 +255,8 @@ def connect(self) -> bool: return True except Exception as error: + if isinstance(error, ConnectionException) and error.args[:1] == (429,): + raise raise ConnectionException() from error def get_detailed_devices(self) -> list[Any]: @@ -782,12 +780,12 @@ def __request( params: Optional[dict[str, Any]] = None, body: Any = None, is_retry: bool = False, + rate_limit_retry: bool = False, ) -> Optional[dict[str, Any]]: """Request with requests""" - if not is_retry and time.time() < self._blocked_until: - raise ConnectionException( - 429, - "Rate limited; skipping request until the block window ends", + if not rate_limit_retry and time.time() < self._blocked_until: + raise self._rate_limit_exception( + "Rate limited; skipping request until the block window ends" ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, @@ -823,7 +821,8 @@ def __request( return self.__request(method, path, params, body, True) raise ConnectionException(response.status_code) - self._rate_limit_streak = 0 + if time.time() >= self._blocked_until: + self._rate_limit_streak = 0 if len(response.content) > 0: json = response.json() _LOGGER.debug("Response %s", json) @@ -853,10 +852,10 @@ def __handle_rate_limit( time.sleep(wait_seconds) if self._claim_rate_limit_retry(epoch): try: - return self.__request(method, path, params, body, True) + return self.__request(method, path, params, body, True, True) finally: self._rate_limit_retry_in_flight = False - raise ConnectionException(response.status_code, content.decode()) + raise self._rate_limit_exception(content.decode()) def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" @@ -992,6 +991,8 @@ async def async_connect(self) -> bool: return True except Exception as error: + if isinstance(error, ConnectionException) and error.args[:1] == (429,): + raise raise ConnectionException() from error async def async_get_detailed_devices(self) -> list[Any]: @@ -1749,12 +1750,12 @@ async def __async_request( body: Any = None, is_retry: bool = False, timeout_seconds: int = 30, + rate_limit_retry: bool = False, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" - if not is_retry and time.time() < self._blocked_until: - raise ConnectionException( - 429, - "Rate limited; skipping request until the block window ends", + if not rate_limit_retry and time.time() < self._blocked_until: + raise self._rate_limit_exception( + "Rate limited; skipping request until the block window ends" ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, @@ -1791,7 +1792,13 @@ async def __async_request( return None case 429: return await self.__async_handle_rate_limit( - response, is_retry, method, path, params, body, timeout_seconds + response, + is_retry, + method, + path, + params, + body, + timeout_seconds, ) case _: if not is_retry: @@ -1801,7 +1808,8 @@ async def __async_request( ) raise ConnectionException(response.status) - self._rate_limit_streak = 0 + if time.time() >= self._blocked_until: + self._rate_limit_streak = 0 if response.content_length and response.content_length > 0: json = await response.json() _LOGGER.debug("Response %s", json) @@ -1837,11 +1845,11 @@ async def __async_handle_rate_limit( if self._claim_rate_limit_retry(epoch): try: return await self.__async_request( - method, path, params, body, True, timeout_seconds + method, path, params, body, True, timeout_seconds, True ) finally: self._rate_limit_retry_in_flight = False - raise ConnectionException(response.status, content) + raise self._rate_limit_exception(content) async def _async_get( self, path: str, params: Optional[dict[str, Any]] = None diff --git a/pyproject.toml b/pyproject.toml index 9b8e893..0aa426f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ ] requires-python = ">=3.11" license = { file = "LICENSE" } -version = "0.19.22" +version = "0.19.23" dynamic = ['description'] [project.urls] diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 1354213..f5a747f 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -120,17 +120,18 @@ def test_429_parses_wait_seconds(self): 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) + http = MagicMock(return_value=_sync_response(429, b"Too many requests")) + api = _api() with patch("ariston.ariston_api.requests.request", http): - result = _api()._get("https://example/api") + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") - self.assertEqual(result, {"ok": True}) - self.assertEqual(self.clock.sleeps, [5]) # documented fallback - self.assertEqual(http.call_count, 2) + self.assertEqual(ctx.exception.args, (429, "Too many requests")) + self.assertEqual(ctx.exception.retry_after, 60.0) + self.assertEqual(self.clock.sleeps, []) # immediate cooldown, no blind 5s retry + self.assertEqual(http.call_count, 1) + self.assertEqual(api._rate_limit_streak, 1) + self.assertEqual(api._blocked_until, self.clock.time() + 60) def test_429_twice_raises(self): body = b"Requests are blocked for 10 seconds" @@ -236,31 +237,31 @@ def test_429_without_duration_escalates_cooldown_and_resets_on_ok(self): body = b"Requests are blocked" http = MagicMock( side_effect=[ - _sync_response(429, body), _sync_response(429, body), _sync_response(429, body), _sync_response(200, b"{}", {"ok": True}), ] ) with patch("ariston.ariston_api.requests.request", http): - with self.assertRaises(ConnectionException): + with self.assertRaises(ConnectionException) as first_err: api._get("https://example/api") - first_cooldown = api._blocked_until - self.clock.time() - self.assertGreater(first_cooldown, 50) + self.assertEqual(first_err.exception.retry_after, 60.0) + self.assertEqual(api._blocked_until - self.clock.time(), 60.0) self.assertEqual(api._rate_limit_streak, 1) - self.assertEqual(self.clock.sleeps, [5]) + self.assertEqual(self.clock.sleeps, []) - api._blocked_until = 0.0 - with self.assertRaises(ConnectionException): + self.clock.now += 60 + with self.assertRaises(ConnectionException) as second_err: api._get("https://example/api") - second_cooldown = api._blocked_until - self.clock.time() - self.assertGreater(second_cooldown, 110) + self.assertEqual(second_err.exception.retry_after, 120.0) + self.assertEqual(api._blocked_until - self.clock.time(), 120.0) self.assertEqual(api._rate_limit_streak, 2) - self.assertEqual(self.clock.sleeps, [5]) + self.assertEqual(self.clock.sleeps, []) - api._blocked_until = 0.0 + self.clock.now += 120 self.assertEqual(api._get("https://example/api"), {"ok": True}) self.assertEqual(api._rate_limit_streak, 0) + self.assertEqual(http.call_count, 3) def test_async_429_without_duration_sets_cooldown_and_retry_after_header(self): api = _api() @@ -270,7 +271,6 @@ def test_async_429_without_duration_sets_cooldown_and_retry_after_header(self): resp_with_header, _FakeAiohttpResponse(200, b"{}", {"ok": True}), _FakeAiohttpResponse(429, b"Requests are blocked"), - _FakeAiohttpResponse(429, b"Requests are blocked"), ] calls: list[int] = [] @@ -281,20 +281,25 @@ async def run(): ): ok = await api._async_get("https://example/api") api._blocked_until = 0.0 - with self.assertRaises(ConnectionException): + with self.assertRaises(ConnectionException) as ctx: await api._async_get("https://example/api") - return ok - - self.assertEqual(asyncio.run(run()), {"ok": True}) - self.assertEqual(self.clock.sleeps, [13, 5]) + return ok, ctx.exception + + ok, exc = asyncio.run(run()) + self.assertEqual(ok, {"ok": True}) + self.assertEqual(exc.args, (429, b"Requests are blocked")) + self.assertEqual(exc.retry_after, 60.0) + self.assertEqual(len(calls), 3) + self.assertEqual(self.clock.sleeps, [13]) self.assertEqual(api._rate_limit_streak, 1) - self.assertGreater(api._blocked_until - self.clock.time(), 50) + self.assertEqual(api._blocked_until - self.clock.time(), 60.0) def test_async_overlapping_429_sends_single_retry(self): api = _api() + body = b"Requests are blocked for 5 seconds" responses = [ - _FakeAiohttpResponse(429, b"Requests are blocked"), - _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, body), + _FakeAiohttpResponse(429, body), _FakeAiohttpResponse(429, b"Requests are blocked"), ] calls: list[int] = [] @@ -314,10 +319,51 @@ async def run(): results = asyncio.run(run()) self.assertEqual(len(calls), 3) # 2 initial calls + 1 single claimed retry - self.assertEqual(self.clock.sleeps, [5, 5]) + self.assertEqual(self.clock.sleeps, [6, 6]) self.assertEqual(api._rate_limit_streak, 1) self.assertTrue(all(isinstance(res, ConnectionException) for res in results)) + async def _run_overlapping_gets( + self, api: AristonAPI, responses: list, calls: list[int] + ) -> list[Any]: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + self._overlapping_session_cls(responses, calls, self.real_sleep), + ): + return await asyncio.gather( + api._async_get("https://example/api/a"), + api._async_get("https://example/api/b"), + return_exceptions=True, + ) + + def test_async_overlapping_unparsable_429_escalates_cooldown_once(self): + for initial_streak, expected_streak, expected_cooldown in ( + (0, 1, 60.0), + (1, 2, 120.0), + ): + with self.subTest(initial_streak=initial_streak): + api = _api() + api._rate_limit_streak = initial_streak + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + ] + calls: list[int] = [] + self.clock.sleeps.clear() + + results = asyncio.run( + self._run_overlapping_gets(api, responses, calls) + ) + self.assertEqual(len(calls), 2) + self.assertEqual(self.clock.sleeps, []) + self.assertEqual(api._rate_limit_streak, expected_streak) + self.assertEqual( + api._blocked_until - self.clock.time(), expected_cooldown + ) + for res in results: + self.assertIsInstance(res, ConnectionException) + self.assertEqual(res.retry_after, expected_cooldown) + async def _overlapping_sleep(self, seconds: int) -> None: self.clock.sleeps.append(seconds) wake_at = self.clock.now + seconds @@ -504,6 +550,236 @@ async def run() -> None: asyncio.run(run()) self.assertEqual(len(calls), 1) + async def _async_get_expecting_connection_error( + self, api: AristonAPI, url: str = "https://example/api" + ) -> ConnectionException: + with self.assertRaises(ConnectionException) as ctx: + await api._async_get(url) + return ctx.exception + + def test_short_circuit_rate_limit_exposes_retry_after(self): + for is_async in (False, True): + with self.subTest(is_async=is_async): + api = _api() + api._blocked_until = self.clock.time() + 45.5 + + if not is_async: + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") + exc = ctx.exception + else: + exc = asyncio.run( + self._async_get_expecting_connection_error(api) + ) + + self.assertEqual(exc.args[0], 429) + self.assertEqual(exc.retry_after, 45.5) + + def test_repeated_parsed_429_exposes_retry_after(self): + body = b"Requests are blocked for 10 seconds" + http = MagicMock( + side_effect=[_sync_response(429, body), _sync_response(429, body)] + ) + api = _api() + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") + self.assertEqual(ctx.exception.args[0], 429) + self.assertEqual(ctx.exception.retry_after, 11.0) + + def test_ok_response_during_active_block_preserves_streak(self): + api = _api() + api._rate_limit_streak = 2 + api._blocked_until = self.clock.time() + 60.0 + with patch( + "ariston.ariston_api.requests.request", + return_value=_sync_response(200, b"{}", {"ok": True}), + ): + result = api._AristonAPI__request( + "GET", "https://example/api", rate_limit_retry=True + ) + self.assertEqual(result, {"ok": True}) + self.assertEqual(api._rate_limit_streak, 2) + + async_api = _api() + async_api._rate_limit_streak = 1 + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + results = asyncio.run( + self._run_overlapping_gets(async_api, responses, calls) + ) + self.assertIsInstance(results[0], ConnectionException) + self.assertEqual(results[1], {"ok": True}) + self.assertEqual(async_api._rate_limit_streak, 2) + + def test_async_5xx_retry_respects_active_rate_limit_block(self): + api = _api() + calls: list[str] = [] + sleep_started = asyncio.Event() + block_active = asyncio.Event() + + async def fake_sleep(seconds: int) -> None: + self.clock.sleeps.append(seconds) + sleep_started.set() + await block_active.wait() + self.clock.now += seconds + + async def request(_method: str, url: str, **kwargs: Any): + calls.append(url) + if url.endswith("/five-hundred"): + return _FakeAiohttpResponse(500) + return _FakeAiohttpResponse(429, b"Requests are blocked") + + async def run(): + with patch("ariston.ariston_api.aiohttp.ClientSession") as session, patch( + "ariston.ariston_api.asyncio.sleep", side_effect=fake_sleep + ): + session.return_value.__aenter__.return_value.request = AsyncMock( + side_effect=request + ) + task_500 = asyncio.create_task( + api._async_get("https://example/api/five-hundred") + ) + await sleep_started.wait() + with self.assertRaises(ConnectionException) as err_429: + await api._async_get("https://example/api/four-two-nine") + block_active.set() + with self.assertRaises(ConnectionException) as err_500: + await task_500 + return err_429.exception, err_500.exception + + err_429, err_500 = asyncio.run(asyncio.wait_for(run(), timeout=5)) + self.assertEqual( + calls, + [ + "https://example/api/five-hundred", + "https://example/api/four-two-nine", + ], + ) # 500 retry did not hit server during active 429 block + self.assertEqual(api._rate_limit_streak, 1) + self.assertEqual(err_429.retry_after, 60.0) + self.assertEqual(err_500.args[0], 429) + self.assertEqual(err_500.retry_after, 55.0) + + def test_connect_preserves_rate_limit_exception_and_retry_after(self): + sync_api = _api() + with patch( + "ariston.ariston_api.requests.request", + return_value=_sync_response(429, b"Requests are blocked"), + ): + with self.assertRaises(ConnectionException) as sync_ctx: + sync_api.connect() + self.assertEqual(sync_ctx.exception.args, (429, "Requests are blocked")) + self.assertEqual(sync_ctx.exception.retry_after, 60.0) + + async_api = _api() + calls: list[int] = [] + + async def run_connect() -> ConnectionException: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls( + [_FakeAiohttpResponse(429, b"Requests are blocked")], calls + ), + ): + with self.assertRaises(ConnectionException) as ctx: + await async_api.async_connect() + return ctx.exception + + async_exc = asyncio.run(run_connect()) + self.assertEqual(async_exc.args, (429, b"Requests are blocked")) + self.assertEqual(async_exc.retry_after, 60.0) + + def test_connect_wraps_non_rate_limit_errors(self): + error = ConnectionException(500) + api = _api() + with patch.object(api, "_post", side_effect=error): + with self.assertRaises(ConnectionException) as ctx: + api.connect() + self.assertEqual(ctx.exception.args, ()) + self.assertIs(ctx.exception.__cause__, error) + + def test_async_menu_discovery_stops_when_relogin_gets_http_500(self): + api = _api() + calls: list[int] = [] + responses = [ + _FakeAiohttpResponse(200, b"[]", []), + _FakeAiohttpResponse(405), + _FakeAiohttpResponse(500), + _FakeAiohttpResponse(500), + ] + + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ): + with self.assertRaises(ConnectionException) as ctx: + asyncio.run(api.async_get_menu_items("gw", include_hybrid_items=True)) + + self.assertEqual(ctx.exception.args, ()) + self.assertIsInstance(ctx.exception.__cause__, ConnectionException) + self.assertEqual(ctx.exception.__cause__.args, (500,)) + self.assertEqual(len(calls), 4) + self.assertNotIn("gw", api._hybrid_menu_items) + + def test_bare_429_starts_cooldown_during_an_in_flight_retry(self): + api = _api() + api._blocked_until = self.clock.now + api._rate_limit_retry_in_flight = True + with patch( + "ariston.ariston_api.requests.request", + return_value=_sync_response(429, b"Requests are blocked"), + ) as http: + with self.assertRaises(ConnectionException) as ctx: + api._get("https://example/api") + with self.assertRaises(ConnectionException): + api._get("https://example/api") + self.assertEqual(ctx.exception.args, (429, "Requests are blocked")) + self.assertEqual(ctx.exception.retry_after, 60.0) + self.assertEqual(api._rate_limit_streak, 1) + self.assertEqual(http.call_count, 1) + + def test_timed_429_records_cooldown_without_a_second_post_retry(self): + url = "https://example/api" + body = b"Requests are blocked for 60 seconds" + for is_async in (False, True): + with self.subTest(is_async=is_async): + api = _api() + self.clock.sleeps.clear() + if is_async: + calls = [] + responses = [ + _FakeAiohttpResponse(500), + _FakeAiohttpResponse(429, body), + _FakeAiohttpResponse(200), + ] + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ): + with self.assertRaises(ConnectionException) as ctx: + asyncio.run(api._async_post(url, {})) + self.assertEqual(len(calls), 2) + else: + responses = [ + _sync_response(500), + _sync_response(429, body), + _sync_response(200), + ] + with patch( + "ariston.ariston_api.requests.request", side_effect=responses + ) as http: + with self.assertRaises(ConnectionException) as ctx: + api._post(url, {}) + self.assertEqual(http.call_count, 2) + self.assertEqual(ctx.exception.args[0], 429) + self.assertEqual(ctx.exception.retry_after, 61.0) + self.assertEqual(api._blocked_until, self.clock.now + 61.0) + self.assertEqual(self.clock.sleeps, [5]) + if __name__ == "__main__": unittest.main()