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

93.54% Statements 58/62
82.85% Branches 29/35
100% Functions 8/8
93.33% Lines 56/60

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 2101x             1x 1x                                   1x 17x                 9x             3x             2x                   14x 1x     13x 13x   1x     12x   12x         12x 12x 1x     1x       11x 1x                     31x   31x   6x   4x   2x   1x   2x   1x   1x   1x   1x   1x   1x   1x   1x   2x   2x   1x     3x                                     12x   12x   5x   5x       3x 3x           1x   1x                       1x   1x               1x 1x 1x     1x 1x         12x      
import {
  EntitySubscriberInterface,
  EventSubscriber,
  InsertEvent,
  UpdateEvent,
  RemoveEvent,
} from 'typeorm';
import { Logger } from '@nestjs/common';
import {
  CacheInvalidationService,
  CacheableEntityType,
  InvalidationContext,
} from './cache-invalidation.service';
 
/**
 * TypeORM Subscriber that listens to entity changes and triggers cache invalidation.
 *
 * Architecture:
 * - Subscriber is registered globally with TypeORM
 * - AfterInsert/AfterUpdate/AfterRemove events trigger invalidation
 * - Uses CacheInvalidationService.getInstance() (singleton pattern) to access service
 * - TypeORM instantiates this subscriber, so constructor dependencies are not possible
 *
 * Note: No constructor needed - TypeORM creates this class without NestJS DI.
 */
@EventSubscriber()
export class CacheInvalidationSubscriber implements EntitySubscriberInterface {
  private readonly logger = new Logger(CacheInvalidationSubscriber.name);
 
  // No constructor - TypeORM creates this without dependencies
  // Access CacheInvalidationService via static singleton pattern
 
  /**
   * After entity is inserted - invalidate relevant cache.
   */
  afterInsert(event: InsertEvent<any>): void {
    this.handleEntityChange('insert', event.entity);
  }
 
  /**
   * After entity is updated - invalidate relevant cache.
   */
  afterUpdate(event: UpdateEvent<any>): void {
    this.handleEntityChange('update', event.entity);
  }
 
  /**
   * After entity is removed - invalidate relevant cache.
   */
  afterRemove(event: RemoveEvent<any>): void {
    this.handleEntityChange('remove', event.entity);
  }
 
  /**
   * Handle entity change and trigger invalidation.
   */
  private handleEntityChange(
    operation: 'insert' | 'update' | 'remove',
    entity: any,
  ): void {
    if (!entity) {
      return;
    }
 
    const entityType = this.getEntityType(entity);
    if (!entityType) {
      // Entity not tracked for caching - skip
      return;
    }
 
    const context = this.extractContext(entity, entityType);
 
    this.logger.debug(
      `Entity ${operation}: ${entityType}, context: ${JSON.stringify(context)}`,
    );
 
    // Get service via singleton - may be null during early startup
    const service = CacheInvalidationService.getInstance();
    if (!service) {
      this.logger.warn(
        'CacheInvalidationService not initialized, skipping invalidation',
      );
      return;
    }
 
    // Fire invalidation (async, non-blocking)
    service.invalidateEntity(entityType, context).catch((err) => {
      this.logger.error(
        `Cache invalidation failed for ${entityType}: ${err.message}`,
      );
    });
  }
 
  /**
   * Determine entity type from entity instance.
   */
  private getEntityType(entity: any): CacheableEntityType | null {
    // Check entity class name or constructor name
    const entityName = entity.constructor?.name;
 
    switch (entityName) {
      case 'Session':
        return 'session';
      case 'SessionInput':
        return 'session_input';
      case 'AIAction':
        return 'ai_action';
      case 'ExecutionLog':
        return 'execution_log';
      case 'ContextTemplate':
        return 'context_template';
      case 'SystemPrompt':
        return 'system_prompt';
      case 'CustomSnippet':
        return 'custom_snippet';
      case 'ContextSnippet':
        return 'context_snippet';
      case 'CustomVariable':
        return 'custom_variable';
      case 'Project':
        return 'project';
      case 'ToolHook':
        return 'tool_hook';
      case 'McpConfig':
        return 'mcp_config';
      case 'SubAgent':
        return 'sub_agent';
      case 'SubAgentRun':
        return 'sub_agent_run';
      case 'ApplicationState':
        return 'application_state';
      case 'LlmCallLog':
        return 'llm_call_log';
      default:
        // Unknown entity - not tracked
        return null;
    }
  }
 
  /**
   * Extract context information from entity for invalidation.
   *
   * Key mappings:
   * - Session: sessionId = entity.id
   * - SessionInput: sessionId = entity.session_id
   * - AIAction: sessionId = lookup via input_id → SessionInput
   * - ExecutionLog: sessionId = lookup via action_id → AIAction → SessionInput
   * - SubAgentRun: parentSessionId, childSessionId from entity
   * - ApplicationState: stateKey = entity.key
   */
  private extractContext(
    entity: any,
    entityType: CacheableEntityType,
  ): InvalidationContext {
    const context: InvalidationContext = {};
 
    switch (entityType) {
      case 'session':
        context.sessionId = entity.id;
        // Note: isActive will be checked in service
        break;
 
      case 'session_input':
        // SessionInput has session_id field directly
        context.sessionId = entity.session_id;
        break;
 
      case 'ai_action':
        // AIAction has input_id, need to get sessionId from loaded relation or field
        // The subscriber may not have the full relation loaded
        // We rely on entity.input?.session_id or need to query
        context.sessionId =
          entity.sessionInput?.session_id || entity.session_id;
        break;
 
      case 'execution_log':
        // ExecutionLog has action_id, need sessionId via AIAction → SessionInput
        context.sessionId =
          entity.aiAction?.sessionInput?.session_id ||
          entity.sessionInput?.session_id ||
          entity.session_id;
        break;
 
      case 'context_template':
        // Check if default flags changed (for update events)
        context.isDefaultChanged =
          entity.is_default_initial || entity.is_default_followup;
        break;
 
      case 'system_prompt':
        // System prompt changes affect sessions
        context.isDefaultChanged = entity.is_default;
        break;
 
      case 'sub_agent_run':
        context.parentSessionId = entity.parent_session_id;
        context.childSessionId = entity.child_session_id;
        break;
 
      case 'application_state':
        context.stateKey = entity.key;
        break;
 
      // Other entities don't need additional context
    }
 
    return context;
  }
}