All files / src/common/cache cache-invalidation.service.ts

96.84% Statements 92/95
87.5% Branches 28/32
100% Functions 17/17
96.73% Lines 89/92

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 4052x 2x 2x                                                                                       2x 29x                   29x 28x 29x     29x                   18x                         24x         24x     24x 57x 57x     24x                         27x 12x     27x   7x     3x     1x     1x     1x     1x     3x     1x     1x     1x     1x     1x     1x     1x     2x     1x                                 7x   7x                     7x     7x 3x       7x   7x                       3x   3x 3x       3x   3x 1x     3x                       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 1x     2x             12x   12x 11x   1x     1x                             1x   1x 3x 6x       1x 5x 5x     1x          
import { Injectable, Logger, Inject, forwardRef } from '@nestjs/common';
import { ETagCacheService } from './etag-cache.service';
import { ApplicationStateService } from '../../application-state/application-state.service';
 
/**
 * Entity types that trigger cache invalidation.
 */
export type CacheableEntityType =
  | 'session'
  | 'session_input'
  | 'ai_action'
  | 'execution_log'
  | 'context_template'
  | 'system_prompt'
  | 'custom_snippet'
  | 'context_snippet'
  | 'custom_variable'
  | 'project'
  | 'tool_hook'
  | 'mcp_config'
  | 'sub_agent'
  | 'sub_agent_run'
  | 'application_state'
  | 'llm_call_log';
 
/**
 * Context information for invalidation.
 */
export interface InvalidationContext {
  sessionId?: string;
  parentSessionId?: string;
  childSessionId?: string;
  isActive?: boolean;
  isDefaultChanged?: boolean;
  stateKey?: string;
}
 
/**
 * Service that maps entity changes to cache invalidation patterns.
 *
 * Architecture:
 * - TypeORM Subscriber detects entity changes (insert/update/delete)
 * - Calls this service with entity type and context
 * - This service maps to cache patterns and calls ETagCacheService.invalidatePattern()
 */
@Injectable()
export class CacheInvalidationService {
  private readonly logger = new Logger(CacheInvalidationService.name);
 
  /**
   * Static singleton instance for access from TypeORM subscriber.
   * TypeORM subscribers are instantiated by TypeORM's container, not NestJS DI.
   * This allows the subscriber to access the service without constructor injection.
   */
  private static instance: CacheInvalidationService;
 
  constructor(
    private readonly etagCacheService: ETagCacheService,
    @Inject(forwardRef(() => ApplicationStateService))
    private readonly applicationStateService: ApplicationStateService,
  ) {
    // Set singleton instance on creation
    CacheInvalidationService.instance = this;
  }
 
  /**
   * Get the singleton instance of this service.
   * Used by CacheInvalidationSubscriber which doesn't have NestJS DI access.
   *
   * @returns The service instance, or null if not yet initialized
   */
  static getInstance(): CacheInvalidationService | null {
    return CacheInvalidationService.instance;
  }
 
  /**
   * Invalidate cache entries for a specific entity change.
   *
   * @param entityType The type of entity that changed
   * @param context Context information (sessionId, isActive, etc.)
   */
  async invalidateEntity(
    entityType: CacheableEntityType,
    context: InvalidationContext = {},
  ): Promise<void> {
    this.logger.debug(
      `Invalidating cache for entity: ${entityType}, context: ${JSON.stringify(context)}`,
    );
 
    // Get patterns based on entity type
    const patterns = await this.getPatternsForEntity(entityType, context);
 
    // Invalidate each pattern
    for (const pattern of patterns) {
      this.logger.debug(`Invalidating pattern: ${pattern}`);
      this.etagCacheService.invalidatePattern(pattern);
    }
 
    this.logger.log(
      `Cache invalidation complete for ${entityType}: ${patterns.length} patterns`,
    );
  }
 
  /**
   * Get cache patterns to invalidate for an entity type.
   */
  private async getPatternsForEntity(
    entityType: CacheableEntityType,
    context: InvalidationContext,
  ): Promise<string[]> {
    // Resolve isActive if sessionId provided but not explicitly set
    if (context.sessionId && context.isActive === undefined) {
      context.isActive = await this.checkIfActiveSession(context.sessionId);
    }
 
    switch (entityType) {
      case 'session':
        return this.getSessionPatterns(context);
 
      case 'session_input':
        return this.getSessionInputPatterns(context);
 
      case 'ai_action':
        return this.getAIActionPatterns(context);
 
      case 'execution_log':
        return this.getExecutionLogPatterns(context);
 
      case 'context_template':
        return this.getContextTemplatePatterns(context);
 
      case 'system_prompt':
        return this.getSystemPromptPatterns(context);
 
      case 'custom_snippet':
        return ['/custom-snippets*'];
 
      case 'context_snippet':
        return ['/context-snippets*'];
 
      case 'custom_variable':
        return ['/custom-variables*'];
 
      case 'project':
        return this.getProjectPatterns(context);
 
      case 'tool_hook':
        return ['/tool-hooks*', '/system-prompts*'];
 
      case 'mcp_config':
        return ['/mcp-configs*', '/mcp-tools*', '/system-prompts*'];
 
      case 'sub_agent':
        return ['/sub-agents*', '/sessions*'];
 
      case 'sub_agent_run':
        return this.getSubAgentRunPatterns(context);
 
      case 'application_state':
        return this.getApplicationStatePatterns(context);
 
      case 'llm_call_log':
        return ['/llm-call-logs*'];
 
      default:
        return [];
    }
  }
 
  /**
   * Session invalidation patterns.
   *
   * When a session changes:
   * - Invalidate session list (sessionInputCount may change)
   * - Invalidate this session's endpoints
   * - Invalidate active session (if this is/was active)
   * - Invalidate application state (activeSessionId)
   */
  private getSessionPatterns(context: InvalidationContext): string[] {
    const patterns: string[] = ['/sessions*'];
 
    if (context.sessionId) {
      // Match all endpoints for this specific session
      // Pattern: /sessions/{id}* covers:
      //   - /sessions/{id}
      //   - /sessions/{id}?includeLogs=true
      //   - /sessions/{id}/inputs
      //   - /sessions/{id}/inputs/{inputId}
      //   - /sessions/{id}/file-changes
      //   - /sessions/{id}/child-sessions
      //   - /sessions/{id}/export
      //   - /sessions/{id}/clone
      patterns.push(`/sessions/${context.sessionId}*`);
    }
 
    if (context.isActive) {
      patterns.push('/sessions/active*');
    }
 
    // Application state always changes when session changes
    patterns.push('/application-state*');
 
    return patterns;
  }
 
  /**
   * SessionInput invalidation patterns.
   *
   * When a session input changes:
   * - Invalidate parent session (sessionInputs relation)
   * - Invalidate session list (sessionInputCount)
   * - Invalidate active session (if parent is active)
   */
  private getSessionInputPatterns(context: InvalidationContext): string[] {
    const patterns: string[] = [];
 
    if (context.sessionId) {
      patterns.push(`/sessions/${context.sessionId}*`);
    }
 
    // Session list changes (sessionInputCount)
    patterns.push('/sessions*');
 
    if (context.isActive) {
      patterns.push('/sessions/active*');
    }
 
    return patterns;
  }
 
  /**
   * AIAction invalidation patterns.
   *
   * When an AI action changes:
   * - Invalidate grandparent session (aiActions relation on sessionInputs)
   * - Invalidate session list (action count may affect display)
   * - Invalidate active session (if grandparent is active)
   */
  private getAIActionPatterns(context: InvalidationContext): string[] {
    const patterns: string[] = [];
 
    if (context.sessionId) {
      patterns.push(`/sessions/${context.sessionId}*`);
    }
 
    patterns.push('/sessions*');
 
    Iif (context.isActive) {
      patterns.push('/sessions/active*');
    }
 
    // AI actions endpoints (if any direct endpoints exist)
    patterns.push('/ai-actions*');
 
    return patterns;
  }
 
  /**
   * ExecutionLog invalidation patterns.
   *
   * When an execution log changes:
   * - Invalidate session (executionLogs loaded on sessionInputs.aiActions)
   * - Invalidate active session (if session is active)
   */
  private getExecutionLogPatterns(context: InvalidationContext): string[] {
    const patterns: string[] = [];
 
    if (context.sessionId) {
      patterns.push(`/sessions/${context.sessionId}*`);
    }
 
    Iif (context.isActive) {
      patterns.push('/sessions/active*');
    }
 
    return patterns;
  }
 
  /**
   * ContextTemplate invalidation patterns.
   *
   * When a context template changes:
   * - Invalidate context templates list
   * - Invalidate sessions (if this is a default template)
   */
  private getContextTemplatePatterns(_context: InvalidationContext): string[] {
    const patterns: string[] = ['/context-templates*'];
 
    // If default flags changed, invalidate sessions (they reference templates)
    // Also invalidate on any change since sessions may have loaded this template
    patterns.push('/sessions*');
 
    return patterns;
  }
 
  /**
   * SystemPrompt invalidation patterns.
   *
   * When a system prompt changes:
   * - Invalidate system prompts list
   * - Invalidate sessions (sessions reference system prompts)
   * - Invalidate sub-agents (sub-agents reference system prompts)
   */
  private getSystemPromptPatterns(_context: InvalidationContext): string[] {
    return ['/system-prompts*', '/sessions*', '/sub-agents*'];
  }
 
  /**
   * Project invalidation patterns.
   *
   * When a project changes:
   * - Invalidate projects list
   * - Invalidate sessions (sessions may reference project)
   */
  private getProjectPatterns(_context: InvalidationContext): string[] {
    return ['/projects*', '/sessions*'];
  }
 
  /**
   * SubAgentRun invalidation patterns.
   *
   * When a sub-agent run changes:
   * - Invalidate sub-agent runs list
   * - Invalidate parent session (shows subAgentRuns)
   * - Invalidate child session (created by run)
   * - Invalidate sessions list
   */
  private getSubAgentRunPatterns(context: InvalidationContext): string[] {
    const patterns: string[] = ['/sub-agent-runs*', '/sessions*'];
 
    if (context.parentSessionId) {
      patterns.push(`/sessions/${context.parentSessionId}*`);
    }
 
    if (context.childSessionId) {
      patterns.push(`/sessions/${context.childSessionId}*`);
    }
 
    return patterns;
  }
 
  /**
   * ApplicationState invalidation patterns.
   *
   * When application state changes:
   * - Invalidate application state batch endpoint
   * - Invalidate sessions/active if activeSessionId changed
   */
  private getApplicationStatePatterns(context: InvalidationContext): string[] {
    const patterns: string[] = ['/application-state*'];
 
    // If activeSessionId changed, invalidate session endpoints
    if (context.stateKey === 'activeSessionId') {
      patterns.push('/sessions*', '/sessions/active*');
    }
 
    return patterns;
  }
 
  /**
   * Check if a session is the current active session.
   */
  private async checkIfActiveSession(sessionId: string): Promise<boolean> {
    try {
      const activeSessionId =
        await this.applicationStateService.getActiveSessionId();
      return sessionId === activeSessionId;
    } catch (error) {
      this.logger.warn(
        `Could not check active session: ${error.message}. Assuming not active.`,
      );
      return false;
    }
  }
 
  /**
   * Batch invalidation for multiple entities.
   * Useful for operations that affect multiple entity types.
   */
  async invalidateEntities(
    entities: Array<{
      type: CacheableEntityType;
      context: InvalidationContext;
    }>,
  ): Promise<void> {
    // Collect all unique patterns
    const allPatterns = new Set<string>();
 
    for (const { type, context } of entities) {
      const patterns = await this.getPatternsForEntity(type, context);
      patterns.forEach((p) => allPatterns.add(p));
    }
 
    // Invalidate all patterns
    for (const pattern of allPatterns) {
      this.logger.debug(`Invalidating pattern: ${pattern}`);
      this.etagCacheService.invalidatePattern(pattern);
    }
 
    this.logger.log(
      `Batch invalidation complete: ${allPatterns.size} unique patterns`,
    );
  }
}