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

0% Statements 0/389
100% Branches 0/0
0% Functions 0/1
0% Lines 0/389

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 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/**
 * Cache Invalidation Service
 *
 * Comprehensive cache invalidation with:
 * - Pattern-based key invalidation
 * - Next.js cache integration (revalidatePath/revalidateTag)
 * - Cascade invalidation for related entities
 * - Logging and monitoring
 */

import { revalidatePath, revalidateTag } from 'next/cache';
import { cacheService } from './cache-service';
import { CacheKeys, InvalidationPatterns, CACHE_VERSION } from './cache-keys';
import { logger } from '@/lib/logging';

// ============================================================================
// Types
// ============================================================================

type EntityType = 'product' | 'category' | 'user' | 'order' | 'hero' | 'promotion' | 'support';

interface InvalidationOptions {
  /** Also invalidate Next.js cache (revalidatePath/revalidateTag) */
  revalidateNext?: boolean;
  /** Specific paths to revalidate */
  paths?: string[];
  /** Tags to revalidate */
  tags?: string[];
  /** Log invalidation details */
  silent?: boolean;
}

interface InvalidationResult {
  keysInvalidated: number;
  pathsRevalidated: number;
  tagsRevalidated: number;
  duration: number;
}

// ============================================================================
// Core Invalidation Service
// ============================================================================

/**
 * Invalidation service for coordinated cache clearing
 */
export const invalidationService = {
  /**
   * Invalidate cache for a specific entity type and ID
   */
  async invalidate(
    entity: EntityType,
    id: number | string,
    options: InvalidationOptions = {}
  ): Promise<InvalidationResult> {
    const startTime = Date.now();
    let keysInvalidated = 0;
    let pathsRevalidated = 0;
    let tagsRevalidated = 0;

    try {
      // Get keys to invalidate based on entity type
      const keys = this.getKeysForEntity(entity, id);

      // Invalidate each key
      for (const key of keys) {
        if (key.includes('*')) {
          // Pattern-based invalidation
          cacheService.deletePattern(key.replace(`${CACHE_VERSION}:`, '^').replace(/\*/g, '.*'));
          keysInvalidated++; // Approximate
        } else {
          cacheService.delete(key);
          keysInvalidated++;
        }
      }

      // Revalidate Next.js cache if requested
      if (options.revalidateNext) {
        // Revalidate paths
        if (options.paths) {
          for (const path of options.paths) {
            try {
              revalidatePath(path);
              pathsRevalidated++;
            } catch {
              // Path revalidation may fail in some contexts
            }
          }
        }

        // Revalidate tags
        if (options.tags) {
          for (const tag of options.tags) {
            try {
              revalidateTag(tag, 'default');
              tagsRevalidated++;
            } catch {
              // Tag revalidation may fail in some contexts
            }
          }
        }
      }

      const result: InvalidationResult = {
        keysInvalidated,
        pathsRevalidated,
        tagsRevalidated,
        duration: Date.now() - startTime,
      };

      // Log invalidation
      if (!options.silent) {
        logger.info('Cache invalidated', {
          category: 'PERFORMANCE',
          entity,
          id,
          ...result,
        });
      }

      return result;
    } catch (error) {
      logger.error(`Invalidation failed for ${entity}:${id}`, error as Error, { category: 'PERFORMANCE' });
      throw error;
    }
  },

  /**
   * Get cache keys for an entity type
   */
  getKeysForEntity(entity: EntityType, id: number | string): string[] {
    switch (entity) {
      case 'product':
        return InvalidationPatterns.product(id);
      case 'category':
        return InvalidationPatterns.category(id);
      case 'user':
        return InvalidationPatterns.user(id);
      case 'hero':
        return InvalidationPatterns.hero();
      default:
        return [];
    }
  },

  // ==========================================================================
  // Entity-Specific Mutation Handlers
  // ==========================================================================

  /**
   * Called after a product is created, updated, or deleted
   */
  async onProductMutation(
    productId: number,
    categoryId?: number | null
  ): Promise<void> {
    await this.invalidate('product', productId, {
      revalidateNext: true,
      paths: [
        '/',
        '/products',
        `/products/${productId}`,
        ...(categoryId ? [`/categories/${categoryId}`] : []),
      ],
      tags: ['products', 'homepage'],
    });

    // Also invalidate category if provided
    if (categoryId) {
      await this.invalidate('category', categoryId, { silent: true });
    }
  },

  /**
   * Called after a category is created, updated, or deleted
   */
  async onCategoryMutation(categoryId: number): Promise<void> {
    await this.invalidate('category', categoryId, {
      revalidateNext: true,
      paths: ['/', '/categories', `/categories/${categoryId}`],
      tags: ['categories', 'products'],
    });
  },

  /**
   * Called after user data changes
   */
  async onUserMutation(userId: number): Promise<void> {
    await this.invalidate('user', userId);
  },

  /**
   * Called after hero/homepage content changes
   */
  async onHeroMutation(): Promise<void> {
    await this.invalidate('hero', 'all', {
      revalidateNext: true,
      paths: ['/'],
      tags: ['hero', 'homepage'],
    });
  },

  /**
   * Called after order changes
   */
  async onOrderMutation(orderId: number, userId?: number): Promise<void> {
    // Invalidate order-specific cache
    cacheService.delete(CacheKeys.orders.byId(orderId));
    cacheService.delete(CacheKeys.orders.recent());
    cacheService.delete(CacheKeys.admin.recentOrders());
    cacheService.delete(CacheKeys.admin.dashboardStats());

    // Invalidate user orders if userId provided
    if (userId) {
      cacheService.delete(CacheKeys.user.orders(userId));
      cacheService.delete(CacheKeys.orders.byUser(userId));
    }
  },

  /**
   * Called after promotion changes
   */
  async onPromotionMutation(code?: string): Promise<void> {
    cacheService.delete(CacheKeys.promotions.active());
    if (code) {
      cacheService.delete(CacheKeys.promotions.byCode(code));
    }
  },
};

// ============================================================================
// Legacy Invalidation Functions (for backward compatibility)
// ============================================================================

/**
 * Invalidate all product-related caches
 */
export function invalidateAllProductCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:products:`);
}

/**
 * Invalidate cache for a specific product
 */
export function invalidateProductCache(productId: number): void {
  cacheService.delete(CacheKeys.products.byId(productId));
  invalidateProductListCaches();
}

/**
 * Invalidate all product list caches (but not individual products)
 */
export function invalidateProductListCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:products:all`);
  cacheService.deletePattern(`^${CACHE_VERSION}:products:category`);
  cacheService.deletePattern(`^${CACHE_VERSION}:products:featured`);
  cacheService.deletePattern(`^${CACHE_VERSION}:products:search`);
  cacheService.deletePattern(`^${CACHE_VERSION}:products:filters`);
  cacheService.deletePattern(`^${CACHE_VERSION}:products:count`);
}

/**
 * Invalidate all category-related caches
 */
export function invalidateAllCategoryCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:categories:`);
}

/**
 * Invalidate cache for a specific category
 */
export function invalidateCategoryCache(categoryId: number): void {
  cacheService.delete(CacheKeys.categories.byId(categoryId));
  cacheService.delete(CacheKeys.categories.all());
  cacheService.delete(CacheKeys.categories.withProductCount());
  cacheService.delete(CacheKeys.categories.tree());
}

/**
 * Called when a category is updated
 */
export function onCategoryUpdate(categoryId: number): void {
  invalidateCategoryCache(categoryId);
  invalidateProductListCaches();
}

/**
 * Invalidate all content-related caches
 */
export function invalidateAllContentCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:content:`);
}

/**
 * Invalidate hero section cache
 */
export function invalidateHeroCache(): void {
  cacheService.delete(CacheKeys.content.hero());
  cacheService.delete(CacheKeys.content.heroCarousel());
  cacheService.delete(CacheKeys.content.heroFeatureCards());
  cacheService.delete(CacheKeys.content.promoBanners());
}

/**
 * Invalidate testimonials cache
 */
export function invalidateTestimonialsCache(): void {
  cacheService.delete(CacheKeys.content.testimonials());
}

/**
 * Invalidate all support article caches
 */
export function invalidateAllSupportCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:support:`);
}

/**
 * Invalidate cache for a specific support article
 */
export function invalidateSupportArticleCache(slug: string): void {
  cacheService.delete(CacheKeys.support.articleBySlug(slug));
  cacheService.delete(CacheKeys.support.articles());
}

/**
 * Invalidate all caches for a specific user
 */
export function invalidateUserCaches(userId: number): void {
  cacheService.delete(CacheKeys.user.profile(userId));
  cacheService.delete(CacheKeys.user.orders(userId));
  cacheService.delete(CacheKeys.user.cart(userId));
  cacheService.delete(CacheKeys.user.wishlist(userId));
  cacheService.delete(CacheKeys.user.addresses(userId));
  cacheService.delete(CacheKeys.user.preferences(userId));
}

/**
 * Invalidate specific user cache type
 */
export function invalidateUserCache(
  userId: number,
  type: 'profile' | 'orders' | 'cart' | 'wishlist' | 'addresses' | 'preferences'
): void {
  cacheService.delete(CacheKeys.user[type](userId));
}

/**
 * Invalidate all promotion caches
 */
export function invalidateAllPromotionCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:promotions:`);
}

/**
 * Invalidate cache for a specific promo code
 */
export function invalidatePromoCodeCache(code: string): void {
  cacheService.delete(CacheKeys.promotions.byCode(code));
  cacheService.delete(CacheKeys.promotions.active());
}

/**
 * Invalidate admin dashboard caches
 */
export function invalidateAdminCaches(): void {
  cacheService.deletePattern(`^${CACHE_VERSION}:admin:`);
}

/**
 * Flush all caches (use with caution!)
 */
export function flushAllCaches(): void {
  cacheService.flush();
}

/**
 * Get current cache statistics
 */
export function getCacheStats() {
  return cacheService.getStats();
}

/**
 * Get all cached keys (for debugging)
 */
export function getCachedKeys(): string[] {
  return cacheService.keys();
}