Spaces:
Running

File size: 5,116 Bytes
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Redis cache service for API response caching."""

import json
import logging

import redis

from src.config import settings

logger = logging.getLogger(__name__)

# Default TTL: 48 hours (in seconds)
DEFAULT_TTL = 48 * 60 * 60  # 172800 seconds


class CacheService:
    """Redis-based caching service for API responses."""

    def __init__(self, redis_url: str = None):
        """
        Initialize the cache service.

        Args:
            redis_url: Redis connection URL (defaults to localhost:6379)
        """
        self.redis_url = redis_url or settings.REDIS_URL or "redis://localhost:6379/0"
        self._client = None
        self._connected = False

    @property
    def client(self) -> redis.Redis:
        """Get Redis client, lazily initialized."""
        if self._client is None:
            try:
                self._client = redis.from_url(
                    self.redis_url,
                    decode_responses=True,
                    socket_connect_timeout=2,
                    socket_timeout=2,
                )
                # Test connection
                self._client.ping()
                self._connected = True
                logger.info("Redis cache connected successfully")
            except (redis.ConnectionError, redis.TimeoutError) as e:
                logger.warning(f"Redis connection failed: {e}. Cache disabled.")
                self._connected = False
                self._client = None
        return self._client

    @property
    def is_available(self) -> bool:
        """Check if cache is available."""
        if self._client is None:
            # Try to connect
            _ = self.client
        return self._connected

    def _make_key(self, source: str, ioc_type: str, ioc: str) -> str:
        """
        Generate a cache key.

        Args:
            source: Source name (e.g., 'virustotal', 'abuseipdb')
            ioc_type: IOC type (e.g., 'ip', 'domain', 'hash')
            ioc: The actual IOC value

        Returns:
            Cache key string
        """
        # Normalize IOC (lowercase, strip whitespace)
        normalized_ioc = ioc.lower().strip()
        return f"ioc:{source}:{ioc_type}:{normalized_ioc}"

    def get(self, source: str, ioc_type: str, ioc: str) -> dict | None:
        """
        Get cached response for an IOC.

        Args:
            source: Source name
            ioc_type: IOC type
            ioc: IOC value

        Returns:
            Cached data dict or None if not found
        """
        if not self.is_available:
            return None

        key = self._make_key(source, ioc_type, ioc)
        try:
            cached = self.client.get(key)
            if cached:
                logger.debug(f"Cache HIT: {key}")
                return json.loads(cached)
            logger.debug(f"Cache MISS: {key}")
            return None
        except (redis.RedisError, json.JSONDecodeError) as e:
            logger.warning(f"Cache get error: {e}")
            return None

    def set(self, source: str, ioc_type: str, ioc: str, data: dict, ttl: int = DEFAULT_TTL) -> bool:
        """
        Cache a response for an IOC.

        Args:
            source: Source name
            ioc_type: IOC type
            ioc: IOC value
            data: Data to cache
            ttl: Time-to-live in seconds (default: 48 hours)

        Returns:
            True if cached successfully
        """
        if not self.is_available:
            return False

        key = self._make_key(source, ioc_type, ioc)
        try:
            self.client.setex(key, ttl, json.dumps(data))
            logger.debug(f"Cache SET: {key} (TTL: {ttl}s)")
            return True
        except redis.RedisError as e:
            logger.warning(f"Cache set error: {e}")
            return False

    def delete(self, source: str, ioc_type: str, ioc: str) -> bool:
        """Delete a cached entry."""
        if not self.is_available:
            return False

        key = self._make_key(source, ioc_type, ioc)
        try:
            self.client.delete(key)
            return True
        except redis.RedisError:
            return False

    def clear_source(self, source: str) -> int:
        """Clear all cache entries for a source."""
        if not self.is_available:
            return 0

        try:
            keys = self.client.keys(f"ioc:{source}:*")
            if keys:
                return self.client.delete(*keys)
            return 0
        except redis.RedisError:
            return 0

    def get_stats(self) -> dict:
        """Get cache statistics."""
        if not self.is_available:
            return {"available": False}

        try:
            info = self.client.info("stats")
            dbsize = self.client.dbsize()
            return {
                "available": True,
                "total_keys": dbsize,
                "hits": info.get("keyspace_hits", 0),
                "misses": info.get("keyspace_misses", 0),
            }
        except redis.RedisError:
            return {"available": False}


# Global cache instance
cache = CacheService()