algospaced-dsa / ai_cache.py
iamfebin's picture
feat: offline review queue caching, connection fallback UI, and cache failure cooldowns
4f6bb9e
Raw History Blame Contribute Delete
9.56 kB
import asyncio
import logging
import os
import re
import threading
import time
from datetime import UTC, datetime
from typing import Any
import cache
import db
logger = logging.getLogger("ai_cache")
logger.setLevel(logging.INFO)
_memory_cache: dict[str, Any] = {}
_cache_lock = threading.Lock()
_last_firestore_failure: float = 0.0
FIRESTORE_FAILURE_COOLDOWN = 60.0 # seconds cooldown when Firestore fails or times out
def is_local_or_sandbox_mode() -> bool:
"""Checks whether the backend is operating in local sandbox/guest mode."""
if os.environ.get("SANDBOX_MODE", "").lower() in ("true", "1", "yes"):
return True
if os.environ.get("LOCAL_MODE", "").lower() in ("true", "1", "yes"):
return True
# If no Firebase credentials are configured in the environment, we are in local sandbox mode
if hasattr(db, "has_firebase_credentials") and not db.has_firebase_credentials():
return True
return False
def _can_attempt_firestore() -> bool:
global _last_firestore_failure
if is_local_or_sandbox_mode():
return False
return (time.monotonic() - _last_firestore_failure) >= FIRESTORE_FAILURE_COOLDOWN
def _record_firestore_failure():
global _last_firestore_failure
_last_firestore_failure = time.monotonic()
def normalize_slug(slug_or_title: str) -> str:
"""Sanitizes titles/slugs for safe Firestore doc IDs and cache keys."""
if not slug_or_title:
return "unknown"
s = slug_or_title.strip().lower()
s = re.sub(r"https?://[^\s/]+/problems/", "", s)
s = re.sub(r"[^a-z0-9_\-]+", "_", s)
return s.strip("_")[:100]
def get_cached_item(cache_key: str) -> Any | None:
"""Checks Memory -> Redis -> Firestore."""
# 1. Memory
with _cache_lock:
if cache_key in _memory_cache:
return _memory_cache[cache_key]
# 2. Redis (if available)
try:
val = cache.get_cache(f"ai_cache:{cache_key}")
if val:
with _cache_lock:
_memory_cache[cache_key] = val
return val
except Exception:
pass
# 3. Firestore (if available and not in local sandbox mode)
if _can_attempt_firestore():
try:
firestore_client = db.init_firebase()
if firestore_client:
doc_ref = firestore_client.collection("ai_cache").document(cache_key)
doc = doc_ref.get(timeout=0.5)
if doc.exists:
data = doc.to_dict()
cached_val = data.get("payload") if data and "payload" in data else data
if cached_val:
with _cache_lock:
_memory_cache[cache_key] = cached_val
return cached_val
else:
_record_firestore_failure()
except Exception as e:
_record_firestore_failure()
logger.debug(f"Firestore cache fetch skipped/failed: {e}")
return None
async def get_cached_item_async(cache_key: str) -> Any | None:
"""Non-blocking async variant checking Memory -> Redis -> Firestore."""
# Fast in-memory check (no I/O)
with _cache_lock:
if cache_key in _memory_cache:
return _memory_cache[cache_key]
def _fetch_remote():
# Redis (if available)
try:
val = cache.get_cache(f"ai_cache:{cache_key}")
if val:
with _cache_lock:
_memory_cache[cache_key] = val
return val
except Exception:
pass
# Firestore (if available and not in local sandbox mode)
if _can_attempt_firestore():
try:
firestore_client = db.init_firebase()
if firestore_client:
doc_ref = firestore_client.collection("ai_cache").document(cache_key)
doc = doc_ref.get(timeout=0.5)
if doc.exists:
data = doc.to_dict()
cached_val = data.get("payload") if data and "payload" in data else data
if cached_val:
with _cache_lock:
_memory_cache[cache_key] = cached_val
return cached_val
else:
_record_firestore_failure()
except Exception as e:
_record_firestore_failure()
logger.debug(f"Firestore cache fetch skipped/failed: {e}")
return None
return await asyncio.to_thread(_fetch_remote)
def set_cached_item(cache_key: str, value: Any, ttl_seconds: int = 86400 * 30):
"""Saves to Memory -> Redis -> Firestore."""
if not value or not cache_key:
return
# 1. Memory
with _cache_lock:
_memory_cache[cache_key] = value
# 2. Redis
try:
cache.set_cache(f"ai_cache:{cache_key}", value, ttl_seconds=ttl_seconds)
except Exception:
pass
# 3. Firestore (if available and not in local sandbox mode)
if _can_attempt_firestore():
try:
firestore_client = db.init_firebase()
if firestore_client:
doc_ref = firestore_client.collection("ai_cache").document(cache_key)
doc_ref.set(
{"payload": value, "cached_at": datetime.now(UTC).isoformat()},
timeout=0.5,
)
else:
_record_firestore_failure()
except Exception as e:
_record_firestore_failure()
logger.debug(f"Firestore cache set skipped/failed: {e}")
async def set_cached_item_async(cache_key: str, value: Any, ttl_seconds: int = 86400 * 30):
"""Non-blocking async variant saving to Memory -> Redis -> Firestore."""
if not value or not cache_key:
return
with _cache_lock:
_memory_cache[cache_key] = value
def _persist_remote():
try:
cache.set_cache(f"ai_cache:{cache_key}", value, ttl_seconds=ttl_seconds)
except Exception:
pass
if _can_attempt_firestore():
try:
firestore_client = db.init_firebase()
if firestore_client:
doc_ref = firestore_client.collection("ai_cache").document(cache_key)
doc_ref.set(
{"payload": value, "cached_at": datetime.now(UTC).isoformat()},
timeout=0.5,
)
else:
_record_firestore_failure()
except Exception as e:
_record_firestore_failure()
logger.debug(f"Firestore cache set skipped/failed: {e}")
await asyncio.to_thread(_persist_remote)
# --- High-level cache helpers ---
def get_daily_python_challenge(date_str: str) -> dict[str, Any] | None:
return get_cached_item(f"daily_python_{date_str}")
async def get_daily_python_challenge_async(date_str: str) -> dict[str, Any] | None:
return await get_cached_item_async(f"daily_python_{date_str}")
def set_daily_python_challenge(date_str: str, challenge: dict[str, Any]):
set_cached_item(f"daily_python_{date_str}", challenge, ttl_seconds=86400 * 7)
async def set_daily_python_challenge_async(date_str: str, challenge: dict[str, Any]):
await set_cached_item_async(f"daily_python_{date_str}", challenge, ttl_seconds=86400 * 7)
def get_daily_sql_challenge(date_str: str) -> dict[str, Any] | None:
return get_cached_item(f"daily_sql_{date_str}")
async def get_daily_sql_challenge_async(date_str: str) -> dict[str, Any] | None:
return await get_cached_item_async(f"daily_sql_{date_str}")
def set_daily_sql_challenge(date_str: str, challenge: dict[str, Any]):
set_cached_item(f"daily_sql_{date_str}", challenge, ttl_seconds=86400 * 7)
async def set_daily_sql_challenge_async(date_str: str, challenge: dict[str, Any]):
await set_cached_item_async(f"daily_sql_{date_str}", challenge, ttl_seconds=86400 * 7)
def get_leetcode_problem(slug_or_url: str) -> dict[str, Any] | None:
slug = normalize_slug(slug_or_url)
return get_cached_item(f"leetcode_meta_{slug}")
async def get_leetcode_problem_async(slug_or_url: str) -> dict[str, Any] | None:
slug = normalize_slug(slug_or_url)
return await get_cached_item_async(f"leetcode_meta_{slug}")
def set_leetcode_problem(slug_or_url: str, data: dict[str, Any]):
slug = normalize_slug(slug_or_url)
set_cached_item(f"leetcode_meta_{slug}", data, ttl_seconds=86400 * 90)
async def set_leetcode_problem_async(slug_or_url: str, data: dict[str, Any]):
slug = normalize_slug(slug_or_url)
await set_cached_item_async(f"leetcode_meta_{slug}", data, ttl_seconds=86400 * 90)
def get_leetcode_intuition(slug_or_title: str) -> dict[str, Any] | None:
slug = normalize_slug(slug_or_title)
return get_cached_item(f"leetcode_intuition_{slug}")
async def get_leetcode_intuition_async(slug_or_title: str) -> dict[str, Any] | None:
slug = normalize_slug(slug_or_title)
return await get_cached_item_async(f"leetcode_intuition_{slug}")
def set_leetcode_intuition(slug_or_title: str, data: dict[str, Any]):
slug = normalize_slug(slug_or_title)
set_cached_item(f"leetcode_intuition_{slug}", data, ttl_seconds=86400 * 90)
async def set_leetcode_intuition_async(slug_or_title: str, data: dict[str, Any]):
slug = normalize_slug(slug_or_title)
await set_cached_item_async(f"leetcode_intuition_{slug}", data, ttl_seconds=86400 * 90)