Merge redeploy database retry (DTF-API-2..7)
All checks were successful
Build and deploy / Validate source (push) Successful in 10s
Build and deploy / Integration suite on a real stack (push) Successful in 7m0s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m23s

This commit is contained in:
Cauê Faleiros
2026-11-13 15:31:39 -03:00
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 # the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration. # prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters - 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 - name: Runtime and retention regressions
run: | 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 router under local.api. This module creates the application, applies the
cross-cutting middleware, and includes them. cross-cutting middleware, and includes them.
""" """
import asyncio
import logging
import time
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI from fastapi import FastAPI
@@ -19,11 +22,30 @@ from .api import artwork, customer, health, machine_log, operator, orders, payme
observability.init('api') observability.init('api')
RETRY_SECONDS = (1, 2, 4, 8, 15)
STARTUP_BUDGET_SECONDS = 90
@asynccontextmanager @asynccontextmanager
async def lifespan(app): async def lifespan(app):
# 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: with db.connect() as c:
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1') c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
storage.health() 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 yield

View File

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

View File

@@ -5,6 +5,7 @@ import os
import threading import threading
import time import time
from http.server import BaseHTTPRequestHandler, HTTPServer from http.server import BaseHTTPRequestHandler, HTTPServer
import psycopg
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
from . import mail, observability, unpaid from . import mail, observability, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime from .adapters import FakeTiny, LocalS3Storage, require_runtime
@@ -27,6 +28,7 @@ last_reconcile = 0.0
last_names = 0.0 last_names = 0.0
names_thread = None names_thread = None
last_tiny_keepalive = 0.0 last_tiny_keepalive = 0.0
db_down_since = None
storage = LocalS3Storage() storage = LocalS3Storage()
scan_thread = None scan_thread = None
render_thread = None render_thread = None
@@ -126,7 +128,8 @@ def resolve_names():
names_thread.start() names_thread.start()
def loop(): def loop():
global last_cleanup global last_cleanup, db_down_since
delay = 1
while True: while True:
try: try:
drain() drain()
@@ -140,8 +143,22 @@ def loop():
tiny_keepalive() tiny_keepalive()
reconcile_payments() reconcile_payments()
resolve_names() 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: except Exception:
logging.exception('Local worker tick failed') 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) time.sleep(1)
class Health(BaseHTTPRequestHandler): class Health(BaseHTTPRequestHandler):

View File

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