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:
@@ -90,7 +90,7 @@ def checked_code(c, table, key, code, request, extra=''):
|
||||
return row, None
|
||||
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
||||
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
|
||||
'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',
|
||||
(identity, [str(uid) for uid in uploads], order['owner']))
|
||||
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)
|
||||
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ def board(user=Depends(operator)):
|
||||
backup = backup_status(c)
|
||||
quotes = quote_views(c, pending + approved)
|
||||
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,
|
||||
'mail': mail.status(c)},
|
||||
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
|
||||
|
||||
@@ -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)
|
||||
return {'ok': True}
|
||||
|
||||
def tiny_status():
|
||||
def tiny_status(c=None):
|
||||
if not tiny.configured():
|
||||
return {'configured': False}
|
||||
return {'configured': True, 'orders_enabled': os.environ.get('TINY_ADAPTER') == 'tiny',
|
||||
**tiny.TinyAuth().status()}
|
||||
**tiny.TinyAuth().status(c)}
|
||||
|
||||
@router.post('/api/operator/tiny/connect')
|
||||
def tiny_connect(user=Depends(can('integrations'))):
|
||||
|
||||
@@ -583,5 +583,5 @@ def regenerate(uid: UUID, user=Depends(can('produce'))):
|
||||
if not prepared:
|
||||
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)
|
||||
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()
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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/.
|
||||
|
||||
@@ -200,7 +200,7 @@ def apply(c, event):
|
||||
except (ValueError, AttributeError):
|
||||
order = None
|
||||
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']}"
|
||||
if event.status != 'approved':
|
||||
return f'ignored: {event.status}'
|
||||
@@ -222,7 +222,7 @@ def apply(c, event):
|
||||
expected = quote['approved']['total_cents']
|
||||
if type(event.amount_cents) is not int or event.amount_cents != expected:
|
||||
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}'
|
||||
|
||||
order, created = create_order(c, quote, {'provider': event.raw.get('provider', 'webhook'), **event.raw}, 'site')
|
||||
|
||||
@@ -148,7 +148,7 @@ def scan_one(storage, scanner=None):
|
||||
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
|
||||
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
|
||||
|
||||
def scan_loop(storage):
|
||||
|
||||
10
app/tiny.py
10
app/tiny.py
@@ -323,10 +323,12 @@ class TinyAuth:
|
||||
operator = self._claim(c, state)
|
||||
return self.authorize_url(operator, offline=False)
|
||||
|
||||
def status(self):
|
||||
with self.connect() as 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()
|
||||
def status(self, c=None):
|
||||
if c is None:
|
||||
with self.connect() as c:
|
||||
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:
|
||||
return {'connected': False}
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
Reference in New Issue
Block a user