Merge 503 during a database restart (DTF-API-8, 9)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m22s
Build and deploy / Integration suite on a real stack (push) Successful in 7m6s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m44s

This commit is contained in:
Cauê Faleiros
2026-11-16 09:46:37 -03:00
6 changed files with 64 additions and 8 deletions

View File

@@ -9,7 +9,8 @@ import logging
import time import time
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI import psycopg
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware 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 = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS) 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') @app.middleware('http')
async def safe_headers(request, call_next): async def safe_headers(request, call_next):
if request.method not in ('GET','HEAD','OPTIONS'): if request.method not in ('GET','HEAD','OPTIONS'):

View File

@@ -4,6 +4,8 @@ import os
import secrets import secrets
import logging import logging
import json import json
import psycopg
import sys
import time import time
from uuid import UUID, uuid4 from uuid import UUID, uuid4
from fastapi import HTTPException, Request from fastapi import HTTPException, Request
@@ -95,7 +97,9 @@ def audit(event, c=None, **fields):
now = time.monotonic() now = time.monotonic()
if _persistence_error_at is None or now-_persistence_error_at >= 60: if _persistence_error_at is None or now-_persistence_error_at >= 60:
_persistence_error_at = now _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): def rate_limit(scope, identity, limit, seconds=900):
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest() key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()

View File

@@ -30,6 +30,7 @@ from decimal import Decimal
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
from uuid import NAMESPACE_URL, UUID, uuid4, uuid5 from uuid import NAMESPACE_URL, UUID, uuid4, uuid5
import psycopg
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from PIL import Image from PIL import Image
@@ -380,10 +381,22 @@ def finish(job, status, detail):
def render_loop(storage): def render_loop(storage):
down_since, delay = None, 2
while True: while True:
try: try:
if render_one(storage): if render_one(storage):
continue 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: except Exception:
logging.exception('Print render worker tick failed') 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) time.sleep(2)

View File

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

View File

@@ -46,13 +46,14 @@ class WorkerDatabaseOutageTest(unittest.TestCase):
mock.patch.object(worker.mail, 'send_pending'), \ mock.patch.object(worker.mail, 'send_pending'), \
mock.patch.object(worker.time, 'sleep', mock.patch.object(worker.time, 'sleep',
side_effect=[None, None, None, self.StopLoop]) as sleep, \ side_effect=[None, None, None, self.StopLoop]) as sleep, \
mock.patch.object(worker.logging, 'error') as error, \ mock.patch.object(worker.logging, 'warning') as warning, \
mock.patch.object(worker.logging, 'info') as info, \ mock.patch.object(worker.logging, 'info') as info, \
mock.patch.object(worker.logging, 'debug') as debug: mock.patch.object(worker.logging, 'debug') as debug:
with self.assertRaises(self.StopLoop): with self.assertRaises(self.StopLoop):
worker.loop() worker.loop()
self.assertEqual(error.call_count, 1) # A warning, not an error: a restart is expected (Sentry DTF-API-8).
self.assertIn('Database unavailable', error.call_args[0][0]) self.assertEqual(warning.call_count, 1)
self.assertIn('Database unavailable', warning.call_args[0][0])
self.assertEqual(info.call_count, 1) self.assertEqual(info.call_count, 1)
self.assertIn('Database back after', info.call_args[0][0]) self.assertIn('Database back after', info.call_args[0][0])
self.assertEqual(debug.call_count, 2) self.assertEqual(debug.call_count, 2)
@@ -76,8 +77,32 @@ class AuditPersistenceOutageTest(unittest.TestCase):
auth.audit('first') auth.audit('first')
auth.audit('second') auth.audit('second')
auth.audit('third') auth.audit('third')
self.assertEqual(error.call_count, 2) # A connection outage: the event lines and, once a minute, a warning.
self.assertEqual(warning.call_count, 3) self.assertEqual(error.call_count, 0)
self.assertEqual(warning.call_count, 5)
def test_any_other_persistence_failure_is_an_error(self):
logger = auth.logging.getLogger('dtf.security')
with mock.patch.object(auth, 'connect', side_effect=RuntimeError('bad table')), \
mock.patch.object(auth.time, 'monotonic', return_value=100.0), \
mock.patch.object(logger, 'error') as error, \
mock.patch.object(logger, 'warning'):
auth.audit('first')
self.assertEqual(error.call_count, 1)
class RequestDuringOutageTest(unittest.TestCase):
def test_a_request_gets_503_with_retry_after(self):
"""Sentry DTF-API-9: the board answered 500 while the database restarted."""
import asyncio
from app import app as module
request = mock.Mock(method='GET', url=mock.Mock(path='/api/operator/board'))
with mock.patch.object(module.logging, 'warning') as warning:
response = asyncio.run(module.database_unavailable(request, psycopg.OperationalError('down')))
self.assertEqual(response.status_code, 503)
self.assertEqual(response.headers['retry-after'], '5')
self.assertIn(b'reiniciando', response.body)
self.assertEqual(warning.call_count, 1)
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -116,6 +116,8 @@
function apiError(path, status, message, detail) { function apiError(path, status, message, detail) {
if (!started || status === 401 || typeof Sentry === 'undefined') return; if (!started || status === 401 || typeof Sentry === 'undefined') return;
// A restart's few seconds without the database (app/app.py): not a bug.
if (status === 503 && /reiniciando/.test(String(message))) return;
try { try {
// One issue per kind of API error: without this Sentry groups them all // One issue per kind of API error: without this Sentry groups them all
// by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for // by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for