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

70.54% Statements 79/112
65.79% Branches 100/152
65.22% Functions 15/23
69.72% Lines 76/109

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              24x 24x 24x 24x   24x 24x         24x                       24x               24x 24x 24x   24x 24x   24x 24x 24x 24x 24x   24x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x               5x                           5x 5x 3x   5x     5x 3x             5x       5x 3x     5x                                         5x                                               5x 5x                                           5x 3x     5x 1x 1x                       5x 5x     5x           2x 2x                 5x     5x       2x 2x 2x 2x   2x 2x       2x 2x 2x   5x                                                                   5x 5x             5x   5x                             7x 7x 3x         7x                                           2x                                                  
/*
 * 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, { useCallback, useEffect, useMemo, useState } from 'react'
import { Formik, FormikForm, useToaster, Utils } from '@wings-software/uicore'
import { debounce, noop } from 'lodash-es'
import { useParams } from 'react-router-dom'
import type { FormikProps } from 'formik'
import isEmpty from 'lodash-es/isEmpty'
import { useStrings } from 'framework/strings'
import type {
  DatadogMetricInfo,
  DatadogMetricsHealthSourceProps
} from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.type'
import {
  validateFormMappings,
  getCustomCreatedMetrics,
  mapDatadogMetricHealthSourceToDatadogMetricSetupSource,
  validate,
  mapSelectedWidgetDataToDatadogMetricInfo,
  mapDatadogDashboardDetailToMetricWidget,
  getSelectedDashboards,
  mapDatadogMetricSetupSourceToDatadogHealthSource,
  getServiceIntance
} from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.utils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import {
  DatadogDashboardDetail,
  TimeSeriesSampleDTO,
  useGetDatadogActiveMetrics,
  useGetDatadogDashboardDetails,
  useGetDatadogSampleData,
  useGetDatadogMetricTags
} from 'services/cv'
import { MANUAL_INPUT_QUERY } from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/components/ManualInputQueryModal/ManualInputQueryModal'
import { DatasourceTypeEnum } from '@cv/pages/monitored-service/components/ServiceHealth/components/MetricsAndLogs/MetricsAndLogs.types'
import { DatadogMetricsHealthSourceFieldNames } from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/DatadogMetricsHealthSource.constants'
import type { MetricWidget } from '@cv/components/MetricDashboardWidgetNav/MetricDashboardWidgetNav.type'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import CloudMetricsHealthSource from '@cv/components/CloudMetricsHealthSource/CloudMetricsHealthSource'
import type { SelectedWidgetMetricData } from '@cv/components/CloudMetricsHealthSource/CloudMetricsHealthSource.type'
import DatadogMetricsDetailsContent from '@cv/pages/health-source/connectors/DatadogMetricsHealthSource/components/DatadogMetricsDetailsContent/DatadogMetricsDetailsContent'
import { FieldNames } from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/GCOMetricsHealthSource.constants'
import { getPlaceholderForIdentifier } from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/GCOMetricsHealthSource.utils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { DatadogMetricsQueryExtractor } from './components/DatadogMetricsDetailsContent/DatadogMetricsDetailsContent.utils'
 
export default function DatadogMetricsHealthSource(props: DatadogMetricsHealthSourceProps): JSX.Element {
  const { data } = props
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const { showError } = useToaster()
  const transformedData = useMemo(() => mapDatadogMetricHealthSourceToDatadogMetricSetupSource(data), [data])
  const [metricHealthDetailsData, setMetricHealthDetailsData] = useState(transformedData.metricDefinition)
  const [activeMetricsTracingId, metricTagsTracingId] = useMemo(() => [Utils.randomId(), Utils.randomId()], [])
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const [selectedMetricId, setSelectedMetricId] = useState<string>()
  const selectedMetricData = metricHealthDetailsData.get(selectedMetricId || '')
  const initialCustomCreatedMetrics = useMemo(() => {
    return getCustomCreatedMetrics(data?.selectedMetrics || transformedData.metricDefinition)
  }, [data?.selectedMetrics, transformedData.metricDefinition])
 
  const {
    data: activeMetrics,
    refetch: refetchActiveMetrics,
    loading: activeMetricsLoading,
    error: activeMetricError
  } = useGetDatadogActiveMetrics({
    queryParams: {
      projectIdentifier,
      orgIdentifier,
      accountId,
      connectorIdentifier: data.connectorRef as string,
      tracingId: activeMetricsTracingId
    }
  })
  const {
    data: timeseriesData,
    refetch: timeseriesRefech,
    loading: timeseriesLoading,
    error: timeseriesDataError
  } = useGetDatadogSampleData({ lazy: true })
  const timeseriesDataErrorMessage = useMemo(() => {
    return getErrorMessage(timeseriesDataError)
  }, [timeseriesDataError])
  const [currentTimeseriesData, setCurrentTimeseriesData] = useState<TimeSeriesSampleDTO[] | null>(
    timeseriesData?.data || null
  )
  useEffect(() => {
    setCurrentTimeseriesData(timeseriesData?.data || null)
  }, [timeseriesData?.data])
 
  const {
    data: metricTags,
    refetch: refetchMetricTags,
    loading: loadingMetricTags
  } = useGetDatadogMetricTags({
    lazy: true
  })
 
  useEffect(() => {
    activeMetricError && showError(getErrorMessage(activeMetricError))
  }, [activeMetricError])
 
  const debounceRefetchActiveMetrics = useCallback(
    debounce((query?: string): void => {
      try {
        const queryObject = query ? { filter: query } : {}
        refetchActiveMetrics({
          queryParams: {
            projectIdentifier,
            orgIdentifier,
            accountId,
            connectorIdentifier: data.connectorRef as string,
            tracingId: activeMetricsTracingId,
            ...queryObject
          }
        })
      } catch (e) {
        showError(getRBACErrorMessage(e))
      }
    }, 1000),
    [data.connectorRef, activeMetricsTracingId]
  )
 
  const debounceRefetchMetricTags = useCallback(
    debounce((query?: string): void => {
      try {
        const queryObject = query ? { filter: query } : {}
        if (selectedMetricData?.metric) {
          refetchMetricTags({
            queryParams: {
              projectIdentifier,
              orgIdentifier,
              accountId,
              connectorIdentifier: data.connectorRef,
              tracingId: metricTagsTracingId,
              metric: selectedMetricData?.metric,
              ...queryObject
            }
          })
        }
      } catch (e) {
        showError(getRBACErrorMessage(e))
      }
    }, 2000),
    [selectedMetricData]
  )
 
  useEffect(() => {
    Iif (selectedMetricData?.metric) {
      refetchMetricTags({
        queryParams: {
          projectIdentifier,
          orgIdentifier,
          accountId,
          connectorIdentifier: data.connectorRef,
          tracingId: metricTagsTracingId,
          metric: selectedMetricData.metric
        }
      })
    }
  }, [
    selectedMetricData?.metric,
    projectIdentifier,
    orgIdentifier,
    accountId,
    data.connectorRef,
    activeMetricsTracingId,
    refetchMetricTags,
    metricTagsTracingId
  ])
  const selectedDashboards = useMemo(() => {
    return getSelectedDashboards(data)
  }, [data])
 
  const handleOnTimeseriesFetch = (query: string): void => {
    Eif (query) {
      timeseriesRefech({
        queryParams: {
          orgIdentifier,
          projectIdentifier,
          accountId,
          tracingId: Utils.randomId(),
          connectorIdentifier: data.connectorRef as string,
          query: query
        }
      })
    }
  }
  useEffect(() => {
    Iif (!activeMetrics?.data) {
      return
    }
    if (
      selectedMetricData &&
      selectedMetricData.metricPath &&
      !selectedMetricData.metric &&
      !selectedMetricData.isCustomCreatedMetric
    ) {
      const queryExtractor = DatadogMetricsQueryExtractor(selectedMetricData.query || '', activeMetrics?.data || [])
      metricHealthDetailsData.set(selectedMetricData.metricPath, {
        ...selectedMetricData,
        metric: queryExtractor.activeMetric,
        metricTags: queryExtractor.metricTags,
        groupingTags: queryExtractor.groupingTags,
        aggregator: queryExtractor.aggregation
      })
    }
  }, [activeMetrics?.data, selectedMetricData, metricHealthDetailsData, activeMetricsLoading])
  const handleOnChangeManualEditQuery = (formikProps: FormikProps<DatadogMetricInfo>, enabled: boolean): void => {
    formikProps.setFieldValue(DatadogMetricsHealthSourceFieldNames.IS_MANUAL_QUERY, enabled)
  }
  const handleOnMetricSelected = (
    selectedWidgetMetricData: SelectedWidgetMetricData,
    formikProps: FormikProps<DatadogMetricInfo>
  ): void => {
    let metricInfo: DatadogMetricInfo | undefined = metricHealthDetailsData.get(selectedWidgetMetricData.id)
    const query = selectedWidgetMetricData.query === MANUAL_INPUT_QUERY ? '' : selectedWidgetMetricData.query
    Eif (!metricInfo) {
      metricInfo = mapSelectedWidgetDataToDatadogMetricInfo(selectedWidgetMetricData, query, activeMetrics?.data || [])
    }
    metricHealthDetailsData.set(selectedWidgetMetricData.id, metricInfo)
    Iif (selectedMetricId) {
      // save changes for previous metric
      metricHealthDetailsData.set(selectedMetricId, { ...selectedMetricData, ...formikProps.values })
    }
    setMetricHealthDetailsData(new Map(metricHealthDetailsData))
    setSelectedMetricId(selectedWidgetMetricData.id)
    setCurrentTimeseriesData(null)
  }
  const handleOnNext = async (formikProps: FormikProps<DatadogMetricInfo>): Promise<void> => {
    formikProps.setTouched({
      ...formikProps.touched,
      [DatadogMetricsHealthSourceFieldNames.GROUP_NAME]: true,
      [DatadogMetricsHealthSourceFieldNames.METRIC]: true,
      [DatadogMetricsHealthSourceFieldNames.SLI]: true,
      [DatadogMetricsHealthSourceFieldNames.RISK_CATEGORY]: true,
      [DatadogMetricsHealthSourceFieldNames.HIGHER_BASELINE_DEVIATION]: true,
      [DatadogMetricsHealthSourceFieldNames.LOWER_BASELINE_DEVIATION]: true,
      [DatadogMetricsHealthSourceFieldNames.SERVICE_INSTANCE]: true
    })
    const errors = validate(formikProps.values, metricHealthDetailsData, getString)
    if (!isEmpty(errors)) {
      formikProps.setErrors({ ...errors })
      return
    }
    if (selectedMetricId) {
      metricHealthDetailsData.set(selectedMetricId, { ...selectedMetricData, ...formikProps.values })
    }
    const filteredData = new Map()
    for (const metric of metricHealthDetailsData) {
      const [metricName, metricInfo] = metric
      if (isEmpty(validateFormMappings(metricInfo, metricHealthDetailsData, getString))) {
        filteredData.set(metricName, metricInfo)
      }
    }
    await props.onSubmit(
      data,
      mapDatadogMetricSetupSourceToDatadogHealthSource({
        ...transformedData,
        metricDefinition: filteredData
      })
    )
  }
  const dashboardRequest = useGetDatadogDashboardDetails({ lazy: true })
  const dashboardDetailToMetricWidgetItemMapper = useCallback(
    (dashboardId: string, datadogDashboardDetail: DatadogDashboardDetail): MetricWidget => {
      return mapDatadogDashboardDetailToMetricWidget(dashboardId, datadogDashboardDetail)
    },
    []
  )
 
  const serviceInstanceList = useMemo(() => getServiceIntance(metricTags?.data?.tagKeys), [metricTags?.data?.tagKeys])
 
  return (
    <Formik<DatadogMetricInfo>
      enableReinitialize={true}
      formName="mapDatadogMetrics"
      initialValues={selectedMetricData || {}}
      onSubmit={noop}
      validate={values => {
        const newMap = new Map(metricHealthDetailsData)
        if (selectedMetricId) {
          newMap.set(selectedMetricId, { ...values })
        }
        return validate(values, newMap, getString)
      }}
    >
      {formikProps => {
        const shouldShowIdentifierPlaceholder = !selectedMetricData?.identifier && !formikProps.values?.identifier
        if (shouldShowIdentifierPlaceholder) {
          formikProps.setFieldValue(
            FieldNames.IDENTIFIER,
            getPlaceholderForIdentifier(formikProps.values?.metricName, getString)
          )
        }
        return (
          <FormikForm>
            <CloudMetricsHealthSource
              onChangeManualEditQuery={enabled => handleOnChangeManualEditQuery(formikProps, enabled)}
              formikProps={formikProps}
              dashboardDetailRequest={dashboardRequest}
              dashboardDetailMapper={dashboardDetailToMetricWidgetItemMapper}
              dataSourceType={DatasourceTypeEnum.DATADOG_METRICS}
              addManualQueryTitle={'cv.monitoringSources.datadog.manualInputQueryModal.modalTitle'}
              manualQueries={initialCustomCreatedMetrics}
              onNextClicked={() => handleOnNext(formikProps)}
              selectedMetricInfo={{
                query: formikProps.values.query,
                queryEditable: formikProps.values.isManualQuery,
                timeseriesData: currentTimeseriesData
              }}
              onFetchTimeseriesData={handleOnTimeseriesFetch}
              timeseriesDataLoading={timeseriesLoading}
              timeseriesDataError={timeseriesDataErrorMessage}
              dashboards={selectedDashboards}
              connectorRef={data?.connectorRef as string}
              onWidgetMetricSelected={selectedWidgetMetricData =>
                handleOnMetricSelected(selectedWidgetMetricData, formikProps)
              }
              serviceInstanceList={serviceInstanceList}
              metricDetailsContent={
                <DatadogMetricsDetailsContent
                  selectedMetric={selectedMetricId}
                  selectedMetricData={selectedMetricData}
                  metricHealthDetailsData={metricHealthDetailsData}
                  formikProps={formikProps}
                  setMetricHealthDetailsData={setMetricHealthDetailsData}
                  metricTags={metricTags?.data?.metricTags || []}
                  activeMetrics={activeMetrics?.data}
                  activeMetricsLoading={activeMetricsLoading}
                  metricTagsLoading={loadingMetricTags}
                  fetchActiveMetrics={debounceRefetchActiveMetrics}
                  fetchMetricTags={debounceRefetchMetricTags}
                />
              }
            />
          </FormikForm>
        )
      }}
    </Formik>
  )
}