-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathredis_cache.py
More file actions
171 lines (149 loc) · 5.21 KB
/
redis_cache.py
File metadata and controls
171 lines (149 loc) · 5.21 KB
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
import os
import redis
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class RedisTokenCache:
def __init__(
self, host: str = None, port: int = 6379, db: int = 0, password: str = None
):
"""
Initialize Redis connection for token caching
Args:
host: Redis host (defaults to REDIS_HOST env var or localhost)
port: Redis port (defaults to 6379)
db: Redis database number (defaults to 0)
password: Redis password (defaults to REDIS_PASSWORD env var)
"""
self.host = host or os.environ.get("REDIS_HOST", "localhost")
self.port = port
self.db = db
self.password = password or os.environ.get("REDIS_PASSWORD")
try:
self.redis_client = redis.Redis(
host=self.host,
port=self.port,
db=self.db,
password=self.password,
decode_responses=True,
socket_connect_timeout=5,
socket_timeout=5,
retry_on_timeout=True,
health_check_interval=30,
)
# Test connection
self.redis_client.ping()
logger.debug(f"Connected to Redis at {self.host}:{self.port}")
except Exception as e:
logger.error(f"Failed to connect to Redis: {e}")
# Fallback to in-memory set for development/testing
self.redis_client = None
self._fallback_cache = set()
def add_token(self, token: str, ttl: int = 3600) -> bool:
"""
Add a token to the cache with optional TTL
Args:
token: The token to cache
ttl: Time to live in seconds (default: 1 hour)
Returns:
True if successful, False otherwise
"""
try:
if self.redis_client:
return self.redis_client.setex(f"token:{token}", ttl, "valid")
else:
# Fallback to in-memory
self._fallback_cache.add(token)
return True
except Exception as e:
logger.error(f"Error adding token to cache: {e}")
return False
def has_token(self, token: str) -> bool:
"""
Check if a token exists in the cache
Args:
token: The token to check
Returns:
True if token exists, False otherwise
"""
try:
if self.redis_client:
return self.redis_client.exists(f"token:{token}") > 0
else:
return token in self._fallback_cache
except Exception as e:
logger.error(f"Error checking token in cache: {e}")
return False
def remove_token(self, token: str) -> bool:
"""
Remove a token from the cache
Args:
token: The token to remove
Returns:
True if successful, False otherwise
"""
try:
if self.redis_client:
return self.redis_client.delete(f"token:{token}") > 0
else:
# Fallback to in-memory
if token in self._fallback_cache:
self._fallback_cache.remove(token)
return True
return False
except Exception as e:
logger.error(f"Error removing token from cache: {e}")
return False
def clear_cache(self) -> bool:
"""
Clear all tokens from the cache
Returns:
True if successful, False otherwise
"""
try:
if self.redis_client:
keys = self.redis_client.keys("token:*")
if keys:
return self.redis_client.delete(*keys) > 0
return True
else:
# Fallback to in-memory
self._fallback_cache.clear()
return True
except Exception as e:
logger.error(f"Error clearing cache: {e}")
return False
def get_cache_stats(self) -> dict:
"""
Get cache statistics
Returns:
Dictionary with cache statistics
"""
try:
if self.redis_client:
info = self.redis_client.info()
keys = self.redis_client.keys("token:*")
return {
"connected": True,
"token_count": len(keys),
"memory_usage": info.get("used_memory_human", "N/A"),
"connections": info.get("connected_clients", 0),
"redis_version": info.get("redis_version", "N/A"),
}
else:
return {
"connected": False,
"token_count": len(self._fallback_cache),
"fallback_mode": True,
}
except Exception as e:
logger.error(f"Error getting cache stats: {e}")
return {"error": str(e)}
# Global instance
_token_cache = None
def get_token_cache() -> RedisTokenCache:
"""Get the global token cache instance"""
global _token_cache
if _token_cache is None:
_token_cache = RedisTokenCache()
return _token_cache