""" 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: 1s → 1s → 2s → 2s → 3s → 3s, max 12s total. Rate limiter integration: each channels.history call acquires a token from the rate limiter to stay under RC's 60 calls/minute limit. """ 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) # With 60 calls/min rate limit, we can do ~1 call/sec. These intervals # give RC breathing room while still polling reasonably fast. _BACKOFF_INTERVALS = [1.0, 1.0, 2.0, 2.0, 3.0, 3.0] _MAX_TOTAL_WAIT = 12.0 # seconds class PollTimeout(Exception): """Raised when the bot does not respond within the timeout.""" 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: if a rate_limiter is provided, each API call acquires a token first. On HTTP 429 errors, uses exponential backoff. 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 12s). rate_limiter: Optional RateLimiter instance for API call throttling. Returns: The first message dict from bot_username found after cursor. Raises: PollTimeout: If no bot message appears within timeout. """ deadline = time.monotonic() + timeout interval_idx = 0 consecutive_429 = 0 while time.monotonic() < deadline: # Rate-limit before API call if rate_limiter is not None: rate_limiter.acquire() 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 # Exponential backoff on rate-limit errors backoff = min(2 ** consecutive_429, 16) # 2s, 4s, 8s, 16s max logger.warning( "Poll: HTTP 429 (consecutive=%d) — backing off %ds", 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 = [] 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 if interval_idx < len(_BACKOFF_INTERVALS): delay = _BACKOFF_INTERVALS[interval_idx] interval_idx += 1 else: delay = 3.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. """ if rate_limiter is not None: rate_limiter.acquire() 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"