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

100% Statements 58/58
80.7% Branches 92/114
100% Functions 7/7
100% Lines 57/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 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              25x 25x       25x           25x     25x           15x 43x   15x 15x 1x     15x 2x     15x 2x     15x 2x     15x 2x     15x     25x 19x 17x     19x   19x 2x 2x               17x   17x 51x 51x                           17x 17x     25x           3x     3x 1x       3x 1x       3x 2x   3x     25x           4x         4x             4x 12x                             4x     25x                                 4x                         4x 4x 1x 1x     3x 3x 3x   3x                    
/*
 * 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 { Utils } from '@harness/uicore'
import { cloneDeep } from 'lodash-es'
import type { FormikErrors, FormikProps } from 'formik'
import type { UseStringsReturn } from 'framework/strings'
import type { CustomHealthSourceLogSpec } from 'services/cv'
import { CustomHealthLogFieldNames, DEFAULT_CUSTOM_LOG_SETUP_SOURCE } from './CustomHealthLogSource.constants'
import type {
  SelectedAndMappedQueries,
  UpdateSelectedQueryMap,
  CustomHealthLogSetupSource
} from './CustomHealthLogSource.types'
import { validateMappingInfo } from '../CustomHealthSource/CustomHealthSource.utils'
import type { UpdatedHealthSource } from '../../HealthSourceDrawer/HealthSourceDrawerContent.types'
 
export function validateSetupSource(
  data: CustomHealthLogSetupSource,
  getString: UseStringsReturn['getString'],
  createdQueryNames: string[],
  selectedIndex: number
): FormikErrors<CustomHealthLogSetupSource> {
  const errors: FormikErrors<CustomHealthLogSetupSource> = {}
  const existingQueryNames = new Set(createdQueryNames.filter((_, idx) => idx !== selectedIndex))
 
  validateMappingInfo(data, errors, getString)
  if (!data?.queryName) {
    errors.queryName = getString('cv.customHealthSource.Querymapping.validation.queryName')
  }
 
  if (data?.queryName && existingQueryNames.has(data?.queryName)) {
    errors.queryName = getString('cv.monitoringSources.gcoLogs.validation.queryNameUnique')
  }
 
  if (!data?.serviceInstanceJsonPath) {
    errors.serviceInstanceJsonPath = getString('cv.monitoringSources.prometheus.validation.serviceInstanceIdentifier')
  }
 
  if (!data?.queryValueJsonPath) {
    errors.queryValueJsonPath = getString('cv.customHealthSource.Querymapping.validation.logMessageJsonPath')
  }
 
  if (!data?.timestampJsonPath) {
    errors.timestampJsonPath = getString('cv.customHealthSource.Querymapping.validation.timestampJsonPath')
  }
 
  return errors
}
 
export function initializeSelectedQueryMap(data: any): SelectedAndMappedQueries {
  const healthSource: UpdatedHealthSource = data?.healthSourceList?.find(
    (source: UpdatedHealthSource) => source.name === data.healthSourceName
  )
 
  const customLogSpec: CustomHealthSourceLogSpec = healthSource?.spec
 
  if (!customLogSpec?.logDefinitions?.length) {
    const selectedQuery = `Custom Log Query_${Utils.randomId()}`
    return {
      selectedQuery: selectedQuery,
      mappedQueries: new Map([
        [selectedQuery, { ...cloneDeep(DEFAULT_CUSTOM_LOG_SETUP_SOURCE), queryName: selectedQuery }]
      ])
    }
  }
 
  const setupSource: SelectedAndMappedQueries = { selectedQuery: '', mappedQueries: new Map() }
 
  for (const logDefinition of customLogSpec.logDefinitions) {
    Eif (logDefinition.queryName) {
      setupSource.mappedQueries.set(logDefinition.queryName, {
        queryName: logDefinition.queryName,
        query: logDefinition.requestDefinition?.requestBody,
        requestMethod: logDefinition.requestDefinition?.method,
        queryValueJsonPath: logDefinition.logMessageJsonPath || '',
        serviceInstanceJsonPath: logDefinition.serviceInstanceJsonPath,
        timestampJsonPath: logDefinition.timestampJsonPath || '',
        startTime: logDefinition.requestDefinition?.startTimeInfo || {},
        endTime: logDefinition.requestDefinition?.endTimeInfo || {},
        pathURL: logDefinition.requestDefinition?.urlPath || ''
      })
    }
  }
 
  setupSource.selectedQuery = Array.from(setupSource.mappedQueries.keys())[0]
  return setupSource
}
 
export function updateSelectedMetricsMap({
  updatedQueryName,
  oldQueryName,
  mappedQuery,
  formikProps
}: UpdateSelectedQueryMap): SelectedAndMappedQueries {
  const updatedMap = new Map(mappedQuery)
 
  // in the case where user updates metric name, update the key for current value
  if (oldQueryName !== formikProps.values?.queryName) {
    updatedMap.delete(oldQueryName)
  }
 
  // if newly created metric create form object
  if (!updatedMap.has(updatedQueryName)) {
    updatedMap.set(updatedQueryName, { ...cloneDeep(DEFAULT_CUSTOM_LOG_SETUP_SOURCE), queryName: updatedQueryName })
  }
 
  // update map with current form data
  if (formikProps.values?.queryName) {
    updatedMap.set(formikProps.values.queryName, formikProps.values)
  }
  return { selectedQuery: updatedQueryName, mappedQueries: updatedMap }
}
 
export function transformSetupSourceToHealthSource(
  sources: CustomHealthLogSetupSource[],
  connectorRef: string,
  healthSourceName: string,
  healthSourceIdentifier: string
): UpdatedHealthSource {
  const spec: CustomHealthSourceLogSpec = {
    connectorRef,
    logDefinitions: []
  }
 
  const sourceSpec: UpdatedHealthSource = {
    type: 'CustomHealthLog',
    identifier: healthSourceIdentifier,
    name: healthSourceName,
    spec
  }
 
  for (const source of sources) {
    spec.logDefinitions?.push({
      requestDefinition: {
        endTimeInfo: source.endTime,
        method: source.requestMethod,
        requestBody: source.query,
        startTimeInfo: source.startTime,
        urlPath: source.pathURL
      },
      queryName: source.queryName,
      logMessageJsonPath: source.queryValueJsonPath,
      serviceInstanceJsonPath: source.serviceInstanceJsonPath,
      timestampJsonPath: source.timestampJsonPath
    })
  }
 
  return sourceSpec
}
 
export async function submitForm({
  formikProps,
  onSubmit,
  sourceData,
  mappedQueries,
  getString,
  selectedIndex,
  createdQueries
}: {
  formikProps: FormikProps<CustomHealthLogSetupSource>
  onSubmit: (formdata: CustomHealthLogSetupSource, UpdatedHealthSource: UpdatedHealthSource) => Promise<void>
  sourceData: CustomHealthLogSetupSource
  mappedQueries: SelectedAndMappedQueries['mappedQueries']
  getString: UseStringsReturn['getString']
  selectedIndex: number
  createdQueries: string[]
}): Promise<void> {
  formikProps.setTouched({
    ...formikProps.touched,
    [CustomHealthLogFieldNames.PATH]: true,
    [CustomHealthLogFieldNames.QUERY]: true,
    [CustomHealthLogFieldNames.QUERY_NAME]: true,
    [CustomHealthLogFieldNames.QUERY_VALUE_JSON_PATH]: true,
    [CustomHealthLogFieldNames.REQUEST_METHOD]: true,
    [CustomHealthLogFieldNames.TIMESTAMP_JSON_PATH]: true,
    [CustomHealthLogFieldNames.SERVICE_INSTANCE_JSON_PATH]: true,
    startTime: { placeholder: true, timestampFormat: true },
    endTime: { placeholder: true, timestampFormat: true }
  })
 
  const errors = validateSetupSource(formikProps.values, getString, createdQueries, selectedIndex)
  if (Object.keys(errors || {}).length > 0) {
    formikProps.validateForm()
    return
  }
 
  const updatedMetric = formikProps.values
  Eif (updatedMetric) {
    mappedQueries.set(formikProps.values.queryName, updatedMetric)
  }
  await onSubmit(
    sourceData,
    transformSetupSourceToHealthSource(
      Array.from(mappedQueries.values()),
      (sourceData as any).connectorRef,
      (sourceData as any).healthSourceName,
      (sourceData as any).healthSourceIdentifier
    )
  )
}