All files / modules/70-pipeline/components/LogsContent/LogsState createSections.ts

93.33% Statements 56/60
76.19% Branches 96/126
85.71% Functions 6/7
94.74% Lines 54/57

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              35x   35x             35x       20x       20x 6x   6x 6x         35x   35x 14x   14x 3x     11x 11x               11x   11x             11x 11x 11x 11x   11x 4x 4x     11x 4x 6x 6x                 11x   10x         10x     10x 10x 10x 10x   10x                       10x         11x   11x 2x 1x     1x   1x               3x 1x   9x 4x     4x 4x       11x   5x 5x     5x     11x                  
/*
 * 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 { findLast, set, snakeCase } from 'lodash-es'
 
import {
  isExecutionComplete,
  isExecutionFailed,
  isExecutionRunningLike,
  isExecutionSuccess
} from '@pipeline/utils/statusHelpers'
 
import { getDefaultReducerState } from './utils'
import type { Action, ActionType, LogSectionData, State, ProgressMapValue, UnitLoadingStatus } from './types'
 
function parseToTime(p: unknown): number | undefined {
  Iif (typeof p === 'number') {
    return p
  }
 
  if (typeof p === 'string') {
    const t = parseInt(p, 10)
 
    Eif (!Number.isNaN(t)) {
      return t
    }
  }
}
 
const NON_MUTATE_STATES: UnitLoadingStatus[] = ['LOADING', 'QUEUED']
 
export function createSections(state: State, action: Action<ActionType.CreateSections>): State {
  const { node, selectedStep, selectedStage, getSectionName } = action.payload
 
  if (!node) {
    return getDefaultReducerState({ selectedStage, selectedStep })
  }
 
  const isSameStage = selectedStage === state.selectedStage
  const isSameStep = isSameStage && selectedStep === state.selectedStep
 
  /**
   * task object must always be picked from the first entry
   * in `executableResponses`
   *
   * It can be either be a `taskChain`, `task` or `sync`
   */
  const executableResponse = node?.executableResponses?.[0] || {}
  const task =
    executableResponse.taskChain ||
    executableResponse.task ||
    executableResponse.sync ||
    executableResponse.async ||
    executableResponse.child
 
  // eslint-disable-next-line prefer-const
  let { units = [], logKeys = [] } = task || ({} as any)
  const progressMap = new Map<string, ProgressMapValue>()
  const isStepComplete = isExecutionComplete(node.status)
  let hasNoUnits = false
 
  if (units.length === 0 && logKeys.length > 0) {
    hasNoUnits = true
    units = logKeys.map((_: unknown, i: number) => getSectionName(i + 1))
  }
 
  if (Array.isArray(node.unitProgresses)) {
    node.unitProgresses.forEach(row => {
      Eif (row.unitName) {
        progressMap.set(row.unitName, {
          status: row.status as UnitLoadingStatus,
          startTime: row.startTime,
          endTime: row.endTime
        })
      }
    })
  }
 
  const dataMap: Record<string, LogSectionData> = units.reduce(
    (acc: Record<string, LogSectionData>, unit: string, i: number) => {
      const key = logKeys[i]
      /**
       * progressMap must have a status for this unit.
       * In case it doesn't, fallback to the 'UNKNOWN' status.
       */
      const unitProgress: ProgressMapValue | undefined = hasNoUnits
        ? { status: snakeCase(node.status || 'NotStarted').toUpperCase() as UnitLoadingStatus }
        : progressMap.get(unit)
      const unitStatus: UnitLoadingStatus = unitProgress?.status || 'NOT_STARTED'
      const currentStatus = state.dataMap[key]?.status
      const manuallyToggled = !!state.dataMap[key]?.manuallyToggled
      const isRunning = isExecutionRunningLike(unitStatus)
 
      acc[key] = {
        title: unit,
        data: isSameStep ? state.dataMap[key]?.data || [] : [],
        isOpen: isSameStep && manuallyToggled ? state.dataMap[key]?.isOpen : isRunning,
        manuallyToggled: isSameStep ? manuallyToggled : false,
        status: isSameStep && NON_MUTATE_STATES.includes(currentStatus) && isRunning ? currentStatus : unitStatus,
        unitStatus,
        startTime: parseToTime(unitProgress?.startTime),
        endTime: parseToTime(unitProgress?.endTime),
        dataSource: isRunning ? 'stream' : 'blob'
      }
 
      return acc
    },
    {}
  )
 
  let unitToOpen: string | null = null
 
  if (logKeys.length > 1) {
    if (isStepComplete) {
      const isStepSuccess = isExecutionSuccess(node.status)
 
      // if step is successful
      Eif (isStepSuccess) {
        // open the first section
        unitToOpen = logKeys[0]
      } else {
        // find and open the first failed section
        const failedUnit = logKeys.find((key: string) => isExecutionFailed(dataMap[key]?.unitStatus))
        unitToOpen = failedUnit || null
      }
    } else {
      // open the running section
      const runningUnit = findLast(logKeys, key => isExecutionRunningLike(dataMap[key]?.unitStatus))
      unitToOpen = runningUnit || null
    }
  } else if (logKeys.length === 1) {
    const isExecutionRunning = isExecutionRunningLike(dataMap[logKeys[0]]?.unitStatus)
 
    // only open the unit if it is running/complete
    Eif (isExecutionRunning || isStepComplete) {
      unitToOpen = logKeys[0]
    }
  }
 
  if (unitToOpen && !dataMap[unitToOpen].manuallyToggled) {
    // if we are opening a section the set it to loading
    Eif (dataMap[unitToOpen].status !== 'QUEUED' && !dataMap[unitToOpen].data.length) {
      set(dataMap[unitToOpen], 'status', 'LOADING')
    }
 
    set(dataMap[unitToOpen], 'isOpen', true)
  }
 
  return {
    units,
    logKeys,
    dataMap,
    selectedStep,
    selectedStage,
    searchData: isSameStep ? { ...state.searchData } : getDefaultReducerState().searchData
  }
}