All files / agent/src lifecycleExecutor.ts

92.18% Statements 283/307
86.95% Branches 40/46
100% Functions 9/9
92.18% Lines 283/307

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 3081x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 26x 27x 27x 27x 26x 26x 27x 5x 5x 26x 26x 26x 27x 27x 27x 27x 27x 5x 27x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 27x 27x 27x 27x 27x 27x 27x 27x 14x 14x 14x 14x 14x 14x 14x 14x 27x 27x 27x 27x 27x 27x 27x 22x 20x 27x 27x 27x 27x 27x 27x 27x 27x 27x 1x 1x 1x 1x 1x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 2x 2x 2x 2x 2x           2x 2x 2x 2x 2x 62x 62x 62x 1x 1x 1x   1x 62x 62x 62x 62x 1x 1x   1x 1x 62x 62x 62x 1x                           1x 1x 1x 1x 1x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x       62x 62x 54x 54x 54x 62x 62x 62x 1x 1x 1x 62x 62x 62x 62x 62x 62x 62x   62x 62x 62x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 80x 80x 1x  
/**
 * Lifecycle Executor - Setup/Execute/Teardown job phases
 *
 * Manages the full lifecycle of a job execution:
 *   1. Setup steps run sequentially
 *   2. Main build command executes
 *   3. Teardown steps ALWAYS run (even on failure)
 */
 
import { spawn, ChildProcess } from 'child_process';
import { RecipeLifecycleStep } from './recipes/types.js';
 
// ---------------------------------------------------------------------------
// Result types
// ---------------------------------------------------------------------------
 
export interface LifecyclePhaseResult {
  phase: 'setup' | 'execute' | 'teardown';
  stepName: string;
  exitCode: number;
  stdout: string;
  stderr: string;
  durationMs: number;
  skipped: boolean;
  error?: string;
}
 
export interface LifecycleResult {
  setupResults: LifecyclePhaseResult[];
  executeResult: LifecyclePhaseResult;
  teardownResults: LifecyclePhaseResult[];
  overallSuccess: boolean;
  totalDurationMs: number;
}
 
export interface LifecycleOptions {
  workDir: string;
  environment?: Record<string, string>;
  onProgress?: (phase: string, step: string, progress: number) => void;
  onLog?: (phase: string, step: string, log: string) => void;
  abortSignal?: AbortSignal;
}
 
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
 
const DEFAULT_STEP_TIMEOUT_S = 300;
const SIGKILL_GRACE_MS = 5000;
 
// ---------------------------------------------------------------------------
// LifecycleExecutor
// ---------------------------------------------------------------------------
 
export class LifecycleExecutor {
  /**
   * Execute full lifecycle: setup -> main command -> teardown
   *
   * CRITICAL BEHAVIORS:
   * 1. Setup steps run sequentially. If a step fails and continueOnError=false,
   *    skip remaining setup + main command, but STILL run teardown.
   * 2. Main command runs only if all required setup steps succeed.
   * 3. Teardown ALWAYS runs, even if setup or main command failed.
   * 4. Each step has its own timeout (default 300s).
   * 5. If abortSignal fires, terminate current step and run teardown.
   */
  async execute(
    setupSteps: RecipeLifecycleStep[],
    mainCommand: string,
    teardownSteps: RecipeLifecycleStep[],
    options: LifecycleOptions
  ): Promise<LifecycleResult> {
    const totalStart = Date.now();
    const setupResults: LifecyclePhaseResult[] = [];
    let executeResult: LifecyclePhaseResult;
    const teardownResults: LifecyclePhaseResult[] = [];
 
    let setupFailed = false;
    let aborted = this.isAborted(options);
 
    // ---- SETUP PHASE (0-30%) ----
    const setupCount = setupSteps.length;
    for (let i = 0; i < setupCount; i++) {
      const step = setupSteps[i];
      const progressBase = (i / Math.max(setupCount, 1)) * 30;
 
      if (aborted || setupFailed) {
        setupResults.push(this.skippedResult('setup', step.name));
        continue;
      }
 
      options.onProgress?.('setup', step.name, Math.round(progressBase));
 
      const result = await this.executeStep(step, 'setup', options);
      setupResults.push(result);
 
      if (result.exitCode !== 0 && !step.continueOnError) {
        setupFailed = true;
      }
 
      aborted = this.isAborted(options);
    }
 
    options.onProgress?.('setup', 'complete', 30);
 
    // ---- EXECUTE PHASE (30-90%) ----
    if (setupFailed || aborted) {
      executeResult = this.skippedResult('execute', mainCommand);
    } else {
      options.onProgress?.('execute', mainCommand, 30);
 
      const mainStep: RecipeLifecycleStep = {
        name: mainCommand,
        command: mainCommand,
        timeout: DEFAULT_STEP_TIMEOUT_S,
        continueOnError: false,
      };
      executeResult = await this.executeStep(mainStep, 'execute', options);
 
      options.onProgress?.('execute', mainCommand, 90);
    }
 
    aborted = this.isAborted(options);
 
    // ---- TEARDOWN PHASE (90-100%) ----
    // Teardown ALWAYS runs fully — strip abortSignal so it cannot be cancelled.
    const teardownOptions: LifecycleOptions = { ...options, abortSignal: undefined };
    const teardownCount = teardownSteps.length;
    for (let i = 0; i < teardownCount; i++) {
      const step = teardownSteps[i];
      const progressBase = 90 + ((i / Math.max(teardownCount, 1)) * 10);
 
      teardownOptions.onProgress?.('teardown', step.name, Math.round(progressBase));
 
      const result = await this.executeStep(step, 'teardown', teardownOptions);
      teardownResults.push(result);
    }
 
    options.onProgress?.('teardown', 'complete', 100);
 
    const totalDurationMs = Date.now() - totalStart;
 
    const overallSuccess =
      !setupFailed &&
      executeResult.exitCode === 0 &&
      !executeResult.skipped;
 
    return {
      setupResults,
      executeResult,
      teardownResults,
      overallSuccess,
      totalDurationMs,
    };
  }
 
  /**
   * Execute a single lifecycle step using child_process.spawn.
   */
  private executeStep(
    step: RecipeLifecycleStep,
    phase: string,
    options: LifecycleOptions
  ): Promise<LifecyclePhaseResult> {
    return new Promise<LifecyclePhaseResult>((resolve) => {
      const start = Date.now();
      const timeoutMs = (step.timeout ?? DEFAULT_STEP_TIMEOUT_S) * 1000;
      let stdout = '';
      let stderr = '';
      let settled = false;
      let proc: ChildProcess;
 
      const finish = (exitCode: number, error?: string) => {
        if (settled) return;
        settled = true;
        clearTimeout(timer);
        removeAbortListener();
        resolve({
          phase: phase as 'setup' | 'execute' | 'teardown',
          stepName: step.name,
          exitCode,
          stdout,
          stderr,
          durationMs: Date.now() - start,
          skipped: false,
          error,
        });
      };
 
      const killProc = (reason: string) => {
        if (settled) return;
        try {
          proc.kill('SIGTERM');
        } catch { /* already dead */ }
        setTimeout(() => {
          if (!settled) {
            try {
              proc.kill('SIGKILL');
            } catch { /* already dead */ }
          }
        }, SIGKILL_GRACE_MS);
        // Don't finish here; let the 'close' event handle it.
        // But set error so close handler knows what happened.
        stderr += `\n[lifecycle] ${reason}`;
      };
 
      // Timeout handler
      const timer = setTimeout(() => {
        killProc(`Step timed out after ${step.timeout ?? DEFAULT_STEP_TIMEOUT_S}s`);
        // If process doesn't close in grace period + 1s, force-resolve
        setTimeout(() => {
          finish(124, `Step timed out after ${step.timeout ?? DEFAULT_STEP_TIMEOUT_S}s`);
        }, SIGKILL_GRACE_MS + 1000);
      }, timeoutMs);
 
      // Abort signal handler
      const onAbort = () => {
        killProc('Aborted by signal');
        setTimeout(() => {
          finish(130, 'Aborted by signal');
        }, SIGKILL_GRACE_MS + 1000);
      };
 
      let removeAbortListener = () => {};
      if (options.abortSignal) {
        if (options.abortSignal.aborted) {
          settled = true;
          resolve({
            phase: phase as 'setup' | 'execute' | 'teardown',
            stepName: step.name,
            exitCode: 130,
            stdout: '',
            stderr: '',
            durationMs: 0,
            skipped: false,
            error: 'Aborted by signal',
          });
          return;
        }
        options.abortSignal.addEventListener('abort', onAbort, { once: true });
        removeAbortListener = () => {
          options.abortSignal?.removeEventListener('abort', onAbort);
        };
      }
 
      // Merge environment
      const env: NodeJS.ProcessEnv = {
        ...process.env,
        ...(options.environment ?? {}),
      };
 
      try {
        proc = spawn('sh', ['-c', step.command], {
          cwd: options.workDir,
          env,
          stdio: ['ignore', 'pipe', 'pipe'],
        });
      } catch (err) {
        finish(1, err instanceof Error ? err.message : String(err));
        return;
      }
 
      proc.stdout?.on('data', (data: Buffer) => {
        const text = data.toString();
        stdout += text;
        options.onLog?.(phase, step.name, text);
      });
 
      proc.stderr?.on('data', (data: Buffer) => {
        const text = data.toString();
        stderr += text;
        options.onLog?.(phase, step.name, text);
      });
 
      proc.on('close', (code: number | null) => {
        finish(code ?? 1);
      });
 
      proc.on('error', (err: Error) => {
        finish(1, err.message);
      });
    });
  }
 
  // ---------------------------------------------------------------------------
  // Helpers
  // ---------------------------------------------------------------------------
 
  private skippedResult(
    phase: 'setup' | 'execute' | 'teardown',
    stepName: string
  ): LifecyclePhaseResult {
    return {
      phase,
      stepName,
      exitCode: -1,
      stdout: '',
      stderr: '',
      durationMs: 0,
      skipped: true,
    };
  }
 
  private isAborted(options: LifecycleOptions): boolean {
    return options.abortSignal?.aborted ?? false;
  }
}