forked from mtusi2026/mtusi2026lab6
68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
"""Shared external state: psycopg connection pool and Redis session store."""
|
|
import os
|
|
from contextlib import contextmanager
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from psycopg_pool import ConnectionPool, PoolTimeout
|
|
from redis import Redis
|
|
from redis.exceptions import RedisError
|
|
|
|
from .core import APIError
|
|
from . import telemetry as ot
|
|
from opentelemetry.trace import SpanKind
|
|
|
|
pool: ConnectionPool | None = None
|
|
redis_client: Redis | None = None
|
|
|
|
|
|
def start() -> None:
|
|
global pool, redis_client
|
|
url = os.environ["DATABASE_URL"]
|
|
size = int(os.getenv("DB_POOL_MAX", "8"))
|
|
pool = ConnectionPool(conninfo=url, min_size=1, max_size=size, timeout=3, kwargs={"row_factory": dict_row, "connect_timeout": 5, "options": "-c statement_timeout=5000"}, open=False)
|
|
pool.open(wait=True, timeout=30)
|
|
redis_client = Redis.from_url(os.environ.get("REDIS_URL", "redis://redis:6379/0"), socket_connect_timeout=2, socket_timeout=2, decode_responses=True)
|
|
redis_client.ping()
|
|
|
|
|
|
def stop() -> None:
|
|
global pool, redis_client
|
|
if pool is not None:
|
|
pool.close()
|
|
pool = None
|
|
if redis_client is not None:
|
|
redis_client.close()
|
|
redis_client = None
|
|
|
|
|
|
@contextmanager
|
|
def db():
|
|
if pool is None:
|
|
raise APIError(503, "unavailable", "Database unavailable")
|
|
try:
|
|
with ot.dependency_span("db.transaction", kind=SpanKind.CLIENT, attrs={"db.system.name":"postgresql"}):
|
|
with pool.connection() as conn:
|
|
yield conn
|
|
except (psycopg.OperationalError, psycopg.InterfaceError, psycopg.errors.QueryCanceled, PoolTimeout) as exc:
|
|
raise APIError(503, "unavailable", "Database unavailable") from exc
|
|
|
|
|
|
def cache() -> Redis:
|
|
if redis_client is None:
|
|
raise APIError(503, "unavailable", "Session store unavailable")
|
|
return redis_client
|
|
|
|
|
|
def ready() -> bool:
|
|
try:
|
|
with db() as conn:
|
|
conn.execute("SELECT 1").fetchone()
|
|
cache().ping()
|
|
# S3 is needed for the mandatory synchronous upload/download path.
|
|
from .attachments import s3_client, BUCKET
|
|
s3_client().head_bucket(Bucket=BUCKET)
|
|
return True
|
|
except Exception:
|
|
return False
|