File size: 10,342 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""
Intent Engine - Redis Cache Module

High-performance async Redis caching for search results and intent extraction.

Features:
- Async Redis client using redis.asyncio
- Intelligent cache key generation
- Configurable TTL for different data types
- Cache-aside pattern with background refresh
- Graceful degradation when Redis unavailable

Usage:
    from app.config.redis_cache import cache

    # Initialize on startup
    await cache.initialize(redis_url="redis://redis:6379/0")

    # Get/set cache
    cached = await cache.get("key")
    await cache.set("key", value, ttl=300)

    # Cache-aside pattern
    result = await cache.get_or_set(
        "search:query123",
        lambda: expensive_search("query123"),
        ttl=300
    )
"""

import asyncio
import hashlib
import json
import logging
import time
from collections.abc import Callable
from typing import Any

import redis.asyncio as redis

logger = logging.getLogger(__name__)


class RedisCache:
    """
    Async Redis cache with intelligent key generation and serialization.

    Provides:
    - Automatic connection management
    - JSON serialization with datetime support
    - Configurable TTL per operation
    - Background cache updates
    - Cache statistics tracking
    """

    def __init__(self):
        self._client: redis.Redis | None = None
        self._initialized = False
        self._enabled = False

        # Default TTL settings (in seconds)
        self._default_ttl = 300  # 5 minutes for general cache
        self._search_ttl = 300  # 5 minutes for search results
        self._intent_ttl = 3600  # 1 hour for intent extraction
        self._ranking_ttl = 600  # 10 minutes for ranking results

        # Key prefix for namespacing
        self._key_prefix = "intent-engine"

        # Statistics
        self._stats = {
            "hits": 0,
            "misses": 0,
            "errors": 0,
            "sets": 0,
        }

    async def initialize(self, redis_url: str = "redis://redis:6379/0"):
        """
        Initialize Redis connection on application startup.

        Args:
            redis_url: Redis connection URL (redis://host:port/db)
        """
        if self._initialized:
            return

        try:
            logger.info(f"Connecting to Redis: {redis_url}")

            self._client = redis.Redis.from_url(
                redis_url,
                encoding="utf-8",
                decode_responses=True,
                socket_connect_timeout=5.0,
                socket_timeout=5.0,
                retry_on_timeout=True,
                health_check_interval=30,
            )

            # Test connection
            await self._client.ping()

            self._initialized = True
            self._enabled = True
            logger.info("Redis cache connected and enabled")

        except Exception as e:
            logger.warning(f"Redis connection failed, caching disabled: {e}")
            self._initialized = True
            self._enabled = False

    async def close(self):
        """Close Redis connection on application shutdown"""
        if self._client:
            await self._client.close()
            logger.info("Redis cache connection closed")
            self._enabled = False

    def _generate_key(self, prefix: str, *args, **kwargs) -> str:
        """
        Generate consistent cache key from arguments.

        Args:
            prefix: Key prefix (e.g., "search", "intent")
            *args: Positional arguments to include in key
            **kwargs: Keyword arguments to include in key

        Returns:
            MD5-hashed cache key with prefix
        """
        # Create deterministic key string
        key_data = {
            "prefix": prefix,
            "args": args,
            "kwargs": sorted(kwargs.items()) if kwargs else [],
        }
        key_string = json.dumps(key_data, sort_keys=True, default=str)
        key_hash = hashlib.md5(key_string.encode()).hexdigest()

        return f"{self._key_prefix}:{prefix}:{key_hash}"

    async def get(self, key: str) -> Any | None:
        """
        Get value from cache.

        Args:
            key: Cache key

        Returns:
            Cached value or None if not found/error
        """
        if not self._enabled or not self._initialized:
            return None

        try:
            start_time = time.perf_counter()
            value = await self._client.get(key)
            elapsed = (time.perf_counter() - start_time) * 1000

            if value:
                self._stats["hits"] += 1
                logger.debug(f"Cache HIT: {key[:80]}... ({elapsed:.2f}ms)")
                return json.loads(value)
            self._stats["misses"] += 1
            logger.debug(f"Cache MISS: {key[:80]}... ({elapsed:.2f}ms)")
            return None

        except Exception as e:
            self._stats["errors"] += 1
            logger.error(f"Redis GET error: {e}")
            return None

    async def set(self, key: str, value: Any, ttl: int | None = None, background: bool = False):
        """
        Set value in cache with TTL.

        Args:
            key: Cache key
            value: Value to cache (will be JSON serialized)
            ttl: Time to live in seconds (default: 300)
            background: If True, cache update happens asynchronously
        """
        if not self._enabled or not self._initialized:
            return

        try:
            serialized = json.dumps(value, default=str)
            effective_ttl = ttl or self._default_ttl

            if background:
                # Non-blocking cache update
                asyncio.create_task(self._set_async(key, serialized, effective_ttl))
            else:
                await self._set_async(key, serialized, effective_ttl)

            self._stats["sets"] += 1
            logger.debug(f"Cache SET: {key[:80]}... (TTL: {effective_ttl}s)")

        except Exception as e:
            self._stats["errors"] += 1
            logger.error(f"Redis SET error: {e}")

    async def _set_async(self, key: str, value: str, ttl: int):
        """Internal async set operation"""
        await self._client.setex(key, ttl, value)

    async def delete(self, key: str):
        """Delete key from cache"""
        if not self._enabled or not self._initialized:
            return

        try:
            await self._client.delete(key)
            logger.debug(f"Cache DELETE: {key[:80]}...")
        except Exception as e:
            self._stats["errors"] += 1
            logger.error(f"Redis DELETE error: {e}")

    async def get_or_set(
        self,
        key: str,
        factory: Callable,
        ttl: int | None = None,
    ) -> Any:
        """
        Get from cache or compute and cache result (cache-aside pattern).

        Args:
            key: Cache key
            factory: Async function to compute value if cache miss
            ttl: Time to live in seconds

        Returns:
            Cached or computed value
        """
        # Try cache first
        cached = await self.get(key)
        if cached is not None:
            return cached

        # Cache miss: compute value
        logger.info(f"Cache miss, computing: {key[:80]}...")

        if asyncio.iscoroutinefunction(factory):
            value = await factory()
        else:
            value = factory()

        # Cache result
        await self.set(key, value, ttl)

        return value

    async def get_search(self, query: str, pageno: int = 1, language: str = "en") -> dict | None:
        """Get cached search results"""
        key = self._generate_key("search", query=query, pageno=pageno, language=language)
        return await self.get(key)

    async def set_search(self, query: str, pageno: int, language: str, results: dict):
        """Cache search results"""
        key = self._generate_key("search", query=query, pageno=pageno, language=language)
        await self.set(key, results, ttl=self._search_ttl, background=True)

    async def get_intent(self, query: str) -> dict | None:
        """Get cached intent extraction"""
        key = self._generate_key("intent", query=query)
        return await self.get(key)

    async def set_intent(self, query: str, intent: dict):
        """Cache intent extraction result"""
        key = self._generate_key("intent", query=query)
        await self.set(key, intent, ttl=self._intent_ttl, background=True)

    async def get_stats(self) -> dict:
        """Get cache statistics"""
        total = self._stats["hits"] + self._stats["misses"]
        hit_rate = (self._stats["hits"] / total * 100) if total > 0 else 0

        return {
            **self._stats,
            "total_requests": total,
            "hit_rate_percent": round(hit_rate, 2),
            "enabled": self._enabled,
            "initialized": self._initialized,
        }

    async def get_memory_usage(self) -> int | None:
        """Get Redis memory usage in MB"""
        if not self._enabled:
            return None

        try:
            info = await self._client.info("memory")
            return round(info.get("used_memory", 0) / 1024 / 1024, 2)
        except Exception:
            return None

    async def flush(self, pattern: str | None = None):
        """
        Flush cache keys matching pattern.

        Args:
            pattern: Key pattern to delete (default: all intent-engine keys)
        """
        if not self._enabled:
            return

        try:
            search_pattern = pattern or f"{self._key_prefix}:*"
            cursor = 0

            while True:
                cursor, keys = await self._client.scan(cursor, match=search_pattern, count=100)
                if keys:
                    await self._client.delete(*keys)
                    logger.info(f"Flushed {len(keys)} cache keys")

                if cursor == 0:
                    break

        except Exception as e:
            logger.error(f"Cache flush error: {e}")


# Global cache instance
cache = RedisCache()


async def get_cache() -> RedisCache:
    """Get global cache instance"""
    return cache


async def initialize_cache(redis_url: str = "redis://redis:6379/0"):
    """Initialize global cache instance"""
    await cache.initialize(redis_url)


async def close_cache():
    """Close global cache instance"""
    await cache.close()