"""Bounded dependencies; PostgreSQL is always the source of truth.""" import os from pathlib import Path from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from redis import Redis from redis.backoff import NoBackoff from redis.retry import Retry def setting(name, default=None): filename = os.environ.get(name + '_FILE') value = Path(filename).read_text().strip() if filename else os.environ.get(name, default) if value is None: raise RuntimeError(f'Missing configuration: {name}') return value class Database: def __init__(self): self.session_ttl = int(setting('SESSION_TTL_SECONDS', '3600')) if self.session_ttl < 1: raise ValueError('SESSION_TTL_SECONDS must be positive') self.pool = ConnectionPool( setting('DATABASE_URL'), min_size=1, max_size=int(setting('POOL_MAX_SIZE', '8')), timeout=2, max_waiting=16, open=False, kwargs={'row_factory': dict_row, 'connect_timeout': 3, 'options': '-c statement_timeout=3000 -c lock_timeout=2000 -c idle_in_transaction_session_timeout=5000'}, ) self.cache = Redis.from_url( setting('CACHE_URL', 'redis://redis:6379/0'), decode_responses=True, socket_connect_timeout=0.2, socket_timeout=0.2, max_connections=8, retry=Retry(NoBackoff(), 0), ) def open(self): self.pool.open(wait=True, timeout=30) def close(self): self.pool.close() self.cache.close()