All files / scripts/pipeline orchestrator.ts

97.61% Statements 41/42
81.81% Branches 18/22
100% Functions 5/5
97.56% Lines 40/41

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                                                                                                        12x 12x 12x                           12x 12x         12x   12x 3x 6x   3x 6x 6x 6x 6x                           9x 11x       12x                           17x 17x 17x 17x 15x 15x     17x   2x 2x 2x     2x                                   12x 12x 12x   12x 17x 5x 5x   17x 17x 15x       12x         12x                  
/**
 * @module pipeline/orchestrator
 * @description Unified pipeline orchestrator.
 *
 * The `PipelineOrchestrator` runs a collection of `ContentPipeline` instances
 * either sequentially (default) or in parallel, collects results, logs
 * progress, and surfaces a structured `OrchestratorResult`.
 *
 * Usage (sequential):
 * ```ts
 * import { PipelineOrchestrator } from './pipeline/orchestrator.js';
 * import { MotionsPipeline } from './pipeline/plugins/motions-pipeline.js';
 *
 * const orchestrator = new PipelineOrchestrator({
 *   pipelines: [new MotionsPipeline()],
 * });
 * const result = await orchestrator.run();
 * ```
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import type {
  ContentPipeline,
  OrchestratorConfig,
  OrchestratorResult,
  PipelineOptions,
  PipelineResult,
} from './types.js';
 
// ---------------------------------------------------------------------------
// PipelineOrchestrator
// ---------------------------------------------------------------------------
 
/**
 * Orchestrates the execution of one or more `ContentPipeline` instances.
 *
 * Key behaviours:
 * - **Error isolation**: a failure in one pipeline does not abort others.
 * - **Parallel mode**: when `config.parallel = true` all pipelines run via
 *   `Promise.allSettled` for throughput and robust error handling; otherwise
 *   they execute sequentially for predictable log output.
 * - **Result aggregation**: all per-pipeline `PipelineResult` objects are
 *   merged into a single `OrchestratorResult`.
 */
export class PipelineOrchestrator {
  private readonly pipelines: ContentPipeline[];
  private readonly parallel: boolean;
  private readonly defaultOptions: PipelineOptions;
 
  constructor(config: OrchestratorConfig) {
    this.pipelines = config.pipelines;
    this.parallel = config.parallel ?? false;
    this.defaultOptions = config.defaultOptions ?? {};
  }
 
  // -------------------------------------------------------------------------
  // Public API
  // -------------------------------------------------------------------------
 
  /**
   * Run all pipelines and return an aggregated `OrchestratorResult`.
   *
   * @param overrideOptions - Options forwarded to every pipeline, merged on
   *                          top of `defaultOptions`.
   */
  async run(overrideOptions?: PipelineOptions): Promise<OrchestratorResult> {
    const startTime = Date.now();
    const effectiveOptions: PipelineOptions = {
      ...this.defaultOptions,
      ...(overrideOptions ?? {}),
    };
 
    const results: Record<string, PipelineResult> = {};
 
    if (this.parallel) {
      const settled = await Promise.allSettled(
        this.pipelines.map(p => this._runSingle(p, effectiveOptions)),
      );
      for (let i = 0; i < this.pipelines.length; i++) {
        const pipeline = this.pipelines[i]!;
        const outcome = settled[i]!;
        if (outcome.status === 'fulfilled') {
          results[pipeline.name] = outcome.value;
        } else E{
          // Promise should never reject because _runSingle catches all errors,
          // but handle it defensively.
          results[pipeline.name] = {
            success: false,
            error: String((outcome as PromiseRejectedResult).reason),
            warnings: [],
            degraded: false,
            files: 0,
          };
        }
      }
    } else {
      for (const pipeline of this.pipelines) {
        results[pipeline.name] = await this._runSingle(pipeline, effectiveOptions);
      }
    }
 
    return this._aggregate(results, Date.now() - startTime);
  }
 
  // -------------------------------------------------------------------------
  // Private helpers
  // -------------------------------------------------------------------------
 
  /**
   * Run a single pipeline, wrapping any unexpected throws in a failed result.
   */
  private async _runSingle(
    pipeline: ContentPipeline,
    options: PipelineOptions,
  ): Promise<PipelineResult> {
    console.log(`[Orchestrator] ▶ Starting pipeline: ${pipeline.name}`);
    const t0 = Date.now();
    try {
      const result = await pipeline.run(options);
      const durationMs = Date.now() - t0;
      console.log(
        `[Orchestrator] ${result.success ? '✅' : '❌'} Pipeline "${pipeline.name}" completed in ${durationMs}ms`,
      );
      return { ...result, durationMs };
    } catch (err: unknown) {
      const durationMs = Date.now() - t0;
      const message = err instanceof Error ? err.message : String(err);
      console.error(
        `[Orchestrator] 💥 Pipeline "${pipeline.name}" threw unexpectedly after ${durationMs}ms: ${message}`,
      );
      return {
        success: false,
        error: message,
        durationMs,
        warnings: [`Unexpected throw from pipeline "${pipeline.name}": ${message}`],
        degraded: false,
        files: 0,
      };
    }
  }
 
  /**
   * Aggregate individual pipeline results into a single orchestrator result.
   */
  private _aggregate(
    results: Record<string, PipelineResult>,
    totalDurationMs: number,
  ): OrchestratorResult {
    let totalFiles = 0;
    let allSucceeded = true;
    const warnings: string[] = [];
 
    for (const [name, result] of Object.entries(results)) {
      if (!result.success) {
        allSucceeded = false;
        console.warn(`[Orchestrator] ⚠ Pipeline "${name}" did not succeed: ${result.error ?? 'unknown error'}`);
      }
      totalFiles += result.files ?? 0;
      if (result.warnings) {
        warnings.push(...result.warnings);
      }
    }
 
    console.log(
      `[Orchestrator] 🏁 All pipelines done. ` +
        `success=${allSucceeded}, files=${totalFiles}, duration=${totalDurationMs}ms`,
    );
 
    return {
      allSucceeded,
      totalFiles,
      results,
      warnings,
      durationMs: totalDurationMs,
    };
  }
}