Spaces:
Sleeping

epl-predictor-api / app /services /cache_service.py
otito254's picture
adding cache functionality
81163d9
Raw History Blame Contribute Delete
5.54 kB
import logging
from datetime import datetime, timezone, timedelta
from typing import Optional
from app.core.supabase_client import get_supabase # ← was: from app.core.supabase_client import supabase
logger = logging.getLogger(__name__)
_memory_cache: dict[str, dict] = {}
def _make_cache_key(league: str) -> str:
return f"upcoming_{league}"
def _calc_ttl_hours(league: str = "epl") -> int:
now = datetime.now(timezone.utc)
weekday = now.weekday()
if weekday in (1, 2, 5, 6):
return 1
return 6
def get_cached(league: str = "epl") -> Optional[list]:
key = _make_cache_key(league)
now = datetime.now(timezone.utc)
# ── 1. Memory cache ───────────────────────────────────────────────────────
if key in _memory_cache:
entry = _memory_cache[key]
if entry["expires_at"] > now:
logger.info(f"⚡ Memory cache hit for {key} "
f"(expires in {int((entry['expires_at'] - now).seconds / 60)} min)")
return entry["payload"]
else:
logger.info(f"⏰ Memory cache expired for {key}")
del _memory_cache[key]
# ── 2. Supabase cache ─────────────────────────────────────────────────────
try:
supabase = get_supabase() # ← call the function each time needed
result = (
supabase.table("predictions_cache")
.select("*")
.eq("cache_key", key)
.gt("expires_at", now.isoformat())
.execute()
)
if result.data:
row = result.data[0]
expires_at = datetime.fromisoformat(row["expires_at"])
_memory_cache[key] = {
"payload": row["payload"],
"expires_at": expires_at,
}
supabase.table("predictions_cache").update(
{"hit_count": row["hit_count"] + 1}
).eq("cache_key", key).execute()
logger.info(f"🗄️ Supabase cache hit for {key} "
f"(expires in {int((expires_at - now).seconds / 60)} min, "
f"hit #{row['hit_count'] + 1})")
return row["payload"]
except Exception as e:
logger.warning(f"Cache read failed for {key}: {e}")
return None
def set_cache(league: str, payload: list) -> None:
key = _make_cache_key(league)
now = datetime.now(timezone.utc)
ttl_hours = _calc_ttl_hours(league)
expires_at = now + timedelta(hours=ttl_hours)
fixture_ids = [str(f.get("fixture_id", "")) for f in payload]
_memory_cache[key] = {
"payload": payload,
"expires_at": expires_at,
}
try:
supabase = get_supabase() # ← call the function each time needed
supabase.table("predictions_cache").upsert({
"cache_key": key,
"league": league,
"payload": payload,
"fixture_ids": fixture_ids,
"fetched_at": now.isoformat(),
"expires_at": expires_at.isoformat(),
"hit_count": 0,
}, on_conflict="cache_key").execute()
logger.info(f"💾 Cache saved for {key} — "
f"{len(payload)} fixtures, TTL {ttl_hours}h "
f"(expires {expires_at.strftime('%H:%M UTC')})")
except Exception as e:
logger.warning(f"Cache write failed for {key}: {e}")
def invalidate_cache(league: str) -> None:
key = _make_cache_key(league)
if key in _memory_cache:
del _memory_cache[key]
try:
supabase = get_supabase() # ← call the function each time needed
supabase.table("predictions_cache").delete().eq("cache_key", key).execute()
logger.info(f"🗑️ Cache invalidated for {key}")
except Exception as e:
logger.warning(f"Cache invalidation failed for {key}: {e}")
def get_cache_status(league: str) -> dict:
key = _make_cache_key(league)
now = datetime.now(timezone.utc)
if key in _memory_cache:
entry = _memory_cache[key]
expires_in = int((entry["expires_at"] - now).seconds / 60)
return {
"source": "memory",
"cached": True,
"fixture_count": len(entry["payload"]),
"expires_in_mins": expires_in,
}
try:
supabase = get_supabase() # ← call the function each time needed
result = (
supabase.table("predictions_cache")
.select("fetched_at, expires_at, hit_count, fixture_ids")
.eq("cache_key", key)
.execute()
)
if result.data:
row = result.data[0]
expires_at = datetime.fromisoformat(row["expires_at"])
is_fresh = expires_at > now
return {
"source": "supabase",
"cached": is_fresh,
"fixture_count": len(row["fixture_ids"]),
"fetched_at": row["fetched_at"],
"expires_in_mins": int((expires_at - now).seconds / 60) if is_fresh else 0,
"total_hits": row["hit_count"],
}
except Exception as e:
logger.warning(f"Cache status check failed: {e}")
return {"cached": False, "source": None}