Spaces:
Paused

yaz / src /core /cache /strategy.py
anaselamr's picture
[PLATFORM] fix(endpoints+templates): Sprint 52 — zero-error operational pass
579285c
Raw History Blame Contribute Delete
6.08 kB
"""
YAZ Care Platform — Cache Strategy (Redis, cache-aside)
=========================================================
TTL POLICY (from spec):
case summaries: 60s (cache:case:{id}:{org_id})
user sessions/perms: 300s (cache:user:{id}:{org_id})
org settings: 600s (cache:org:{id})
report results: 3600s (cache:report:{hash}:{org_id})
operative notes: DO NOT CACHE
current payment status: DO NOT CACHE
Pattern: cache-aside only (never write-through on clinical data)
Stampede protection: Redis SET NX with 5s lock TTL
Key namespace: cache:{entity_type}:{id}:{org_id}
Invalidation: on CASE_UPDATED and PAYMENT_RECORDED, delete cache key
Usage::
cache = get_cache()
value = await cache.get("case", case_id, org_id)
await cache.set("case", case_id, org_id, data)
await cache.invalidate("case", case_id, org_id)
"""
from __future__ import annotations
import json
import structlog
import os
from typing import Any, Optional
logger = structlog.get_logger(__name__)
# ---------------------------------------------------------------------------
# TTL constants (seconds)
# ---------------------------------------------------------------------------
TTL = {
"case": 60,
"user": 300,
"org": 600,
"report": 3600,
}
# These entity types MUST NEVER be cached (clinical safety)
NEVER_CACHE = {"operative_note", "payment_status"}
def _key(entity_type: str, entity_id: str, org_id: str) -> str:
"""Build a namespaced cache key."""
return f"cache:{entity_type}:{entity_id}:{org_id}"
def _lock_key(entity_type: str, entity_id: str, org_id: str) -> str:
return f"lock:{entity_type}:{entity_id}:{org_id}"
class CacheStrategy:
"""
Redis cache-aside with TTL policy and stampede protection.
Falls back to no-cache if Redis is unavailable.
"""
def __init__(self) -> None:
self._client: Optional[Any] = None
async def _get_client(self) -> Optional[Any]:
if self._client is None:
try:
import redis.asyncio as aioredis # type: ignore[import-untyped]
url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
self._client = aioredis.from_url(url, decode_responses=True)
except Exception as exc:
logger.warning("Redis unavailable for cache: %s", exc)
return self._client
# ------------------------------------------------------------------
async def get(self, entity_type: str, entity_id: str, org_id: str) -> Optional[Any]:
"""
Cache-aside GET. Returns None on cache miss or if caching is forbidden.
"""
if entity_type in NEVER_CACHE:
logger.debug("cache_blocked entity_type=%s reason=never_cache", entity_type)
return None
client = await self._get_client()
if client is None:
return None
k = _key(entity_type, entity_id, org_id)
try:
raw = await client.get(k)
if raw is None:
return None
return json.loads(raw)
except Exception as exc:
logger.warning("cache_get_error key=%s error=%s", k, exc)
return None
async def set(self, entity_type: str, entity_id: str, org_id: str, value: Any) -> bool:
"""
Cache-aside SET with TTL policy and stampede protection.
Returns True on success.
"""
if entity_type in NEVER_CACHE:
logger.warning("cache_write_blocked entity_type=%s reason=never_cache", entity_type)
return False
ttl = TTL.get(entity_type)
if ttl is None:
logger.debug("cache_skip entity_type=%s reason=no_ttl_policy", entity_type)
return False
client = await self._get_client()
if client is None:
return False
k = _key(entity_type, entity_id, org_id)
lock_k = _lock_key(entity_type, entity_id, org_id)
try:
# Stampede protection: SET NX with 5s lock
acquired = await client.set(lock_k, "1", nx=True, ex=5)
if not acquired:
# Another coroutine is already writing — skip to prevent stampede
return False
try:
await client.set(k, json.dumps(value, default=str), ex=ttl)
return True
finally:
await client.delete(lock_k)
except Exception as exc:
logger.warning("cache_set_error key=%s error=%s", k, exc)
return False
async def invalidate(self, entity_type: str, entity_id: str, org_id: str) -> None:
"""Delete a cache key on entity mutation (CASE_UPDATED, PAYMENT_RECORDED…)."""
client = await self._get_client()
if client is None:
return
k = _key(entity_type, entity_id, org_id)
try:
await client.delete(k)
logger.debug("cache_invalidated key=%s", k)
except Exception as exc:
logger.warning("cache_invalidate_error key=%s error=%s", k, exc)
async def invalidate_pattern(self, pattern: str) -> int:
"""
Invalidate all keys matching a glob pattern.
Use sparingly — SCAN-based, not atomic.
"""
client = await self._get_client()
if client is None:
return 0
deleted = 0
try:
async for key in client.scan_iter(match=pattern, count=100):
await client.delete(key)
deleted += 1
except Exception as exc:
logger.warning("cache_invalidate_pattern_error pattern=%s error=%s", pattern, exc)
return deleted
# ---------------------------------------------------------------------------
# Module-level singleton
# ---------------------------------------------------------------------------
_cache: Optional[CacheStrategy] = None
def get_cache() -> CacheStrategy:
global _cache
if _cache is None:
_cache = CacheStrategy()
return _cache