Files
2026-10-16 19:49:48 +03:00

58 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Пул соединений PostgreSQL: ограниченный размер, таймауты, проверка соединения при выдаче."""
import threading
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolClosed, PoolTimeout
from . import config
# Ошибки «зависимость недоступна/перегружена» -> 503, а не 500.
TRANSIENT = (psycopg.OperationalError, PoolTimeout, PoolClosed, psycopg.errors.QueryCanceled,
psycopg.errors.LockNotAvailable)
_pool = None
_lock = threading.Lock()
def get_pool():
"""Пул создаётся лениво в каждом worker-процессе (после fork), без ожидания БД при старте."""
global _pool
if _pool is None:
with _lock:
if _pool is None:
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL(_FILE) is not configured")
options = ("-c statement_timeout=%d -c lock_timeout=3000 "
"-c idle_in_transaction_session_timeout=10000" % config.DB_STATEMENT_TIMEOUT_MS)
pool = ConnectionPool(
config.DATABASE_URL,
min_size=config.DB_POOL_MIN, max_size=config.DB_POOL_MAX,
timeout=config.DB_POOL_TIMEOUT, max_lifetime=1800, max_idle=300,
reconnect_timeout=5,
check=ConnectionPool.check_connection, # после рестарта PostgreSQL мёртвые соединения отбрасываются
kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": options,
"application_name": "messenger-api"},
open=False)
pool.open(wait=False)
_pool = pool
return _pool
def connection(timeout=None):
"""Транзакция: COMMIT при выходе из with, ROLLBACK при исключении."""
return get_pool().connection(timeout=timeout)
def ping():
with connection(timeout=1.5) as conn:
conn.execute("SELECT 1")
def close():
"""Корректное закрытие пула при остановке процесса (SIGTERM)."""
global _pool
if _pool is not None:
_pool.close(timeout=5)
_pool = None