""" REST Client Wrapper for Rocket.Chat Live Tests. Provides a clean Python interface to the Rocket.Chat REST API for the test harness running on .101 (Bernd). Zero external dependencies — stdlib only. """ from __future__ import annotations import json import logging import time import urllib.error import urllib.request from typing import Any, Dict, List, Optional logger = logging.getLogger(__name__) class RCRestError(Exception): """Raised when the RC REST API returns an error.""" 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, 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 ────────────────────────────────────────────── def _request( self, method: str, endpoint: str, data: Optional[dict] = None, ) -> 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. Raises: RCRestError: On HTTP errors or connection failures. """ url = f"{self.base_url}{endpoint}" headers = { "X-Auth-Token": self.auth_token, "X-User-Id": self.user_id, } body = None if data is not None: headers["Content-Type"] = "application/json" body = json.dumps(data).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method=method) # 429 retry with exponential backoff: 5s → 10s → 20s → 40s (max 4 retries) # Total possible wait: 75s — gives RC enough time to reset its rate-limit window. _429_BACKOFFS = [5.0, 10.0, 20.0, 40.0] max_429_retries = len(_429_BACKOFFS) 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 = _429_BACKOFFS[attempt] 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 ───────────────────────────────────────────────────── def self_check(self) -> dict: """Verify that the configured token matches the user identity. Calls users.info?username=bernd and compares the returned _id with the configured X-User-Id header. Returns: {"ok": True, "user_id": "...", "username": "..."} on success. Raises: RCRestError: If the token is invalid or user IDs don't match. """ # Use users.info with userId parameter (more reliable than username lookup) r = self._request( "GET", f"/api/v1/users.info?userId={self.user_id}", ) if not r.get("success"): raise RCRestError( f"Self-check failed: users.info returned success=false. " f"Token may be invalid." ) user = r.get("user", {}) returned_id = user.get("_id", "") if returned_id != self.user_id: raise RCRestError( f"Self-check FAILED: X-User-Id={self.user_id} but " f"users.info returned _id={returned_id}. " f"Token/user mismatch — ABORT." ) return { "ok": True, "user_id": returned_id, "username": user.get("username", "unknown"), } def post_message(self, room_id: str, text: str) -> tuple[str, str]: """Post a message to a room. Args: room_id: The room ID to post to. text: The message text. Returns: A tuple of (message_id, timestamp) from the API response. The timestamp can be used as a cursor for subsequent polling, avoiding an extra channels.history call. Raises: RCRestError: On API failure. """ r = self._request( "POST", "/api/v1/chat.postMessage", data={"roomId": room_id, "text": text}, ) if not r.get("success"): raise RCRestError( f"chat.postMessage failed: {r.get('error', 'unknown error')}" ) msg = r.get("message", {}) msg_id = msg.get("_id", "") ts = msg.get("ts", "") logger.info("Posted message %s (ts=%s) to room %s", msg_id[:12], ts[:19], room_id[:12]) return msg_id, ts def get_history( self, room_id: str, count: int = 20, oldest: Optional[str] = None, latest: Optional[str] = None, ) -> List[dict]: """Fetch recent messages from a room via channels.history. Args: room_id: The room ID. count: Number of messages to fetch (max 100). oldest: ISO timestamp — only messages AFTER this time. latest: ISO timestamp — only messages BEFORE this time. Returns: List of message objects (sorted oldest→newest by RC). """ params = [f"roomId={room_id}", f"count={min(count, 100)}"] if oldest: params.append(f"oldest={oldest}") if latest: params.append(f"latest={latest}") query = "&".join(params) r = self._request("GET", f"/api/v1/channels.history?{query}") if not r.get("success"): raise RCRestError( f"channels.history failed: {r.get('error', 'unknown error')}" ) return r.get("messages", []) def get_room_info(self, room_id: str) -> dict: """Get room information via channels.info.""" r = self._request( "GET", f"/api/v1/channels.info?roomId={room_id}", ) if not r.get("success"): raise RCRestError( f"channels.info failed: {r.get('error', 'unknown error')}" ) return r.get("channel", {}) def delete_message(self, room_id: str, message_id: str) -> bool: """Delete a message via chat.delete. Returns True on success. """ r = self._request( "POST", "/api/v1/chat.delete", data={"roomId": room_id, "msgId": message_id}, ) return bool(r.get("success")) def get_user_info(self, username: str) -> dict: """Get user info by username.""" r = self._request( "GET", f"/api/v1/users.info?username={username}", ) if not r.get("success"): raise RCRestError( f"users.info for {username} failed: {r.get('error', 'unknown error')}" ) return r.get("user", {})