All files / modules/85-cv/pages/health-source/connectors/CustomHealthSource CustomHealthSource.utils.ts

78.81% Statements 93/118
73.22% Branches 257/351
81.25% Functions 13/16
78.26% Lines 90/115

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              28x                 28x   28x           13x   13x   13x     28x             13x   39x 13x   13x 13x 13x         13x   13x       13x       13x 1x     13x   13x       13x       13x       13x       13x 13x     28x         28x 7x     28x 8x         28x 7x     28x 9x         28x 7x         28x 8x         28x 19x 1x       19x           3x         28x             13x 13x   13x 13x 13x     13x         13x     28x 2x 1x     2x 1x                                                                         1x               1x 1x 1x                                                                                     1x     28x     1x         1x             1x                                         1x   1x       1x 1x 1x     1x 1x     1x                                                                   1x     28x                     3x                                                                                             9x                       28x 3x 3x 3x 9x   3x                   3x   3x                   3x   3x                                                 3x                           28x 6x    
/*
 * Copyright 2022 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 { cloneDeep } from 'lodash-es'
import type { CustomHealthSourceMetricSpec, RiskProfile, MetricPackDTO, useGetMetricPacks } from 'services/cv'
import type { StringKeys, UseStringsReturn } from 'framework/strings'
import type {
  MapCustomHealthToService,
  CustomHealthSourceSetupSource,
  onSubmitCustomHealthSourceInterface
} from './CustomHealthSource.types'
import type { UpdatedHealthSource } from '../../HealthSourceDrawer/HealthSourceDrawerContent.types'
import { CustomHealthSourceFieldNames, defaultMetricName, INITFORMDATA } from './CustomHealthSource.constants'
 
export function validateMappings(
  getString: UseStringsReturn['getString'],
  createdMetrics: string[],
  selectedMetricIndex: number,
  values?: MapCustomHealthToService
): { [fieldName: string]: string } {
  let errors = {}
 
  errors = validateCustomMetricFields(values, createdMetrics, selectedMetricIndex, {}, getString)
 
  return errors
}
 
const validateCustomMetricFields = (
  values: any,
  createdMetrics: string[],
  selectedMetricIndex: number,
  errors: any,
  getString: (key: StringKeys) => string
): ((key: string | boolean | string[]) => string) => {
  let completErrors = cloneDeep(errors)
 
  const isAssignComponentValid = [values?.sli, values?.continuousVerification, values?.healthScore].find(i => i)
  const isRiskCategoryValid = !!values?.riskCategory
 
  const duplicateNames = createdMetrics?.filter((metricName, index) => {
    Eif (index === selectedMetricIndex) {
      return false
    }
    return metricName === values.metricName
  })
 
  const formValues = values || {}
 
  Iif (!formValues.groupName || !formValues.groupName?.value) {
    completErrors['groupName'] = getString('cv.monitoringSources.prometheus.validation.groupName')
  }
 
  Iif (!formValues.metricName) {
    completErrors['metricName'] = getString('cv.monitoringSources.metricNameValidation')
  }
 
  if (!formValues.queryType) {
    completErrors['queryType'] = getString('cv.customHealthSource.Querymapping.validation.queryType')
  }
 
  validateMappingInfo(formValues, completErrors, getString)
 
  Iif (formValues.requestMethod === 'POST' && !formValues.query) {
    completErrors['query'] = getString('cv.customHealthSource.Querymapping.validation.body')
  }
 
  Iif (!formValues.metricValue) {
    completErrors['metricValue'] = getString('cv.healthSource.connectors.NewRelic.validations.metricValue')
  }
 
  Iif (!formValues.timestamp) {
    completErrors['timestamp'] = getString('cv.healthSource.connectors.NewRelic.validations.timestamp')
  }
 
  Iif (formValues.metricName && duplicateNames.length) {
    completErrors['metricName'] = getString('cv.monitoringSources.prometheus.validation.metricNameUnique')
  }
 
  completErrors = validateAssignComponent(isAssignComponentValid, completErrors, getString, values, isRiskCategoryValid)
  return completErrors
}
 
export function validateMappingInfo(
  formValues: any,
  completErrors: any,
  getString: UseStringsReturn['getString']
): void {
  if (!formValues.pathURL) {
    completErrors['pathURL'] = getString('cv.customHealthSource.Querymapping.validation.path')
  }
 
  if (!formValues.startTime?.timestampFormat) {
    completErrors['startTime.timestampFormat'] = getString(
      'cv.customHealthSource.Querymapping.validation.startTime.timestamp'
    )
  }
 
  if (!formValues.requestMethod) {
    completErrors['requestMethod'] = getString('connectors.customHealth.requestMethod')
  }
 
  if (!formValues.startTime?.placeholder) {
    completErrors['startTime.placeholder'] = getString(
      'cv.customHealthSource.Querymapping.validation.startTime.placeholder'
    )
  }
 
  if (!formValues.endTime?.timestampFormat) {
    completErrors['endTime.timestampFormat'] = getString(
      'cv.customHealthSource.Querymapping.validation.endTime.timestamp'
    )
  }
 
  if (!formValues.endTime?.placeholder) {
    completErrors['endTime.placeholder'] = getString(
      'cv.customHealthSource.Querymapping.validation.endTime.placeholder'
    )
  }
 
  if (formValues.endTime?.placeholder && formValues.startTime?.placeholder) {
    if (formValues.startTime.placeholder === formValues.endTime.placeholder) {
      completErrors['startTime.placeholder'] = getString(
        'cv.customHealthSource.Querymapping.validation.startAndEndTime'
      )
    }
    if (
      (!formValues.pathURL?.includes(formValues.startTime.placeholder) ||
        !formValues.pathURL?.includes(formValues.endTime.placeholder)) &&
      (!formValues.query?.includes(formValues.startTime.placeholder) ||
        !formValues.query.includes(formValues.endTime.placeholder))
    ) {
      completErrors['pathURL'] = getString('cv.customHealthSource.Querymapping.validation.pathWithoutPlaceholder')
    }
  }
}
 
const validateAssignComponent = (
  isAssignComponentValid: boolean,
  errors: any,
  getString: (key: StringKeys) => string,
  values: any,
  isRiskCategoryValid: boolean
): ((key: string | boolean | string[]) => string) => {
  const _error = cloneDeep(errors)
  Iif (!isAssignComponentValid) {
    _error['sli'] = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.baseline')
  } else Eif (isAssignComponentValid) {
    Eif (values.continuousVerification || values.healthScore) {
      Iif (values.lowerBaselineDeviation !== true && values.higherBaselineDeviation !== true) {
        _error['lowerBaselineDeviation'] = getString('cv.monitoringSources.prometheus.validation.deviation')
      }
      Iif (!isRiskCategoryValid) {
        _error['riskCategory'] = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.riskCategory')
      }
    }
  }
  return _error
}
 
export function transformCustomHealthSourceToSetupSource(sourceData: any): CustomHealthSourceSetupSource {
  const healthSource: UpdatedHealthSource = sourceData?.healthSourceList?.find(
    (source: UpdatedHealthSource) => source.identifier === sourceData.healthSourceIdentifier
  )
 
  if (!healthSource) {
    return {
      isEdit: false,
      healthSourceIdentifier: sourceData.healthSourceIdentifier,
      mappedServicesAndEnvs: new Map([
        [
          defaultMetricName,
          {
            metricName: defaultMetricName,
            identifier: '',
            query: '',
            queryType: undefined,
            requestMethod: undefined,
            metricIdentifier: defaultMetricName.split(' ').join('_'),
            baseURL: '',
            pathURL: '',
            metricValue: '',
            timestamp: '',
            timestampFormat: '',
            serviceInstancePath: '',
            startTime: {
              placeholder: '',
              timestampFormat: 'SECONDS',
              customTimestampFormat: ''
            },
            endTime: {
              placeholder: '',
              timestampFormat: 'SECONDS',
              customTimestampFormat: ''
            }
          }
        ]
      ]),
      healthSourceName: sourceData.healthSourceName,
      connectorRef: sourceData.connectorRef
    }
  }
 
  const setupSource: CustomHealthSourceSetupSource = {
    isEdit: sourceData.isEdit,
    mappedServicesAndEnvs: new Map(),
    healthSourceIdentifier: sourceData.healthSourceIdentifier,
    healthSourceName: sourceData.healthSourceName,
    connectorRef: sourceData.connectorRef
  }
 
  for (const metricDefinition of (healthSource?.spec as CustomHealthSourceMetricSpec)?.metricDefinitions || []) {
    Eif (metricDefinition?.metricName) {
      setupSource.mappedServicesAndEnvs.set(metricDefinition.metricName, {
        metricName: metricDefinition.metricName,
        metricIdentifier: metricDefinition.identifier,
        groupName: { label: metricDefinition.groupName || '', value: metricDefinition.groupName || '' },
 
        // assign section
        continuousVerification: Boolean(metricDefinition?.analysis?.deploymentVerification?.enabled),
        healthScore: Boolean(metricDefinition.analysis?.liveMonitoring?.enabled),
        sli: Boolean(metricDefinition.sli?.enabled),
        riskCategory:
          metricDefinition.analysis?.riskProfile?.category && metricDefinition.analysis.riskProfile.metricType
            ? `${metricDefinition.analysis.riskProfile.category}/${metricDefinition.analysis.riskProfile.metricType}`
            : '',
        serviceInstanceIdentifier: metricDefinition.metricResponseMapping?.serviceInstanceJsonPath || '',
        lowerBaselineDeviation:
          metricDefinition.analysis?.riskProfile?.thresholdTypes?.includes('ACT_WHEN_LOWER') || false,
        higherBaselineDeviation:
          metricDefinition.analysis?.riskProfile?.thresholdTypes?.includes('ACT_WHEN_HIGHER') || false,
 
        //
        queryType: metricDefinition.queryType,
        requestMethod: metricDefinition.requestDefinition?.method,
        query: metricDefinition.requestDefinition?.requestBody || '',
        baseURL: '', // get this from connector API
        pathURL: metricDefinition.requestDefinition?.urlPath || '',
        metricValue: metricDefinition.metricResponseMapping?.metricValueJsonPath || '',
        timestamp: metricDefinition.metricResponseMapping?.timestampJsonPath || '',
        timestampFormat: metricDefinition.metricResponseMapping?.timestampFormat || '',
        serviceInstancePath: metricDefinition.metricResponseMapping?.serviceInstanceJsonPath || '',
        startTime: {
          placeholder: metricDefinition.requestDefinition?.startTimeInfo?.placeholder,
          timestampFormat: metricDefinition.requestDefinition?.startTimeInfo?.timestampFormat,
          customTimestampFormat: metricDefinition.requestDefinition?.startTimeInfo?.customTimestampFormat
        },
        endTime: {
          placeholder: metricDefinition.requestDefinition?.endTimeInfo?.placeholder,
          timestampFormat: metricDefinition.requestDefinition?.endTimeInfo?.timestampFormat,
          customTimestampFormat: metricDefinition.requestDefinition?.endTimeInfo?.customTimestampFormat
        }
      })
    }
  }
 
  return setupSource
}
 
export function transformCustomSetupSourceToHealthSource(
  setupSource: CustomHealthSourceSetupSource
): UpdatedHealthSource {
  const spec: CustomHealthSourceMetricSpec = {
    connectorRef: setupSource?.connectorRef,
    metricDefinitions: []
  }
 
  const dsConfig: UpdatedHealthSource = {
    type: 'CustomHealthMetric',
    identifier: setupSource.healthSourceIdentifier,
    name: setupSource.healthSourceName,
    spec
  }
 
  for (const entry of setupSource.mappedServicesAndEnvs.entries()) {
    const {
      metricName,
      metricIdentifier,
      groupName,
      queryType,
      requestMethod,
      query,
      riskCategory,
      lowerBaselineDeviation,
      higherBaselineDeviation,
      sli,
      continuousVerification,
      serviceInstanceIdentifier,
      healthScore,
      pathURL,
      startTime,
      endTime,
      metricValue,
      timestamp,
      timestampFormat
    }: MapCustomHealthToService = entry[1]
 
    Iif (!groupName || !metricName) {
      continue
    }
 
    const [category, metricType] = riskCategory?.split('/') || []
    const thresholdTypes: RiskProfile['thresholdTypes'] = []
    Iif (lowerBaselineDeviation) {
      thresholdTypes.push('ACT_WHEN_LOWER')
    }
    Eif (higherBaselineDeviation) {
      thresholdTypes.push('ACT_WHEN_HIGHER')
    }
 
    spec.metricDefinitions?.push({
      identifier: metricIdentifier,
      requestDefinition: {
        urlPath: pathURL,
        method: requestMethod,
        requestBody: query,
        startTimeInfo: startTime,
        endTimeInfo: endTime
      },
      queryType,
      metricName,
      groupName: groupName.value as string,
      metricResponseMapping: {
        metricValueJsonPath: metricValue,
        timestampJsonPath: timestamp,
        serviceInstanceJsonPath: serviceInstanceIdentifier,
        timestampFormat: timestampFormat
      },
      sli: { enabled: Boolean(sli) },
      analysis: {
        riskProfile: {
          category: category as RiskProfile['category'],
          metricType: metricType as RiskProfile['metricType'],
          thresholdTypes
        },
        liveMonitoring: { enabled: Boolean(healthScore) },
        deploymentVerification: {
          enabled: Boolean(continuousVerification),
          serviceInstanceMetricPath: serviceInstanceIdentifier
        }
      }
    })
  }
 
  return dsConfig
}
 
export const onSubmitCustomHealthSource = ({
  formikProps,
  createdMetrics,
  selectedMetricIndex,
  mappedMetrics,
  selectedMetric,
  onSubmit,
  sourceData,
  transformedSourceData,
  getString
}: onSubmitCustomHealthSourceInterface) => {
  return async () => {
    formikProps.setTouched({
      ...formikProps.touched,
      [CustomHealthSourceFieldNames.SLI]: true,
      [CustomHealthSourceFieldNames.GROUP_NAME]: true,
      [CustomHealthSourceFieldNames.METRIC_NAME]: true,
      [CustomHealthSourceFieldNames.LOWER_BASELINE_DEVIATION]: true,
      [CustomHealthSourceFieldNames.RISK_CATEGORY]: true,
      [CustomHealthSourceFieldNames.BASE_URL]: true,
      [CustomHealthSourceFieldNames.METRIC_VALUE]: true,
      [CustomHealthSourceFieldNames.TIMESTAMP_FORMAT]: true,
      [CustomHealthSourceFieldNames.TIMESTAMP_LOCATOR]: true,
      [CustomHealthSourceFieldNames.PATH]: true,
      [CustomHealthSourceFieldNames.QUERY_TYPE]: true,
      [CustomHealthSourceFieldNames.REQUEST_METHOD]: true,
      startTime: { placeholder: true, timestampFormat: true },
      endTime: { placeholder: true, timestampFormat: true }
    })
    if (formikProps?.values) {
      const errors = validateMappings(getString, createdMetrics, selectedMetricIndex, formikProps.values)
      if (Object.keys(errors || {})?.length > 0) {
        formikProps.validateForm()
        return
      }
    } else {
      return
    }
 
    const updatedMetric = formikProps.values
    if (updatedMetric) {
      mappedMetrics.set(selectedMetric, updatedMetric)
    }
    await onSubmit(
      sourceData,
      transformCustomSetupSourceToHealthSource({
        ...transformedSourceData,
        mappedServicesAndEnvs: mappedMetrics
      } as CustomHealthSourceSetupSource)
    )
  }
}
 
function getMetricPackDTO(
  identifier: MetricPackDTO['identifier'],
  category: MetricPackDTO['category'],
  metrics: MetricPackDTO['metrics']
): MetricPackDTO {
  return {
    uuid: '2',
    accountId: '',
    orgIdentifier: '',
    projectIdentifier: '',
    dataSourceType: 'CUSTOM_HEALTH_METRIC',
    identifier,
    category,
    metrics
  }
}
 
export function generateCustomMetricPack(): ReturnType<typeof useGetMetricPacks> {
  const categories: MetricPackDTO['category'][] = ['ERRORS', 'INFRASTRUCTURE', 'PERFORMANCE']
  const packs: MetricPackDTO[] = []
  for (const category of categories) {
    switch (category) {
      case 'ERRORS':
        packs.push(
          getMetricPackDTO('Errors', 'Errors' as MetricPackDTO['category'], [
            {
              name: 'Errors',
              type: 'ERROR',
              thresholds: [],
              included: false
            }
          ])
        )
        break
      case 'INFRASTRUCTURE':
        packs.push(
          getMetricPackDTO('Infrastructure', 'Infrastructure' as MetricPackDTO['category'], [
            {
              name: 'Infrastructure',
              type: 'INFRA',
              thresholds: [],
              included: false
            }
          ])
        )
        break
      case 'PERFORMANCE':
        packs.push(
          getMetricPackDTO('Performance', 'Performance' as MetricPackDTO['category'], [
            {
              name: 'Throughput',
              type: 'THROUGHPUT',
              thresholds: [],
              included: false
            },
            {
              name: 'Other',
              type: 'ERROR',
              thresholds: [],
              included: false
            },
            {
              name: 'Response Time',
              type: 'RESP_TIME',
              thresholds: [],
              included: false
            }
          ])
        )
    }
  }
 
  return {
    loading: false,
    error: null,
    data: {
      metaData: {},
      resource: packs
    },
    absolutePath: '',
    cancel: () => undefined,
    refetch: () => Promise.resolve(),
    response: null
  }
}
 
export const getInitCustomMetricData = (baseURL: string) => {
  return { ...INITFORMDATA, baseURL }
}