fix: a redeploy's short database outage no longer takes the API down

Sentry DTF-API-2..7 (redeploy of 5a7fc0f, 13/11): the name db did not
resolve for about 12 s; the new API exited at startup and the worker and
audit() logged the error every second. The API now waits up to 90 s with
a backoff, the worker reports an outage once and backs off to 15 s, the
audit persistence error is logged at most once a minute, and api, site
and kanban update start-first so the old container serves meanwhile.

Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-13 15:25:29 -03:00
parent 5a7fc0f378
commit 445d686f43
6 changed files with 142 additions and 7 deletions

View File

@@ -101,7 +101,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain -v
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage -v
- name: Runtime and retention regressions
run: |

View File

@@ -4,6 +4,9 @@ Configuration and shared helpers are in local.runtime; every route lives in a
router under local.api. This module creates the application, applies the
cross-cutting middleware, and includes them.
"""
import asyncio
import logging
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
@@ -19,11 +22,30 @@ from .api import artwork, customer, health, machine_log, operator, orders, payme
observability.init('api')
RETRY_SECONDS = (1, 2, 4, 8, 15)
STARTUP_BUDGET_SECONDS = 90
@asynccontextmanager
async def lifespan(app):
with db.connect() as c:
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
storage.health()
# A redeploy briefly removes the database name; wait it out, warning once
# per attempt (a warning, not an error: Sentry only takes errors).
deadline = time.monotonic() + STARTUP_BUDGET_SECONDS
attempt = 0
while True:
try:
with db.connect() as c:
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
storage.health()
break
except Exception:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise
delay = min(RETRY_SECONDS[min(attempt, len(RETRY_SECONDS) - 1)], remaining)
logging.warning('Database not reachable yet, retrying in %d s', max(1, round(delay)))
await asyncio.sleep(delay)
attempt += 1
yield

View File

@@ -4,6 +4,7 @@ import os
import secrets
import logging
import json
import time
from uuid import UUID, uuid4
from fastapi import HTTPException, Request
from ..core.db import connect
@@ -71,10 +72,14 @@ def transfer_guest(c, previous, identity):
c.execute(f'UPDATE dtf_local.{table} SET owner=%s WHERE owner=%s', (identity,previous['owner']))
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (previous['owner'],))
_persistence_error_at = None
def audit(event, c=None, **fields):
"""Record a security event. `c` is the caller's open connection, when there
is one, so the event commits with that transaction instead of opening a
second connection."""
global _persistence_error_at
# Only explicit metadata: never cookies, passwords, signed URLs or request bodies.
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
try:
@@ -85,8 +90,12 @@ def audit(event, c=None, **fields):
with connect() as c:
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
except Exception:
# Logging must still work during a DB outage without recursively auditing itself.
logging.getLogger('dtf.security').error('Security event persistence unavailable')
# Logging must still work during a DB outage without recursively auditing
# itself; the error is reported once per minute, not on every event.
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')
def rate_limit(scope, identity, limit, seconds=900):
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()

View File

@@ -5,6 +5,7 @@ import os
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import psycopg
from psycopg.types.json import Jsonb
from . import mail, observability, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
@@ -27,6 +28,7 @@ last_reconcile = 0.0
last_names = 0.0
names_thread = None
last_tiny_keepalive = 0.0
db_down_since = None
storage = LocalS3Storage()
scan_thread = None
render_thread = None
@@ -126,7 +128,8 @@ def resolve_names():
names_thread.start()
def loop():
global last_cleanup
global last_cleanup, db_down_since
delay = 1
while True:
try:
drain()
@@ -140,8 +143,22 @@ def loop():
tiny_keepalive()
reconcile_payments()
resolve_names()
except psycopg.OperationalError as exc:
if db_down_since is None:
db_down_since = time.monotonic()
logging.error('Database unavailable, retrying: %s', exc)
else:
logging.debug('Database still unavailable, retrying in %s s', delay)
time.sleep(delay)
delay = min(delay * 2, 15)
continue
except Exception:
logging.exception('Local worker tick failed')
else:
if db_down_since is not None:
logging.info('Database back after %s s', int(time.monotonic()-db_down_since))
db_down_since = None
delay = 1
time.sleep(1)
class Health(BaseHTTPRequestHandler):

View File

@@ -253,6 +253,7 @@ services:
start_period: 30s
deploy:
replicas: 1
update_config: {order: start-first, failure_action: rollback}
restart_policy: {condition: on-failure, delay: 5s}
worker:
@@ -332,6 +333,7 @@ services:
start_period: 15s
deploy:
replicas: 1
update_config: {order: start-first, failure_action: rollback}
restart_policy: {condition: on-failure, delay: 5s}
kanban:
@@ -358,6 +360,7 @@ services:
start_period: 15s
deploy:
replicas: 1
update_config: {order: start-first, failure_action: rollback}
restart_policy: {condition: on-failure, delay: 5s}
configs:

84
tests/test_db_outage.py Normal file
View File

@@ -0,0 +1,84 @@
"""A short database outage during a redeploy: bounded retries, one report.
Run from the repository root: python3 -m unittest tests.test_db_outage -v.
The worker imports psycopg and boto3, so a host without the API image's
dependencies cannot import it; CI runs this in the api container.
"""
import unittest
from unittest import mock
import psycopg
from app import worker
from app.core import auth
class WorkerDatabaseOutageTest(unittest.TestCase):
class StopLoop(Exception):
pass
class Connection:
def __enter__(self):
return self
def __exit__(self, *exc_info):
return False
def execute(self, *args, **kwargs):
return self
def fetchone(self):
return None
def setUp(self):
worker.db_down_since = None
self.addCleanup(setattr, worker, 'db_down_since', None)
def test_one_error_and_one_info_with_growing_sleeps(self):
outage = psycopg.OperationalError('connection refused')
with mock.patch.object(worker, 'connect',
side_effect=[outage, outage, outage, self.Connection()]), \
mock.patch.object(worker, 'last_cleanup', worker.time.monotonic()), \
mock.patch.object(worker, 'cleanup'), \
mock.patch.object(worker, 'tiny_keepalive'), \
mock.patch.object(worker, 'reconcile_payments'), \
mock.patch.object(worker, 'resolve_names'), \
mock.patch.object(worker.mail, 'send_pending'), \
mock.patch.object(worker.time, 'sleep',
side_effect=[None, None, None, self.StopLoop]) as sleep, \
mock.patch.object(worker.logging, 'error') as error, \
mock.patch.object(worker.logging, 'info') as info, \
mock.patch.object(worker.logging, 'debug') as debug:
with self.assertRaises(self.StopLoop):
worker.loop()
self.assertEqual(error.call_count, 1)
self.assertIn('Database unavailable', error.call_args[0][0])
self.assertEqual(info.call_count, 1)
self.assertIn('Database back after', info.call_args[0][0])
self.assertEqual(debug.call_count, 2)
self.assertEqual([call.args[0] for call in sleep.call_args_list[:3]],
[1, 2, 4])
class AuditPersistenceOutageTest(unittest.TestCase):
def setUp(self):
auth._persistence_error_at = None
self.addCleanup(setattr, auth, '_persistence_error_at', None)
def test_persistence_error_is_logged_at_most_once_per_minute(self):
logger = auth.logging.getLogger('dtf.security')
outage = psycopg.OperationalError('database is down')
with mock.patch.object(auth, 'connect', side_effect=outage), \
mock.patch.object(auth.time, 'monotonic',
side_effect=[100.0, 130.0, 161.0]), \
mock.patch.object(logger, 'error') as error, \
mock.patch.object(logger, 'warning') as warning:
auth.audit('first')
auth.audit('second')
auth.audit('third')
self.assertEqual(error.call_count, 2)
self.assertEqual(warning.call_count, 3)
if __name__ == '__main__':
unittest.main()