All files / src/lib/core cache.ts

76.89% Statements 223/290
72.41% Branches 21/29
64.7% Functions 11/17
76.89% Lines 223/290

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2911x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1534x 1534x 1534x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x                     9x 9x 9x 9x 9x 9x 9x 9x 9x                           1x 1x 1x 1x 1x 1x 29x 29x 29x 29x 22x 22x 29x 2x 2x 2x 20x 20x 20x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x     8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 1x 1x 1x 1x 1x 1x 29x 2x     2x 29x 27x 27x           27x 27x 29x 1x 1x 1x 1x 1x 1x                                             1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x     9x 9x 9x 8x 8x 8x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 5x 2x 2x 2x 5x 3x 3x 3x 1x 1x 1x                        
/**
 * Hybrid Cache Utility
 *
 * Uses Redis when available, falls back to in-memory cache.
 * Provides a unified API for caching operations.
 */
 
import { logger } from '@/lib/logging';
import { redisGet, redisSet, redisDel, redisKeys, isRedisAvailable, CACHE_TTL } from '@/lib/integrations';
 
// Re-export CACHE_TTL for convenience
export { CACHE_TTL };
 
interface CacheEntry<T> {
  data: T;
  timestamp: number;
  ttl: number;
}
 
// Cache statistics tracking
interface CacheStatistics {
  hits: number;
  misses: number;
}
 
// Use globalThis to persist cache across hot reloads in development
const globalForCache = globalThis as unknown as {
  memoryCache: Map<string, CacheEntry<unknown>>;
  cacheStats: CacheStatistics;
};
 
// Initialize cache map (persists across hot reloads in dev)
if (!globalForCache.memoryCache) {
  globalForCache.memoryCache = new Map<string, CacheEntry<unknown>>();
}
 
// Initialize stats (persists across hot reloads in dev)
if (!globalForCache.cacheStats) {
  globalForCache.cacheStats = { hits: 0, misses: 0 };
}
 
const memoryCache = globalForCache.memoryCache;
const cacheStats = globalForCache.cacheStats;
 
/**
 * Clear all memory cache entries (useful for tests)
 */
export function clearMemoryCache(): void {
  memoryCache.clear();
}
 
// Cache key generators
export const CACHE_KEYS = {
  categories: () => 'categories:all',
  categoryProducts: (id: number) => `categories:${id}:products`,
  product: (id: number) => `products:${id}`,
  productList: (params: string) => `products:list:${params}`,
  filters: () => 'products:filters',
  search: (query: string) => `search:${query}`,
};
 
 
/**
 * Get cached data from Redis or memory cache
 * @param key Cache key
 * @returns Cached data or null if not found/expired
 */
export async function getCached<T>(key: string): Promise<T | null> {
  // Try Redis first
  if (await isRedisAvailable()) {
    const data = await redisGet<T>(key);
    if (data !== null) {
      cacheStats.hits++;
      logger.debug(`Redis hit for ${key}`, { category: 'CACHE' });
      return data;
    }
    cacheStats.misses++;
    logger.debug(`Redis miss for ${key}`, { category: 'CACHE' });
    return null;
  }
 
  // Fall back to memory cache
  const entry = memoryCache.get(key) as CacheEntry<T> | undefined;
 
  if (!entry) {
    cacheStats.misses++;
    logger.debug(`Memory miss for ${key}`, { category: 'CACHE' });
    return null;
  }

  const now = Date.now();
  if (now - entry.timestamp > entry.ttl) {
    memoryCache.delete(key);
    cacheStats.misses++;
    logger.debug(`Memory expired for ${key}`, { category: 'CACHE' });
    return null;
  }

  cacheStats.hits++;
  logger.debug(`Memory hit for ${key}`, { category: 'CACHE' });
  return entry.data;
}
 
/**
 * Synchronous version for memory-only cache access
 * @param key Cache key
 * @returns Cached data or null if not found/expired
 */
export function getCachedSync<T>(key: string): T | null {
  const entry = memoryCache.get(key) as CacheEntry<T> | undefined;
 
  if (!entry) return null;
 
  const now = Date.now();
  if (now - entry.timestamp > entry.ttl) {
    memoryCache.delete(key);
    return null;
  }
 
  return entry.data;
}
 
/**
 * Set data in cache (Redis + memory)
 * @param key Cache key
 * @param data Data to cache
 * @param ttlSeconds Time to live in seconds (default: 5 minutes)
 */
export async function setCached<T>(
  key: string,
  data: T,
  ttlSeconds: number = 300
): Promise<void> {
  // Set in Redis if available
  if (await isRedisAvailable()) {
    await redisSet(key, data, ttlSeconds);
  }
 
  // Also set in memory cache
  memoryCache.set(key, {
    data,
    timestamp: Date.now(),
    ttl: ttlSeconds * 1000, // Convert to milliseconds for memory cache
  });
}
 
/**
 * Synchronous version for memory-only cache write
 * @param key Cache key
 * @param data Data to cache
 * @param ttlMs Time to live in milliseconds (default: 5 minutes)
 */
export function setCachedSync<T>(
  key: string,
  data: T,
  ttlMs: number = 5 * 60 * 1000
): void {
  memoryCache.set(key, {
    data,
    timestamp: Date.now(),
    ttl: ttlMs});
}
 
/**
 * Clear cached data
 * @param key Optional cache key to clear. If not provided, clears all cache
 */
export async function clearCache(key?: string): Promise<void> {
  if (key) {
    if (await isRedisAvailable()) {
      await redisDel(key);
    }
    memoryCache.delete(key);
  } else {
    // Clear pattern in Redis
    if (await isRedisAvailable()) {
      const keys = await redisKeys('*');
      if (keys.length > 0) {
        await redisDel(...keys);
      }
    }
    memoryCache.clear();
  }
}
 
/**
 * Invalidate cache entries matching a pattern
 * @param pattern Pattern to match (e.g., 'products:*')
 */
export async function invalidatePattern(pattern: string): Promise<void> {
  // Invalidate in Redis
  if (await isRedisAvailable()) {
    const keys = await redisKeys(pattern);
    if (keys.length > 0) {
      await redisDel(...keys);
      logger.debug(`Invalidated ${keys.length} Redis keys matching ${pattern}`, { category: 'CACHE' });
    }
  }

  // Invalidate in memory cache
  const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
  let removed = 0;
  for (const key of memoryCache.keys()) {
    if (regex.test(key)) {
      memoryCache.delete(key);
      removed++;
    }
  }
  if (removed > 0) {
    logger.debug(`Invalidated ${removed} memory cache keys matching ${pattern}`, { category: 'CACHE' });
  }
}
 
/**
 * Get or set cache with fetcher function
 * @param key Cache key
 * @param fetcher Function to fetch data if not cached
 * @param ttlSeconds Time to live in seconds
 * @returns Cached or fetched data
 */
export async function getOrSet<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttlSeconds: number
): Promise<T> {
  // Try cache first
  const cached = await getCached<T>(key);
  if (cached !== null) {
    return cached;
  }
 
  // Fetch and cache
  const data = await fetcher();
  await setCached(key, data, ttlSeconds);
  return data;
}
 
/**
 * Get cache statistics
 * @returns Object with cache size, keys, hits, and misses
 */
export function getCacheStats(): {
  size: number;
  keys: string[];
  hits: number;
  misses: number;
  hitRate: number;
} {
  const total = cacheStats.hits + cacheStats.misses;
  return {
    size: memoryCache.size,
    keys: Array.from(memoryCache.keys()),
    hits: cacheStats.hits,
    misses: cacheStats.misses,
    hitRate: total > 0 ? cacheStats.hits / total : 0,
  };
}
 
/**
 * Cleanup expired entries in memory cache
 * Call this periodically to prevent memory leaks
 * @returns Number of entries removed
 */
export function cleanupExpiredEntries(): number {
  const now = Date.now();
  let removed = 0;
 
  for (const [key, entry] of memoryCache.entries()) {
    if (now - entry.timestamp > entry.ttl) {
      memoryCache.delete(key);
      removed++;
    }
  }
 
  return removed;
}
 
// Auto-cleanup expired entries every hour
if (typeof window === 'undefined' && process.env.NODE_ENV !== 'test') {
  // Only run cleanup on server-side (not in tests)
  const cleanupTimer = setInterval(() => {
    const removed = cleanupExpiredEntries();
    if (removed > 0) {
      logger.debug(`Cleaned up ${removed} expired memory entries`, { category: 'CACHE' });
    }
  }, 60 * 60 * 1000); // 1 hour

  // Unref to not prevent process exit
  cleanupTimer.unref();
}