acupedia-api/app/lifespan.py

213 lines
4.9 KiB
Python

from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from typing import AsyncIterator
from fastapi import FastAPI
from app.cache.client import RedisRuntime
from app.cache.config import CacheSettings
from app.cache.invalidation import ContentCacheInvalidator
from app.cache.service import CacheService
logger = logging.getLogger(
"acupedia.lifecycle"
)
@asynccontextmanager
async def lifespan(
app: FastAPI,
) -> AsyncIterator[None]:
"""
Application lifecycle.
Startup:
- load cache settings
- initialize Redis pool/client
- perform health check
- create shared cache services
Shutdown:
- close Redis client
- close Redis connection pool
"""
cache_settings = CacheSettings.from_env()
logger.info(
"Cache configuration loaded: "
"enabled=%s redis_url=%s fail_open=%s",
cache_settings.enabled,
_safe_redis_url(
cache_settings.redis_url
),
cache_settings.fail_open,
)
redis_runtime = RedisRuntime(
settings=cache_settings,
)
cache_service = CacheService(
runtime=redis_runtime,
settings=cache_settings,
)
cache_invalidator = (
ContentCacheInvalidator(
cache=cache_service,
)
)
# -----------------------------------------------------------------
# Register state before startup.
#
# This also makes fail-open mode usable if Redis cannot connect.
# -----------------------------------------------------------------
app.state.cache_settings = (
cache_settings
)
app.state.redis_runtime = (
redis_runtime
)
app.state.cache_service = (
cache_service
)
app.state.content_cache_invalidator = (
cache_invalidator
)
try:
# =============================================================
# STARTUP
# =============================================================
await redis_runtime.startup()
if (
cache_settings.enabled
and redis_runtime.available
):
logger.info(
"Redis cache subsystem ready"
)
elif cache_settings.enabled:
logger.warning(
"Redis unavailable. "
"Application continuing with "
"cache fail-open=%s",
cache_settings.fail_open,
)
else:
logger.info(
"Redis caching disabled"
)
# -------------------------------------------------------------
# Ensure commerce.invoice_monthly_sequences table exists
# -------------------------------------------------------------
try:
from app.db.session import engine
from sqlalchemy import text
async with engine.begin() as conn:
await conn.execute(text(
"""
CREATE TABLE IF NOT EXISTS commerce.invoice_monthly_sequences (
year_month VARCHAR(7) PRIMARY KEY,
last_serial INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
"""
))
logger.info("Commerce invoice sequence table verified")
except Exception as exc:
logger.warning("Could not auto-verify invoice sequence table on startup: %s", exc)
yield
finally:
# =============================================================
# SHUTDOWN
# =============================================================
logger.info(
"Shutting down cache subsystem"
)
await redis_runtime.shutdown()
app.state.content_cache_invalidator = (
None
)
app.state.cache_service = (
None
)
app.state.redis_runtime = (
None
)
app.state.cache_settings = (
None
)
logger.info(
"Application cache shutdown complete"
)
def _safe_redis_url(
redis_url: str,
) -> str:
"""
Avoid accidentally logging Redis credentials.
"""
try:
from urllib.parse import (
urlsplit,
urlunsplit,
)
parsed = urlsplit(
redis_url
)
hostname = (
parsed.hostname
or "unknown"
)
port = (
f":{parsed.port}"
if parsed.port
else ""
)
netloc = (
f"{hostname}{port}"
)
return urlunsplit(
(
parsed.scheme,
netloc,
parsed.path,
"",
"",
)
)
except Exception:
return "<redacted>"