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

@@ -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('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.
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
try:
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)))
else:
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')

View File

@@ -1,11 +1,18 @@
import os
import threading
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
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
# treating characters in a generated password as URL syntax. Local and
# test environments retain DATABASE_URL compatibility.
@@ -19,6 +26,42 @@ def connect():
)
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():
with connect() as c:
# The schema lives at the package root, one level up from core/.