57ebbc6d6b
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
202 lines
7.1 KiB
Python
202 lines
7.1 KiB
Python
"""
|
|
Cursor-based polling for bot responses in Rocket.Chat live tests.
|
|
|
|
Waits for a message from a specific user (the bot) to appear in a room's
|
|
history after a given cursor timestamp. Uses progressive backoff with
|
|
rate limiting: 2s → 3s → 5s → 8s, max 18s total.
|
|
|
|
Rate limiter integration: each channels.history call acquires a token
|
|
from the rate limiter to stay under RC's 30 calls/minute limit.
|
|
|
|
CURSOR CACHING: Once messages are found, subsequent polls skip
|
|
channels.history and only scan the cached batch — avoiding unnecessary
|
|
API calls that trigger RC's aggressive 429 rate limiting.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import time
|
|
from typing import Optional
|
|
|
|
from .rc_rest import RCRestClient
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Progressive backoff intervals in seconds (rate-limiter-friendly).
|
|
# RC triggers 429 at 3-4 channels.history calls in <10s, so we use
|
|
# longer intervals: 2s → 3s → 5s → 8s (max 18s total).
|
|
_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
|
_MAX_TOTAL_WAIT = 18.0 # seconds
|
|
|
|
# 429 exponential backoff: 3s → 6s → 12s → 24s (max)
|
|
_MAX_429_BACKOFF = 24.0
|
|
# After 3 consecutive 429s, abort with SKIP instead of retrying forever
|
|
_MAX_CONSECUTIVE_429 = 3
|
|
|
|
|
|
class PollTimeout(Exception):
|
|
"""Raised when the bot does not respond within the timeout."""
|
|
|
|
|
|
class RateLimitSkip(Exception):
|
|
"""Raised when 3 consecutive 429s occur — test should SKIP."""
|
|
|
|
|
|
def wait_for_bot_message(
|
|
client: RCRestClient,
|
|
room_id: str,
|
|
bot_username: str,
|
|
cursor: str,
|
|
timeout: float = _MAX_TOTAL_WAIT,
|
|
rate_limiter=None,
|
|
) -> dict:
|
|
"""Poll channels.history until a message from bot_username appears.
|
|
|
|
Uses the cursor (ISO timestamp) to only look at messages newer than
|
|
the test message that was just posted.
|
|
|
|
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
|
|
triggering RC's aggressive rate limiting.
|
|
|
|
Args:
|
|
client: Authenticated RCRestClient instance.
|
|
room_id: The room to poll.
|
|
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: Deprecated — rate limiting is now in RCRestClient._request().
|
|
|
|
Returns:
|
|
The first message dict from bot_username found after cursor.
|
|
|
|
Raises:
|
|
PollTimeout: If no bot message appears within timeout.
|
|
RateLimitSkip: If 3 consecutive 429s occur (test should SKIP).
|
|
"""
|
|
deadline = time.monotonic() + timeout
|
|
interval_idx = 0
|
|
consecutive_429 = 0
|
|
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
|
|
|
while time.monotonic() < deadline:
|
|
# Cursor caching: if we already have messages, scan them first
|
|
if cached_messages:
|
|
for msg in cached_messages:
|
|
ts = msg.get("ts", "")
|
|
if ts <= cursor:
|
|
continue
|
|
u = msg.get("u", {})
|
|
username = (u.get("username", "") or "").lower()
|
|
if username == bot_username.lower():
|
|
logger.info(
|
|
"Poll: found bot message %s after %.1fs (cached)",
|
|
msg.get("_id", "")[:12],
|
|
time.monotonic() - (deadline - timeout),
|
|
)
|
|
return msg
|
|
# No match in cache — clear and re-fetch on next iteration
|
|
cached_messages = []
|
|
|
|
# Rate limiting is handled by RCRestClient._request() internally
|
|
try:
|
|
messages = client.get_history(
|
|
room_id=room_id,
|
|
count=10,
|
|
oldest=cursor,
|
|
)
|
|
consecutive_429 = 0 # reset on success
|
|
except Exception as e:
|
|
error_str = str(e)
|
|
if "429" in error_str:
|
|
consecutive_429 += 1
|
|
if consecutive_429 >= _MAX_CONSECUTIVE_429:
|
|
raise RateLimitSkip(
|
|
"3 consecutive HTTP 429s from RC — rate limit is too "
|
|
"aggressive. Consider increasing poll intervals or "
|
|
"reducing concurrent test load."
|
|
)
|
|
# Exponential backoff on rate-limit errors: 3s → 6s → 12s → 24s
|
|
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
|
logger.warning(
|
|
"Poll: HTTP 429 (consecutive=%d/%d) — backing off %ds",
|
|
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
|
)
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
break
|
|
time.sleep(min(backoff, remaining))
|
|
continue
|
|
else:
|
|
logger.warning("Poll: history fetch failed (will retry): %s", e)
|
|
messages = []
|
|
|
|
# Cache messages for cursor-caching optimization
|
|
cached_messages = messages
|
|
|
|
for msg in messages:
|
|
ts = msg.get("ts", "")
|
|
# Only consider messages strictly after cursor
|
|
if ts <= cursor:
|
|
continue
|
|
u = msg.get("u", {})
|
|
username = (u.get("username", "") or "").lower()
|
|
if username == bot_username.lower():
|
|
logger.info(
|
|
"Poll: found bot message %s after %.1fs",
|
|
msg.get("_id", "")[:12],
|
|
time.monotonic() - (deadline - timeout),
|
|
)
|
|
return msg
|
|
|
|
# Progressive backoff: 2s → 3s → 5s → 8s
|
|
if interval_idx < len(_BACKOFF_INTERVALS):
|
|
delay = _BACKOFF_INTERVALS[interval_idx]
|
|
interval_idx += 1
|
|
else:
|
|
delay = 8.0
|
|
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
break
|
|
time.sleep(min(delay, remaining))
|
|
|
|
raise PollTimeout(
|
|
f"Bot '{bot_username}' did not respond in room {room_id[:12]} "
|
|
f"within {timeout}s (cursor={cursor[:19]})"
|
|
)
|
|
|
|
|
|
def get_latest_timestamp(
|
|
client: RCRestClient,
|
|
room_id: str,
|
|
rate_limiter=None,
|
|
) -> str:
|
|
"""Get the timestamp of the most recent message in a room.
|
|
|
|
Used as a cursor before posting a test message — ensures we only
|
|
look at messages that appear AFTER our post.
|
|
|
|
Args:
|
|
client: Authenticated RCRestClient instance.
|
|
room_id: The room ID.
|
|
rate_limiter: Optional RateLimiter instance.
|
|
|
|
Returns:
|
|
ISO timestamp string, or "1970-01-01T00:00:00.000Z" if room is empty.
|
|
"""
|
|
# Rate limiting is handled by RCRestClient._request() internally
|
|
try:
|
|
messages = client.get_history(room_id=room_id, count=1)
|
|
except Exception:
|
|
return "1970-01-01T00:00:00.000Z"
|
|
|
|
if messages:
|
|
return messages[0].get("ts", "1970-01-01T00:00:00.000Z")
|
|
return "1970-01-01T00:00:00.000Z"
|