fix: a request during a database restart answers 503, and the logs stay quiet

Sentry DTF-API-8/9 (stack restart, 16/11 09:15): the startup retry kept
the API up, but a board request in the ~7 s without the database got a
500, and the render thread logged its error every 2 s. A request that
hits psycopg.OperationalError now answers 503 "O servidor está
reiniciando" with Retry-After (the web does not report it); the render
thread warns once per outage and backs off; the worker's first outage
line and the audit's connection outage are warnings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-16 09:32:50 -03:00
parent 00c7fa3dfa
commit bcba1fbe67
6 changed files with 64 additions and 8 deletions

View File

@@ -4,6 +4,8 @@ import os
import secrets
import logging
import json
import psycopg
import sys
import time
from uuid import UUID, uuid4
from fastapi import HTTPException, Request
@@ -95,7 +97,9 @@ def audit(event, c=None, **fields):
now = time.monotonic()
if _persistence_error_at is None or now-_persistence_error_at >= 60:
_persistence_error_at = now
logging.getLogger('dtf.security').error('Security event persistence unavailable')
log = logging.getLogger('dtf.security')
(log.warning if isinstance(sys.exc_info()[1], psycopg.OperationalError) else log.error)(
'Security event persistence unavailable')
def rate_limit(scope, identity, limit, seconds=900):
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()