forked from mtusi2026/mtusi2026lab5
Implement lab5 async image processing with RabbitMQ and outbox
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""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
|
||||
|
||||
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 pool.connection() as conn:
|
||||
yield conn
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError, 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
|
||||
Reference in New Issue
Block a user