fix(adapter): exponential backoff retry for 429 rate-limit on chat.postMessage
This commit is contained in:
+86
-36
@@ -21,8 +21,15 @@ import struct
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class RocketChatRateLimitError(Exception):
|
||||
"""HTTP 429 Too Many Requests from Rocket.Chat REST API."""
|
||||
pass
|
||||
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
|
||||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||||
@@ -104,6 +111,13 @@ class RocketChatREST:
|
||||
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:
|
||||
raise RocketChatRateLimitError(
|
||||
f"HTTP 429 on {method} {endpoint}"
|
||||
) from e
|
||||
logger.debug("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.debug("REST %s %s failed: %s", method, endpoint, e)
|
||||
return None
|
||||
@@ -471,6 +485,42 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Auto-Onboarding v2: structured interview state
|
||||
self._onboarding_state: Dict[str, Any] = {}
|
||||
|
||||
async def _post_message_with_retry(
|
||||
self, room_id: str, text: str,
|
||||
attachments: Optional[List[dict]] = None,
|
||||
max_retries: int = 3,
|
||||
) -> bool:
|
||||
"""Send chat.postMessage with exponential backoff on HTTP 429.
|
||||
|
||||
Retries only on RocketChatRateLimitError (HTTP 429). All other
|
||||
failures return False immediately. Uses asyncio.sleep so the
|
||||
gateway listen loop is never blocked.
|
||||
|
||||
Retry delays: 2s, 4s, 8s.
|
||||
"""
|
||||
delays = [2, 4, 8]
|
||||
for attempt in range(max_retries + 1):
|
||||
try:
|
||||
return self.rest.post_message(room_id, text, attachments=attachments)
|
||||
except RocketChatRateLimitError:
|
||||
if attempt < max_retries:
|
||||
delay = delays[min(attempt, len(delays) - 1)]
|
||||
logger.warning(
|
||||
"Rate-limited (429), retry %d/%d in %ds (room=%s)",
|
||||
attempt + 1, max_retries, delay, room_id[:8],
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
else:
|
||||
logger.error(
|
||||
"chat.postMessage failed after %d retries (room=%s)",
|
||||
max_retries, room_id[:8],
|
||||
)
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.debug("chat.postMessage failed (non-429): %s", e)
|
||||
return False
|
||||
return False
|
||||
|
||||
async def connect(self) -> bool:
|
||||
if not self.base_url or not self.user or not self.password:
|
||||
logger.error("[rocketchat] Missing configuration")
|
||||
@@ -781,18 +831,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Rüberkopieren
|
||||
target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}"
|
||||
if move_req.get("username"):
|
||||
self.rest.post_message(move_req["target_room"], target_txt)
|
||||
await self._post_message_with_retry(move_req["target_room"], target_txt)
|
||||
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
|
||||
forwarded = True
|
||||
feedback_type = "confirm"
|
||||
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
|
||||
# Nicht mehr fragen / sticky_room setzen
|
||||
self._sticky_rooms[room_id] = time.time()
|
||||
self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
|
||||
await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
|
||||
feedback_type = "never"
|
||||
else:
|
||||
# "Hier bleiben" / "2" / "2️⃣" — Default
|
||||
self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
|
||||
await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
|
||||
feedback_type = "stay"
|
||||
|
||||
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
|
||||
@@ -916,7 +966,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"username": username,
|
||||
"message_id": msg_id,
|
||||
}
|
||||
self.rest.post_message(room_id, note, attachments=attachments)
|
||||
await self._post_message_with_retry(room_id, note, attachments=attachments)
|
||||
except Exception:
|
||||
# Fallback: Textoptionen (wenn Button-Send fehlschlägt)
|
||||
note = (
|
||||
@@ -934,15 +984,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"username": username,
|
||||
"message_id": msg_id,
|
||||
}
|
||||
self.rest.post_message(room_id, note)
|
||||
await self._post_message_with_retry(room_id, note)
|
||||
# Kein Forwarding — auf User-Antwort warten
|
||||
forwarded = True
|
||||
else:
|
||||
# Typ 1: Silent Copy — Nachricht in Zielraum kopieren
|
||||
self.rest.post_message(decision.target_room,
|
||||
await self._post_message_with_retry(decision.target_room,
|
||||
f"*(Thema passt zu {target_name} — von @{username})*\n{text}")
|
||||
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
|
||||
self.rest.post_message(room_id, note)
|
||||
await self._post_message_with_retry(room_id, note)
|
||||
# Agent soll im Zielraum antworten, nicht im Ursprungsraum
|
||||
_CURRENT_ORIGIN_ROOM.set(decision.target_room)
|
||||
forwarded = True
|
||||
@@ -1037,7 +1087,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""Callback for Archivar forwarding — sends a message copy to a target room."""
|
||||
if not self.rest.auth_token:
|
||||
return False
|
||||
return self.rest.post_message(room_id, text)
|
||||
return await self._post_message_with_retry(room_id, text)
|
||||
|
||||
async def _send_archivar_buttons(self, room_id: str, text: str, payload: dict) -> bool:
|
||||
"""Callback for Archivar — sends native Rocket.Chat Action-Buttons.
|
||||
@@ -1068,7 +1118,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
actions = payload.get("actions", [])
|
||||
if not actions:
|
||||
return self.rest.post_message(room_id, text)
|
||||
return await self._post_message_with_retry(room_id, text)
|
||||
|
||||
# Detect Archivar v4 Move-Request (Butler-Prinzip: ✅Ja / 📍Hier)
|
||||
move_req_ctx = payload.get("_move_request")
|
||||
@@ -1111,7 +1161,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"actions": buttons,
|
||||
}]
|
||||
|
||||
success = self.rest.post_message(room_id, text, attachments=attachments)
|
||||
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
||||
if success:
|
||||
# Mark room so the response stays here (no Archivar routing)
|
||||
self._rooms_with_pending_questions.add(room_id)
|
||||
@@ -1194,7 +1244,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"actions": buttons,
|
||||
}]
|
||||
|
||||
success = self.rest.post_message(operator_room_id, text, attachments=attachments)
|
||||
success = await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||||
if success:
|
||||
logger.info("[rocketchat] Onboarding v2 gestartet: %d Räume fehlen", len(missing_rooms))
|
||||
else:
|
||||
@@ -1230,16 +1280,16 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if 0 <= index < len(all_rooms):
|
||||
rid, name = all_rooms[index]
|
||||
self._set_catch_all(rid)
|
||||
self.rest.post_message(operator_room_id, f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
||||
await self._post_message_with_retry(operator_room_id, f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
||||
logger.info("[rocketchat] Catch-All geändert zu: %s", name)
|
||||
else:
|
||||
self.rest.post_message(operator_room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
|
||||
await self._post_message_with_retry(operator_room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
|
||||
return # onboarding_active bleibt True, warte auf korrekte Antwort
|
||||
elif single_line.lower() in ("überspringen", "skip", "nein", "no", "behalten"):
|
||||
self.rest.post_message(operator_room_id, "👍 Catch-All bleibt unverändert.")
|
||||
await self._post_message_with_retry(operator_room_id, "👍 Catch-All bleibt unverändert.")
|
||||
logger.info("[rocketchat] Catch-All unverändert")
|
||||
else:
|
||||
self.rest.post_message(operator_room_id, "❌ Bitte eine Raumnummer (1, 2, …) oder 'überspringen' eingeben.")
|
||||
await self._post_message_with_retry(operator_room_id, "❌ Bitte eine Raumnummer (1, 2, …) oder 'überspringen' eingeben.")
|
||||
return # onboarding_active bleibt True
|
||||
# Catch-All-Frage beantwortet → Onboarding wirklich abschließen
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
@@ -1262,14 +1312,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if rid not in state["skipped_rooms"]:
|
||||
state["skipped_rooms"].append(rid)
|
||||
logger.info("[rocketchat] Onboarding: alle Räume übersprungen (skip_all)")
|
||||
self._onboarding_next_room()
|
||||
await self._onboarding_next_room()
|
||||
return
|
||||
|
||||
if "later" in action:
|
||||
# Onboarding pausieren
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self._onboarding_state = {}
|
||||
self.rest.post_message(operator_room_id,
|
||||
await self._post_message_with_retry(operator_room_id,
|
||||
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||||
logger.info("[rocketchat] Onboarding pausiert (later)")
|
||||
return
|
||||
@@ -1281,14 +1331,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Einzelnen Raum überspringen
|
||||
state["skipped_rooms"].append(target_room_id)
|
||||
logger.info("[rocketchat] Onboarding: Raum %s übersprungen", target_room_id[:8])
|
||||
self._onboarding_next_room()
|
||||
await self._onboarding_next_room()
|
||||
return
|
||||
|
||||
if "Später" in action or "⏰" in action:
|
||||
# Onboarding pausieren
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self._onboarding_state = {}
|
||||
self.rest.post_message(operator_room_id,
|
||||
await self._post_message_with_retry(operator_room_id,
|
||||
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||||
logger.info("[rocketchat] Onboarding pausiert (Später)")
|
||||
return
|
||||
@@ -1308,7 +1358,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
break
|
||||
|
||||
if state["current_room_index"] >= 0:
|
||||
self._ask_onboarding_question(operator_room_id)
|
||||
await self._ask_onboarding_question(operator_room_id)
|
||||
return
|
||||
|
||||
# ── Modus 2: Text-Antwort auf Interview-Frage ────────────────────
|
||||
@@ -1328,12 +1378,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if current_q == 1:
|
||||
theme = text.strip()
|
||||
if not theme or len(theme) < 3:
|
||||
self.rest.post_message(operator_room_id,
|
||||
await self._post_message_with_retry(operator_room_id,
|
||||
"❌ Bitte gib eine kurze Beschreibung ein (mindestens 3 Zeichen).")
|
||||
return
|
||||
data["theme"] = theme
|
||||
state["current_question"] = 2
|
||||
self._ask_onboarding_question(operator_room_id)
|
||||
await self._ask_onboarding_question(operator_room_id)
|
||||
return
|
||||
|
||||
# Frage 2: keywords_100
|
||||
@@ -1349,7 +1399,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||||
data["keywords_100"] = kws[:10]
|
||||
state["current_question"] = 3
|
||||
self._ask_onboarding_question(operator_room_id)
|
||||
await self._ask_onboarding_question(operator_room_id)
|
||||
return
|
||||
|
||||
# Frage 3: keywords_context
|
||||
@@ -1364,7 +1414,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||||
data["keywords_context"] = kws[:10]
|
||||
state["current_question"] = 4
|
||||
self._ask_onboarding_question(operator_room_id)
|
||||
await self._ask_onboarding_question(operator_room_id)
|
||||
return
|
||||
|
||||
# Frage 4: catch_all
|
||||
@@ -1396,17 +1446,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
# Feedback an Operator
|
||||
catch_marker = " 🎯 Catch-All" if is_catch_all else ""
|
||||
self.rest.post_message(operator_room_id,
|
||||
await self._post_message_with_retry(operator_room_id,
|
||||
f"✅ {room_name} eingerichtet:{catch_marker}\n"
|
||||
f"Thema: {data['theme']}\n"
|
||||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||||
|
||||
# Nächster Raum oder Abschluss
|
||||
self._onboarding_next_room()
|
||||
await self._onboarding_next_room()
|
||||
return
|
||||
|
||||
def _ask_onboarding_question(self, operator_room_id: str) -> None:
|
||||
async def _ask_onboarding_question(self, operator_room_id: str) -> None:
|
||||
"""Sendet die aktuelle Interview-Frage an den Operator."""
|
||||
state = self._onboarding_state
|
||||
if not state:
|
||||
@@ -1431,9 +1481,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
text = questions.get(current_q, "")
|
||||
if text:
|
||||
self.rest.post_message(operator_room_id, text)
|
||||
await self._post_message_with_retry(operator_room_id, text)
|
||||
|
||||
def _onboarding_next_room(self) -> None:
|
||||
async def _onboarding_next_room(self) -> None:
|
||||
"""Gehe zum nächsten fehlenden Raum oder schließe Onboarding ab."""
|
||||
state = self._onboarding_state
|
||||
if not state:
|
||||
@@ -1486,14 +1536,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"title": "Weitere Räume einrichten?",
|
||||
"actions": buttons,
|
||||
}]
|
||||
self.rest.post_message(operator_room_id, "\n".join(lines), attachments=attachments)
|
||||
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
||||
else:
|
||||
self._finish_onboarding(operator_room_id)
|
||||
await self._finish_onboarding(operator_room_id)
|
||||
else:
|
||||
# Alle Räume bearbeitet
|
||||
self._finish_onboarding(operator_room_id)
|
||||
await self._finish_onboarding(operator_room_id)
|
||||
|
||||
def _finish_onboarding(self, operator_room_id: str) -> None:
|
||||
async def _finish_onboarding(self, operator_room_id: str) -> None:
|
||||
"""Onboarding abschließen: Übersicht zeigen, Catch-All-Frage stellen."""
|
||||
# NICHT onboarding_active=False setzen — wir warten noch auf Catch-All-Antwort
|
||||
# Stattdessen: Phase wechseln zu "catch_all_change"
|
||||
@@ -1519,7 +1569,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
lines.append("")
|
||||
lines.append("Möchtest du den Catch-All-Raum ändern? Antworte mit der Raumnummer, oder **überspringen** zum Behalten.")
|
||||
|
||||
self.rest.post_message(operator_room_id, "\n".join(lines))
|
||||
await self._post_message_with_retry(operator_room_id, "\n".join(lines))
|
||||
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
||||
|
||||
@staticmethod
|
||||
@@ -1751,7 +1801,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"original_text": content,
|
||||
}
|
||||
|
||||
success = self.rest.post_message(real_room_id, content, attachments=attachments)
|
||||
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
||||
if success:
|
||||
# If this message has buttons, mark the room so the next user
|
||||
# message from here stays put (no Archivar routing). Button
|
||||
@@ -1904,7 +1954,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
}]
|
||||
|
||||
# Send message with buttons
|
||||
success = self.rest.post_message(real_room_id, text, attachments=attachments)
|
||||
success = await self._post_message_with_retry(real_room_id, text, attachments=attachments)
|
||||
|
||||
if success:
|
||||
# Store clarify state for gateway identification
|
||||
|
||||
Reference in New Issue
Block a user