Spaces:
Running
Running
File size: 9,560 Bytes
664a5eb 8800c81 4f6bb9e 8800c81 4f6bb9e 8800c81 4f6bb9e 8800c81 4f6bb9e 8800c81 664a5eb 4f6bb9e 664a5eb 8800c81 4f6bb9e 8800c81 664a5eb 4f6bb9e 664a5eb 8800c81 664a5eb 8800c81 664a5eb 8800c81 664a5eb 8800c81 664a5eb 8800c81 664a5eb 8800c81 664a5eb 8800c81 664a5eb 8800c81 664a5eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | 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)
|