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
+6 -11
View File
@@ -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:
+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 ─────────────────────────────────────────────────────