All files / modules/85-cv/pages/health-source/connectors/DatadogMetricsHealthSource/components/DatadogMetricsDetailsContent DatadogMetricsDetailsContent.utils.tsx

88.5% Statements 100/113
70.8% Branches 80/113
86.67% Functions 26/30
87.76% Lines 86/98

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              33x   33x             33x         33x 33x                                   33x                   19x 13x 7x 6x 2x   4x         4x         7x 7x 7x 6x 6x             7x 7x 7x 7x 1x       1x   7x               33x                   8x 2x         24x 6x       6x 4x 10x 4x   6x     4x   2x     6x 1x     1x     6x     6x 2x   4x   6x   6x           33x 1x 1x     6x       4x   4x                   33x 6x 24x             33x 6x 24x             33x       16x 10x 10x 10x   26x     33x         38x                 33x 32x   33x       8x 18x   8x 5x   8x     33x                   6x 3x       3x                   33x 16x   33x     33x                                                   33x         16x             16x               16x      
/*
 * 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 type { FormikProps } from 'formik'
import { Icon, SelectOption } from '@wings-software/uicore'
import type {
  DatadogAggregation,
  DatadogAggregationType,
  DatadogMetricInfo
} from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.type'
import type { StringKeys, UseStringsReturn } from 'framework/strings'
import {
  DatadogMetricsHealthSourceFieldNames,
  QUERY_CONTAINS_VALIDATION_PARAM
} from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.constants'
 
const datadogAggregations: DatadogAggregationType[] = ['avg', 'max', 'min', 'sum']
export const datadogAggregationOptions: DatadogAggregation[] = [
  {
    label: 'cv.monitoringSources.prometheus.avgAggregator',
    value: 'avg'
  },
  {
    label: 'cv.monitoringSources.prometheus.maxAggregator',
    value: 'max'
  },
  {
    label: 'cv.monitoringSources.prometheus.minAggregator',
    value: 'min'
  },
  {
    label: 'cv.monitoringSources.prometheus.sumAggregator',
    value: 'sum'
  }
]
export const DatadogMetricsQueryExtractor = (
  query: string,
  activeMetricValues: string[],
  aggregations: DatadogAggregationType[] = datadogAggregations
): {
  aggregation?: DatadogAggregationType
  activeMetric?: string
  metricTags: SelectOption[]
  groupingTags: string[]
} => {
  const aggregation = aggregations.find(aggregationItem => query.startsWith(aggregationItem))
  let activeMetric = activeMetricValues.find(metric => query.includes(metric))
  if (!activeMetric) {
    if (aggregation) {
      activeMetric = query.substring(query.indexOf(':') + 1, query.indexOf('{'))
    } else {
      Iif (query.indexOf('(') < query.indexOf('{')) {
        // this indicates that query contains function which starts with (
        activeMetric = query.substring(query.indexOf('(') + 1, query.indexOf('{'))
      } else {
        // there is no function and there is no aggregation, so metric starts from 0
        activeMetric = query.substring(0, query.indexOf('{'))
      }
    }
  }
  // extracting metricTags from query
  let metricTags: SelectOption[] = []
  const tagsString = query.substring(query.indexOf('{') + 1, query.indexOf('}'))
  if (tagsString !== '*') {
    metricTags = (tagsString.includes(',') ? tagsString.split(',') : [tagsString]).map(tag => {
      return {
        label: tag,
        value: tag
      }
    })
  }
  // extracting grouping tags from query
  let groupingTags: string[] = []
  const hostGroupingSearchString = 'by {'
  const hostGroupingIndex = query.indexOf(hostGroupingSearchString)
  if (hostGroupingIndex !== -1) {
    const groupingTagsString = query.substring(
      hostGroupingIndex + hostGroupingSearchString.length,
      query.indexOf('}', hostGroupingIndex + hostGroupingSearchString.length)
    )
    groupingTags = groupingTagsString.includes(',') ? groupingTagsString.split(',') : [groupingTagsString]
  }
  return {
    aggregation,
    activeMetric,
    metricTags,
    groupingTags
  }
}
 
export const DatadogMetricsQueryBuilder = (
  activeMetric: string,
  aggregation?: DatadogAggregationType,
  tags: string[] = [],
  groupingTags: string[] = [],
  serviceInstanceIdentifier?: string
): {
  query?: string
  groupingQuery?: string
} => {
  if (activeMetric?.length === 0) {
    return {
      query: ''
    }
  }
  let query: string
  Eif (aggregation && datadogAggregationOptions?.map(aggregationItem => aggregationItem.value).includes(aggregation)) {
    query = `${aggregation}:${activeMetric}`
  } else {
    query = activeMetric
  }
  if (tags.length > 0) {
    const tagsQueryPart = tags.reduce((prev, next) => {
      if (prev.length === 1) {
        return prev + next
      } else {
        return `${prev},${next}`
      }
    }, '{')
    query = `${query}${tagsQueryPart}}`
  } else {
    query = `${query}{*}`
  }
 
  if (groupingTags.length > 0) {
    const groupsQueryPart = groupingTags.reduce((prev, next) => {
      return `${prev},${next}`
    })
    query = `${query} by {${groupsQueryPart}}`
  }
 
  let groupedQuery = query
  // if there is serviceInstanceIdentifier selected and existing datadog query doesn't have grouping,
  // we should create groupedQuery to use it for CV
  if (serviceInstanceIdentifier && !groupingTags.length) {
    groupedQuery = `${query} by {${serviceInstanceIdentifier}}${QUERY_CONTAINS_VALIDATION_PARAM}`
  } else {
    groupedQuery = `${groupedQuery}${QUERY_CONTAINS_VALIDATION_PARAM}`
  }
  query = `${query}${QUERY_CONTAINS_VALIDATION_PARAM}`
 
  return {
    query,
    groupingQuery: groupedQuery
  }
}
 
export function mapMetricTagsHostIdentifierKeysOptions(metricTags: string[]): SelectOption[] {
  Eif (metricTags && Array.isArray(metricTags)) {
    return Array.from(
      new Set(
        metricTags.concat('host').map(metricTag => {
          return metricTag.split(':')?.[0]
        })
      )
    )
      .filter(tagKey => !!tagKey)
      .map(tagKey => {
        return {
          label: tagKey,
          value: tagKey
        }
      })
  } else {
    return []
  }
}
 
export function mapMetricTagsToMetricTagsOptions(metricTags: string[]): SelectOption[] {
  return metricTags.map(metricTag => {
    return {
      value: metricTag,
      label: metricTag
    }
  })
}
 
export function getDatadogAggregationOptions(getString: (key: StringKeys) => string): SelectOption[] {
  return datadogAggregationOptions.map(aggregation => {
    return {
      label: getString(aggregation.label),
      value: aggregation.value
    }
  })
}
 
export function initializeDatadogGroupNames(
  mappedMetrics: Map<string, DatadogMetricInfo>,
  getString: UseStringsReturn['getString']
): SelectOption[] {
  const groupNames = Array.from(mappedMetrics, keyValue => {
    const { groupName } = keyValue?.[1] || {}
    return groupName
  }).filter(groupItem => groupItem !== null) as SelectOption[]
 
  return [{ label: getString('cv.addNew'), value: '' }, ...groupNames].filter(val => val)
}
 
export const getOptions = (
  options: SelectOption[],
  getString: UseStringsReturn['getString'],
  loading?: boolean
): SelectOption[] =>
  loading
    ? [
        {
          value: getString('loading'),
          label: getString('loading')
        }
      ]
    : options
 
export const renderSearchLoading = (loading?: boolean): JSX.Element =>
  loading ? <Icon name="spinner" size={18} margin={{ top: 'xsmall', right: 'medium' }} /> : <></>
 
export const getActiveMetric = (
  activeMetricsOptions: SelectOption[],
  selectedMetricData?: DatadogMetricInfo
): SelectOption => {
  let activeMetricItem = activeMetricsOptions.find(activeMetric => {
    return selectedMetricData?.metric?.includes(activeMetric.value as string)
  })
  if (!activeMetricItem) {
    activeMetricItem = { label: selectedMetricData?.metric || '', value: selectedMetricData?.metric || '' }
  }
  return activeMetricItem
}
 
export const setServiceInstanceTag = (
  formikProps: FormikProps<DatadogMetricInfo>,
  onRebuildMetricData: (
    activeMetric?: string | undefined,
    aggregator?: DatadogAggregationType | undefined,
    selectedMetricTagOptions?: SelectOption[],
    serviceInstanceIdentifier?: string | undefined,
    groupName?: SelectOption | undefined
  ) => void
): void => {
  if (formikProps.values.serviceInstanceIdentifierTag !== formikProps.values?.serviceInstance) {
    formikProps.setFieldValue(
      DatadogMetricsHealthSourceFieldNames.SERVICE_INSTANCE_IDENTIFIER_TAG,
      formikProps.values.serviceInstanceIdentifierTag
    )
    onRebuildMetricData(
      formikProps.values.metric,
      formikProps.values.aggregator,
      formikProps.values.metricTags,
      formikProps.values?.serviceInstance as string,
      formikProps.values.groupName
    )
  }
}
 
export const getPlaceholder = (getString: UseStringsReturn['getString'], loading?: boolean): string =>
  loading ? getString('loading') : ''
 
export const getMetricValue = (currentActiveMetric: SelectOption, loading?: boolean): SelectOption =>
  loading ? { label: '', value: '' } : currentActiveMetric
 
export const onMetricChange = (
  value: string,
  formikProps: FormikProps<DatadogMetricInfo>,
  onRebuildMetricData: (
    activeMetric?: string | undefined,
    aggregator?: DatadogAggregationType | undefined,
    selectedMetricTagOptions?: SelectOption[],
    serviceInstanceIdentifier?: string | undefined,
    groupName?: SelectOption | undefined
  ) => void,
  resetActiveMetrics?: () => void
): void => {
  if (!value) {
    resetActiveMetrics?.()
  }
  formikProps.setFieldValue(DatadogMetricsHealthSourceFieldNames.METRIC, value)
  const filteredMetricTags = formikProps.values.metricTags?.filter(tag => tag.value)
  onRebuildMetricData(
    value as string,
    formikProps.values.aggregator,
    filteredMetricTags,
    formikProps.values.serviceInstanceIdentifierTag,
    formikProps.values.groupName
  )
}
 
export const setSearchPredicate = (
  getString: UseStringsReturn['getString'],
  search: string,
  itemList: SelectOption[]
): SelectOption[] => {
  Iif (!itemList.length && search.length) {
    return [
      {
        label: getString('cv.monitoredServices.noMatchingData'),
        value: getString('cv.monitoredServices.noMatchingData')
      }
    ]
  } else Iif (!itemList.length && !search.length) {
    return [
      {
        label: getString('cv.monitoredServices.noMatchingData'),
        value: getString('cv.monitoredServices.noMatchingData')
      }
    ]
  } else {
    return itemList
  }
}