All files / src/hooks executor.ts

0% Statements 0/379
0% Branches 0/1
0% Functions 0/1
0% Lines 0/379

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * V3 Hooks System - Hook Executor
 *
 * Executes hooks in priority order with timeout handling and error recovery.
 * Integrates with event bus for coordination and monitoring.
 *
 * @module v3/shared/hooks/executor
 */

import type { IEventBus } from '../core/interfaces/event.interface.js';
import { HookRegistry } from './registry.js';
import {
  HookEvent,
  HookContext,
  HookResult,
  HookExecutionOptions,
} from './types.js';

/**
 * Hook execution result aggregation
 */
export interface AggregatedHookResult {
  /** Whether all hooks succeeded */
  success: boolean;

  /** Individual hook results */
  results: HookResult[];

  /** Total execution time in ms */
  totalExecutionTime: number;

  /** Number of hooks executed */
  hooksExecuted: number;

  /** Number of hooks failed */
  hooksFailed: number;

  /** Whether operation was aborted */
  aborted: boolean;

  /** Final merged context (from all hooks) */
  finalContext?: Partial<HookContext>;
}

/**
 * Hook executor implementation
 */
export class HookExecutor {
  private registry: HookRegistry;
  private eventBus?: IEventBus;

  constructor(registry: HookRegistry, eventBus?: IEventBus) {
    this.registry = registry;
    this.eventBus = eventBus;
  }

  /**
   * Execute all hooks for an event
   *
   * @param event - Hook event type
   * @param context - Hook context
   * @param options - Execution options
   * @returns Aggregated results
   */
  async execute(
    event: HookEvent,
    context: HookContext,
    options: HookExecutionOptions = {}
  ): Promise<AggregatedHookResult> {
    const startTime = Date.now();
    const results: HookResult[] = [];
    let aborted = false;
    let finalContext: Partial<HookContext> = {};

    // Get enabled hooks for this event
    const hooks = this.registry.getHandlers(event, false);

    // Emit pre-execution event
    this.eventBus?.emit('hooks:pre-execute', {
      event,
      hookCount: hooks.length,
      context,
    });

    // Execute hooks in priority order
    for (const hook of hooks) {
      if (aborted) {
        break;
      }

      try {
        const result = await this.executeSingleHook(
          hook.handler,
          context,
          hook.timeout || options.timeout
        );

        results.push(result);

        // Record execution statistics
        this.registry.recordExecution(result.success, result.executionTime || 0);

        // Merge context modifications
        if (result.data) {
          finalContext = { ...finalContext, ...result.data };
          // Update context for next hooks
          Object.assign(context, result.data);
        }

        // Check if we should abort
        if (result.abort) {
          aborted = true;
          break;
        }

        // Check if we should stop the chain
        if (result.continueChain === false) {
          break;
        }

        // Check if we should stop on error
        if (!result.success && !options.continueOnError) {
          aborted = true;
          break;
        }
      } catch (error) {
        const errorResult: HookResult = {
          success: false,
          error: error instanceof Error ? error : new Error(String(error)),
          continueChain: options.continueOnError,
        };

        results.push(errorResult);
        this.registry.recordExecution(false, 0);

        // Emit error event
        this.eventBus?.emit('hooks:error', {
          event,
          hookId: hook.id,
          error,
        });

        if (!options.continueOnError) {
          aborted = true;
          break;
        }
      }
    }

    const totalExecutionTime = Date.now() - startTime;
    const hooksFailed = results.filter(r => !r.success).length;

    // Build aggregated result
    const aggregatedResult: AggregatedHookResult = {
      success: hooksFailed === 0 && !aborted,
      results: options.collectResults ? results : [],
      totalExecutionTime,
      hooksExecuted: results.length,
      hooksFailed,
      aborted,
      finalContext,
    };

    // Emit post-execution event
    this.eventBus?.emit('hooks:post-execute', {
      event,
      ...aggregatedResult,
    });

    return aggregatedResult;
  }

  /**
   * Execute hooks with timeout
   *
   * @param event - Hook event type
   * @param context - Hook context
   * @param timeout - Timeout in ms
   * @returns Aggregated results
   */
  async executeWithTimeout(
    event: HookEvent,
    context: HookContext,
    timeout: number
  ): Promise<AggregatedHookResult> {
    return this.withTimeout(
      this.execute(event, context, { timeout }),
      timeout
    );
  }

  /**
   * Execute a single hook with timeout and error handling
   *
   * @param handler - Hook handler function
   * @param context - Hook context
   * @param timeout - Optional timeout in ms
   * @returns Hook result
   */
  private async executeSingleHook(
    handler: (context: HookContext) => Promise<HookResult> | HookResult,
    context: HookContext,
    timeout?: number
  ): Promise<HookResult> {
    const startTime = Date.now();

    try {
      let resultPromise = Promise.resolve(handler(context));

      // Apply timeout if specified
      if (timeout && timeout > 0) {
        resultPromise = this.withTimeout(resultPromise, timeout);
      }

      const result = await resultPromise;
      const executionTime = Date.now() - startTime;

      return {
        ...result,
        executionTime,
      };
    } catch (error) {
      const executionTime = Date.now() - startTime;

      return {
        success: false,
        error: error instanceof Error ? error : new Error(String(error)),
        executionTime,
      };
    }
  }

  /**
   * Execute multiple hooks in parallel
   *
   * @param events - Array of hook events
   * @param contexts - Array of contexts (matched by index)
   * @param options - Execution options
   * @returns Array of aggregated results
   */
  async executeParallel(
    events: HookEvent[],
    contexts: HookContext[],
    options: HookExecutionOptions = {}
  ): Promise<AggregatedHookResult[]> {
    if (events.length !== contexts.length) {
      throw new Error('Events and contexts arrays must have same length');
    }

    const maxParallel = options.maxParallel || events.length;
    const results: AggregatedHookResult[] = [];

    // Execute in batches
    for (let i = 0; i < events.length; i += maxParallel) {
      const batch = events.slice(i, i + maxParallel);
      const batchContexts = contexts.slice(i, i + maxParallel);

      const batchResults = await Promise.allSettled(
        batch.map((event, index) =>
          this.execute(event, batchContexts[index], options)
        )
      );

      for (const result of batchResults) {
        if (result.status === 'fulfilled') {
          results.push(result.value);
        } else {
          // Create error result for rejected promises
          results.push({
            success: false,
            results: [{
              success: false,
              error: result.reason instanceof Error
                ? result.reason
                : new Error(String(result.reason)),
            }],
            totalExecutionTime: 0,
            hooksExecuted: 0,
            hooksFailed: 1,
            aborted: true,
          });
        }
      }
    }

    return results;
  }

  /**
   * Execute hooks sequentially with context chaining
   *
   * @param events - Array of hook events
   * @param initialContext - Initial context
   * @param options - Execution options
   * @returns Final aggregated result with chained context
   */
  async executeSequential(
    events: HookEvent[],
    initialContext: HookContext,
    options: HookExecutionOptions = {}
  ): Promise<AggregatedHookResult> {
    const results: HookResult[] = [];
    let currentContext = { ...initialContext };
    let totalExecutionTime = 0;
    let aborted = false;

    for (const event of events) {
      if (aborted) {
        break;
      }

      const result = await this.execute(event, currentContext, options);

      results.push(...result.results);
      totalExecutionTime += result.totalExecutionTime;

      // Merge context for next event
      if (result.finalContext) {
        currentContext = { ...currentContext, ...result.finalContext };
      }

      if (result.aborted || !result.success) {
        aborted = true;
        break;
      }
    }

    const hooksFailed = results.filter(r => !r.success).length;

    return {
      success: hooksFailed === 0 && !aborted,
      results: options.collectResults ? results : [],
      totalExecutionTime,
      hooksExecuted: results.length,
      hooksFailed,
      aborted,
      finalContext: currentContext,
    };
  }

  /**
   * Wrap a promise with timeout
   */
  private async withTimeout<T>(
    promise: Promise<T>,
    timeout: number
  ): Promise<T> {
    return Promise.race([
      promise,
      new Promise<T>((_, reject) =>
        setTimeout(() => reject(new Error(`Hook execution timeout after ${timeout}ms`)), timeout)
      ),
    ]);
  }

  /**
   * Set event bus for coordination
   */
  setEventBus(eventBus: IEventBus): void {
    this.eventBus = eventBus;
  }

  /**
   * Get hook registry
   */
  getRegistry(): HookRegistry {
    return this.registry;
  }
}

/**
 * Create a new hook executor
 */
export function createHookExecutor(
  registry: HookRegistry,
  eventBus?: IEventBus
): HookExecutor {
  return new HookExecutor(registry, eventBus);
}