233 lines
5.4 KiB
Python
233 lines
5.4 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
from dataclasses import dataclass
|
|
|
|
from redis.asyncio import Redis
|
|
from redis.asyncio.connection import (
|
|
ConnectionPool,
|
|
)
|
|
|
|
from .config import CacheSettings
|
|
|
|
|
|
logger = logging.getLogger(
|
|
"acupedia.cache"
|
|
)
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class RedisRuntime:
|
|
settings: CacheSettings
|
|
|
|
pool: ConnectionPool | None = None
|
|
client: Redis | None = None
|
|
|
|
available: bool = False
|
|
|
|
async def startup(
|
|
self,
|
|
) -> None:
|
|
# -------------------------------------------------------------
|
|
# Defensive programming.
|
|
# -------------------------------------------------------------
|
|
|
|
# if not isinstance(
|
|
# self.settings,
|
|
# CacheSettings,
|
|
# ):
|
|
# raise TypeError(
|
|
# "RedisRuntime.settings must be "
|
|
# "a CacheSettings instance. "
|
|
# f"Received: "
|
|
# f"{type(self.settings)!r}. "
|
|
# "Use CacheSettings.from_env() "
|
|
# "or CacheSettings()."
|
|
# )
|
|
|
|
if not self.settings.enabled:
|
|
logger.info(
|
|
"Redis caching disabled"
|
|
)
|
|
|
|
self.available = False
|
|
return
|
|
|
|
redis_url = (
|
|
self.settings.redis_url
|
|
)
|
|
|
|
# if not isinstance(
|
|
# redis_url,
|
|
# str,
|
|
# ):
|
|
# raise TypeError(
|
|
# "CacheSettings.redis_url must "
|
|
# "be a string. "
|
|
# f"Received "
|
|
# f"{type(redis_url)!r}: "
|
|
# f"{redis_url!r}"
|
|
# )
|
|
|
|
redis_url = (
|
|
redis_url.strip()
|
|
)
|
|
|
|
if not redis_url:
|
|
raise ValueError(
|
|
"CacheSettings.redis_url "
|
|
"must not be empty"
|
|
)
|
|
|
|
if not (
|
|
redis_url.startswith(
|
|
"redis://"
|
|
)
|
|
or redis_url.startswith(
|
|
"rediss://"
|
|
)
|
|
):
|
|
raise ValueError(
|
|
"REDIS_URL must start with "
|
|
"'redis://' or 'rediss://'. "
|
|
f"Received: {redis_url!r}"
|
|
)
|
|
|
|
try:
|
|
self.pool = (
|
|
ConnectionPool.from_url(
|
|
redis_url,
|
|
|
|
max_connections=(
|
|
self.settings
|
|
.max_connections
|
|
),
|
|
|
|
decode_responses=True,
|
|
|
|
socket_connect_timeout=(
|
|
self.settings
|
|
.connect_timeout_seconds
|
|
),
|
|
|
|
socket_timeout=(
|
|
self.settings
|
|
.socket_timeout_seconds
|
|
),
|
|
|
|
health_check_interval=(
|
|
self.settings
|
|
.healthcheck_interval_seconds
|
|
),
|
|
)
|
|
)
|
|
|
|
self.client = Redis(
|
|
connection_pool=self.pool,
|
|
)
|
|
|
|
await self.client.ping()
|
|
|
|
self.available = True
|
|
|
|
logger.info(
|
|
"Redis connection "
|
|
"established successfully"
|
|
)
|
|
|
|
except Exception:
|
|
self.available = False
|
|
|
|
logger.exception(
|
|
"Redis startup failed"
|
|
)
|
|
|
|
if (
|
|
not self.settings
|
|
.fail_open
|
|
):
|
|
await self.shutdown()
|
|
|
|
raise
|
|
|
|
# ---------------------------------------------------------
|
|
# fail_open=True:
|
|
#
|
|
# PostgreSQL remains available and the cache layer behaves
|
|
# as a cache miss.
|
|
# ---------------------------------------------------------
|
|
|
|
logger.warning(
|
|
"Continuing without Redis "
|
|
"because CACHE_FAIL_OPEN=true"
|
|
)
|
|
|
|
async def shutdown(
|
|
self,
|
|
) -> None:
|
|
self.available = False
|
|
|
|
client = self.client
|
|
pool = self.pool
|
|
|
|
self.client = None
|
|
self.pool = None
|
|
|
|
if client is not None:
|
|
try:
|
|
await client.aclose()
|
|
|
|
except Exception:
|
|
logger.exception(
|
|
"Failed to close Redis client"
|
|
)
|
|
|
|
if pool is not None:
|
|
try:
|
|
await pool.aclose()
|
|
|
|
except Exception:
|
|
logger.exception(
|
|
"Failed to close Redis "
|
|
"connection pool"
|
|
)
|
|
|
|
async def ping(
|
|
self,
|
|
) -> bool:
|
|
if (
|
|
not self.settings.enabled
|
|
or self.client is None
|
|
):
|
|
return False
|
|
|
|
try:
|
|
response = (
|
|
await self.client.ping()
|
|
)
|
|
|
|
self.available = bool(
|
|
response
|
|
)
|
|
|
|
return self.available
|
|
|
|
except Exception:
|
|
self.available = False
|
|
|
|
logger.exception(
|
|
"Redis health check failed"
|
|
)
|
|
|
|
return False
|
|
|
|
def require_client(
|
|
self,
|
|
) -> Redis:
|
|
if self.client is None:
|
|
raise RuntimeError(
|
|
"Redis client has not "
|
|
"been initialized"
|
|
)
|
|
|
|
return self.client |