Coverage for app\infrastructure\cache\meta_fetch_cache.py: 0%
30 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-05 12:56 +0530
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-05 12:56 +0530
1"""Redis cache for /api/v1/metadata results.
3Keys: ``meta_fetch:{sha256(url)}``. Successes cache for an hour (a
4destination's tags rarely change mid-session); failures negative-cache
5briefly so a flapping destination doesn't burn the caller's rate limit
6AND our outbound fetches. None-redis tolerant like url_cache.
7"""
9from __future__ import annotations
11import hashlib
12import json
14import redis.asyncio as aioredis
16from app.infrastructure.logging import get_logger
18log = get_logger(__name__)
21class MetaFetchCache:
22 def __init__(
23 self,
24 redis_client: aioredis.Redis | None,
25 *,
26 ttl_seconds: int = 3600,
27 negative_ttl_seconds: int = 300,
28 prefix: str = "meta_fetch",
29 ) -> None:
30 self._redis = redis_client
31 self._ttl = ttl_seconds
32 self._negative_ttl = negative_ttl_seconds
33 self._prefix = prefix
35 def _key(self, url: str) -> str:
36 return f"{self._prefix}:{hashlib.sha256(url.encode()).hexdigest()}"
38 async def get(self, url: str) -> dict | None:
39 if self._redis is None:
40 return None
41 try:
42 raw = await self._redis.get(self._key(url))
43 return json.loads(raw) if raw else None
44 except Exception as exc:
45 log.warning("meta_fetch_cache_get_error", error=str(exc))
46 return None
48 async def set(self, url: str, payload: dict, *, negative: bool = False) -> None:
49 if self._redis is None:
50 return
51 try:
52 await self._redis.setex(
53 self._key(url),
54 self._negative_ttl if negative else self._ttl,
55 json.dumps(payload),
56 )
57 except Exception as exc:
58 log.warning("meta_fetch_cache_set_error", error=str(exc))