-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_manager.py
More file actions
431 lines (369 loc) · 13.1 KB
/
Copy pathcache_manager.py
File metadata and controls
431 lines (369 loc) · 13.1 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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
"""
Multi-level caching strategy for email validation.
Maximizes cache hit rates and minimizes external calls.
"""
import redis
import hashlib
import time
from typing import Optional, Dict, List, Any
from dataclasses import dataclass
from functools import lru_cache
import json
import logging
logger = logging.getLogger(__name__)
@dataclass
class CacheConfig:
"""Cache TTL configuration."""
mx_records: int = 3600 # 1 hour - MX records change rarely
smtp_results: int = 1800 # 30 minutes - SMTP results semi-volatile
disposable: int = 86400 # 24 hours - Disposable domains stable
syntax: int = -1 # Forever - Syntax doesn't change
rate_limit: int = 60 # 1 minute - Rate limit tracking
domain_info: int = 86400 # 24 hours - Domain information
class MultiLevelCache:
"""
Multi-level caching system:
Level 1: In-memory LRU cache (fastest, smallest)
Level 2: Local Redis (fast, moderate size)
Level 3: Shared Redis Cluster (slower, largest)
"""
def __init__(
self,
redis_host: str = 'localhost',
redis_port: int = 6379,
redis_db: int = 0,
redis_password: Optional[str] = None,
lru_size: int = 10000,
enable_redis: bool = True
):
self.config = CacheConfig()
# Level 2/3: Redis
self.enable_redis = enable_redis
self.redis = None
if enable_redis:
try:
self.redis = redis.Redis(
host=redis_host,
port=redis_port,
db=redis_db,
password=redis_password,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
max_connections=50,
health_check_interval=30,
)
# Test connection
self.redis.ping()
logger.info("Connected to Redis cache")
except Exception as e:
logger.warning(f"Could not connect to Redis: {e}")
self.redis = None
self.enable_redis = False
# Level 1: In-memory LRU cache
self._lru_size = lru_size
self._lru_cache: Dict[str, Any] = {}
self._lru_access_times: Dict[str, float] = {}
# Cache statistics
self.stats = {
'lru_hits': 0,
'redis_hits': 0,
'misses': 0,
'sets': 0,
'evictions': 0,
}
def _lru_get(self, key: str) -> Optional[Any]:
"""Get from LRU cache with access time update."""
if key in self._lru_cache:
self._lru_access_times[key] = time.time()
return self._lru_cache[key]
return None
def _lru_set(self, key: str, value: Any):
"""Set in LRU cache with eviction if needed."""
# Evict oldest if at capacity
while len(self._lru_cache) >= self._lru_size:
if self._lru_access_times:
oldest_key = min(self._lru_access_times, key=self._lru_access_times.get)
del self._lru_cache[oldest_key]
del self._lru_access_times[oldest_key]
self.stats['evictions'] += 1
else:
break
self._lru_cache[key] = value
self._lru_access_times[key] = time.time()
def _lru_delete(self, key: str):
"""Delete from LRU cache."""
if key in self._lru_cache:
del self._lru_cache[key]
del self._lru_access_times[key]
def get_mx_records(self, domain: str) -> Optional[List[str]]:
"""
Get cached MX records with multi-level lookup.
Order: LRU -> Redis -> None
"""
cache_key = f"mx:{domain.lower()}"
# Level 1: Check LRU
cached = self._lru_get(cache_key)
if cached is not None:
self.stats['lru_hits'] += 1
return cached
# Level 2: Check Redis
if self.redis:
try:
cached = self.redis.get(cache_key)
if cached:
self.stats['redis_hits'] += 1
records = json.loads(cached)
# Promote to LRU
self._lru_set(cache_key, records)
return records
except redis.RedisError as e:
logger.debug(f"Redis error: {e}")
self.stats['misses'] += 1
return None
def set_mx_records(self, domain: str, records: List[str]):
"""Cache MX records at all levels."""
cache_key = f"mx:{domain.lower()}"
# Level 1: LRU
self._lru_set(cache_key, records)
# Level 2: Redis
if self.redis:
try:
self.redis.setex(
cache_key,
self.config.mx_records,
json.dumps(records)
)
self.stats['sets'] += 1
except redis.RedisError as e:
logger.debug(f"Redis error: {e}")
def get_smtp_result(self, email: str) -> Optional[Dict]:
"""Get cached SMTP validation result."""
cache_key = f"smtp:{self._hash_email(email)}"
# Level 1: LRU
cached = self._lru_get(cache_key)
if cached is not None:
self.stats['lru_hits'] += 1
return cached
# Level 2: Redis
if self.redis:
try:
cached = self.redis.get(cache_key)
if cached:
self.stats['redis_hits'] += 1
result = json.loads(cached)
self._lru_set(cache_key, result)
return result
except redis.RedisError:
pass
self.stats['misses'] += 1
return None
def set_smtp_result(self, email: str, result: Dict):
"""Cache SMTP validation result."""
cache_key = f"smtp:{self._hash_email(email)}"
# Level 1: LRU
self._lru_set(cache_key, result)
# Level 2: Redis
if self.redis:
try:
self.redis.setex(
cache_key,
self.config.smtp_results,
json.dumps(result)
)
self.stats['sets'] += 1
except redis.RedisError:
pass
def is_disposable(self, domain: str) -> Optional[bool]:
"""Check if domain is disposable (cached)."""
cache_key = f"disposable:{domain.lower()}"
# Check LRU first
cached = self._lru_get(cache_key)
if cached is not None:
self.stats['lru_hits'] += 1
return cached
# Check Redis
if self.redis:
try:
cached = self.redis.get(cache_key)
if cached is not None:
self.stats['redis_hits'] += 1
result = cached == '1'
self._lru_set(cache_key, result)
return result
except redis.RedisError:
pass
self.stats['misses'] += 1
return None
def set_disposable(self, domain: str, is_disposable: bool):
"""Cache disposable domain check."""
cache_key = f"disposable:{domain.lower()}"
self._lru_set(cache_key, is_disposable)
if self.redis:
try:
self.redis.setex(
cache_key,
self.config.disposable,
'1' if is_disposable else '0'
)
except redis.RedisError:
pass
def get_domain_info(self, domain: str) -> Optional[Dict]:
"""Get cached domain information."""
cache_key = f"domain_info:{domain.lower()}"
# Check LRU
cached = self._lru_get(cache_key)
if cached is not None:
self.stats['lru_hits'] += 1
return cached
# Check Redis
if self.redis:
try:
cached = self.redis.get(cache_key)
if cached:
self.stats['redis_hits'] += 1
info = json.loads(cached)
self._lru_set(cache_key, info)
return info
except redis.RedisError:
pass
self.stats['misses'] += 1
return None
def set_domain_info(self, domain: str, info: Dict):
"""Cache domain information."""
cache_key = f"domain_info:{domain.lower()}"
self._lru_set(cache_key, info)
if self.redis:
try:
self.redis.setex(
cache_key,
self.config.domain_info,
json.dumps(info)
)
except redis.RedisError:
pass
def _hash_email(self, email: str) -> str:
"""Create consistent hash for email."""
return hashlib.sha256(email.lower().encode()).hexdigest()[:16]
def get_stats(self) -> Dict[str, Any]:
"""Get cache statistics."""
total_requests = self.stats['lru_hits'] + self.stats['redis_hits'] + self.stats['misses']
hit_rate = 0
if total_requests > 0:
hit_rate = (self.stats['lru_hits'] + self.stats['redis_hits']) / total_requests
return {
**self.stats,
'hit_rate': hit_rate,
'lru_size': len(self._lru_cache),
'total_requests': total_requests,
}
def clear(self):
"""Clear all caches."""
self._lru_cache.clear()
self._lru_access_times.clear()
if self.redis:
try:
# Only clear our keys
for pattern in ['mx:*', 'smtp:*', 'disposable:*', 'domain_info:*']:
keys = self.redis.keys(pattern)
if keys:
self.redis.delete(*keys)
except redis.RedisError as e:
logger.error(f"Error clearing Redis cache: {e}")
def warmup(self, domains: List[str], mx_records_map: Dict[str, List[str]]):
"""
Warm up cache with known MX records.
Useful for common domains like gmail.com, yahoo.com, etc.
"""
for domain in domains:
if domain in mx_records_map:
self.set_mx_records(domain, mx_records_map[domain])
logger.info(f"Cache warmed up with {len(domains)} domains")
# Cache TTL Recommendations
CACHE_TTL_RECOMMENDATIONS = {
# MX Records: 1 hour
# - MX records change very rarely
# - Reduces DNS queries by ~70%
'mx_records': 3600,
# SMTP Results: 30 minutes
# - Mailbox status can change
# - Balance between accuracy and performance
'smtp_results': 1800,
# Disposable Domains: 24 hours
# - Disposable domain lists are relatively stable
# - Update daily from GitHub sources
'disposable_domains': 86400,
# Syntax Validation: Permanent
# - Email syntax doesn't change
# - Can cache indefinitely
'syntax': None,
# Rate Limit Tracking: 1 minute
# - Short TTL for rate limit windows
'rate_limit': 60,
# Domain Information: 24 hours
# - Provider info, rate limits, etc.
'domain_info': 86400,
}
# Common domain MX records for cache warmup
COMMON_MX_RECORDS = {
'gmail.com': [
'gmail-smtp-in.l.google.com',
'alt1.gmail-smtp-in.l.google.com',
'alt2.gmail-smtp-in.l.google.com',
'alt3.gmail-smtp-in.l.google.com',
'alt4.gmail-smtp-in.l.google.com',
],
'googlemail.com': [
'gmail-smtp-in.l.google.com',
'alt1.gmail-smtp-in.l.google.com',
'alt2.gmail-smtp-in.l.google.com',
],
'yahoo.com': [
'mta5.am0.yahoodns.net',
'mta6.am0.yahoodns.net',
'mta7.am0.yahoodns.net',
],
'ymail.com': [
'mta5.am0.yahoodns.net',
'mta6.am0.yahoodns.net',
'mta7.am0.yahoodns.net',
],
'outlook.com': [
'outlook-com.olc.protection.outlook.com',
],
'hotmail.com': [
'hotmail-com.olc.protection.outlook.com',
],
'live.com': [
'live-com.olc.protection.outlook.com',
],
'aol.com': [
'mx-aol.mail.gm0.yahoodns.net',
],
'icloud.com': [
'mx01.mail.icloud.com',
'mx02.mail.icloud.com',
'mx03.mail.icloud.com',
'mx04.mail.icloud.com',
'mx05.mail.icloud.com',
'mx06.mail.icloud.com',
],
'me.com': [
'mx01.mail.icloud.com',
'mx02.mail.icloud.com',
],
'protonmail.com': [
'mail.protonmail.ch',
'mailsec.protonmail.ch',
],
'zoho.com': [
'mx.zoho.com',
'mx2.zoho.com',
'mx3.zoho.com',
],
}
def create_warmed_cache(redis_url: Optional[str] = None) -> MultiLevelCache:
"""Create a cache pre-warmed with common domain MX records."""
cache = MultiLevelCache()
cache.warmup(list(COMMON_MX_RECORDS.keys()), COMMON_MX_RECORDS)
return cache