export async function waitPipelineExecution()

in lib/apitools.ts [86:142]


export async function waitPipelineExecution(pipeline: string, executionId: string, maxWaitSeconds: number = 30*60): Promise<boolean> {
  const client = new CodePipelineClient({ region: process.env.AWS_REGION });
  const input: GetPipelineExecutionCommandInput = {
    pipelineName: pipeline,
    pipelineExecutionId: executionId,
  };

  console.log('Waiting for pipeline execution to complete.');
  const startTime = Date.now();
  for (;;) {

    // We wait in 20s intervals by default for the pipeline to finish
    // First verify that we haven't waited too long
    if ((Date.now() - startTime) > maxWaitSeconds*1000) {
      console.error('Maximum wait time of 30 minutes exceeded. Aborting.');
      return false;
    }
    await new Promise(r => setTimeout(r, 20000));

    const command = new GetPipelineExecutionCommand(input);
    const response = await client.send(command);

    const status = response.pipelineExecution?.status || 'undefined';

    if (status === 'Succeeded') {
      console.log('Pipeline execution has finished.');
      return true;
    } else if (status === 'InProgress') {
      console.log('Execution in progress, waiting..');
    } else if (status === 'Cancelled' || status === 'Superseded') {
      /*
       * CDK Pipeline self-mutate will cancel the original
       * execution, and start a new one. If this happens, we need
       * to lookup the latest execution ID, and wait for it instead.
       *
       * A Superseded status indicates that our execution has been
       * stopped in favor of a more recent one. This should not happen
       * unless you trigger pipeline executions outside of this solution.
       * If it does happen, we can treat it as we do the Cancelled status.
       */
      console.log('Execution was '+status+', looking up new latest executionId');
      const newExecutionId = await getLatestPipelineExecutionId(pipeline);
      if (newExecutionId === undefined) {
        console.error('Could not determine latest pipeline executionId');
        return false;
      } else {
        console.log('Latest executionId is ' + newExecutionId);
        input.pipelineExecutionId = newExecutionId;
        continue;
      }
    } else {
      // All other status codes (Stopped, Stopping, Failed) indicate a failure
      console.error('Pipeline status is ' + status + ', aborting.');
      return false;
    }
  }
}