Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f3cc02148 | |||
| 6aaadcdb88 |
+61
-23
@@ -6537,6 +6537,53 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self.ddp = None
|
self.ddp = None
|
||||||
logger.info("[rocketchat] Disconnected")
|
logger.info("[rocketchat] Disconnected")
|
||||||
|
|
||||||
|
# ── P1: Quick-Reply Dedup Helper ──────────────────────────────────
|
||||||
|
# Zentraler Helper für Quick-Reply — verhindert 3x-Senden durch
|
||||||
|
# Dedup-Flag im _TurnHandle und kontextabhängigen Text (same-room
|
||||||
|
# vs cross-room).
|
||||||
|
|
||||||
|
async def _maybe_send_quick_reply(
|
||||||
|
self, gate_room_id: str, active_room_id: Optional[str], active_room_name: str
|
||||||
|
) -> Optional[SendResult]:
|
||||||
|
"""Sendet Quick-Reply wenn noch keiner für diesen Raum gesendet wurde.
|
||||||
|
|
||||||
|
Dedup: quick_reply_already_sent prüft das Flag im _TurnHandle.
|
||||||
|
Kontextabhängiger Text:
|
||||||
|
- Same-Raum (active_room_id == gate_room_id): kein Raum-Name
|
||||||
|
- Cross-Raum mit Name: „Ich antworte gerade in #RaumX — …"
|
||||||
|
- Cross-Raum ohne Name: generischer Fallback
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
SendResult wenn Quick-Reply gesendet wurde, None wenn bereits
|
||||||
|
gesendet (Dedup).
|
||||||
|
"""
|
||||||
|
if self._outbound_gate.quick_reply_already_sent(gate_room_id):
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Kontextabhängiger Text
|
||||||
|
same_room = (active_room_id is not None and active_room_id == gate_room_id)
|
||||||
|
if same_room:
|
||||||
|
text = "Ich bin gerade beschäftigt — einen Moment bitte, ich bin gleich bei dir."
|
||||||
|
elif active_room_name:
|
||||||
|
text = (
|
||||||
|
f"Ich antworte gerade in #{active_room_name} — "
|
||||||
|
f"einen Moment bitte, ich bin gleich bei dir."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
text = (
|
||||||
|
"Ich antworte gerade in einem anderen Raum — "
|
||||||
|
"einen Moment bitte, ich bin gleich bei dir."
|
||||||
|
)
|
||||||
|
|
||||||
|
await self._post_message_unlocked(gate_room_id, text)
|
||||||
|
self._outbound_gate.mark_quick_reply_sent(gate_room_id)
|
||||||
|
self._outbound_gate.stats.quick_reply += 1
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
||||||
|
gate_room_id[:8], active_room_name or "unknown",
|
||||||
|
)
|
||||||
|
return SendResult(success=True, message_id="quick_reply")
|
||||||
|
|
||||||
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
|
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
|
||||||
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
||||||
if not self.rest.auth_token:
|
if not self.rest.auth_token:
|
||||||
@@ -6627,25 +6674,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
decision = GateDecision(allow=False, reason="timeout")
|
decision = GateDecision(allow=False, reason="timeout")
|
||||||
|
|
||||||
if not decision.allow:
|
if not decision.allow:
|
||||||
# Quick-Reply: anderer Raum blockiert immer noch
|
# Quick-Reply via zentralem Helper (Dedup + kontextabhängiger Text)
|
||||||
active_room = self._outbound_gate.active_room_id
|
active_room = self._outbound_gate.active_room_id
|
||||||
active_name = ""
|
active_name = ""
|
||||||
if active_room and active_room in self._room_info:
|
if active_room and active_room in self._room_info:
|
||||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||||
quick_reply_text = (
|
qr_result = await self._maybe_send_quick_reply(
|
||||||
f"Ich antworte gerade in #{active_name} — "
|
_gate_room_id, active_room, active_name
|
||||||
f"einen Moment bitte, ich bin gleich bei dir."
|
|
||||||
) if active_name else (
|
|
||||||
"Ich antworte gerade in einem anderen Raum — "
|
|
||||||
"einen Moment bitte, ich bin gleich bei dir."
|
|
||||||
)
|
)
|
||||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
if qr_result is not None:
|
||||||
self._outbound_gate.stats.quick_reply += 1
|
return qr_result
|
||||||
logger.info(
|
# Dedup: Quick-Reply bereits gesendet → trotzdem return
|
||||||
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
return SendResult(success=True, message_id="quick_reply_dedup")
|
||||||
_gate_room_id[:8], active_name,
|
|
||||||
)
|
|
||||||
return SendResult(success=True, message_id="quick_reply")
|
|
||||||
# Fell through: decision.allow is True — track if WE created the entry
|
# Fell through: decision.allow is True — track if WE created the entry
|
||||||
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||||
_gate_acquired = (decision.reason == "gate_clear")
|
_gate_acquired = (decision.reason == "gate_clear")
|
||||||
@@ -7083,20 +7123,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
decision = GateDecision(allow=False, reason="timeout")
|
decision = GateDecision(allow=False, reason="timeout")
|
||||||
if not decision.allow:
|
if not decision.allow:
|
||||||
|
# Quick-Reply via zentralem Helper (Dedup + kontextabhängiger Text)
|
||||||
active_room = self._outbound_gate.active_room_id
|
active_room = self._outbound_gate.active_room_id
|
||||||
active_name = ""
|
active_name = ""
|
||||||
if active_room and active_room in self._room_info:
|
if active_room and active_room in self._room_info:
|
||||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||||
quick_reply_text = (
|
qr_result = await self._maybe_send_quick_reply(
|
||||||
f"Ich antworte gerade in #{active_name} — "
|
_gate_room_id, active_room, active_name
|
||||||
f"einen Moment bitte, ich bin gleich bei dir."
|
|
||||||
) if active_name else (
|
|
||||||
"Ich antworte gerade in einem anderen Raum — "
|
|
||||||
"einen Moment bitte, ich bin gleich bei dir."
|
|
||||||
)
|
)
|
||||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
if qr_result is not None:
|
||||||
self._outbound_gate.stats.quick_reply += 1
|
return qr_result
|
||||||
return SendResult(success=True, message_id="quick_reply")
|
# Dedup: Quick-Reply bereits gesendet → trotzdem return
|
||||||
|
return SendResult(success=True, message_id="quick_reply_dedup")
|
||||||
# Fell through: decision.allow is True — track if WE created the entry
|
# Fell through: decision.allow is True — track if WE created the entry
|
||||||
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||||
_gate_acquired = (decision.reason == "gate_clear")
|
_gate_acquired = (decision.reason == "gate_clear")
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ class _TurnHandle:
|
|||||||
real_room_id: str
|
real_room_id: str
|
||||||
task: Optional[asyncio.Task] = None
|
task: Optional[asyncio.Task] = None
|
||||||
chat_id: str = ""
|
chat_id: str = ""
|
||||||
|
quick_reply_sent: bool = False
|
||||||
|
|
||||||
|
|
||||||
# ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
|
# ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
|
||||||
@@ -134,6 +135,8 @@ class OutboundGate:
|
|||||||
self._lock = asyncio.Lock()
|
self._lock = asyncio.Lock()
|
||||||
# A4: Per-Raum Dict statt flat List — kein False-Wake-Bug
|
# A4: Per-Raum Dict statt flat List — kein False-Wake-Bug
|
||||||
self._waiters: Dict[str, List[asyncio.Event]] = {}
|
self._waiters: Dict[str, List[asyncio.Event]] = {}
|
||||||
|
# P1: Quick-Reply Dedup — separates Tracking fuer Trigger-Raeume
|
||||||
|
self._quick_reply_sent: Dict[str, bool] = {}
|
||||||
self.default_timeout_s = default_timeout_s
|
self.default_timeout_s = default_timeout_s
|
||||||
self.max_entry_age_s = max_entry_age_s
|
self.max_entry_age_s = max_entry_age_s
|
||||||
self.stats = GateStats()
|
self.stats = GateStats()
|
||||||
@@ -227,6 +230,39 @@ class OutboundGate:
|
|||||||
reason="gate_clear",
|
reason="gate_clear",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ── Quick-Reply Dedup (P1) ──────────────────────────────────────────
|
||||||
|
# Separates Tracking-Dict unabhaengig von _in_flight:
|
||||||
|
# Quick-Reply wird fuer den TRIGGER-Raum gesendet, der NICHT in
|
||||||
|
# _in_flight ist (dort ist nur der aktive/beschaeftigte Raum).
|
||||||
|
|
||||||
|
def mark_quick_reply_sent(self, room_id: str) -> bool:
|
||||||
|
"""Markiert dass ein Quick-Reply fuer diesen Raum gesendet wurde.
|
||||||
|
|
||||||
|
Idempotent: returns True beim ersten Aufruf (Quick-Reply wurde
|
||||||
|
tatsaechlich gesendet), False bei allen weiteren Aufrufen.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID (der Trigger-Raum, nicht der aktive).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True wenn dies das erste Markieren war, False wenn bereits markiert.
|
||||||
|
"""
|
||||||
|
if room_id not in self._quick_reply_sent:
|
||||||
|
self._quick_reply_sent[room_id] = True
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def quick_reply_already_sent(self, room_id: str) -> bool:
|
||||||
|
"""Prueft ob bereits ein Quick-Reply fuer diesen Raum gesendet wurde.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True wenn bereits ein Quick-Reply gesendet wurde.
|
||||||
|
"""
|
||||||
|
return room_id in self._quick_reply_sent
|
||||||
|
|
||||||
# ── release (idempotent) ──────────────────────────────────────────────
|
# ── release (idempotent) ──────────────────────────────────────────────
|
||||||
|
|
||||||
def release(self, room_id: str, task_token: str) -> None:
|
def release(self, room_id: str, task_token: str) -> None:
|
||||||
|
|||||||
@@ -280,3 +280,53 @@ def test_outbound_gate_stats_defaults():
|
|||||||
assert stats.quick_reply == 0
|
assert stats.quick_reply == 0
|
||||||
assert stats.stale_swept == 0
|
assert stats.stale_swept == 0
|
||||||
assert stats.released_total == 0
|
assert stats.released_total == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 6.1: mark_quick_reply_sent returns True on first call
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
def test_mark_quick_reply_sent_first_call_returns_true():
|
||||||
|
"""6.1: mark_quick_reply_sent returns True beim ersten Aufruf."""
|
||||||
|
gate = OutboundGate()
|
||||||
|
room = "ROOM_QR_TEST_1"
|
||||||
|
|
||||||
|
result = gate.mark_quick_reply_sent(room)
|
||||||
|
assert result is True, "First mark_quick_reply_sent should return True"
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 6.2: mark_quick_reply_sent returns False on second call (idempotent)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
def test_mark_quick_reply_sent_second_call_returns_false():
|
||||||
|
"""6.2: mark_quick_reply_sent returns False beim zweiten Aufruf (idempotent)."""
|
||||||
|
gate = OutboundGate()
|
||||||
|
room = "ROOM_QR_TEST_2"
|
||||||
|
|
||||||
|
first = gate.mark_quick_reply_sent(room)
|
||||||
|
assert first is True
|
||||||
|
|
||||||
|
second = gate.mark_quick_reply_sent(room)
|
||||||
|
assert second is False, "Second mark_quick_reply_sent should return False (idempotent)"
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 6.3: quick_reply_already_sent returns correct before/after mark
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
def test_quick_reply_already_sent_before_and_after():
|
||||||
|
"""6.3: quick_reply_already_sent returns korrekt vor/nach mark."""
|
||||||
|
gate = OutboundGate()
|
||||||
|
room = "ROOM_QR_TEST_3"
|
||||||
|
|
||||||
|
# Before mark: should be False
|
||||||
|
assert gate.quick_reply_already_sent(room) is False
|
||||||
|
|
||||||
|
gate.mark_quick_reply_sent(room)
|
||||||
|
|
||||||
|
# After mark: should be True
|
||||||
|
assert gate.quick_reply_already_sent(room) is True
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""
|
||||||
|
P1: Quick-Reply Dedup — Integration-Tests fuer _maybe_send_quick_reply.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
from plugin.archivar.outbound_gate import OutboundGate
|
||||||
|
|
||||||
|
|
||||||
|
def _make_bare_adapter():
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
return RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_parallel_tasks_quick_reply_only_once():
|
||||||
|
"""Parallele Tasks → Quick-Reply nur 1x (Dedup)."""
|
||||||
|
adapter = _make_bare_adapter()
|
||||||
|
gate = OutboundGate()
|
||||||
|
adapter._outbound_gate = gate
|
||||||
|
await gate.try_acquire("ROOM_A", "token-a")
|
||||||
|
|
||||||
|
call_count = 0
|
||||||
|
async def mock_post(room_id, text):
|
||||||
|
nonlocal call_count; call_count += 1; return "ok"
|
||||||
|
adapter._post_message_unlocked = mock_post
|
||||||
|
|
||||||
|
results = await asyncio.gather(
|
||||||
|
adapter._maybe_send_quick_reply("ROOM_B", "ROOM_A", "Alpha"),
|
||||||
|
adapter._maybe_send_quick_reply("ROOM_B", "ROOM_A", "Alpha"),
|
||||||
|
)
|
||||||
|
assert call_count == 1
|
||||||
|
assert sum(1 for r in results if r is not None) == 1
|
||||||
|
assert sum(1 for r in results if r is None) == 1
|
||||||
|
gate.release("ROOM_A", "token-a")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_same_room_quick_reply_text_no_room_name():
|
||||||
|
"""Same-Raum → Text OHNE Raum-Namen."""
|
||||||
|
adapter = _make_bare_adapter()
|
||||||
|
gate = OutboundGate()
|
||||||
|
adapter._outbound_gate = gate
|
||||||
|
await gate.try_acquire("ROOM_S", "token-s")
|
||||||
|
|
||||||
|
posted = []
|
||||||
|
async def mock_post(room_id, text):
|
||||||
|
posted.append(text); return "ok"
|
||||||
|
adapter._post_message_unlocked = mock_post
|
||||||
|
|
||||||
|
result = await adapter._maybe_send_quick_reply("ROOM_S", "ROOM_S", "Testraum")
|
||||||
|
assert result is not None
|
||||||
|
assert "Testraum" not in posted[0]
|
||||||
|
assert "#" not in posted[0]
|
||||||
|
assert "beschäftigt" in posted[0]
|
||||||
|
gate.release("ROOM_S", "token-s")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_cross_room_quick_reply_text_has_room_name():
|
||||||
|
"""Cross-Raum → Text MIT Raum-Namen."""
|
||||||
|
adapter = _make_bare_adapter()
|
||||||
|
gate = OutboundGate()
|
||||||
|
adapter._outbound_gate = gate
|
||||||
|
await gate.try_acquire("ROOM_A", "token-c")
|
||||||
|
|
||||||
|
posted = []
|
||||||
|
async def mock_post(room_id, text):
|
||||||
|
posted.append(text); return "ok"
|
||||||
|
adapter._post_message_unlocked = mock_post
|
||||||
|
|
||||||
|
result = await adapter._maybe_send_quick_reply("ROOM_T", "ROOM_A", "Gamma")
|
||||||
|
assert result is not None
|
||||||
|
assert "Gamma" in posted[0]
|
||||||
|
assert "#" in posted[0]
|
||||||
|
gate.release("ROOM_A", "token-c")
|
||||||
@@ -94,10 +94,10 @@ class RateLimiter:
|
|||||||
"""Simple token-bucket rate limiter.
|
"""Simple token-bucket rate limiter.
|
||||||
|
|
||||||
Allows max_tokens calls per window_seconds. Thread-safe via lock.
|
Allows max_tokens calls per window_seconds. Thread-safe via lock.
|
||||||
Default: 30 calls/minute (was 60 — RC triggers 429 at 3-4 calls in <10s).
|
Default: 15 calls/minute (was 30 — RC triggers 429 aggressively).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, max_tokens: int = 30, window_seconds: float = 60.0):
|
def __init__(self, max_tokens: int = 15, window_seconds: float = 60.0):
|
||||||
self.max_tokens = max_tokens
|
self.max_tokens = max_tokens
|
||||||
self.window_seconds = window_seconds
|
self.window_seconds = window_seconds
|
||||||
self.tokens = float(max_tokens)
|
self.tokens = float(max_tokens)
|
||||||
@@ -138,7 +138,7 @@ _rate_limiter: RateLimiter | None = None
|
|||||||
def _get_rate_limiter() -> RateLimiter:
|
def _get_rate_limiter() -> RateLimiter:
|
||||||
global _rate_limiter
|
global _rate_limiter
|
||||||
if _rate_limiter is None:
|
if _rate_limiter is None:
|
||||||
_rate_limiter = RateLimiter(max_tokens=30, window_seconds=60.0)
|
_rate_limiter = RateLimiter(max_tokens=15, window_seconds=60.0)
|
||||||
return _rate_limiter
|
return _rate_limiter
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ from .rc_rest import RCRestClient
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Progressive backoff intervals in seconds (rate-limiter-friendly).
|
# Progressive backoff intervals in seconds (rate-limiter-friendly).
|
||||||
# Default: 2s -> 3s -> 5s -> 8s (max 18s total).
|
# Default: 5s -> 8s -> 12s -> 20s (max 45s total).
|
||||||
# Callers can override the first interval via initial_interval.
|
# Callers can override the first interval via initial_interval.
|
||||||
_DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
_DEFAULT_BACKOFF_INTERVALS = [5.0, 8.0, 12.0, 20.0]
|
||||||
_MAX_TOTAL_WAIT = 18.0 # seconds
|
_MAX_TOTAL_WAIT = 45.0 # seconds
|
||||||
|
|
||||||
# 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
|
# 429 exponential backoff: 5s -> 10s -> 20s -> 40s (max)
|
||||||
_MAX_429_BACKOFF = 30.0
|
_MAX_429_BACKOFF = 40.0
|
||||||
# After 5 consecutive 429s, abort with SKIP instead of retrying forever
|
# After 5 consecutive 429s, abort with SKIP instead of retrying forever
|
||||||
_MAX_CONSECUTIVE_429 = 5
|
_MAX_CONSECUTIVE_429 = 5
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ def wait_for_bot_message(
|
|||||||
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
||||||
|
|
||||||
# Build backoff intervals with caller's initial_interval
|
# Build backoff intervals with caller's initial_interval
|
||||||
backoff_intervals = [initial_interval, 3.0, 5.0, 8.0]
|
backoff_intervals = [initial_interval, 8.0, 12.0, 20.0]
|
||||||
|
|
||||||
while time.monotonic() < deadline:
|
while time.monotonic() < deadline:
|
||||||
# Cursor caching: if we already have messages, scan them first
|
# Cursor caching: if we already have messages, scan them first
|
||||||
@@ -137,8 +137,8 @@ def wait_for_bot_message(
|
|||||||
"aggressive. Consider increasing poll intervals or "
|
"aggressive. Consider increasing poll intervals or "
|
||||||
"reducing concurrent test load."
|
"reducing concurrent test load."
|
||||||
)
|
)
|
||||||
# Exponential backoff on rate-limit errors: 3s -> 6s -> 12s -> 20s -> 30s
|
# Exponential backoff on rate-limit errors: 5s -> 10s -> 20s -> 40s
|
||||||
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
backoff = min(5.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
|
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
|
||||||
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
||||||
@@ -170,12 +170,12 @@ def wait_for_bot_message(
|
|||||||
)
|
)
|
||||||
return msg
|
return msg
|
||||||
|
|
||||||
# Progressive backoff: initial_interval -> 3s -> 5s -> 8s
|
# Progressive backoff: initial_interval -> 8s -> 12s -> 20s
|
||||||
if interval_idx < len(backoff_intervals):
|
if interval_idx < len(backoff_intervals):
|
||||||
delay = backoff_intervals[interval_idx]
|
delay = backoff_intervals[interval_idx]
|
||||||
interval_idx += 1
|
interval_idx += 1
|
||||||
else:
|
else:
|
||||||
delay = 8.0
|
delay = 20.0
|
||||||
|
|
||||||
remaining = deadline - time.monotonic()
|
remaining = deadline - time.monotonic()
|
||||||
if remaining <= 0:
|
if remaining <= 0:
|
||||||
|
|||||||
@@ -77,9 +77,9 @@ class RCRestClient:
|
|||||||
|
|
||||||
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||||
|
|
||||||
# 429 retry with exponential backoff: 3s → 6s → 12s → 20s → 30s (max 5 retries)
|
# 429 retry with exponential backoff: 5s → 10s → 20s → 40s (max 4 retries)
|
||||||
# Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
|
# Total possible wait: 75s — gives RC enough time to reset its rate-limit window.
|
||||||
_429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
|
_429_BACKOFFS = [5.0, 10.0, 20.0, 40.0]
|
||||||
max_429_retries = len(_429_BACKOFFS)
|
max_429_retries = len(_429_BACKOFFS)
|
||||||
for attempt in range(max_429_retries + 1):
|
for attempt in range(max_429_retries + 1):
|
||||||
# Rate-limit before every API call (protects post, history, delete, etc.)
|
# Rate-limit before every API call (protects post, history, delete, etc.)
|
||||||
|
|||||||
Reference in New Issue
Block a user