feat: a database connection pool behind DB_POOL (off in production)

Every db.connect() opened a new Postgres connection; with DB_POOL=on each
process keeps a psycopg_pool pool (DB_POOL_SIZE, default 20, 10 s
acquisition timeout, dropped connections replaced) with the same
commit/rollback contract. Production stays off until switched in Portainer;
the local stack and CI run with it on. Two nested acquisitions that ran on
every board load and in audits now reuse the caller's connection.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 17:57:42 -03:00
parent 085c2d0009
commit 5b7e95ad86
17 changed files with 190 additions and 16 deletions

View File

@@ -23,6 +23,7 @@ jobs:
deploy.test_production_preflight \ deploy.test_production_preflight \
tests.test_pricing \ tests.test_pricing \
tests.test_cart_pricing \ tests.test_cart_pricing \
tests.test_db_pool \
tests.test_coupons \ tests.test_coupons \
tests.test_grade_rules \ tests.test_grade_rules \
tests.test_migrate \ tests.test_migrate \

View File

@@ -90,7 +90,7 @@ def checked_code(c, table, key, code, request, extra=''):
return row, None return row, None
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],)) c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
left = CODE_ATTEMPTS - row['attempts'] - 1 left = CODE_ATTEMPTS - row['attempts'] - 1
audit('code_wrong', kind=table, ip=client_ip(request)) audit('code_wrong', kind=table, ip=client_ip(request), c=c)
return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else return None, HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.')) 'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
@@ -157,7 +157,7 @@ def claim_orders(c, identity, profile):
c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s', c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s',
(identity, [str(uid) for uid in uploads], order['owner'])) (identity, [str(uid) for uid in uploads], order['owner']))
if orders: if orders:
audit('account_orders_claimed', account=str(identity), orders=len(orders)) audit('account_orders_claimed', account=str(identity), orders=len(orders), c=c)
return len(orders) return len(orders)

View File

@@ -60,7 +60,7 @@ def board(user=Depends(operator)):
backup = backup_status(c) backup = backup_status(c)
quotes = quote_views(c, pending + approved) quotes = quote_views(c, pending + approved)
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK, return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user, 'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(c), 'operator': user,
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup, 'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
'mail': mail.status(c)}, 'mail': mail.status(c)},
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN, 'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,

View File

@@ -127,11 +127,11 @@ def resolve_payment(uid: UUID, body: Resolution, user=Depends(can('manage'))):
audit('payment_issue_resolved', payment_event=str(uid), operator=user) audit('payment_issue_resolved', payment_event=str(uid), operator=user)
return {'ok': True} return {'ok': True}
def tiny_status(): def tiny_status(c=None):
if not tiny.configured(): if not tiny.configured():
return {'configured': False} return {'configured': False}
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny', return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
**tiny.TinyAuth().status()} **tiny.TinyAuth().status(c)}
@router.post('/api/operator/tiny/connect') @router.post('/api/operator/tiny/connect')
def tiny_connect(user=Depends(can('integrations'))): def tiny_connect(user=Depends(can('integrations'))):

View File

@@ -583,5 +583,5 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
if not prepared: if not prepared:
raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.') raise HTTPException(409, 'Prepare e aprove o PNG completo no pedido pai antes de gerar a prova de novo.')
queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True) queue_print_files(c, uid, len(row['snapshot']['items']), only_missing=True)
audit('print_file_requeued', order=str(uid), operator=user) audit('print_file_requeued', order=str(uid), operator=user, c=c)
return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall() return c.execute('SELECT * FROM dtf_local.print_files WHERE order_id=%s ORDER BY item_index', (uid,)).fetchall()

View File

@@ -71,13 +71,19 @@ 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'],))
def audit(event, **fields): 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."""
# 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:
from psycopg.types.json import Jsonb from psycopg.types.json import Jsonb
with connect() as c: if c is not None:
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)))
else:
with connect() as c:
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.
logging.getLogger('dtf.security').error('Security event persistence unavailable') logging.getLogger('dtf.security').error('Security event persistence unavailable')

View File

@@ -1,11 +1,18 @@
import os import os
import threading
from pathlib import Path from pathlib import Path
import psycopg import psycopg
from psycopg.rows import dict_row from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .. import migrate from .. import migrate
def connect(): # One pool per process, created on first use when DB_POOL is on (default off).
_pool = None
_pool_lock = threading.Lock()
def _direct():
# Production passes credentials as discrete libpq fields. This avoids # Production passes credentials as discrete libpq fields. This avoids
# treating characters in a generated password as URL syntax. Local and # treating characters in a generated password as URL syntax. Local and
# test environments retain DATABASE_URL compatibility. # test environments retain DATABASE_URL compatibility.
@@ -19,6 +26,42 @@ def connect():
) )
return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row) return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row)
def _pool_arguments():
"""The conninfo and kwargs for the pool, matching _direct()'s settings."""
if os.environ.get('DATABASE_HOST'):
return '', {
'host': os.environ['DATABASE_HOST'],
'dbname': os.environ['DATABASE_NAME'],
'user': os.environ['DATABASE_USER'],
'password': os.environ['DATABASE_PASSWORD'],
'row_factory': dict_row,
}
return os.environ['DATABASE_URL'], {'row_factory': dict_row}
def _pool_instance():
global _pool
if _pool is None:
with _pool_lock:
if _pool is None:
conninfo, kwargs = _pool_arguments()
_pool = ConnectionPool(
conninfo, kwargs=kwargs, min_size=1,
max_size=int(os.environ.get('DB_POOL_SIZE') or 20),
open=True, timeout=10, check=ConnectionPool.check_connection)
return _pool
def connect():
"""A connection for one `with` block. Pooled when DB_POOL is on (default
off): the same commit/rollback contract, the connection goes back to the
pool instead of closing."""
if os.environ.get('DB_POOL', 'off').lower() != 'on':
return _direct()
return _pool_instance().connection()
def initialize(): def initialize():
with connect() as c: with connect() as c:
# The schema lives at the package root, one level up from core/. # The schema lives at the package root, one level up from core/.

View File

@@ -200,7 +200,7 @@ def apply(c, event):
except (ValueError, AttributeError): except (ValueError, AttributeError):
order = None order = None
if order: if order:
audit('payment_reversed', order=order['number'], status=event.status) audit('payment_reversed', order=order['number'], status=event.status, c=c)
return f"attention: payment {event.status} for order {order['number']}" return f"attention: payment {event.status} for order {order['number']}"
if event.status != 'approved': if event.status != 'approved':
return f'ignored: {event.status}' return f'ignored: {event.status}'
@@ -222,7 +222,7 @@ def apply(c, event):
expected = quote['approved']['total_cents'] expected = quote['approved']['total_cents']
if type(event.amount_cents) is not int or event.amount_cents != expected: if type(event.amount_cents) is not int or event.amount_cents != expected:
audit('payment_amount_mismatch', quote=str(quote_id), audit('payment_amount_mismatch', quote=str(quote_id),
expected_cents=expected, paid_cents=event.amount_cents) expected_cents=expected, paid_cents=event.amount_cents, c=c)
return f'refused: paid {event.amount_cents} but quote total is {expected}' return f'refused: paid {event.amount_cents} but quote total is {expected}'
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site') order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')

View File

@@ -148,7 +148,7 @@ def scan_one(storage, scanner=None):
scan_after=now()+interval '1 minute', scan_after=now()+interval '1 minute',
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(name,state,reason,state,row['id'])) WHERE id=%s""",(name,state,reason,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state) audit('artwork_scan', upload=str(row['id']), result=state, c=c)
return True return True
def scan_loop(storage): def scan_loop(storage):

View File

@@ -323,10 +323,12 @@ class TinyAuth:
operator = self._claim(c, state) operator = self._claim(c, state)
return self.authorize_url(operator, offline=False) return self.authorize_url(operator, offline=False)
def status(self): def status(self, c=None):
with self.connect() as c: if c is None:
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline, with self.connect() as c:
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone() return self.status(c)
row = c.execute('''SELECT connected_by,connected_at,refresh_expires_at,updated_at,offline,
refresh_failed_at,refused_at FROM dtf_local.provider_tokens WHERE provider='tiny' ''').fetchone()
if not row: if not row:
return {'connected': False} return {'connected': False}
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)

View File

@@ -213,6 +213,10 @@ services:
api: api:
<<: *app <<: *app
environment:
<<: *environment
# CI and local tests exercise the pool (Critical Corrections item 4).
DB_POOL: "on"
command: uvicorn app.app:app --host 0.0.0.0 --port 8000 --no-access-log command: uvicorn app.app:app --host 0.0.0.0 --port 8000 --no-access-log
depends_on: depends_on:
db-init: {condition: service_completed_successfully} db-init: {condition: service_completed_successfully}
@@ -225,6 +229,10 @@ services:
worker: worker:
<<: *app <<: *app
environment:
<<: *environment
# CI and local tests exercise the pool (Critical Corrections item 4).
DB_POOL: "on"
command: python -m app.worker command: python -m app.worker
depends_on: depends_on:
api: {condition: service_healthy} api: {condition: service_healthy}

View File

@@ -17,6 +17,9 @@ SITE_PORT=8080
KANBAN_PORT=8081 KANBAN_PORT=8081
# API processes: 2 by default; 1 runs one process, as before. API only. # API processes: 2 by default; 1 runs one process, as before. API only.
API_WORKERS=2 API_WORKERS=2
# Database connection pool: off keeps one connection per block, as before.
DB_POOL=off
DB_POOL_SIZE=20
R2_ENDPOINT=TBD R2_ENDPOINT=TBD
R2_PUBLIC_ENDPOINT=TBD R2_PUBLIC_ENDPOINT=TBD

View File

@@ -8,6 +8,10 @@ x-app-environment: &app-environment
# Must differ from POSTGRES_PASSWORD: the runtime role is DML-only, and reusing # Must differ from POSTGRES_PASSWORD: the runtime role is DML-only, and reusing
# the administrator credential would make that restriction meaningless. # the administrator credential would make that restriction meaningless.
DATABASE_PASSWORD: ${APP_DB_PASSWORD:?set APP_DB_PASSWORD} DATABASE_PASSWORD: ${APP_DB_PASSWORD:?set APP_DB_PASSWORD}
# Reuse database connections per API/worker process when on; off keeps one
# connection per `with` block, exactly as before (the production default).
DB_POOL: ${DB_POOL:-off}
DB_POOL_SIZE: ${DB_POOL_SIZE:-20}
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT} S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT} S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET} S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}

View File

@@ -235,6 +235,14 @@ only process; the API's `/tmp` is sized for two such checks at once. It applies
to the API only, never to the worker. Set it in the stack's environment and to the API only, never to the worker. Set it in the stack's environment and
redeploy. redeploy.
## 10. Database connection pool
`DB_POOL` reuses database connections inside each API process and the worker
instead of opening one per `with` block (default `off`, the previous
behaviour). Set it to `on` in the stack's environment and redeploy to keep
between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults
to 20); set it back to `off` to return to one connection per block.
## Current blocker ## Current blocker
This is the final deployment shape, but it is not authorized for production This is the final deployment shape, but it is not authorized for production

View File

@@ -453,6 +453,10 @@ psycopg-binary==3.2.9 \
--hash=sha256:fa5c80d8b4cbf23f338db88a7251cef8bb4b68e0f91cf8b6ddfa93884fdbb0c1 \ --hash=sha256:fa5c80d8b4cbf23f338db88a7251cef8bb4b68e0f91cf8b6ddfa93884fdbb0c1 \
--hash=sha256:fb7599e436b586e265bea956751453ad32eb98be6a6e694252f4691c31b16edb --hash=sha256:fb7599e436b586e265bea956751453ad32eb98be6a6e694252f4691c31b16edb
# via psycopg # via psycopg
psycopg-pool==3.2.8 \
--hash=sha256:5474137f3a58e697e0141d0311e70ec067fc4466031496d7f9ef3e2c28a1dc09 \
--hash=sha256:854e17c2a637c3b9f8d8b24faad57d4cf850baf3fc03ca56ef7e5b4998e391b9
# via -r infra/requirements.txt
pydantic==2.13.5 \ pydantic==2.13.5 \
--hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \ --hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \
--hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08 --hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08
@@ -629,6 +633,7 @@ typing-extensions==4.16.0 \
# anyio # anyio
# fastapi # fastapi
# psycopg # psycopg
# psycopg-pool
# pydantic # pydantic
# pydantic-core # pydantic-core
# starlette # starlette

View File

@@ -2,6 +2,7 @@ fastapi==0.141.1
starlette==1.6.0 starlette==1.6.0
uvicorn==0.34.2 uvicorn==0.34.2
psycopg[binary]==3.2.9 psycopg[binary]==3.2.9
psycopg-pool==3.2.8
boto3==1.38.23 boto3==1.38.23
httpx==0.28.1 httpx==0.28.1
pillow==13.0.0 pillow==13.0.0

93
tests/test_db_pool.py Normal file
View File

@@ -0,0 +1,93 @@
"""The DB_POOL switch in app/core/db.py (Critical Corrections item 4).
Run from repository root: python3 -m unittest tests.test_db_pool -v.
The host validation runner has no psycopg; small stand-ins are installed before
importing the module, then mocked in each test.
"""
import os
import sys
import types
import unittest
from unittest import mock
try:
import psycopg # noqa: F401
except ModuleNotFoundError:
psycopg = types.ModuleType('psycopg')
psycopg.connect = mock.MagicMock()
rows = types.ModuleType('psycopg.rows')
rows.dict_row = object()
psycopg.rows = rows
sys.modules['psycopg'] = psycopg
sys.modules['psycopg.rows'] = rows
try:
import psycopg_pool # noqa: F401
except ModuleNotFoundError:
psycopg_pool = types.ModuleType('psycopg_pool')
psycopg_pool.ConnectionPool = mock.MagicMock()
sys.modules['psycopg_pool'] = psycopg_pool
from app.core import db
class DatabasePoolTests(unittest.TestCase):
def setUp(self):
db._pool = None
self.addCleanup(lambda: setattr(db, '_pool', None))
def test_pool_is_off_by_default(self):
with mock.patch.dict(os.environ, {'DATABASE_HOST': '',
'DATABASE_URL': 'postgresql://env/dtf'}, clear=True), \
mock.patch.object(db.psycopg, 'connect') as connect, \
mock.patch.object(db, 'ConnectionPool') as pool_class:
connection = db.connect()
connect.assert_called_once_with('postgresql://env/dtf', row_factory=db.dict_row)
self.assertIs(connection, connect.return_value)
pool_class.assert_not_called()
def test_off_uses_a_direct_connection(self):
with mock.patch.dict(os.environ, {'DB_POOL': 'off', 'DATABASE_HOST': '',
'DATABASE_URL': 'postgresql://env/dtf'}), \
mock.patch.object(db.psycopg, 'connect') as connect, \
mock.patch.object(db, 'ConnectionPool') as pool_class:
connection = db.connect()
connect.assert_called_once_with('postgresql://env/dtf', row_factory=db.dict_row)
self.assertIs(connection, connect.return_value)
pool_class.assert_not_called()
def test_on_returns_the_pool_connection_and_builds_the_pool_once(self):
with mock.patch.dict(os.environ, {'DB_POOL': 'on', 'DB_POOL_SIZE': '7',
'DATABASE_HOST': '',
'DATABASE_URL': 'postgresql://env/dtf'}), \
mock.patch.object(db, 'ConnectionPool') as pool_class:
first = db.connect()
second = db.connect()
pool_class.assert_called_once()
args, kwargs = pool_class.call_args
self.assertEqual(args, ('postgresql://env/dtf',))
self.assertEqual(kwargs['kwargs'], {'row_factory': db.dict_row})
self.assertEqual(kwargs['min_size'], 1)
self.assertEqual(kwargs['max_size'], 7)
self.assertIs(kwargs['open'], True)
self.assertEqual(kwargs['timeout'], 10)
self.assertIs(kwargs['check'], pool_class.check_connection)
self.assertEqual(pool_class.return_value.connection.call_count, 2)
self.assertIs(first, pool_class.return_value.connection.return_value)
self.assertIs(second, first)
def test_on_uses_the_host_settings_and_default_size(self):
with mock.patch.dict(os.environ, {'DB_POOL': 'on', 'DATABASE_HOST': 'db',
'DATABASE_NAME': 'dtf', 'DATABASE_USER': 'app',
'DATABASE_PASSWORD': 'secret'}, clear=True), \
mock.patch.object(db, 'ConnectionPool') as pool_class:
db.connect()
args, kwargs = pool_class.call_args
self.assertEqual(args, ('',))
self.assertEqual(kwargs['max_size'], 20)
self.assertEqual(kwargs['kwargs'], {'host': 'db', 'dbname': 'dtf', 'user': 'app',
'password': 'secret', 'row_factory': db.dict_row})
if __name__ == '__main__':
unittest.main()