All files / modules/70-pipeline/components/PipelineSteps/AdvancedSteps/FailureStrategyPanel validation.ts

95.83% Statements 46/48
89.47% Branches 17/19
100% Functions 10/10
95.83% Lines 46/48

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              127x 127x 127x     127x 127x   127x     199x 152x   152x       127x     72x         25x 1x     24x                   24x 24x 11x   13x             40x 2x                   38x 22x                     16x                         127x     72x                   127x     36x                                                                                                                                                                                                       36x           59x   59x           59x 54x   54x 54x   47x 47x 47x     54x     5x         127x     43x 43x         4x 2x 2x 2x                
/*
 * 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 * as Yup from 'yup'
import { omit } from 'lodash-es'
import { getMultiTypeFromValue, MultiTypeInputType } from '@wings-software/uicore'
 
import type { UseStringsReturn } from 'framework/strings'
import { getDurationValidationSchema } from '@common/components/MultiTypeDuration/MultiTypeDuration'
import { ErrorType, Strategy } from '@pipeline/utils/FailureStrategyUtils'
 
const MAX_RETRIES = 10000
 
function updateErrorPaths(e: Yup.ValidationError, prefix = ''): void {
  e.inner.forEach(e2 => {
    e2.path = `${prefix}${e2.path}`
 
    updateErrorPaths(e2, prefix)
  })
}
 
export function getRetryActionBaseFields(
  getString: UseStringsReturn['getString']
): Record<string, Yup.Schema<unknown>> {
  return {
    retryCount: Yup.mixed().test({
      name: 'failureStrategies-retryCount',
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      test(value: any) {
        if (getMultiTypeFromValue(value) !== MultiTypeInputType.FIXED) {
          return true
        }
 
        const schema = Yup.number()
          .typeError(getString('pipeline.failureStrategies.validation.retryCountInteger'))
          .integer(getString('pipeline.failureStrategies.validation.retryCountInteger'))
          .min(1, getString('pipeline.failureStrategies.validation.retryCountMinimum'))
          .max(
            MAX_RETRIES,
            getString('pipeline.failureStrategies.validation.retryCountMaximum', { count: MAX_RETRIES })
          )
          .required(getString('pipeline.failureStrategies.validation.retryCountRequired'))
 
        try {
          schema.validateSync(value)
          return true
        } catch (e) {
          return this.createError({ message: e.message })
        }
      }
    }),
    retryIntervals: Yup.array().when(
      'retryCount',
      (retryCount: string | number, schema: Yup.NotRequiredArraySchema<unknown>) => {
        if (typeof retryCount === 'string' && getMultiTypeFromValue(retryCount) !== MultiTypeInputType.FIXED) {
          return schema
            .of(
              getDurationValidationSchema().required(
                getString('pipeline.failureStrategies.validation.retryIntervalRequired')
              )
            )
            .min(1, getString('pipeline.failureStrategies.validation.retryIntervalMinimum'))
            .required(getString('pipeline.failureStrategies.validation.retryIntervalRequired'))
        }
 
        if (typeof retryCount === 'number') {
          return schema
            .of(
              getDurationValidationSchema().required(
                getString('pipeline.failureStrategies.validation.retryIntervalRequired')
              )
            )
            .min(1, getString('pipeline.failureStrategies.validation.retryIntervalMinimum'))
            .max(retryCount, getString('pipeline.failureStrategies.validation.retryIntervalMaxmimum'))
            .required(getString('pipeline.failureStrategies.validation.retryIntervalRequired'))
        }
 
        return schema
          .of(
            getDurationValidationSchema().required(
              getString('pipeline.failureStrategies.validation.retryIntervalRequired')
            )
          )
          .min(1, getString('pipeline.failureStrategies.validation.retryIntervalMinimum'))
          .required(getString('pipeline.failureStrategies.validation.retryIntervalRequired'))
      }
    )
  }
}
 
export function getManualInterventionBaseFields(
  getString: UseStringsReturn['getString']
): Record<string, Yup.Schema<unknown>> {
  return {
    timeout: getDurationValidationSchema().required(getString('pipeline.failureStrategies.validation.timeoutRequired'))
  }
}
 
export interface GetFailureStrategiesValidationSchemaOptions {
  required?: boolean
  minLength?: number
}
 
export function getFailureStrategiesValidationSchema(
  getString: UseStringsReturn['getString']
): Yup.MixedSchema<unknown> {
  const failureStrategySchema = Yup.object()
    .shape({
      onFailure: Yup.object()
        .shape({
          errors: Yup.array()
            .of(Yup.mixed().oneOf(Object.values(ErrorType)).required())
            .min(1, getString('pipeline.failureStrategies.validation.errorsMinimum'))
            .required(getString('pipeline.failureStrategies.validation.errorsRequired')),
          action: Yup.object()
            .shape({
              type: Yup.mixed()
                .oneOf(Object.values(Strategy))
                .required(getString('pipeline.failureStrategies.validation.actionRequired')),
              spec: Yup.mixed()
                .when('type', {
                  is: Strategy.Retry,
                  then: Yup.object()
                    .shape({
                      ...getRetryActionBaseFields(getString),
                      onRetryFailure: Yup.object()
                        .shape({
                          action: Yup.object().shape({
                            type: Yup.mixed()
                              .oneOf(Object.values(omit(Strategy, [Strategy.Retry])))
                              .required(getString('pipeline.failureStrategies.validation.onRetryFailureRequired')),
                            spec: Yup.mixed().when('type', {
                              is: Strategy.ManualIntervention,
                              then: Yup.object().shape({
                                ...getManualInterventionBaseFields(getString),
                                onTimeout: Yup.object().shape({
                                  action: Yup.object()
                                    .shape({
                                      type: Yup.mixed()
                                        .oneOf(
                                          Object.values(omit(Strategy, [Strategy.ManualIntervention, Strategy.Retry]))
                                        )
                                        .required(getString('pipeline.failureStrategies.validation.onTimeoutRequired'))
                                    })
                                    .required(getString('pipeline.failureStrategies.validation.onTimeoutRequired'))
                                    .required(getString('pipeline.failureStrategies.validation.onTimeoutRequired'))
                                })
                              })
                            })
                          })
                        })
                        .required(getString('pipeline.failureStrategies.validation.onRetryFailureRequired'))
                    })
                    .required()
                })
                .when('type', {
                  is: Strategy.ManualIntervention,
                  then: Yup.object()
                    .shape({
                      ...getManualInterventionBaseFields(getString),
                      onTimeout: Yup.object().shape({
                        action: Yup.object()
                          .shape({
                            type: Yup.mixed()
                              .oneOf(Object.values(omit(Strategy, [Strategy.ManualIntervention])))
                              .required(getString('pipeline.failureStrategies.validation.onTimeoutRequired')),
                            spec: Yup.mixed().when('type', {
                              is: Strategy.Retry,
                              then: Yup.object()
                                .shape({
                                  ...getRetryActionBaseFields(getString),
                                  onRetryFailure: Yup.object()
                                    .shape({
                                      action: Yup.object()
                                        .shape({
                                          type: Yup.mixed()
                                            .oneOf(
                                              Object.values(
                                                omit(Strategy, [Strategy.Retry, Strategy.ManualIntervention])
                                              )
                                            )
                                            .required(
                                              getString('pipeline.failureStrategies.validation.onRetryFailureRequired')
                                            )
                                        })
                                        .required(
                                          getString('pipeline.failureStrategies.validation.onRetryFailureRequired')
                                        )
                                    })
                                    .required(getString('pipeline.failureStrategies.validation.onRetryFailureRequired'))
                                })
                                .required(getString('pipeline.failureStrategies.validation.onRetryFailureRequired'))
                            })
                          })
                          .required(getString('pipeline.failureStrategies.validation.onTimeoutRequired'))
                      })
                    })
                    .required()
                })
            })
            .required(getString('pipeline.failureStrategies.validation.actionRequired'))
        })
        .required()
    })
    .required()
 
  return Yup.mixed().test({
    name: 'FailureStrategiesArray',
    // we need to implement custom logic due to bug in Yup v0.29.2,
    // where `array().required()` sets minimum required length of the array as 1
    // TODO: get rid of this custom logic once we upgrade Yup
    test(value: unknown): boolean | Yup.ValidationError {
      const isUndefined = typeof value === 'undefined'
 
      Iif (!isUndefined && !Array.isArray(value)) {
        return this.createError({
          message: getString('pipeline.failureStrategies.validation.arrayOrUndefined')
        })
      }
 
      if (Array.isArray(value)) {
        let validationError: boolean | Yup.ValidationError = true
 
        try {
          Yup.array().of(failureStrategySchema).validateSync(value, { abortEarly: false })
        } catch (e: unknown) {
          validationError = e as Yup.ValidationError
          validationError.path = this.path
          updateErrorPaths(validationError, this.path)
        }
 
        return validationError
      }
 
      return true
    }
  })
}
 
export function getVariablesValidationField(
  getString: UseStringsReturn['getString']
): Record<string, Yup.Schema<unknown>> {
  const requiredValueLabel = getString('common.validation.valueIsRequired')
  return {
    variables: Yup.array().of(
      Yup.object().shape({
        name: Yup.string().trim().required(getString('common.validation.nameIsRequired')),
        value: Yup.lazy((value): Yup.Schema<unknown> => {
          if (typeof value === 'string') {
            return Yup.string().trim().required(requiredValueLabel)
          } else Eif (typeof value === 'number') {
            return Yup.number().required(requiredValueLabel)
          }
          return Yup.mixed().required(requiredValueLabel)
        })
      })
    )
  }
}