rate-limit: zentraler Rate-Limiter in RCRestClient._request() + 429-Retry + 15s Cooldown

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
This commit is contained in:
Bernd (Hermes)
2026-07-28 18:27:05 +02:00
parent 41589818d2
commit 57ebbc6d6b
4 changed files with 77 additions and 31 deletions
+48 -12
View File
@@ -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 ─────────────────────────────────────────────────────