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

75.76% Statements 50/66
72.22% Branches 117/162
62.5% Functions 15/24
76.19% Lines 48/63

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              25x   25x 25x 25x   25x 25x                           25x   25x   25x                         16x 16x 16x       16x   16x 6x 15x       16x 6x       18x                 16x 16x 16x       16x 6x 6x 6x   6x     16x 6x     16x 8x       16x 6x     16x 10x                                             16x             9x 3x             3x 3x 3x                     3x       16x 10x 5x   5x         16x                                                                                         16x                                                                                                        
/*
 * 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 React, { useEffect, useMemo, useState } from 'react'
import type { ITagInputProps } from '@blueprintjs/core'
import { FormInput, SelectOption } from '@wings-software/uicore'
import { DatadogMetricsHealthSourceFieldNames } from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.constants'
import GroupName from '@cv/components/GroupName/GroupName'
import type { DatadogAggregationType } from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.type'
import { useStrings } from 'framework/strings'
import {
  DatadogMetricsQueryBuilder,
  DatadogMetricsQueryExtractor,
  getActiveMetric,
  getDatadogAggregationOptions,
  getOptions,
  getPlaceholder,
  initializeDatadogGroupNames,
  mapMetricTagsToMetricTagsOptions,
  onMetricChange,
  renderSearchLoading,
  setSearchPredicate,
  setServiceInstanceTag
} from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/components/DatadogMetricsDetailsContent/DatadogMetricsDetailsContent.utils'
import { NameId } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import type { DatadogMetricsDetailsContentProps } from './DatadogMetricsDetailsContent.type'
import css from '../../DatadogMetricsHealthSource.module.scss'
 
export default function DatadogMetricsDetailsContent(props: DatadogMetricsDetailsContentProps): JSX.Element {
  const {
    selectedMetric,
    selectedMetricData,
    formikProps,
    metricHealthDetailsData,
    setMetricHealthDetailsData,
    metricTags,
    activeMetrics,
    metricTagsLoading,
    activeMetricsLoading,
    fetchActiveMetrics,
    fetchMetricTags
  } = props
  const { getString } = useStrings()
  const [metricGroupNames, setMetricGroupNames] = useState<SelectOption[]>(
    initializeDatadogGroupNames(metricHealthDetailsData, getString)
  )
 
  const aggregationItems = useMemo(() => getDatadogAggregationOptions(getString), [])
 
  const currentAggregation = useMemo(() => {
    return aggregationItems.find(aggregationItem => {
      return selectedMetricData?.aggregator === aggregationItem.value
    })
  }, [selectedMetricData?.aggregator, aggregationItems])
 
  const activeMetricsOptions = useMemo(() => {
    return (
      (activeMetrics &&
        Array.isArray(activeMetrics) &&
        activeMetrics?.map(activeMetric => {
          return {
            value: activeMetric,
            label: activeMetric
          }
        })) ||
      []
    )
  }, [activeMetrics, activeMetricsLoading])
 
  const [isDefaultMetricSet, setIsDefaultMetricSet] = useState(false)
  const [defaultMetric, setDefaultMetric] = useState<SelectOption[]>()
  const [itemList, setItemList] = useState<SelectOption[]>(
    getOptions(activeMetricsOptions, getString, activeMetricsLoading)
  )
 
  useEffect(() => {
    Eif (!isDefaultMetricSet && activeMetricsOptions.length) {
      setIsDefaultMetricSet(true)
      setDefaultMetric(activeMetricsOptions)
    }
    setItemList(getOptions(activeMetricsOptions, getString, activeMetricsLoading))
  }, [activeMetricsOptions])
 
  const metricTagsOptions = useMemo(() => {
    return mapMetricTagsToMetricTagsOptions(metricTags || [])
  }, [metricTags])
 
  const currentActiveMetric: SelectOption = useMemo(
    () => getActiveMetric(activeMetricsOptions, selectedMetricData),
    [selectedMetricData?.metric, activeMetricsOptions]
  )
 
  useEffect(() => {
    setServiceInstanceTag(formikProps, onRebuildMetricData)
  }, [formikProps.values?.serviceInstance])
 
  useEffect(() => {
    Iif (
      selectedMetricData?.metricPath &&
      formikProps.values.metricPath === selectedMetricData?.metricPath &&
      formikProps.values.isManualQuery
    ) {
      const queryExtractor = DatadogMetricsQueryExtractor(formikProps.values.query || '', [])
      metricHealthDetailsData.set(selectedMetricData.metricPath, {
        ...selectedMetricData,
        query: formikProps.values.query,
        metric: queryExtractor.activeMetric,
        metricTags: queryExtractor.metricTags,
        groupingTags: queryExtractor.groupingTags,
        aggregator: queryExtractor.aggregation
      })
    }
  }, [
    selectedMetricData,
    metricHealthDetailsData,
    formikProps.values.query,
    formikProps.values.metricPath,
    formikProps.values.isManualQuery,
    selectedMetricData?.metricPath
  ])
  const onRebuildMetricData = (
    activeMetric?: string,
    aggregator?: DatadogAggregationType,
    selectedMetricTagOptions: SelectOption[] = [],
    serviceInstanceIdentifier?: string,
    groupName?: SelectOption
  ): void => {
    const selectedMetricTags = selectedMetricTagOptions?.map(tagOption => tagOption.value as string)
    const queryBuilder = DatadogMetricsQueryBuilder(
      activeMetric || '',
      aggregator,
      selectedMetricTags,
      formikProps.values.groupingTags || [],
      serviceInstanceIdentifier
    )
    const query = formikProps.values.isManualQuery ? formikProps.values.query : queryBuilder.query
    Eif (selectedMetric && selectedMetricData) {
      metricHealthDetailsData.set(selectedMetric, {
        ...formikProps.values,
        isCustomCreatedMetric: selectedMetricData.isCustomCreatedMetric,
        groupName: groupName,
        query: query,
        groupingQuery: queryBuilder.groupingQuery,
        aggregator: aggregator,
        metric: activeMetric,
        serviceInstanceIdentifierTag: serviceInstanceIdentifier,
        metricTags: selectedMetricTagOptions
      })
      setMetricHealthDetailsData(new Map(metricHealthDetailsData))
    }
  }
 
  useEffect(() => {
    if (!selectedMetricData || formikProps.values.metricPath !== selectedMetricData.metricPath) {
      return
    }
    Iif (Boolean(selectedMetricData?.isManualQuery) !== Boolean(formikProps.values.isManualQuery)) {
      onRebuildMetricData(undefined, undefined, undefined, undefined, selectedMetricData?.groupName)
    }
  }, [formikProps.values.isManualQuery, formikProps.values.identifier, selectedMetricData])
 
  return (
    <>
      <NameId
        nameLabel={getString('cv.monitoringSources.metricNameLabel')}
        identifierProps={{
          inputName: DatadogMetricsHealthSourceFieldNames.METRIC_NAME,
          idName: DatadogMetricsHealthSourceFieldNames.METRIC_IDENTIFIER,
          isIdentifierEditable: Boolean(!selectedMetricData?.identifier || selectedMetricData?.isNew)
        }}
      />
      <GroupName
        disabled={!selectedMetricData?.isCustomCreatedMetric}
        item={formikProps?.values?.groupName || { label: '', value: '' }}
        fieldName={DatadogMetricsHealthSourceFieldNames.GROUP_NAME}
        title={getString('cv.monitoringSources.datadog.newDatadogGroupName')}
        groupNames={metricGroupNames}
        onChange={(fieldName: string, chosenOption: SelectOption) => {
          formikProps.setFieldValue(fieldName, chosenOption)
          const filteredMetricTags = formikProps.values.metricTags?.filter(tag => tag.value)
          onRebuildMetricData(
            formikProps.values.metric,
            formikProps.values.aggregator,
            filteredMetricTags,
            formikProps.values.serviceInstanceIdentifierTag,
            chosenOption
          )
        }}
        setGroupNames={setMetricGroupNames}
      />
 
      <FormInput.Select
        disabled={!selectedMetricData?.isCustomCreatedMetric || formikProps?.values?.isManualQuery}
        label={getString('cv.monitoringSources.metricLabel')}
        name={DatadogMetricsHealthSourceFieldNames.METRIC}
        items={itemList}
        value={currentActiveMetric}
        onQueryChange={search => {
          if (search) {
            fetchActiveMetrics?.(search)
          }
        }}
        placeholder={getPlaceholder(getString, activeMetricsLoading)}
        selectProps={{
          addClearBtn: !activeMetricsLoading,
          whenPopoverClosed: () => defaultMetric && setItemList(defaultMetric),
          itemListPredicate: search => setSearchPredicate(getString, search, itemList)
        }}
        inputGroup={{ rightElement: renderSearchLoading(activeMetricsLoading) }}
        onChange={event => {
          onMetricChange(event.value as string, formikProps, onRebuildMetricData, fetchActiveMetrics)
        }}
      />
      <FormInput.Select
        disabled={!selectedMetricData?.isCustomCreatedMetric || formikProps?.values?.isManualQuery}
        label={getString('cv.monitoringSources.prometheus.aggregator')}
        name={DatadogMetricsHealthSourceFieldNames.AGGREGATOR}
        items={aggregationItems}
        isOptional={true}
        value={currentAggregation || { label: '', value: '' }}
        onChange={event => {
          formikProps.setFieldValue(DatadogMetricsHealthSourceFieldNames.AGGREGATOR, event.value)
          onRebuildMetricData(
            formikProps.values.metric,
            event.value as DatadogAggregationType,
            formikProps.values.metricTags,
            formikProps.values.serviceInstanceIdentifierTag,
            formikProps.values.groupName
          )
        }}
        selectProps={{
          addClearBtn: true
        }}
      />
      <FormInput.MultiSelect
        className={css.metricTag}
        disabled={!selectedMetricData?.isCustomCreatedMetric || formikProps?.values?.isManualQuery}
        label={getString('cv.monitoringSources.gco.mapMetricsToServicesPage.metricTagsLabel')}
        name={DatadogMetricsHealthSourceFieldNames.METRIC_TAGS}
        items={getOptions(metricTagsOptions, getString, metricTagsLoading)}
        isOptional={true}
        tagInputProps={{ rightElement: renderSearchLoading(metricTagsLoading) } as unknown as ITagInputProps}
        multiSelectProps={{
          onQueryChange: search => fetchMetricTags?.(search)
        }}
        onChange={selectedOptions => {
          onRebuildMetricData(
            formikProps.values.metric,
            formikProps.values.aggregator,
            selectedOptions.filter(value => (value.value as string).length),
            formikProps.values.serviceInstanceIdentifierTag,
            formikProps.values.groupName
          )
        }}
      />
    </>
  )
}