Spaces:
Sleeping

File size: 2,683 Bytes
20ee727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from typing import Any, Optional, Union
import logging
from app.core.redis import get_redis
from redis.exceptions import ConnectionError, TimeoutError

logger = logging.getLogger(__name__)

class CacheService:
    def __init__(self):
        self.use_redis = True
        self._memory_cache = {} # Fallback

    async def get(self, key: str) -> Optional[Any]:
        if self.use_redis:
            try:
                redis = get_redis()
                val = await redis.get(key)
                if val:
                    try:
                        return json.loads(val)
                    except json.JSONDecodeError:
                        return val
                return None
            except (ConnectionError, TimeoutError, OSError):
                logger.warning("Redis connection failed. Switch to memory fallback (temporary).")
                self.use_redis = False
                return self._memory_cache.get(key)
            except Exception as e:
                logger.error(f"Cache get error: {e}")
                return None
        else:
            return self._memory_cache.get(key)

    async def set(self, key: str, value: Any, ttl: int = 3600):
        """
        Set key with TTL (seconds). Default 1 hour.
        """
        # Serialize if dict/list
        str_val = value
        if isinstance(value, (dict, list)):
            str_val = json.dumps(value, default=str) # handle datetimes properly in real implementation
            
        if self.use_redis:
            try:
                redis = get_redis()
                await redis.set(key, str_val, ex=ttl)
            except (ConnectionError, TimeoutError, OSError):
                self.use_redis = False
                self._memory_cache[key] = value # No TTL support in simple dict fallback
            except Exception as e:
                logger.error(f"Cache set error: {e}")
        else:
            self._memory_cache[key] = value

    async def delete(self, key: str):
        if self.use_redis:
            try:
                redis = get_redis()
                await redis.delete(key)
            except Exception:
                pass
        
        if key in self._memory_cache:
            del self._memory_cache[key]

    async def clear_prefix(self, prefix: str):
        """Clear all keys starting with prefix."""
        if self.use_redis:
            try:
                redis = get_redis()
                keys = await redis.keys(f"{prefix}*")
                if keys:
                    await redis.delete(*keys)
            except Exception as e:
                logger.error(f"Cache clear error: {e}")

cache_service = CacheService()