cosmo_backend/app/api/cache.py

74 lines
2.4 KiB
Python

"""
Cache Management API routes
"""
import logging
from fastapi import APIRouter, HTTPException, Query
from app.services.cache import cache_service
from app.services.redis_cache import redis_cache
from app.services.cache_preheat import (
preheat_all_caches,
preheat_current_positions,
preheat_historical_positions
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/cache", tags=["cache"])
@router.post("/clear")
async def clear_cache():
"""
Clear the data cache (admin endpoint)
Clears both memory cache and Redis cache
"""
# Clear memory cache
cache_service.clear()
# Clear Redis cache
positions_cleared = await redis_cache.clear_pattern("positions:*")
nasa_cleared = await redis_cache.clear_pattern("nasa:*")
total_cleared = positions_cleared + nasa_cleared
return {
"message": f"Cache cleared successfully ({total_cleared} Redis keys deleted)",
"memory_cache": "cleared",
"redis_cache": {
"positions_keys": positions_cleared,
"nasa_keys": nasa_cleared,
"total": total_cleared
}
}
@router.post("/preheat")
async def preheat_cache(
mode: str = Query("all", description="Preheat mode: 'all', 'current', 'historical'"),
days: int = Query(3, description="Number of days for historical preheat", ge=1, le=30)
):
"""
Manually trigger cache preheat (admin endpoint)
Args:
mode: 'all' (both current and historical), 'current' (current positions only), 'historical' (historical only)
days: Number of days to preheat for historical mode (default: 3, max: 30)
"""
try:
if mode == "all":
await preheat_all_caches()
return {"message": f"Successfully preheated all caches (current + {days} days historical)"}
elif mode == "current":
await preheat_current_positions()
return {"message": "Successfully preheated current positions"}
elif mode == "historical":
await preheat_historical_positions(days=days)
return {"message": f"Successfully preheated {days} days of historical positions"}
else:
raise HTTPException(status_code=400, detail=f"Invalid mode: {mode}. Use 'all', 'current', or 'historical'")
except Exception as e:
logger.error(f"Cache preheat failed: {e}")
raise HTTPException(status_code=500, detail=f"Preheat failed: {str(e)}")