Spaces:
Sleeping
Sleeping
File size: 7,758 Bytes
7851df6 | 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 | const logger = require('../utils/logger');
/**
* Advanced caching service for web search results with intelligent cache management
*/
class SearchCacheService {
constructor() {
// In-memory cache (could be Redis in production)
this.cache = new Map();
// Cache configuration
this.config = {
// Different TTL for different types of content
ttl: {
news: 15 * 60 * 1000, // 15 minutes for news
events: 30 * 60 * 1000, // 30 minutes for events
academic: 60 * 60 * 1000, // 1 hour for academic info
services: 20 * 60 * 1000, // 20 minutes for services/hours
general: 45 * 60 * 1000, // 45 minutes for general queries
uga_official: 120 * 60 * 1000 // 2 hours for UGA official content
},
maxCacheSize: 500, // Maximum number of cached items
cleanupInterval: 10 * 60 * 1000 // Cleanup every 10 minutes
};
// Statistics
this.stats = {
hits: 0,
misses: 0,
stores: 0,
evictions: 0,
cleanups: 0
};
// Start periodic cleanup
this.startCleanupTimer();
logger.info('SearchCacheService initialized', {
maxCacheSize: this.config.maxCacheSize,
ttlConfig: this.config.ttl
});
}
/**
* Generate cache key from query and options
*/
generateCacheKey(query, options = {}) {
const normalizedQuery = query.toLowerCase().trim();
const optionsHash = this.hashOptions(options);
return `search:${Buffer.from(normalizedQuery).toString('base64')}:${optionsHash}`;
}
/**
* Hash options for cache key generation
*/
hashOptions(options) {
const relevantOptions = {
ugaOnly: options.ugaOnly,
searchType: options.searchType,
maxResults: options.maxResults
};
return Buffer.from(JSON.stringify(relevantOptions)).toString('base64').slice(0, 8);
}
/**
* Get cached result
*/
get(query, options = {}) {
const key = this.generateCacheKey(query, options);
const cached = this.cache.get(key);
if (!cached) {
this.stats.misses++;
return null;
}
// Check if expired
if (this.isExpired(cached)) {
this.cache.delete(key);
this.stats.misses++;
return null;
}
// Update access time and hit count
cached.lastAccessed = Date.now();
cached.hitCount = (cached.hitCount || 0) + 1;
this.stats.hits++;
logger.debug('Cache hit', {
key: key.slice(0, 20) + '...',
age: Date.now() - cached.timestamp,
hitCount: cached.hitCount
});
return cached.result;
}
/**
* Store result in cache
*/
set(query, options = {}, result) {
const key = this.generateCacheKey(query, options);
const searchType = this.detectSearchType(query, result);
const ttl = this.config.ttl[searchType] || this.config.ttl.general;
const cacheEntry = {
result,
timestamp: Date.now(),
lastAccessed: Date.now(),
ttl,
searchType,
query: query.slice(0, 100), // Store truncated query for debugging
hitCount: 0
};
// Ensure cache doesn't exceed max size
if (this.cache.size >= this.config.maxCacheSize) {
this.evictLeastRecentlyUsed();
}
this.cache.set(key, cacheEntry);
this.stats.stores++;
logger.debug('Cache store', {
key: key.slice(0, 20) + '...',
searchType,
ttl,
cacheSize: this.cache.size
});
}
/**
* Detect search type from query and results
*/
detectSearchType(query, result) {
const lowerQuery = query.toLowerCase();
// Check UGA official sources first
if (result.keyInfo && result.keyInfo.ugaOfficial && result.keyInfo.ugaOfficial.length > 0) {
return 'uga_official';
}
// Detect based on query content
if (lowerQuery.includes('news')) return 'news';
if (lowerQuery.includes('event') || lowerQuery.includes('calendar')) return 'events';
if (lowerQuery.includes('registration') || lowerQuery.includes('academic')) return 'academic';
if (lowerQuery.includes('hours') || lowerQuery.includes('dining') || lowerQuery.includes('service')) return 'services';
return 'general';
}
/**
* Check if cache entry has expired
*/
isExpired(cacheEntry) {
return (Date.now() - cacheEntry.timestamp) > cacheEntry.ttl;
}
/**
* Evict least recently used item
*/
evictLeastRecentlyUsed() {
let oldestKey = null;
let oldestTime = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (entry.lastAccessed < oldestTime) {
oldestTime = entry.lastAccessed;
oldestKey = key;
}
}
if (oldestKey) {
this.cache.delete(oldestKey);
this.stats.evictions++;
logger.debug('Evicted LRU cache entry', { key: oldestKey.slice(0, 20) + '...' });
}
}
/**
* Clean expired entries
*/
cleanup() {
const beforeSize = this.cache.size;
let cleaned = 0;
for (const [key, entry] of this.cache.entries()) {
if (this.isExpired(entry)) {
this.cache.delete(key);
cleaned++;
}
}
this.stats.cleanups++;
if (cleaned > 0) {
logger.info('Cache cleanup completed', {
cleaned,
beforeSize,
afterSize: this.cache.size
});
}
}
/**
* Start periodic cleanup timer
*/
startCleanupTimer() {
setInterval(() => {
this.cleanup();
}, this.config.cleanupInterval);
}
/**
* Invalidate cache entries by pattern
*/
invalidate(pattern) {
let invalidated = 0;
for (const [key, entry] of this.cache.entries()) {
if (entry.query && entry.query.toLowerCase().includes(pattern.toLowerCase())) {
this.cache.delete(key);
invalidated++;
}
}
logger.info('Cache invalidation completed', {
pattern,
invalidated,
remainingSize: this.cache.size
});
return invalidated;
}
/**
* Clear all cache
*/
clear() {
const size = this.cache.size;
this.cache.clear();
logger.info('Cache cleared', { clearedEntries: size });
}
/**
* Get cache statistics
*/
getStats() {
const hitRate = this.stats.hits + this.stats.misses > 0
? (this.stats.hits / (this.stats.hits + this.stats.misses)) * 100
: 0;
return {
...this.stats,
hitRate: Math.round(hitRate * 100) / 100,
cacheSize: this.cache.size,
maxCacheSize: this.config.maxCacheSize
};
}
/**
* Get cache entries by type
*/
getEntriesByType() {
const byType = {};
for (const [key, entry] of this.cache.entries()) {
const type = entry.searchType || 'unknown';
if (!byType[type]) {
byType[type] = [];
}
byType[type].push({
key: key.slice(0, 20) + '...',
query: entry.query,
age: Date.now() - entry.timestamp,
hitCount: entry.hitCount
});
}
return byType;
}
/**
* Preload common UGA queries
*/
async preloadCommonQueries() {
const commonQueries = [
'UGA registration dates',
'UGA academic calendar',
'UGA dining hours',
'UGA events this week',
'UGA news today'
];
logger.info('Starting cache preload for common queries', {
queries: commonQueries.length
});
// This would be called with actual search results in practice
// For now, just log the intent
commonQueries.forEach(query => {
logger.debug('Would preload query', { query });
});
}
/**
* Cache warming for frequently accessed content
*/
warmCache(searchService) {
// Implementation would depend on integration with search service
logger.info('Cache warming initiated');
}
}
module.exports = new SearchCacheService(); |