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();