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

@@ -9,7 +9,8 @@ import logging
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
import psycopg
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware
@@ -52,6 +53,17 @@ async def lifespan(app):
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
# The seconds a restart takes the database away (Sentry DTF-API-9): the
# request is answered "try again" instead of a 500, and only a warning is
# logged (Sentry takes errors). The page retries by itself or on reload.
RESTARTING = 'O servidor está reiniciando. Tente de novo em alguns segundos.'
@app.exception_handler(psycopg.OperationalError)
async def database_unavailable(request: Request, exc):
logging.warning('Database unavailable for %s %s: %s', request.method, request.url.path, exc)
return JSONResponse({'detail': RESTARTING}, status_code=503, headers={'Retry-After': '5'})
@app.middleware('http')
async def safe_headers(request, call_next):
if request.method not in ('GET','HEAD','OPTIONS'):

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()

View File

@@ -30,6 +30,7 @@ from decimal import Decimal
from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
import psycopg
from psycopg.types.json import Jsonb
from PIL import Image
@@ -380,10 +381,22 @@ def finish(job, status, detail):
def render_loop(storage):
down_since, delay = None, 2
while True:
try:
if render_one(storage):
continue
except psycopg.OperationalError as exc:
# A restart takes the database away for seconds: say so once.
if down_since is None:
down_since = time.monotonic()
logging.warning('Print render worker: database unavailable, retrying: %s', exc)
time.sleep(delay)
delay = min(delay * 2, 15)
continue
except Exception:
logging.exception('Print render worker tick failed')
if down_since is not None:
logging.info('Print render worker: database back after %s s', int(time.monotonic() - down_since))
down_since, delay = None, 2
time.sleep(2)

View File

@@ -146,7 +146,7 @@ def loop():
except psycopg.OperationalError as exc:
if db_down_since is None:
db_down_since = time.monotonic()
logging.error('Database unavailable, retrying: %s', exc)
logging.warning('Database unavailable, retrying: %s', exc)
else:
logging.debug('Database still unavailable, retrying in %s s', delay)
time.sleep(delay)