▮ RECOMMENDED USE
A starting skeleton for a stdlib webhook bridge where someone will finish the eviction sweep, cap the retry loop, and add SO_REUSEADDR before it ships.
▮ REFACTORED PATCH
# 1) Evict stale idempotency entries (bounded store + monotonic clock)
import time
IDEMPOTENCY_TTL = 300
def is_idempotent(event_id):
now = time.monotonic()
stale = [k for k, ts in list(idempotency_store.items()) if now - ts > IDEMPOTENCY_TTL]
for k in stale[:64]: del idempotency_store[k]
if event_id in idempotency_store and now - idempotency_store[event_id] < IDEMPOTENCY_TTL:
idempotency_store[event_id] = now; return True
idempotency_store[event_id] = now; return False
# 2) Cap 429 retries so a stuck Discord never hangs the server
MAX_429_RETRIES = 1
async def forward_to_discord(self, data):
while not rate_limit(): await asyncio.sleep(0.05)
payload = {"content": f"Event {data.get('type')}: {data.get('data', {}).get('message', '')}"}
attempts = 0
while True:
try: await discord_send(payload); return
except Exception as e:
if 'HTTP 429' in str(e) and attempts < MAX_429_RETRIES:
m = re.search(r'Retry-After (\d+)', str(e))
await asyncio.sleep(int(m.group(1)) if m else 1); attempts += 1; continue
raise # let caller return a clear 502, do not swallow
# 3) SO_REUSEADDR + clean shutdown (fixes EADDRINUSE)
class ReusableHTTPServer(HTTPServer): allow_reuse_address = True
if __name__ == '__main__':
unittest.main(argv=[''], exit=False, verbosity=2)
server = ReusableHTTPServer(('localhost', 8080), WebhookHandler)
try: server.serve_forever()
finally: server.server_close()