diff --git a/backend/api/app/core/cache.py b/backend/api/app/core/cache.py index bcec835b5..dea43d26c 100644 --- a/backend/api/app/core/cache.py +++ b/backend/api/app/core/cache.py @@ -72,6 +72,16 @@ async def clear_pattern(self, pattern: str) -> int: logger.error(f"Cache clear pattern error for {pattern}: {e}") return 0 + async def flush_all(self) -> bool: + """Flush all keys from the current database""" + try: + await self.redis.flushdb() + logger.info("Cache flushed successfully") + return True + except redis.RedisError as e: + logger.error(f"Cache flush error: {e}") + return False + async def get_stats(self) -> Dict[str, Any]: """Get cache statistics""" try: diff --git a/backend/api/app/core/dependencies.py b/backend/api/app/core/dependencies.py index b49924b6b..a896d8f5c 100644 --- a/backend/api/app/core/dependencies.py +++ b/backend/api/app/core/dependencies.py @@ -14,3 +14,9 @@ async def get_cache_service() -> CacheService: settings = get_settings() _cache_service = CacheService(settings.REDIS_URL) return _cache_service + + +def reset_cache_service() -> None: + """Reset the global cache service instance (used during shutdown)""" + global _cache_service + _cache_service = None diff --git a/backend/api/app/main.py b/backend/api/app/main.py index 75023dde4..d0ca30f28 100644 --- a/backend/api/app/main.py +++ b/backend/api/app/main.py @@ -1,16 +1,36 @@ +import logging +from contextlib import asynccontextmanager + from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.v1 import cache, health, ncbi_links, version from app.core.config import get_settings +from app.core.dependencies import get_cache_service, reset_cache_service +logger = logging.getLogger(__name__) settings = get_settings() + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Startup and shutdown events for the application""" + # Startup: flush cache to ensure fresh data after restart + cache_service = await get_cache_service() + await cache_service.flush_all() + logger.info("Cache cleared on startup") + yield + # Shutdown: close cache connection and reset singleton + await cache_service.close() + reset_cache_service() + + app = FastAPI( title="BRC Analytics API", version=settings.APP_VERSION, docs_url="/api/docs", redoc_url="/api/redoc", + lifespan=lifespan, ) app.add_middleware(