All files / src/common/hooks/performance useCacheInvalidation.ts

84.56% Statements 241/285
77.96% Branches 46/59
88.88% Functions 8/9
84.56% Lines 241/285

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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 4071x 1x   1x 1x                                                 1x 22x 22x 22x 22x 22x 22x   22x 22x 22x 22x 22x 22x 22x 22x 22x 22x     22x 7x 7x   7x 7x 7x   7x   7x     7x 7x 12x 7x 7x   7x 7x 7x   7x                   7x                 22x     22x 15x     15x 15x 7x     7x         7x 15x   8x     8x 1x 1x 1x 1x 1x 8x 22x     22x 22x 38x   38x 38x 37x 37x   38x                   38x 1x 1x 1x 1x 1x 1x 1x 1x 38x 22x 22x     22x 22x 15x 15x 15x 22x 22x     22x 22x 8x 8x 8x 22x 22x   22x 22x 6x 6x 6x 22x 22x   22x 22x 3x 3x 3x 22x 22x   22x 22x 1x 1x 1x 22x 22x     22x 22x 5x   5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x   5x 5x 1x 1x 1x 1x   1x   5x 5x 1x 1x 1x 1x 1x 1x   5x 5x 5x         5x 5x         5x   1x 1x 1x 1x   5x   1x 1x 5x     5x 5x 22x 22x 22x 22x 22x 22x 22x 22x 22x     22x 4x 4x 22x     22x 1x 1x 1x 1x 22x     22x 22x         22x   22x   22x 22x 22x     22x 22x 22x 22x     22x 22x 22x 22x           7x     7x 7x   7x 15x     14x   15x 12x 12x   14x 14x   7x   12x 11x 1x   12x 7x 7x                                 1x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x         1x   1x 2x 2x   1x 1x 1x 1x 1x 1x 1x 1x     1x 1x         1x  
import { useCallback, useRef, useMemo } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
import { useDebouncedCallback } from '../usePerformanceOptimizations';
import { useLogger } from '@common/utils/logger/useLogger';
 
interface InvalidationBatch {
  queryKeys: Array<readonly unknown[]>;
  timestamp: number;
}
 
interface CacheInvalidationOptions {
  batchDelay?: number;
  debounceDelay?: number;
  maxBatchSize?: number;
  enableLogging?: boolean;
}
 
interface InvalidationMetrics {
  totalInvalidations: number;
  batchedInvalidations: number;
  debouncedInvalidations: number;
  lastInvalidation: number;
}
 
/**
 * Optimized cache invalidation hook with batching and debouncing
 * Reduces redundant invalidations and improves performance
 */
export const useCacheInvalidation = (options: CacheInvalidationOptions = {}) => {
  const {
    batchDelay = 100,
    debounceDelay = 500,
    maxBatchSize = 50,
    enableLogging = process.env.NODE_ENV === 'development',
  } = options;
 
  const queryClient = useQueryClient();
  const log = useLogger('useCacheInvalidation');
  const batchRef = useRef<InvalidationBatch>({ queryKeys: [], timestamp: 0 });
  const metricsRef = useRef<InvalidationMetrics>({
    totalInvalidations: 0,
    batchedInvalidations: 0,
    debouncedInvalidations: 0,
    lastInvalidation: 0,
  });
  const batchTimeoutRef = useRef<NodeJS.Timeout>();
 
  // Process batched invalidations
  const processBatch = useCallback(async () => {
    const batch = batchRef.current;
    if (batch.queryKeys.length === 0) return;
 
    const startTime = performance.now();
    const queryKeys = [...batch.queryKeys];
    batchRef.current = { queryKeys: [], timestamp: 0 };
 
    try {
      // Group similar query keys to optimize invalidation
      const groupedKeys = groupQueryKeys(queryKeys);
 
      // Invalidate each group
      await Promise.all(
        groupedKeys.map(group =>
          queryClient.invalidateQueries({ queryKey: group.baseKey })
        )
      );
 
      const duration = performance.now() - startTime;
      metricsRef.current.batchedInvalidations += queryKeys.length;
      metricsRef.current.lastInvalidation = Date.now();
 
      if (enableLogging) {
        log.debug('Batch invalidation completed', {
          action: 'batch_invalidation',
          metadata: {
            batchSize: queryKeys.length,
            groupCount: groupedKeys.length,
            duration: duration.toFixed(2),
          },
        });
      }
    } catch (error) {
      log.error('Batch invalidation failed', {
        action: 'batch_invalidation_error',
        metadata: {
          batchSize: queryKeys.length,
          error: error instanceof Error ? error.message : 'Unknown error',
        },
      }, error instanceof Error ? error : new Error(String(error)));
    }
  }, [queryClient, enableLogging, log]);
 
  // Add query key to batch
  const addToBatch = useCallback((queryKey: readonly unknown[]) => {
    const now = Date.now();
 
    // If batch is empty or timeout expired, start new batch
    if (batchRef.current.queryKeys.length === 0 ||
        now - batchRef.current.timestamp > batchDelay) {
      batchRef.current = { queryKeys: [queryKey], timestamp: now };
 
      // Clear existing timeout
      if (batchTimeoutRef.current) {
        clearTimeout(batchTimeoutRef.current);
      }
 
      // Set new timeout
      batchTimeoutRef.current = setTimeout(processBatch, batchDelay);
    } else {
      // Add to existing batch
      batchRef.current.queryKeys.push(queryKey);
 
      // Process immediately if batch is full
      if (batchRef.current.queryKeys.length >= maxBatchSize) {
        if (batchTimeoutRef.current) {
          clearTimeout(batchTimeoutRef.current);
        }
        processBatch();
      }
    }
  }, [batchDelay, maxBatchSize, processBatch]);
 
  // Immediate invalidation (no batching)
  const invalidateImmediate = useCallback(
    async (queryKey: readonly unknown[]) => {
      const startTime = performance.now();
 
      try {
        await queryClient.invalidateQueries({ queryKey });
        metricsRef.current.totalInvalidations++;
        metricsRef.current.lastInvalidation = Date.now();
 
        if (enableLogging) {
          const duration = performance.now() - startTime;
          log.debug('Immediate invalidation completed', {
            action: 'immediate_invalidation',
            metadata: {
              queryKey,
              duration: duration.toFixed(2),
            },
          });
        }
      } catch (error) {
        log.error('Immediate invalidation failed', {
          action: 'immediate_invalidation_error',
          metadata: {
            queryKey,
            error: error instanceof Error ? error.message : 'Unknown error',
          },
        }, error instanceof Error ? error : new Error(String(error)));
      }
    },
    [queryClient, enableLogging, log]
  );
 
  // Batched invalidation
  const invalidateBatched = useCallback(
    (queryKey: readonly unknown[]) => {
      metricsRef.current.totalInvalidations++;
      addToBatch(queryKey);
    },
    [addToBatch]
  );
 
  // Debounced invalidation for specific query types
  const invalidateNewsletterList = useDebouncedCallback(
    async () => {
      await invalidateImmediate(['newsletters']);
      metricsRef.current.debouncedInvalidations++;
    },
    debounceDelay
  );
 
  const invalidateUnreadCount = useDebouncedCallback(
    async () => {
      await invalidateImmediate(['unreadCount']);
      metricsRef.current.debouncedInvalidations++;
    },
    debounceDelay
  );
 
  const invalidateTags = useDebouncedCallback(
    async () => {
      await invalidateImmediate(['tags']);
      metricsRef.current.debouncedInvalidations++;
    },
    debounceDelay
  );
 
  const invalidateNewsletterSources = useDebouncedCallback(
    async () => {
      await invalidateImmediate(['newsletter-sources']);
      metricsRef.current.debouncedInvalidations++;
    },
    debounceDelay
  );
 
  // Smart invalidation based on operation type
  const invalidateByOperation = useCallback(
    async (operation: string, entityId?: string) => {
      const invalidations: Array<() => void | Promise<void>> = [];
 
      switch (operation) {
        case 'newsletter-archive':
        case 'newsletter-unarchive':
        case 'newsletter-like':
        case 'newsletter-unlike':
          if (entityId) {
            invalidateImmediate(['newsletter', entityId]);
          }
          invalidations.push(invalidateNewsletterList);
          invalidations.push(invalidateUnreadCount);
          break;
 
        case 'newsletter-mark-read':
        case 'newsletter-mark-unread':
          if (entityId) {
            invalidateImmediate(['newsletter', entityId]);
          }
          invalidations.push(invalidateUnreadCount);
          // Don't invalidate full list for read status changes
          break;
 
        case 'newsletter-tag-add':
        case 'newsletter-tag-remove':
          if (entityId) {
            invalidateImmediate(['newsletter', entityId]);
          }
          invalidations.push(invalidateTags);
          invalidations.push(invalidateNewsletterList);
          break;
 
        case 'tag-create':
        case 'tag-update':
        case 'tag-delete':
          invalidations.push(invalidateTags);
          invalidations.push(invalidateNewsletterList);
          break;
 
        case 'newsletter-source-update':
        case 'newsletter-source-archive':
          invalidations.push(invalidateNewsletterSources);
          invalidations.push(invalidateNewsletterList);
          break;
 
        case 'bulk-operation':
          // For bulk operations, use batched invalidation
          invalidateBatched(['newsletters']);
          invalidations.push(invalidateUnreadCount);
          invalidations.push(invalidateTags);
          break;
 
        default:
          // Fallback to full invalidation
          invalidations.push(invalidateNewsletterList);
          break;
      }
 
      // Execute all invalidations
      await Promise.all(invalidations.map(fn => fn()));
    },
    [
      invalidateImmediate,
      invalidateBatched,
      invalidateNewsletterList,
      invalidateUnreadCount,
      invalidateTags,
      invalidateNewsletterSources,
    ]
  );
 
  // Get current metrics
  const getMetrics = useCallback(() => ({
    ...metricsRef.current,
    pendingBatchSize: batchRef.current.queryKeys.length,
  }), []);
 
  // Force process any pending batches
  const flush = useCallback(async () => {
    if (batchTimeoutRef.current) {
      clearTimeout(batchTimeoutRef.current);
    }
    await processBatch();
  }, [processBatch]);
 
  // Cleanup on unmount
  useMemo(() => {
    return () => {
      if (batchTimeoutRef.current) {
        clearTimeout(batchTimeoutRef.current);
      }
    };
  }, []);
 
  return {
    // Core invalidation methods
    invalidateImmediate,
    invalidateBatched,
    invalidateByOperation,
 
    // Specific debounced invalidations
    invalidateNewsletterList,
    invalidateUnreadCount,
    invalidateTags,
    invalidateNewsletterSources,
 
    // Utilities
    getMetrics,
    flush,
  };
};
 
/**
 * Group similar query keys to optimize invalidation
 * This reduces the number of invalidation calls by finding common prefixes
 */
function groupQueryKeys(queryKeys: Array<readonly unknown[]>): Array<{
  baseKey: readonly unknown[];
  keys: Array<readonly unknown[]>;
}> {
  const groups = new Map<string, Array<readonly unknown[]>>();
 
  for (const queryKey of queryKeys) {
    if (queryKey.length === 0) continue;
 
    // Use first element as group key
    const groupKey = JSON.stringify(queryKey[0]);
 
    if (!groups.has(groupKey)) {
      groups.set(groupKey, []);
    }
 
    groups.get(groupKey)!.push(queryKey);
  }
 
  return Array.from(groups.entries()).map(([_, keys]) => {
    // Find the most specific common prefix
    const baseKey = keys.length === 1
      ? keys[0]
      : [keys[0][0]]; // Use just the first element as base
 
    return { baseKey, keys };
  });
}
 
/**
 * Type-safe cache invalidation for specific query types
 */
export interface TypedCacheInvalidation {
  newsletter: (id: string) => Promise<void>;
  newsletters: () => void;
  unreadCount: () => void;
  tags: () => void;
  newsletterSources: () => void;
  readingQueue: () => Promise<void>;
}
 
/**
 * Hook for type-safe cache invalidation
 */
export const useTypedCacheInvalidation = (): TypedCacheInvalidation => {
  const {
    invalidateImmediate,
    invalidateNewsletterList,
    invalidateUnreadCount,
    invalidateTags,
    invalidateNewsletterSources,
  } = useCacheInvalidation();
 
  return {
    newsletter: (id: string) => invalidateImmediate(['newsletter', id]),
    newsletters: invalidateNewsletterList,
    unreadCount: invalidateUnreadCount,
    tags: invalidateTags,
    newsletterSources: invalidateNewsletterSources,
    readingQueue: () => invalidateImmediate(['reading-queue']),
  };
};
 
/**
 * Global cache invalidation instance for use outside of React components
 */
let globalQueryClient: QueryClient | null = null;
 
export const setGlobalQueryClient = (client: QueryClient) => {
  globalQueryClient = client;
};
 
export const globalCacheInvalidation = {
  invalidateNewsletter: (id: string) => {
    if (globalQueryClient) {
      globalQueryClient.invalidateQueries({ queryKey: ['newsletter', id] });
    }
  },
  invalidateNewsletters: () => {
    if (globalQueryClient) {
      globalQueryClient.invalidateQueries({ queryKey: ['newsletters'] });
    }
  },
  invalidateUnreadCount: () => {
    if (globalQueryClient) {
      globalQueryClient.invalidateQueries({ queryKey: ['unreadCount'] });
    }
  },
};