diff --git a/ariston/__init__.py b/ariston/__init__.py index 5958362..13c6c54 100644 --- a/ariston/__init__.py +++ b/ariston/__init__.py @@ -4,7 +4,7 @@ import logging from typing import Any, Optional, Type -from .ariston_api import AristonAPI, ConnectionException +from .ariston_api import AristonAPI, ConnectionException, RateLimitException from .const import ( ARISTON_API_URL, ARISTON_USER_AGENT, diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 8e15817..394c0ae 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -57,23 +57,41 @@ 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.""" - 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 - _LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1) - return parsed + 1 +def _parse_retry_after(response: Any) -> Optional[int]: + """Extract a delta-seconds Retry-After header, if the server sent one.""" + headers = getattr(response, "headers", None) + if not headers: + return None + value = headers.get("Retry-After") + if not isinstance(value, str) or not value.strip().isdigit(): + return None + return int(value.strip()) + + +# Back-off for 429s that do not say how long the block lasts (the cloud +# answers a bare "Requests are blocked"). Retrying a few seconds later keeps +# the account blocked, so wait progressively longer and do not retry inline. +_UNKNOWN_BLOCK_BASE_SECONDS = 60 +_UNKNOWN_BLOCK_MAX_SECONDS = 900 class ConnectionException(Exception): """When can not connect to Ariston cloud""" +class RateLimitException(ConnectionException): + """Ariston cloud is rate limiting this account (HTTP 429). + + ``args`` stays ``(429, content)`` so callers that inspect + ``error.args[0]`` keep working; ``retry_after`` is the number of + seconds until the block window is expected to end. + """ + + def __init__(self, content: Any, retry_after: float) -> None: + super().__init__(429, content) + self.retry_after = max(0.0, retry_after) + + class AristonAPI: """Ariston API class""" @@ -98,6 +116,9 @@ 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 + # Consecutive 429s without a block duration; drives the back-off + # and resets on the next successful response. + self._rate_limit_strikes = 0 # Sync (requests) R2 web-app session; created lazily on first use. self.__r2_requests_session: Optional[requests.Session] = None @@ -568,11 +589,8 @@ def __request( is_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 is_retry: + self._raise_if_blocked() headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -607,6 +625,7 @@ def __request( return self.__request(method, path, params, body, True) raise ConnectionException(response.status_code) + self._rate_limit_strikes = 0 if len(response.content) > 0: json = response.json() _LOGGER.debug("Response %s", json) @@ -627,14 +646,56 @@ 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 known 429 block window and retry once, else raise.""" content = response.content - wait_seconds = _rate_limit_wait_seconds(content) - self._blocked_until = time.time() + wait_seconds - if not is_retry: + wait_seconds, known = self._register_rate_limit(response, content) + if known and not is_retry: time.sleep(wait_seconds) return self.__request(method, path, params, body, True) - raise ConnectionException(response.status_code, content.decode()) + raise RateLimitException(content.decode(errors="replace"), wait_seconds) + + def _raise_if_blocked(self) -> None: + """Skip the request while this instance is inside a 429 block window.""" + remaining = self._blocked_until - time.time() + if remaining > 0: + raise RateLimitException( + "Rate limited; skipping request until the block window ends", + remaining, + ) + + def _register_rate_limit(self, response: Any, content: bytes) -> tuple[int, bool]: + """Record a 429 and return (wait seconds, whether the duration is known). + + A known duration (body text or Retry-After header) is honoured with a + 1s margin. Without one, back off 60s, doubling per consecutive 429 up + to 15 minutes, because quick blind retries keep the account blocked. + """ + parsed = _parse_block_seconds(content) + if parsed is None: + parsed = _parse_retry_after(response) + if parsed is not None: + wait_seconds = parsed + 1 + _LOGGER.warning( + "Rate limited (429) for %s seconds; waiting it out", wait_seconds + ) + self._blocked_until = max(self._blocked_until, time.time() + wait_seconds) + return wait_seconds, True + + # Concurrent requests rejected by the same block count as one strike. + if time.time() >= self._blocked_until: + self._rate_limit_strikes += 1 + wait_seconds = min( + _UNKNOWN_BLOCK_BASE_SECONDS * 2 ** max(self._rate_limit_strikes - 1, 0), + _UNKNOWN_BLOCK_MAX_SECONDS, + ) + self._blocked_until = max(self._blocked_until, time.time() + wait_seconds) + _LOGGER.warning( + "Rate limited (429) without a block duration (%s in a row); " + "pausing requests for %s seconds", + self._rate_limit_strikes, + wait_seconds, + ) + return wait_seconds, False def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" @@ -1508,11 +1569,8 @@ async def __async_request( timeout_seconds: int = 30, ) -> 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 is_retry: + self._raise_if_blocked() headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -1558,6 +1616,7 @@ async def __async_request( ) raise ConnectionException(response.status) + self._rate_limit_strikes = 0 if response.content_length and response.content_length > 0: json = await response.json() _LOGGER.debug("Response %s", json) @@ -1583,16 +1642,15 @@ 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 known 429 block window and retry once, else raise.""" content = await response.content.read() - wait_seconds = _rate_limit_wait_seconds(content) - self._blocked_until = time.time() + wait_seconds - if not is_retry: + wait_seconds, known = self._register_rate_limit(response, content) + if known and not is_retry: await asyncio.sleep(wait_seconds) return await self.__async_request( method, path, params, body, True, timeout_seconds ) - raise ConnectionException(response.status, content) + raise RateLimitException(content, wait_seconds) async def _async_get( self, path: str, params: Optional[dict[str, Any]] = None diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 951952e..d4e519e 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -9,6 +9,7 @@ from ariston.ariston_api import ( AristonAPI, ConnectionException, + RateLimitException, _parse_block_seconds, ) @@ -17,11 +18,17 @@ def _api() -> AristonAPI: return AristonAPI("user", "pass") -def _sync_response(status: int, content: bytes = b"", json_data: Any = None): +def _sync_response( + status: int, + content: bytes = b"", + json_data: Any = None, + headers: Optional[dict[str, str]] = None, +): response = MagicMock() response.ok = status < 400 response.status_code = status response.content = content + response.headers = headers or {} if json_data is not None: response.json.return_value = json_data return response @@ -37,9 +44,14 @@ async def read(self) -> bytes: class _FakeAiohttpResponse: def __init__( - self, status: int, payload: bytes = b"", json_data: Any = None + self, + status: int, + payload: bytes = b"", + json_data: Any = None, + headers: Optional[dict[str, str]] = None, ) -> None: self.status = status + self.headers = headers or {} self.ok = status < 400 self.content = _FakeAiohttpContent(payload) self.content_length = len(payload) @@ -67,6 +79,19 @@ async def request(self, *args: Any, **kwargs: Any): return _Session +def _yielding_session_cls(responses: list, calls: list): + """Like _fake_session_cls, but lets other tasks run mid-request.""" + base = _fake_session_cls(responses, calls) + + class _Session(base): + async def request(self, *args: Any, **kwargs: Any): + calls.append(1) + await asyncio.sleep(0) + return responses.pop(0) + + return _Session + + class RateLimitTests(unittest.TestCase): """429 handling: parse, sleep-out with a single retry, per-instance window.""" @@ -99,9 +124,60 @@ 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): + def test_429_without_parsable_body_backs_off_without_retry(self): + """A bare "Requests are blocked" must not be retried a few seconds later.""" + 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 + ): + with self.assertRaises(RateLimitException) as ctx: + api._get("https://example/api") + + self.assertEqual(http.call_count, 1) # no blind retry + self.assertEqual(sleeps, []) + self.assertEqual(ctx.exception.args[0], 429) # ConnectionException shape + self.assertIsInstance(ctx.exception, ConnectionException) + self.assertEqual(ctx.exception.retry_after, 60) + self.assertAlmostEqual(api._blocked_until, time.time() + 60, delta=2) + + def test_unknown_block_backoff_doubles_and_caps(self): + api = _api() + waits = [] + for _ in range(6): + api._blocked_until = 0.0 # previous window has expired + http = MagicMock(side_effect=[_sync_response(429, b"Requests are blocked")]) + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(RateLimitException) as ctx: + api._get("https://example/api") + waits.append(ctx.exception.retry_after) + + self.assertEqual(waits, [60, 120, 240, 480, 900, 900]) + + def test_success_resets_backoff(self): + api = _api() + http = MagicMock( + side_effect=[ + _sync_response(429, b"Requests are blocked"), + _sync_response(200, b"{}", {"ok": True}), + _sync_response(429, b"Requests are blocked"), + ] + ) + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(RateLimitException): + api._get("https://example/api") + api._blocked_until = 0.0 + self.assertEqual(api._get("https://example/api"), {"ok": True}) + api._blocked_until = 0.0 + with self.assertRaises(RateLimitException) as ctx: + api._get("https://example/api") + + self.assertEqual(ctx.exception.retry_after, 60) # back to the base wait + + def test_retry_after_header_is_honoured(self): responses = [ - _sync_response(429, b"Too many requests"), + _sync_response(429, b"Requests are blocked", headers={"Retry-After": "20"}), _sync_response(200, b"{}", {"ok": True}), ] http = MagicMock(side_effect=responses) @@ -112,8 +188,7 @@ def test_429_without_parsable_body(self): result = _api()._get("https://example/api") self.assertEqual(result, {"ok": True}) - self.assertEqual(sleeps, [5]) # documented fallback - self.assertEqual(http.call_count, 2) + self.assertEqual(sleeps, [21]) def test_429_twice_raises(self): body = b"Requests are blocked for 10 seconds" @@ -134,10 +209,11 @@ def test_blocked_until_short_circuits(self): api._blocked_until = time.time() + 30 http = MagicMock() with patch("ariston.ariston_api.requests.request", http): - with self.assertRaises(ConnectionException): + with self.assertRaises(RateLimitException) as ctx: api._get("https://example/api") http.assert_not_called() # no network call inside the block window + self.assertAlmostEqual(ctx.exception.retry_after, 30, delta=2) def test_block_window_is_per_instance(self): """A 429 on one instance must not silence other instances.""" @@ -182,6 +258,55 @@ async def run() -> Any: self.assertEqual(len(calls), 2) # exactly one retry self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin + def test_async_429_without_parsable_body_backs_off_without_retry(self): + responses = [_FakeAiohttpResponse(429, b"Requests are blocked")] + calls: list[int] = [] + sleeps: list[Optional[int]] = [] + api = _api() + + async def run() -> None: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append + ): + await api._async_get("https://example/api") + + with self.assertRaises(RateLimitException) as ctx: + asyncio.run(run()) + + self.assertEqual(len(calls), 1) # no blind retry + self.assertEqual(sleeps, []) + self.assertEqual(ctx.exception.retry_after, 60) + + def test_async_concurrent_429s_count_as_one_strike(self): + """Gathered requests rejected by the same block must not double the wait.""" + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked"), + _FakeAiohttpResponse(429, b"Requests are blocked"), + ] + calls: list[int] = [] + api = _api() + + async def run() -> list: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _yielding_session_cls(responses, calls), + ): + return await asyncio.gather( + api._async_get("https://example/a"), + api._async_get("https://example/b"), + return_exceptions=True, + ) + + results = asyncio.run(run()) + + self.assertEqual(len(calls), 2) + self.assertTrue(all(isinstance(r, RateLimitException) for r in results)) + self.assertEqual(api._rate_limit_strikes, 1) + self.assertEqual([r.retry_after for r in results], [60, 60]) + def test_async_blocked_until_short_circuits(self): calls: list[int] = [] api = _api()