File size: 1,999 Bytes
0ddcb86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Async Redis cache wrapper with graceful degradation."""
from __future__ import annotations
import json
import hashlib
from typing import Any, Optional
import redis.asyncio as aioredis
from app.config import settings
from app.utils.logger import logger


class CacheService:
    def __init__(self) -> None:
        self._client: Optional[aioredis.Redis] = None
        self._enabled = True

    async def client(self) -> Optional[aioredis.Redis]:
        if self._client is None and self._enabled:
            try:
                self._client = aioredis.from_url(
                    settings.redis_url, decode_responses=True
                )
                await self._client.ping()
            except Exception as e:
                logger.warning(f"Redis unavailable, caching disabled: {e}")
                self._enabled = False
                self._client = None
        return self._client

    @staticmethod
    def key(*parts: Any) -> str:
        raw = "|".join(str(p) for p in parts)
        return "rasta:" + hashlib.sha1(raw.encode()).hexdigest()

    async def get_json(self, key: str) -> Optional[dict]:
        c = await self.client()
        if not c:
            return None
        try:
            raw = await c.get(key)
            return json.loads(raw) if raw else None
        except Exception as e:
            logger.warning(f"Cache get failed: {e}")
            return None

    async def set_json(self, key: str, value: dict, ttl: Optional[int] = None) -> None:
        c = await self.client()
        if not c:
            return
        try:
            await c.set(key, json.dumps(value, default=str), ex=ttl or settings.cache_ttl_seconds)
        except Exception as e:
            logger.warning(f"Cache set failed: {e}")

    async def ping(self) -> bool:
        c = await self.client()
        if not c:
            return False
        try:
            return bool(await c.ping())
        except Exception:
            return False


cache = CacheService()