All files / src/lib/cache swr-cache.ts

88.96% Statements 274/308
80% Branches 20/25
83.33% Functions 5/6
88.96% Lines 274/308

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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 3091x 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 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 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 3x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 7x 7x 7x 7x 4x 4x 4x 4x 4x 4x 4x 4x 4x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 3x 3x 3x 9x 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 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 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x           2x  
/**
 * Stale-While-Revalidate (SWR) Cache
 *
 * Implements the stale-while-revalidate caching strategy:
 * 1. Fresh data (<staleTime): Return cached data immediately
 * 2. Stale data (<maxStaleTime): Return cached data, revalidate in background
 * 3. Expired data (>maxStaleTime): Fetch fresh data
 *
 * Benefits:
 * - Fast responses for users (serve from cache)
 * - Fresh data (background revalidation)
 * - Resilience (serve stale on fetch failure)
 */
 
import { cacheService } from './cache-service';
import { logger } from '@/lib/logging';
 
// ============================================================================
// Types
// ============================================================================
 
interface SWRCacheEntry<T> {
  data: T;
  timestamp: number;
  isRevalidating?: boolean;
}
 
interface SWROptions<T> {
  /** Time in seconds data is considered fresh */
  staleTime: number;
  /** Maximum time in seconds stale data can be served */
  maxStaleTime: number;
  /** Function to fetch fresh data */
  fetcher: () => Promise<T>;
  /** Optional callback on successful revalidation */
  onSuccess?: (data: T) => void;
  /** Optional callback on revalidation error */
  onError?: (error: Error) => void;
}
 
interface SWRResult<T> {
  data: T | null;
  isStale: boolean;
  isRevalidating: boolean;
}
 
// ============================================================================
// SWR Cache Implementation
// ============================================================================
 
/**
 * Get data with stale-while-revalidate strategy
 *
 * @example
 * ```typescript
 * const products = await getWithSWR('products:featured', {
 *   staleTime: 60,        // Fresh for 1 minute
 *   maxStaleTime: 3600,   // Serve stale up to 1 hour
 *   fetcher: () => fetchFeaturedProducts(),
 * });
 * ```
 */
export async function getWithSWR<T>(
  key: string,
  options: SWROptions<T>
): Promise<SWRResult<T>> {
  const { staleTime, maxStaleTime, fetcher, onSuccess, onError } = options;
  const now = Date.now();
 
  // Try to get from cache
  const cached = cacheService.get<SWRCacheEntry<T>>(key);
 
  if (cached) {
    const ageSeconds = (now - cached.timestamp) / 1000;
 
    // Data is fresh - return immediately
    if (ageSeconds < staleTime) {
      return {
        data: cached.data,
        isStale: false,
        isRevalidating: false,
      };
    }
 
    // Data is stale but within max stale time
    if (ageSeconds < maxStaleTime) {
      // Return stale data immediately
      const result: SWRResult<T> = {
        data: cached.data,
        isStale: true,
        isRevalidating: !cached.isRevalidating,
      };
 
      // Revalidate in background if not already revalidating
      if (!cached.isRevalidating) {
        // Mark as revalidating to prevent duplicate fetches
        cacheService.set(key, { ...cached, isRevalidating: true });
 
        // Start background revalidation
        revalidateInBackground(key, fetcher, maxStaleTime, onSuccess, onError);
      }
 
      return result;
    }
 
    // Data is too old - need fresh data
    logger.debug(`Cache expired for ${key}`, { category: 'PERFORMANCE', ageSeconds, maxStaleTime });
  }
 
  // No cache or expired - fetch fresh data
  try {
    const freshData = await fetcher();
 
    // Cache the fresh data
    const entry: SWRCacheEntry<T> = {
      data: freshData,
      timestamp: now,
      isRevalidating: false,
    };
    cacheService.set(key, entry, maxStaleTime);
 
    onSuccess?.(freshData);
 
    return {
      data: freshData,
      isStale: false,
      isRevalidating: false,
    };
  } catch (error) {
    // If fetch fails and we have stale data, return it
    if (cached) {
      logger.warn(`Fetch failed for ${key}, returning stale data`, {
        category: 'PERFORMANCE',
        error: (error as Error).message,
      });
 
      onError?.(error as Error);
 
      return {
        data: cached.data,
        isStale: true,
        isRevalidating: false,
      };
    }
 
    // No stale data to fall back to
    onError?.(error as Error);
    throw error;
  }
}
 
/**
 * Background revalidation helper
 */
async function revalidateInBackground<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number,
  onSuccess?: (data: T) => void,
  onError?: (error: Error) => void
): Promise<void> {
  try {
    const freshData = await fetcher();
 
    const entry: SWRCacheEntry<T> = {
      data: freshData,
      timestamp: Date.now(),
      isRevalidating: false,
    };
    cacheService.set(key, entry, ttl);
 
    logger.debug(`Background revalidation complete for ${key}`, { category: 'PERFORMANCE' });
    onSuccess?.(freshData);
  } catch (error) {
    // Clear revalidating flag on error
    const cached = cacheService.get<SWRCacheEntry<T>>(key);
    if (cached) {
      cacheService.set(key, { ...cached, isRevalidating: false });
    }

    logger.warn(`Background revalidation failed for ${key}`, {
      category: 'PERFORMANCE',
      error: (error as Error).message,
    });
    onError?.(error as Error);
  }
}
 
// ============================================================================
// SWR Cache Presets
// ============================================================================
 
/**
 * Preset configurations for common use cases
 */
export const SWRPresets = {
  /** For frequently updated data (e.g., product prices, stock) */
  frequent: {
    staleTime: 30,      // Fresh for 30 seconds
    maxStaleTime: 300,  // Serve stale up to 5 minutes
  },
 
  /** For moderately updated data (e.g., product lists, categories) */
  moderate: {
    staleTime: 300,     // Fresh for 5 minutes
    maxStaleTime: 1800, // Serve stale up to 30 minutes
  },
 
  /** For rarely updated data (e.g., hero content, testimonials) */
  static: {
    staleTime: 1800,    // Fresh for 30 minutes
    maxStaleTime: 7200, // Serve stale up to 2 hours
  },
 
  /** For user-specific data (e.g., cart, wishlist) */
  user: {
    staleTime: 10,      // Fresh for 10 seconds
    maxStaleTime: 60,   // Serve stale up to 1 minute
  },
} as const;
 
// ============================================================================
// Convenience Functions
// ============================================================================
 
/**
 * Simple SWR wrapper with moderate preset
 */
export async function swrFetch<T>(
  key: string,
  fetcher: () => Promise<T>
): Promise<T | null> {
  const result = await getWithSWR(key, {
    ...SWRPresets.moderate,
    fetcher,
  });
  return result.data;
}
 
/**
 * SWR fetch with custom stale times
 */
export async function swrFetchWithTimes<T>(
  key: string,
  fetcher: () => Promise<T>,
  staleTime: number,
  maxStaleTime: number
): Promise<T | null> {
  const result = await getWithSWR(key, {
    staleTime,
    maxStaleTime,
    fetcher,
  });
  return result.data;
}
 
/**
 * Invalidate an SWR cache entry and optionally trigger immediate revalidation
 */
export async function invalidateSWR<T>(
  key: string,
  fetcher?: () => Promise<T>
): Promise<void> {
  cacheService.delete(key);
 
  // Optionally warm the cache with fresh data
  if (fetcher) {
    try {
      const freshData = await fetcher();
      const entry: SWRCacheEntry<T> = {
        data: freshData,
        timestamp: Date.now(),
        isRevalidating: false,
      };
      cacheService.set(key, entry);
    } catch (error) {
      logger.warn(`Failed to warm cache for ${key}`, {
        category: 'PERFORMANCE',
        error: (error as Error).message,
      });
    }
  }
}
 
/**
 * Prefetch data into SWR cache (cache warming)
 */
export async function prefetchSWR<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number = SWRPresets.moderate.maxStaleTime
): Promise<void> {
  try {
    const data = await fetcher();
    const entry: SWRCacheEntry<T> = {
      data,
      timestamp: Date.now(),
      isRevalidating: false,
    };
    cacheService.set(key, entry, ttl);
    logger.debug(`Prefetched ${key}`, { category: 'PERFORMANCE' });
  } catch (error) {
    logger.warn(`Prefetch failed for ${key}`, {
      category: 'PERFORMANCE',
      error: (error as Error).message,
    });
  }
}