From 57ebbc6d6b312f6b9671a3bb4f794ace145f192f Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Tue, 28 Jul 2026 18:27:05 +0200 Subject: [PATCH] rate-limit: zentraler Rate-Limiter in RCRestClient._request() + 429-Retry + 15s Cooldown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AUFGABE 1 — Rate-Limiter in _request(): - RCRestClient.__init__ nimmt optionalen rate_limiter - _request() ruft rate_limiter.acquire() VOR jedem API-Call auf - Schützt ALLE Endpoints: postMessage, channels.history, users.info, chat.delete - rc_client Fixture (session-scoped) injiziert rate_limiter in den Client AUFGABE 2 — 15s Cooldown zwischen Tests: - rate_limit_cooldown autouse Fixture in conftest.py - yield + time.sleep(15) nach jedem Test - RC Rate-Limit-Window (~10s) wird zuverlässig resettet AUFGABE 3 — test_03 Skip-Ursache: - test_02 und test_03 pollen nicht mehr direkt hintereinander ohne Pause - 15s Cooldown + zentraler Rate-Limiter verhindern kaskadierende 429s AUFGABE 4 — 429-Retry mit Backoff: - _request() retryed HTTP 429 mit 3s → 6s → 12s Backoff (max 3 Retries) - post_message failt nicht mehr sofort bei 429 CLEANUP: - Redundante rate_limiter.acquire() aus polling.py (wait_for_bot_message, get_latest_timestamp), conftest.py (post_test_message) und test_04_multi_room.py entfernt - rate_limiter Fixture auf session-scope (war eh globaler Singleton) - Docstrings aktualisiert --- tests/live_rc/conftest.py | 30 +++++++++++---- tests/live_rc/helpers/polling.py | 17 +++----- tests/live_rc/helpers/rc_rest.py | 60 +++++++++++++++++++++++------ tests/live_rc/test_04_multi_room.py | 1 - 4 files changed, 77 insertions(+), 31 deletions(-) diff --git a/tests/live_rc/conftest.py b/tests/live_rc/conftest.py index 5de03ba..47aebe1 100644 --- a/tests/live_rc/conftest.py +++ b/tests/live_rc/conftest.py @@ -217,15 +217,18 @@ def rc_config() -> dict: @pytest.fixture(scope="session") -def rc_client(rc_config: dict) -> RCRestClient: +def rc_client(rc_config: dict, rate_limiter) -> RCRestClient: """Create an authenticated RCRestClient for the test session. Performs self-check: verifies that the token matches the user identity. + The rate_limiter is injected into the client so every API call + (post, history, delete, users.info) is rate-limited automatically. """ client = RCRestClient( base_url=rc_config["url"], auth_token=rc_config["token"], user_id=rc_config["user_id"], + rate_limiter=rate_limiter, ) # P0: Self-check — verify token matches user identity @@ -249,6 +252,18 @@ def _suite_cleanup(request, rc_config: dict): _release_suite_lock() +@pytest.fixture(autouse=True) +def rate_limit_cooldown(): + """Wait 15s between tests for RC rate-limit window reset. + + RC's rate-limit window is ~10s. A 15s pause between tests ensures + the token bucket has time to refill, preventing cascading 429s + when tests run back-to-back. + """ + yield + time.sleep(15) + + @pytest.fixture def test_room_id(rc_config: dict) -> str: """The test room ID for the current test.""" @@ -310,9 +325,9 @@ def bot_status_check(rc_client: RCRestClient, bot_user_id: str, bot_username: st return user -@pytest.fixture +@pytest.fixture(scope="session") def rate_limiter() -> RateLimiter: - """Rate limiter to stay under 30 calls/minute.""" + """Rate limiter to stay under 30 calls/minute (session-scoped).""" return _get_rate_limiter() @@ -370,20 +385,21 @@ def post_test_message( posted_ids: list, limiter: RateLimiter | None = None, ) -> str: - """Post a test message with rate limiting and cleanup tracking. + """Post a test message with cleanup tracking. + + Rate limiting is handled by the RCRestClient internally (via _request). + The limiter parameter is kept for backward compatibility but is unused. Args: client: Authenticated RCRestClient. room_id: Target room ID. text: Message text. posted_ids: List to append the message ID to (for cleanup). - limiter: Optional rate limiter. + limiter: Deprecated — rate limiting is now in RCRestClient._request(). Returns: The message _id. """ - if limiter: - limiter.acquire() msg_id = client.post_message(room_id, text) posted_ids.append(msg_id) return msg_id diff --git a/tests/live_rc/helpers/polling.py b/tests/live_rc/helpers/polling.py index 6a55b31..ca43219 100644 --- a/tests/live_rc/helpers/polling.py +++ b/tests/live_rc/helpers/polling.py @@ -56,10 +56,9 @@ def wait_for_bot_message( Uses the cursor (ISO timestamp) to only look at messages newer than the test message that was just posted. - Rate limiting: if a rate_limiter is provided, each API call acquires - a token first. On HTTP 429 errors, uses exponential backoff - (3s → 6s → 12s → 24s). After 3 consecutive 429s, raises - RateLimitSkip so the test can SKIP instead of failing. + Rate limiting is handled by RCRestClient._request() internally + (token-bucket + 429 retry with exponential backoff). The rate_limiter + parameter is kept for backward compatibility but is unused. Cursor caching: once messages are fetched, subsequent polls scan the cached batch without calling channels.history again — avoids @@ -71,7 +70,7 @@ def wait_for_bot_message( bot_username: The bot's username (case-insensitive match). cursor: ISO timestamp — only messages after this time are considered. timeout: Maximum total wait time in seconds (default 18s). - rate_limiter: Optional RateLimiter instance for API call throttling. + rate_limiter: Deprecated — rate limiting is now in RCRestClient._request(). Returns: The first message dict from bot_username found after cursor. @@ -104,10 +103,7 @@ def wait_for_bot_message( # No match in cache — clear and re-fetch on next iteration cached_messages = [] - # Rate-limit before API call - if rate_limiter is not None: - rate_limiter.acquire() - + # Rate limiting is handled by RCRestClient._request() internally try: messages = client.get_history( room_id=room_id, @@ -194,8 +190,7 @@ def get_latest_timestamp( Returns: ISO timestamp string, or "1970-01-01T00:00:00.000Z" if room is empty. """ - if rate_limiter is not None: - rate_limiter.acquire() + # Rate limiting is handled by RCRestClient._request() internally try: messages = client.get_history(room_id=room_id, count=1) except Exception: diff --git a/tests/live_rc/helpers/rc_rest.py b/tests/live_rc/helpers/rc_rest.py index 8cccdbd..a4ec98e 100644 --- a/tests/live_rc/helpers/rc_rest.py +++ b/tests/live_rc/helpers/rc_rest.py @@ -27,12 +27,23 @@ class RCRestClient: """Thin wrapper around Rocket.Chat REST API for test automation. Authenticates via personal access token (X-Auth-Token + X-User-Id headers). + + Rate limiting: if a rate_limiter is provided, every API call acquires + a token before the HTTP request. On HTTP 429, retries with exponential + backoff (3s → 6s → 12s, max 3 retries). """ - def __init__(self, base_url: str, auth_token: str, user_id: str): + def __init__( + self, + base_url: str, + auth_token: str, + user_id: str, + rate_limiter=None, + ): self.base_url = base_url.rstrip("/") self.auth_token = auth_token self.user_id = user_id + self.rate_limiter = rate_limiter # ── Low-level request ────────────────────────────────────────────── @@ -44,6 +55,10 @@ class RCRestClient: ) -> dict: """Send an authenticated request to the RC REST API. + Rate limiting: acquires a token from self.rate_limiter (if set) + before every API call. On HTTP 429, retries with exponential + backoff (3s → 6s → 12s, max 3 retries). + Returns: Parsed JSON response dict. @@ -61,17 +76,38 @@ class RCRestClient: body = json.dumps(data).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method=method) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - return json.loads(resp.read().decode("utf-8")) - except urllib.error.HTTPError as e: - raise RCRestError( - f"HTTP {e.code} on {method} {endpoint}: {e.reason}" - ) from e - except Exception as e: - raise RCRestError( - f"Connection error on {method} {endpoint}: {e}" - ) from e + + # 429 retry with exponential backoff: 3s → 6s → 12s, max 3 retries + max_429_retries = 3 + for attempt in range(max_429_retries + 1): + # Rate-limit before every API call (protects post, history, delete, etc.) + if self.rate_limiter is not None: + self.rate_limiter.acquire() + + try: + with urllib.request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + if e.code == 429 and attempt < max_429_retries: + backoff = 3.0 * (2 ** attempt) # 3s, 6s, 12s + logger.warning( + "HTTP 429 on %s %s (attempt %d/%d) — backing off %ds", + method, endpoint, attempt + 1, max_429_retries + 1, backoff, + ) + time.sleep(backoff) + continue + raise RCRestError( + f"HTTP {e.code} on {method} {endpoint}: {e.reason}" + ) from e + except Exception as e: + raise RCRestError( + f"Connection error on {method} {endpoint}: {e}" + ) from e + + # Should never reach here — all paths either return or raise + raise RCRestError( + f"Exhausted {max_429_retries + 1} attempts on {method} {endpoint}" + ) # ── Public API ───────────────────────────────────────────────────── diff --git a/tests/live_rc/test_04_multi_room.py b/tests/live_rc/test_04_multi_room.py index 3d0785a..18847e8 100644 --- a/tests/live_rc/test_04_multi_room.py +++ b/tests/live_rc/test_04_multi_room.py @@ -126,7 +126,6 @@ def test_04_multi_room( time.sleep(5.0) try: - rate_limiter.acquire() project_messages = rc_client.get_history( room_id=project_room, count=20,