All files / modules/70-pipeline/utils executionUtils.ts

85.04% Statements 233/274
60.76% Branches 466/767
86.11% Functions 31/36
84.88% Lines 219/258

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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772                  26x   26x                               26x           26x 26x 26x 26x   26x 26x 26x 26x   26x                               26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x     26x           26x             26x                               26x                                                                                     26x       19x     44x 8x 16x 16x 16x       36x     44x 32x 32x 32x         19x 12x 12x     19x     26x 26x 26x             26x 45x 45x     45x 45x 45x 40x 40x 106x 106x 106x 48x 20x 86x       86x 86x 47x   39x         45x       4x 4x 5x   5x 1x   4x 1x   3x             26x       14x     14x 14x   14x 3x         11x 4x 4x   4x 3x 1x   1x 1x 1x       1x 1x             9x 6x     6x 5x 3x     1x 2x     1x 1x         5x     26x         40x   40x 7x     33x   33x   32x 32x   32x       32x 11x   11x 12x 12x   12x       26x 17x   17x     14x               3x     11x     26x 85x 85x 85x       85x       2x   83x       26x 19x 19x   19x         19x     26x 2x                     2x 2x     26x       2x 2x   2x   2x                       2x       26x               2x 2x       2x     2x 2x 2x       2x                 2x 2x     26x           4x 4x 4x 4x 4x                 4x                                                     4x   2x 4x   2x   2x                           4x 4x 2x 2x 2x                 2x                                             2x                         2x 2x 2x       4x     26x 2x               26x 21x     21x 21x 21x   21x     21x 21x 78x   78x 78x 78x   2x     2x 2x 2x                                                               76x                   76x                             78x     21x     26x 44x   44x 32x   12x     26x 82x     82x       82x     26x         80x 80x         80x     80x 80x                       26x       24x 9x                                                                                  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import type * as React from 'react'
import type { IconName } from '@wings-software/uicore'
import { defaultTo, has, isEmpty } from 'lodash-es'
 
import {
  ExecutionStatus,
  ExecutionStatusEnum,
  isExecutionSuccess,
  isExecutionCompletedWithBadState,
  isExecutionRunning,
  isExecutionWaiting,
  isExecutionSkipped
} from '@pipeline/utils/statusHelpers'
import type {
  GraphLayoutNode,
  PipelineExecutionSummary,
  ExecutionGraph,
  ExecutionNode,
  ExecutionNodeAdjacencyList
} from 'services/pipeline-ng'
import {
  ExecutionPipelineNode,
  ExecutionPipelineNodeType,
  ExecutionPipelineItem,
  ExecutionPipelineGroupInfo
} from '@pipeline/components/ExecutionStageDiagram/ExecutionPipelineModel'
import factory from '@pipeline/components/PipelineSteps/PipelineStepFactory'
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { stagesCollection } from '@pipeline/components/PipelineStudio/Stages/StagesCollection'
import { isApprovalStep } from './stepUtils'
 
export const LITE_ENGINE_TASK = 'liteEngineTask'
export const STATIC_SERVICE_GROUP_NAME = 'static_service_group'
export const RollbackIdentifier = 'Rollback'
export const StepGroupRollbackIdentifier = '(Rollback)'
 
export const RollbackContainerCss: React.CSSProperties = {
  borderColor: 'var(--red-450)'
}
 
// TODO: remove use DTO
export interface ServiceDependency {
  identifier: string
  name: string | null
  image: string
  status: string
  startTime: string
  endTime: string | null
  errorMessage: string | null
  errorReason: string | null
}
 
export enum NodeType {
  SERVICE = 'SERVICE',
  SERVICE_CONFIG = 'SERVICE_CONFIG',
  INFRASTRUCTURE = 'INFRASTRUCTURE',
  GENERIC_SECTION = 'GENERIC_SECTION',
  STEP_GROUP = 'STEP_GROUP',
  NG_SECTION = 'NG_SECTION',
  ROLLBACK_OPTIONAL_CHILD_CHAIN = 'ROLLBACK_OPTIONAL_CHILD_CHAIN',
  FORK = 'NG_FORK',
  INFRASTRUCTURE_SECTION = 'INFRASTRUCTURE_SECTION',
  DEPLOYMENT_STAGE_STEP = 'DEPLOYMENT_STAGE_STEP',
  APPROVAL_STAGE = 'APPROVAL_STAGE',
  NG_SECTION_WITH_ROLLBACK_INFO = 'NG_SECTION_WITH_ROLLBACK_INFO',
  NG_EXECUTION = 'NG_EXECUTION'
}
 
export const NonSelectableNodes: NodeType[] = [
  NodeType.NG_SECTION,
  NodeType.FORK,
  NodeType.DEPLOYMENT_STAGE_STEP,
  NodeType.APPROVAL_STAGE
]
export const TopLevelNodes: NodeType[] = [
  NodeType.NG_SECTION,
  NodeType.ROLLBACK_OPTIONAL_CHILD_CHAIN,
  NodeType.INFRASTRUCTURE_SECTION,
  NodeType.NG_SECTION_WITH_ROLLBACK_INFO,
  NodeType.NG_EXECUTION
]
export const StepTypeIconsMap: { [key in NodeType]: IconName } = {
  SERVICE: 'services',
  SERVICE_CONFIG: 'services',
  GENERIC_SECTION: 'step-group',
  NG_SECTION_WITH_ROLLBACK_INFO: 'step-group',
  NG_SECTION: 'step-group',
  NG_EXECUTION: 'step-group',
  ROLLBACK_OPTIONAL_CHILD_CHAIN: 'step-group',
  INFRASTRUCTURE_SECTION: 'step-group',
  STEP_GROUP: 'step-group',
  INFRASTRUCTURE: 'infrastructure',
  NG_FORK: 'fork',
  DEPLOYMENT_STAGE_STEP: 'circle',
  APPROVAL_STAGE: 'approval-stage-icon'
}
 
export const ExecutionStatusIconMap: Record<ExecutionStatus, IconName> = {
  Success: 'tick-circle',
  Running: 'main-more',
  AsyncWaiting: 'main-more',
  TaskWaiting: 'main-more',
  TimedWaiting: 'main-more',
  Failed: 'circle-cross',
  Errored: 'circle-cross',
  IgnoreFailed: 'tick-circle',
  Expired: 'expired',
  Aborted: 'banned',
  Discontinuing: 'banned',
  Suspended: 'banned',
  Queued: 'queued',
  NotStarted: 'pending',
  Paused: 'pause',
  ResourceWaiting: 'waiting',
  Skipped: 'skipped',
  ApprovalRejected: 'circle-cross',
  InterventionWaiting: 'waiting',
  ApprovalWaiting: 'waiting',
  Pausing: 'pause'
}
 
/**
 * @deprecated use import { ExecutionPathProps } from '@common/interfaces/RouteInterfaces' instead
 */
export interface ExecutionPathParams {
  orgIdentifier: string
  projectIdentifier: string
  pipelineIdentifier: string
  executionIdentifier: string
  accountId: string
}
 
export interface ExecutionQueryParams {
  stage?: string
  step?: string
  view?: 'log' | 'graph'
  filterAnomalous?: string
  type?: string
}
 
export function getPipelineStagesMap(
  layoutNodeMap: PipelineExecutionSummary['layoutNodeMap'],
  startingNodeId?: string
): Map<string, GraphLayoutNode> {
  const map = new Map<string, GraphLayoutNode>()
 
  function recursiveSetInMap(node: GraphLayoutNode): void {
    if (node.nodeType === NodeTypes.Parallel) {
      node.edgeLayoutList?.currentNodeChildren?.forEach(item => {
        Eif (item && layoutNodeMap?.[item]) {
          map.set(layoutNodeMap[item].nodeUuid || '', layoutNodeMap[item])
          return
        }
      })
    } else {
      map.set(node.nodeUuid || '', node)
    }
 
    node.edgeLayoutList?.nextIds?.forEach(item => {
      Eif (item && layoutNodeMap?.[item]) {
        recursiveSetInMap(layoutNodeMap[item])
        return
      }
    })
  }
 
  if (startingNodeId && layoutNodeMap?.[startingNodeId]) {
    const node = layoutNodeMap[startingNodeId]
    recursiveSetInMap(node)
  }
 
  return map
}
 
enum NodeTypes {
  Parallel = 'parallel',
  Stage = 'stage'
}
export interface ProcessLayoutNodeMapResponse {
  stage?: GraphLayoutNode
  parallel?: GraphLayoutNode[]
}
 
export const processLayoutNodeMap = (executionSummary?: PipelineExecutionSummary): ProcessLayoutNodeMapResponse[] => {
  const response: ProcessLayoutNodeMapResponse[] = []
  Iif (!executionSummary) {
    return response
  }
  const startingNodeId = executionSummary.startingNodeId
  const layoutNodeMap = executionSummary.layoutNodeMap
  if (startingNodeId && layoutNodeMap?.[startingNodeId]) {
    let node: GraphLayoutNode | undefined = layoutNodeMap[startingNodeId]
    while (node) {
      const currentNodeChildren: string[] | undefined = node?.edgeLayoutList?.currentNodeChildren
      const nextIds: string[] | undefined = node?.edgeLayoutList?.nextIds
      if (node.nodeType === NodeTypes.Parallel && currentNodeChildren && currentNodeChildren.length > 1) {
        response.push({ parallel: currentNodeChildren.map(item => layoutNodeMap[item]) })
        node = layoutNodeMap[node.edgeLayoutList?.nextIds?.[0] || '']
      } else Iif (node.nodeType === NodeTypes.Parallel && currentNodeChildren && layoutNodeMap[currentNodeChildren[0]]) {
        response.push({ stage: layoutNodeMap[currentNodeChildren[0]] })
        node = layoutNodeMap[node.edgeLayoutList?.nextIds?.[0] || '']
      } else {
        response.push({ stage: node })
        if (nextIds && nextIds.length === 1) {
          node = layoutNodeMap[nextIds[0]]
        } else {
          node = undefined
        }
      }
    }
  }
  return response
}
 
function parseStages(stages: ProcessLayoutNodeMapResponse[] | GraphLayoutNode[]): string {
  const n = stages.length
  for (let i = n - 1; i >= 0; i--) {
    const stage = (stages[i] as ProcessLayoutNodeMapResponse)?.stage ?? (stages[i] as GraphLayoutNode)
 
    if ((stage as ProcessLayoutNodeMapResponse).parallel) {
      return parseStages((stage as ProcessLayoutNodeMapResponse)?.parallel as GraphLayoutNode[])
    } else {
      if (isExecutionSkipped(stage.status)) {
        continue
      } else {
        return defaultTo(stage.nodeUuid, '')
      }
    }
  }
  return ''
}
 
export function getActiveStageForPipeline(
  executionSummary?: PipelineExecutionSummary,
  pipelineExecutionStatus?: ExecutionStatus
): string | null {
  Iif (!executionSummary) {
    return null
  }
  const stages = processLayoutNodeMap(executionSummary)
  const n = stages.length
  // for completed pipeline, select the last completed stage
  if (isExecutionSuccess(pipelineExecutionStatus)) {
    return parseStages(stages)
  }
 
  // for errored pipeline, select the errored stage
  // for waiting status, select the waiting state
  if (isExecutionCompletedWithBadState(pipelineExecutionStatus) || isExecutionWaiting(pipelineExecutionStatus)) {
    for (let i = stages.length - 1; i >= 0; i--) {
      const stage = stages[i]
 
      if (stage.stage) {
        if (isExecutionCompletedWithBadState(stage.stage.status) || isExecutionWaiting(stage.stage.status)) {
          return stage.stage.nodeUuid || ''
        }
      } else Eif (stage.parallel && Array.isArray(stage.parallel)) {
        const erroredStage = stage.parallel.find(
          item => isExecutionCompletedWithBadState(item.status) || isExecutionWaiting(item.status)
        )
 
        /* istanbul ignore else */
        if (erroredStage) {
          return erroredStage.nodeUuid || ''
        }
      }
    }
  }
 
  // find the current running stage
  for (let i = 0; i < n; i++) {
    const stage = stages[i]
 
    // for normal stage
    if (stage.stage) {
      if (isExecutionRunning(stage.stage.status)) {
        return stage.stage.nodeUuid || ''
      }
      // for parallel stage
    } else Eif (stage.parallel && Array.isArray(stage.parallel)) {
      const activeStage = stage.parallel.filter(item => isExecutionRunning(item.status))[0]
 
      /* istanbul ignore else */
      if (activeStage) {
        return activeStage.nodeUuid || ''
      }
    }
  }
 
  return null
}
 
export function getActiveStep(
  graph: ExecutionGraph,
  nodeId?: string,
  layoutNodeMap?: Record<string, GraphLayoutNode>
): string | null {
  const { rootNodeId, nodeMap, nodeAdjacencyListMap } = graph
 
  if (!nodeMap || !nodeAdjacencyListMap) {
    return null
  }
 
  const currentNodeId = nodeId || rootNodeId
 
  if (!currentNodeId) return null
 
  const node = nodeMap[currentNodeId]
  const nodeAdjacencyList = nodeAdjacencyListMap[currentNodeId]
 
  Iif (!node || !nodeAdjacencyList) {
    return null
  }
 
  if (Array.isArray(nodeAdjacencyList.children) && nodeAdjacencyList.children.length > 0) {
    const n = nodeAdjacencyList.children.length
 
    for (let i = 0; i < n; i++) {
      const childNodeId = nodeAdjacencyList.children[i]
      const step = getActiveStep(graph, childNodeId, layoutNodeMap)
 
      if (typeof step === 'string') return step
    }
  }
 
  if (nodeAdjacencyList.nextIds && nodeAdjacencyList.nextIds[0]) {
    const step = getActiveStep(graph, nodeAdjacencyList.nextIds[0], layoutNodeMap)
 
    if (typeof step === 'string') return step
  }
 
  if (
    !NonSelectableNodes.includes(node.stepType as NodeType) &&
    currentNodeId !== rootNodeId &&
    !has(layoutNodeMap, node.setupId || '') &&
    (isExecutionRunning(node.status) ||
      isExecutionWaiting(node.status) ||
      isExecutionCompletedWithBadState(node.status))
  ) {
    return currentNodeId
  }
 
  return null
}
 
export function getIconFromStageModule(stageModule: 'cd' | 'ci' | string | undefined, stageType?: string): IconName {
  Eif (stageType) {
    const icon = stagesCollection.getStageAttributes(stageType, (key: string) => key)?.icon
    Iif (icon) {
      return icon
    }
  }
  switch (stageModule) {
    case 'cd':
      return 'pipeline-deploy'
    case 'ci':
      return 'pipeline-build'
    default:
      return 'pipeline-deploy'
  }
}
 
export function getIconStylesFromCollection(stageType?: string): React.CSSProperties {
  Eif (stageType) {
    const iconColor = stagesCollection.getStageAttributes(stageType, key => key)?.iconColor
 
    Iif (iconColor) {
      return { color: iconColor }
    }
  }
 
  return {}
}
 
const addDependencyToArray = (service: ServiceDependency, arr: ExecutionPipelineNode<ExecutionNode>[]): void => {
  const stepItem: ExecutionPipelineItem<ExecutionNode> = {
    identifier: service.identifier as string,
    name: service.name as string,
    type: ExecutionPipelineNodeType.NORMAL,
    status: service.status as ExecutionStatus,
    icon: 'dependency-step',
    data: service as ExecutionNode,
    itemType: 'service-dependency'
  }
 
  // add step node
  const stepNode: ExecutionPipelineNode<ExecutionNode> = { item: stepItem }
  arr.push(stepNode)
}
 
const addDependencies = (
  dependencies: ServiceDependency[],
  stepsPipelineNodes: ExecutionPipelineNode<ExecutionNode>[]
): void => {
  Eif (dependencies && dependencies.length > 0) {
    const items: ExecutionPipelineNode<ExecutionNode>[] = []
 
    dependencies.forEach(_service => addDependencyToArray(_service, items))
 
    const dependenciesGroup: ExecutionPipelineGroupInfo<ExecutionNode> = {
      identifier: STATIC_SERVICE_GROUP_NAME,
      name: 'Dependencies', // TODO: use getString('execution.dependencyGroupName'),
      status: dependencies[0].status as ExecutionStatus, // use status of first service
      data: {},
      icon: 'step-group',
      verticalStepGroup: true,
      isOpen: true,
      items: [{ parallel: items }]
    }
 
    // dependency goes at the beginning
    stepsPipelineNodes.unshift({ group: dependenciesGroup })
  }
}
 
const processLiteEngineTask = (
  nodeData: ExecutionNode | undefined,
  rootNodes: ExecutionPipelineNode<ExecutionNode>[],
  parentNode?: ExecutionNode
): void => {
  // NOTE: liteEngineTask contains information about dependencies
  const serviceDependencyList: ServiceDependency[] =
    // Array check is required for legacy support
    (Array.isArray(nodeData?.outcomes)
      ? nodeData?.outcomes?.find((_item: any) => !!_item.serviceDependencyList)?.serviceDependencyList
      : nodeData?.outcomes?.dependencies?.serviceDependencyList) || []
 
  // 1. Add dependency services
  addDependencies(serviceDependencyList, rootNodes)
 
  // 2. Exclude Initialize duration from the parent
  Eif (nodeData && parentNode) {
    const taskDuration = nodeData.endTs! - nodeData.startTs!
    parentNode.startTs = Math.min(parentNode.startTs! + taskDuration, parentNode.endTs!)
  }
 
  // 3. Add Initialize step ( at the first place in array )
  const stepItem: ExecutionPipelineItem<ExecutionNode> = {
    identifier: nodeData?.uuid as string,
    name: 'Initialize',
    type: getExecutionPipelineNodeType(nodeData?.stepType),
    status: nodeData?.status as ExecutionStatus,
    icon: 'initialize-step',
    data: nodeData as ExecutionNode,
    itemType: 'service-dependency'
  }
  const stepNode: ExecutionPipelineNode<ExecutionNode> = { item: stepItem }
  rootNodes.unshift(stepNode)
}
 
const processNodeData = (
  children: string[],
  nodeMap: ExecutionGraph['nodeMap'],
  nodeAdjacencyListMap: ExecutionGraph['nodeAdjacencyListMap'],
  rootNodes: Array<ExecutionPipelineNode<ExecutionNode>>
): Array<ExecutionPipelineNode<ExecutionNode>> => {
  const items: Array<ExecutionPipelineNode<ExecutionNode>> = []
  children?.forEach(item => {
    const nodeData = nodeMap?.[item]
    const isRollback = nodeData?.name?.endsWith(StepGroupRollbackIdentifier) ?? false
    Iif (nodeData?.stepType === NodeType.FORK) {
      items.push({
        parallel: processNodeData(
          nodeAdjacencyListMap?.[item].children || /* istanbul ignore next */ [],
          nodeMap,
          nodeAdjacencyListMap,
          rootNodes
        )
      })
    } else Iif (
      nodeData?.stepType === NodeType.STEP_GROUP ||
      nodeData?.stepType === NodeType.NG_SECTION ||
      (nodeData && isRollback)
    ) {
      items.push({
        group: {
          name: nodeData.name || /* istanbul ignore next */ '',
          identifier: item,
          data: nodeData,
          containerCss: {
            ...(isRollback ? RollbackContainerCss : {})
          },
          status: nodeData.status as ExecutionStatus,
          isOpen: true,
          skipCondition: nodeData.skipInfo?.evaluatedCondition ? nodeData.skipInfo.skipCondition : undefined,
          when: nodeData.nodeRunInfo,
          ...getIconDataBasedOnType(nodeData),
          items: processNodeData(
            nodeAdjacencyListMap?.[item].children || /* istanbul ignore next */ [],
            nodeMap,
            nodeAdjacencyListMap,
            rootNodes
          )
        }
      })
    } else {
      if (nodeData?.stepType === LITE_ENGINE_TASK) {
        const parentNodeId =
          Object.entries(nodeAdjacencyListMap || {}).find(([_, val]) => {
            return (val?.children?.indexOf(nodeData.uuid!) ?? -1) >= 0
          })?.[0] || ''
        processLiteEngineTask(nodeData, rootNodes, nodeMap?.[parentNodeId])
      } else {
        items.push({
          item: {
            name: nodeData?.name || /* istanbul ignore next */ '',
            ...getIconDataBasedOnType(nodeData),
            identifier: item,
            skipCondition: nodeData?.skipInfo?.evaluatedCondition ? nodeData?.skipInfo.skipCondition : undefined,
            when: nodeData?.nodeRunInfo,
            status: nodeData?.status as ExecutionStatus,
            type: getExecutionPipelineNodeType(nodeData?.stepType),
            data: nodeData
          }
        })
      }
    }
    const nextIds = nodeAdjacencyListMap?.[item].nextIds || /* istanbul ignore next */ []
    nextIds.forEach(id => {
      const nodeDataNext = nodeMap?.[id]
      const isRollbackNext = nodeDataNext?.name?.endsWith(StepGroupRollbackIdentifier) ?? false
      Iif (nodeDataNext?.stepType === NodeType.FORK) {
        items.push({
          parallel: processNodeData(
            nodeAdjacencyListMap?.[id].children || /* istanbul ignore next */ [],
            nodeMap,
            nodeAdjacencyListMap,
            rootNodes
          )
        })
      } else Iif (nodeDataNext?.stepType === NodeType.STEP_GROUP || (isRollbackNext && nodeDataNext)) {
        items.push({
          group: {
            name: nodeDataNext.name || /* istanbul ignore next */ '',
            identifier: id,
            data: nodeDataNext,
            containerCss: {
              ...(isRollbackNext ? RollbackContainerCss : {})
            },
            skipCondition: nodeDataNext.skipInfo?.evaluatedCondition ? nodeDataNext.skipInfo.skipCondition : undefined,
            when: nodeDataNext.nodeRunInfo,
            status: nodeDataNext.status as ExecutionStatus,
            isOpen: true,
            ...getIconDataBasedOnType(nodeDataNext),
            items: processNodeData(
              nodeAdjacencyListMap?.[id].children || /* istanbul ignore next */ [],
              nodeMap,
              nodeAdjacencyListMap,
              rootNodes
            )
          }
        })
      } else {
        items.push({
          item: {
            name: nodeDataNext?.name || /* istanbul ignore next */ '',
            ...getIconDataBasedOnType(nodeDataNext),
            identifier: id,
            skipCondition: nodeDataNext?.skipInfo?.evaluatedCondition ? nodeDataNext.skipInfo.skipCondition : undefined,
            when: nodeDataNext?.nodeRunInfo,
            status: nodeDataNext?.status as ExecutionStatus,
            type: getExecutionPipelineNodeType(nodeDataNext?.stepType),
            data: nodeDataNext
          }
        })
      }
      const nextLevels = nodeAdjacencyListMap?.[id].nextIds
      Eif (nextLevels) {
        items.push(...processNodeData(nextLevels, nodeMap, nodeAdjacencyListMap, rootNodes))
      }
    })
  })
  return items
}
 
const hasOnlyLiteEngineTask = (children?: string[], graph?: ExecutionGraph): boolean => {
  return (
    !!children &&
    children.length === 1 &&
    graph?.nodeMap?.[children[0]]?.stepType === LITE_ENGINE_TASK &&
    graph?.nodeAdjacencyListMap?.[children[0]]?.nextIds?.length === 0
  )
}
 
export const processExecutionData = (graph?: ExecutionGraph): Array<ExecutionPipelineNode<ExecutionNode>> => {
  const items: Array<ExecutionPipelineNode<ExecutionNode>> = []
 
  /* istanbul ignore else */
  if (graph?.nodeAdjacencyListMap && graph?.rootNodeId) {
    const nodeAdjacencyListMap = graph.nodeAdjacencyListMap
    const rootNode = graph.rootNodeId
    // Ignore the graph when its fqn is pipeline, as this doesn't render pipeline graph
    Iif (graph?.nodeMap?.[rootNode].baseFqn === 'pipeline') {
      return items
    }
    let nodeId = nodeAdjacencyListMap[rootNode].children?.[0]
    while (nodeId && nodeAdjacencyListMap[nodeId]) {
      const nodeData = graph?.nodeMap?.[nodeId]
      /* istanbul ignore else */
      if (nodeData) {
        const isRollback = nodeData.name?.endsWith(StepGroupRollbackIdentifier) ?? false
        if (nodeData.stepType && (TopLevelNodes.indexOf(nodeData.stepType as NodeType) > -1 || isRollback)) {
          // NOTE: exception if we have only lite task engine in Execution group
          Iif (hasOnlyLiteEngineTask(nodeAdjacencyListMap[nodeId].children, graph)) {
            const liteTaskEngineId = nodeAdjacencyListMap?.[nodeId]?.children?.[0] || ''
            processLiteEngineTask(graph?.nodeMap?.[liteTaskEngineId], items, nodeData)
          } else Eif (!isEmpty(nodeAdjacencyListMap[nodeId].children)) {
            Eif (nodeData.identifier === 'execution') {
              items.push(
                ...processNodeData(
                  nodeAdjacencyListMap[nodeId].children || /* istanbul ignore next */ [],
                  graph?.nodeMap,
                  graph?.nodeAdjacencyListMap,
                  items
                )
              )
            } else {
              items.push({
                group: {
                  name: nodeData.name || /* istanbul ignore next */ '',
                  identifier: nodeId,
                  data: nodeData,
                  skipCondition: nodeData.skipInfo?.evaluatedCondition ? nodeData.skipInfo.skipCondition : undefined,
                  when: nodeData.nodeRunInfo,
                  containerCss: {
                    ...(RollbackIdentifier === nodeData.identifier || isRollback ? RollbackContainerCss : {})
                  },
                  status: nodeData.status as ExecutionStatus,
                  isOpen: true,
                  ...getIconDataBasedOnType(nodeData),
                  items: processNodeData(
                    nodeAdjacencyListMap[nodeId].children || /* istanbul ignore next */ [],
                    graph?.nodeMap,
                    graph?.nodeAdjacencyListMap,
                    items
                  )
                }
              })
            }
          }
        } else Iif (nodeData.stepType === NodeType.FORK) {
          items.push({
            parallel: processNodeData(
              nodeAdjacencyListMap[nodeId].children || /* istanbul ignore next */ [],
              graph?.nodeMap,
              graph?.nodeAdjacencyListMap,
              items
            )
          })
        } else {
          items.push({
            item: {
              name: nodeData.name || /* istanbul ignore next */ '',
              skipCondition: nodeData.skipInfo?.evaluatedCondition ? nodeData.skipInfo.skipCondition : undefined,
              when: nodeData.nodeRunInfo,
              ...getIconDataBasedOnType(nodeData),
              showInLabel: nodeData.stepType === NodeType.SERVICE || nodeData.stepType === NodeType.INFRASTRUCTURE,
              identifier: nodeId,
              status: nodeData.status as ExecutionStatus,
              type: getExecutionPipelineNodeType(nodeData?.stepType),
              data: nodeData
            }
          })
        }
      }
      nodeId = nodeAdjacencyListMap[nodeId].nextIds?.[0]
    }
  }
  return items
}
 
export function getStageType(node?: GraphLayoutNode): 'ci' | 'cd' | 'unknown' {
  Iif (node?.module?.toLowerCase?.() === 'ci' || !isEmpty(node?.moduleInfo?.ci)) {
    return 'ci'
  } else if (node?.module?.toLowerCase?.() === 'cd' || !isEmpty(node?.moduleInfo?.cd)) {
    return 'cd'
  }
  return 'unknown'
}
 
export function getExecutionPipelineNodeType(stepType?: string): ExecutionPipelineNodeType {
  Iif (stepType === StepType.Barrier || stepType === StepType.ResourceConstraint) {
    return ExecutionPipelineNodeType.ICON
  }
  Iif (isApprovalStep(stepType)) {
    return ExecutionPipelineNodeType.DIAMOND
  }
 
  return ExecutionPipelineNodeType.NORMAL
}
 
export function getIconDataBasedOnType(nodeData?: ExecutionNode): {
  icon: IconName
  iconSize: number
  iconStyle?: { marginBottom: string }
} {
  Eif (nodeData) {
    Iif (nodeData.stepType === StepType.Barrier) {
      return nodeData.status === 'Success'
        ? { icon: 'barrier-close', iconSize: 57 }
        : { icon: 'barrier-open', iconSize: 70, iconStyle: { marginBottom: '38px' } }
    }
    Iif (nodeData.stepType === StepType.ResourceConstraint) {
      return { icon: 'traffic-lights', iconSize: 40 }
    }
    const icon = StepTypeIconsMap[nodeData?.stepType as NodeType] || factory.getStepIcon(nodeData?.stepType || '')
    return {
      icon,
      iconSize: 20
    }
  }
  return {
    icon: 'cross',
    iconSize: 20
  }
}
 
/** Add dependency services to nodeMap */
export const addServiceDependenciesFromLiteTaskEngine = (
  nodeMap: { [key: string]: ExecutionNode },
  adjacencyMap?: { [key: string]: ExecutionNodeAdjacencyList }
): void => {
  const liteEngineTask = Object.values(nodeMap).find(item => item.stepType === LITE_ENGINE_TASK)
  Iif (liteEngineTask) {
    const parentNodeId =
      Object.entries(adjacencyMap || {}).find(([_, val]) => {
        return (val?.children?.indexOf(liteEngineTask.uuid!) ?? -1) >= 0
      })?.[0] || ''
    const parentNode: ExecutionNode | undefined = nodeMap[parentNodeId]
 
    // NOTE: liteEngineTask contains information about dependency services
    const serviceDependencyList: ExecutionNode[] =
      // Array check is required for legacy support
      (Array.isArray(liteEngineTask.outcomes)
        ? liteEngineTask.outcomes.find((_item: any) => !!_item.serviceDependencyList)?.serviceDependencyList
        : liteEngineTask.outcomes?.dependencies?.serviceDependencyList) || []
 
    // 1. add service dependencies to nodeMap
    serviceDependencyList.forEach(service => {
      if (service?.identifier) {
        service.stepType = 'dependency-service'
        service.executableResponses = [
          {
            task: {
              logKeys: (service as any).logKeys
            } as any
          }
        ]
        if (parentNode && isExecutionRunning(parentNode.status)) {
          // If execution is still running, we should be getting logs as stream, not blob
          service.status = ExecutionStatusEnum.Running
        }
        nodeMap[service.identifier] = service
      }
    })
 
    // 2. add Initialize (Initialize step is liteEngineTask step)
    // override step name
    if (liteEngineTask.uuid) {
      liteEngineTask.name = 'Initialize'
      nodeMap[liteEngineTask.uuid] = liteEngineTask
    }
  }
}