All files / modules/70-pipeline/components/PipelineSteps/AdvancedSteps/FailureStrategyPanel/StrategySelection StrategySelection.tsx

98.04% Statements 50/51
82.35% Branches 28/34
100% Functions 10/10
98.04% Lines 50/51

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              37x 37x 37x 37x 37x 37x 37x   37x 37x 37x 37x 37x   37x 37x                             37x 8x   8x   8x                                                       37x 24x 24x 24x 24x 24x   24x 24x 24x 24x 24x               24x                                     1x   1x 1x                             2x 2x     24x       19x       19x     1x 1x     19x         19x                                                                                                                         37x 123x   123x 123x 123x     7x     123x                                                             37x  
/*
 * 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 React from 'react'
import { FormGroup, Intent } from '@blueprintjs/core'
import { connect, FormikContext, FieldArray } from 'formik'
import { get, difference } from 'lodash-es'
import { MultiTextInput, Button, MultiTypeInputType } from '@wings-software/uicore'
import { v4 as uuid } from 'uuid'
import cx from 'classnames'
 
import { errorCheck } from '@common/utils/formikHelpers'
import { useStrings } from 'framework/strings'
import { FormMultiTypeDurationField } from '@common/components/MultiTypeDuration/MultiTypeDuration'
import MultiTypeFieldSelector from '@common/components/MultiTypeFieldSelector/MultiTypeFieldSelector'
import { Strategy } from '@pipeline/utils/FailureStrategyUtils'
 
import { StrategyStepsList } from './StrategyStepsList'
import css from './StrategySelection.module.scss'
 
/**
 * NOTE: Failure strategies do not support runtime inputs
 */
 
export interface BaseStepProps {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  formik: FormikContext<any>
  name: string
  parentStrategy?: Strategy
  allowedStrategies: Strategy[]
  disabled?: boolean
}
 
export function ManualInterventionStep(props: BaseStepProps): React.ReactElement {
  const { formik, parentStrategy, allowedStrategies, name, disabled } = props
 
  const { getString } = useStrings()
 
  return (
    <div className={css.step}>
      <FormMultiTypeDurationField
        name={`${name}.timeout`}
        label={getString('pipelineSteps.timeoutLabel')}
        className={css.sm}
        multiTypeDurationProps={{
          enableConfigureOptions: false,
          allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]
        }}
        disabled={disabled}
      />
      <StrategySelection
        label={getString('pipeline.failureStrategies.fieldLabels.onTimeoutLabel')}
        name={`${name}.onTimeout.action`}
        formik={formik}
        parentStrategy={Strategy.ManualIntervention}
        allowedStrategies={difference(allowedStrategies, [
          Strategy.ManualIntervention,
          parentStrategy || Strategy.ManualIntervention,
          Strategy.Retry
        ])}
        disabled={disabled}
      />
    </div>
  )
}
 
export function RetryStep(props: BaseStepProps): React.ReactElement {
  const { formik, parentStrategy, allowedStrategies, name, disabled } = props
  const { getString } = useStrings()
  const uids = React.useRef<string[]>([])
  const retryIntervalsFieldName = `${name}.retryIntervals`
  const retryCountFieldName = `${name}.retryCount`
 
  const intervals: string[] = get(formik.values, retryIntervalsFieldName) || []
  const retryCountHasError = errorCheck(retryCountFieldName, formik)
  const intent = retryCountHasError ? Intent.DANGER : Intent.NONE
  const helperText = retryCountHasError ? get(formik?.errors, retryCountFieldName) : null
  const retryCountValue = get(formik?.values, retryCountFieldName, '')
 
  /**
   * We are using `MultiTextInput` here because we want to
   * parse the value to an integer (whenever possible)
   *
   * It is not possible when using `FormInput.MultiTextInput`
   */
  return (
    <div className={cx(css.step, css.retryStep)}>
      <FormGroup
        label={getString('pipeline.failureStrategies.fieldLabels.retryCountLabel')}
        labelFor={retryCountFieldName}
        helperText={helperText}
        intent={intent}
        className={css.sm}
      >
        <MultiTextInput
          textProps={{
            type: 'number',
            min: 0,
            name: retryCountFieldName
          }}
          name={retryCountFieldName}
          allowableTypes={[MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]}
          value={retryCountValue}
          onChange={newValue => {
            const parsedValue = parseInt(newValue as string)
 
            formik.setFieldValue(retryCountFieldName, Number.isNaN(parsedValue) ? newValue : parsedValue)
            formik.setFieldTouched(retryCountFieldName, true)
          }}
          disabled={disabled}
        />
      </FormGroup>
      <MultiTypeFieldSelector
        name={retryIntervalsFieldName}
        label={getString('pipeline.failureStrategies.fieldLabels.retryIntervalsLabel')}
        defaultValueToReset={['1d']}
        disableTypeSelection
        disabled={disabled}
      >
        <FieldArray name={retryIntervalsFieldName}>
          {({ push, remove }) => {
            function handleAdd(): void {
              uids.current.push(uuid())
              push('')
            }
 
            return (
              <div className={cx(css.retryStepIntervals, css.sm)}>
                {intervals.map((_, i) => {
                  // generated uuid if they are not present
                  Iif (!uids.current[i]) {
                    uids.current[i] = uuid()
                  }
 
                  const key = uids.current[i]
 
                  function handleRemove(): void {
                    uids.current.splice(i, 1)
                    remove(i)
                  }
 
                  return (
                    <div className={css.row} key={key}>
                      <FormMultiTypeDurationField
                        name={`${retryIntervalsFieldName}[${i}]`}
                        label=""
                        skipErrorsIf={form => typeof get(form?.errors, retryIntervalsFieldName) === 'string'}
                        multiTypeDurationProps={{
                          enableConfigureOptions: false,
                          allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION],
                          defaultValueToReset: ''
                        }}
                        disabled={disabled}
                      />
                      <Button
                        minimal
                        small
                        icon="main-trash"
                        className={css.removeBtn}
                        onClick={handleRemove}
                        data-testid={`remove-retry-interval-${i}`}
                        disabled={disabled}
                      />
                    </div>
                  )
                })}
                {typeof retryCountValue !== 'number' || intervals.length < retryCountValue ? (
                  <Button
                    icon="plus"
                    minimal
                    intent="primary"
                    data-testid="add-retry-interval"
                    onClick={handleAdd}
                    disabled={disabled}
                  >
                    {getString('add')}
                  </Button>
                ) : null}
              </div>
            )
          }}
        </FieldArray>
      </MultiTypeFieldSelector>
      <StrategySelection
        label={getString('pipeline.failureStrategies.fieldLabels.onRetryFailureLabel')}
        name={`${name}.onRetryFailure.action`}
        formik={formik}
        disabled={disabled}
        parentStrategy={Strategy.Retry}
        allowedStrategies={difference(allowedStrategies, [Strategy.Retry, parentStrategy || Strategy.Retry])}
      />
    </div>
  )
}
 
export interface StrategySelectionProps {
  label: string
  name: string
  allowedStrategies: Strategy[]
  parentStrategy?: Strategy
  disabled?: boolean
}
 
export interface ConnectedStrategySelectionProps extends StrategySelectionProps {
  formik: FormikContext<Record<string, never>>
}
 
export function StrategySelection(props: ConnectedStrategySelectionProps): React.ReactElement {
  const { name, label, formik, allowedStrategies, parentStrategy, disabled } = props
 
  const typePath = `${name}.type`
  const specPath = `${name}.spec`
  const value: Strategy | undefined = get(formik.values, typePath)
 
  function handleOnChange(): void {
    formik.setFieldValue(specPath, undefined)
  }
 
  return (
    <FormGroup label={label} labelFor={name}>
      <StrategyStepsList
        allowedStrategies={allowedStrategies}
        name={typePath}
        formik={formik}
        disabled={disabled}
        onChange={handleOnChange}
      />
      {value === Strategy.ManualIntervention ? (
        <ManualInterventionStep
          name={specPath}
          formik={formik}
          parentStrategy={parentStrategy}
          allowedStrategies={allowedStrategies}
          disabled={disabled}
        />
      ) : null}
      {value === Strategy.Retry ? (
        <RetryStep
          name={specPath}
          formik={formik}
          parentStrategy={parentStrategy}
          allowedStrategies={allowedStrategies}
          disabled={disabled}
        />
      ) : null}
    </FormGroup>
  )
}
 
export default connect<StrategySelectionProps>(StrategySelection)