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

84.72% Statements 122/144
76.97% Branches 127/165
78.26% Functions 18/23
85.11% Lines 120/141

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              24x 24x                         24x 24x 24x 24x 24x 24x 24x 24x 24x   24x           24x 24x 24x 24x 24x 24x 24x 24x                         24x   24x 24x 24x 24x   24x     68x 68x 68x       68x 14x     68x 12x                   56x 24x                   32x 20x     12x 3x             9x 3x           1x           6x                                   24x 49x   48x   48x   48x   48x 48x 48x     48x 48x 48x 48x 48x 48x 48x 8x                   48x   48x 15x     48x 48x   48x   7x 7x 7x 7x 7x 7x     6x 6x 6x   6x           1x     1x       1x 1x 1x   1x           48x   48x   48x       48x   48x             19x 19x 18x     19x                 79x   79x   75x       79x   79x 16x       16x     79x   75x       79x   79x                                                                               6x 4x   6x                             14x 1x   13x         1x 1x                                                                                                     1x                   1x 1x 1x 1x                                                                     7x                       7x 7x 7x 7x   7x                    
/*
 * 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, useContext, useEffect, useMemo, useState } from 'react'
import {
  Container,
  Formik,
  FormikForm,
  FormInput,
  Heading,
  Text,
  Icon,
  Utils,
  FormError,
  PageError,
  NoDataCard
} from '@wings-software/uicore'
import cx from 'classnames'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import { noop } from 'lodash-es'
import HighchartsReact from 'highcharts-react-official'
import Highcharts from 'highcharts'
import { Drawer } from '@blueprintjs/core'
import isEmpty from 'lodash-es/isEmpty'
import MonacoEditor from '@common/components/MonacoEditor/MonacoEditor'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import {
  StackdriverDefinition,
  useGetMetricPacks,
  useGetStackdriverDashboardDetail,
  useGetStackdriverSampleData
} from 'services/cv'
import { useStrings } from 'framework/strings'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import { SetupSourceLayout } from '@cv/components/CVSetupSourcesView/SetupSourceLayout/SetupSourceLayout'
import { SetupSourceTabsContext } from '@cv/components/CVSetupSourcesView/SetupSourceTabs/SetupSourceTabs'
import { QueryContent } from '@cv/components/QueryViewer/QueryViewer'
import { NameId } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import MetricDashboardWidgetNav from '@cv/components/MetricDashboardWidgetNav/MetricDashboardWidgetNav'
import {
  getManuallyCreatedQueries,
  formatJSON,
  initializeSelectedMetrics,
  transformSampleDataIntoHighchartOptions,
  validate,
  ensureFieldsAreFilled,
  transformGCOMetricSetupSourceToGCOHealthSource,
  transformGCOMetricHealthSourceToGCOMetricSetupSource,
  getPlaceholderForIdentifier,
  mapstackdriverDashboardDetailToMetricWidget,
  onSelectNavItem
} from './GCOMetricsHealthSource.utils'
import DrawerFooter from '../../common/DrawerFooter/DrawerFooter'
import type { GCOMetricInfo, GCOMetricsHealthSourceProps, ValidationChartProps } from './GCOMetricsHealthSource.type'
import { OVERALL, FieldNames, DrawerOptions } from './GCOMetricsHealthSource.constants'
import SelectHealthSourceServices from '../../common/SelectHealthSourceServices/SelectHealthSourceServices'
import MetricErrorAndLoading from '../../common/MetricErrorAndLoading/MetricErrorAndLoading'
import css from './GCOMetricsHealthSource.module.scss'
 
const GroupByClause = 'groupByFields'
 
function ValidationChart(props: ValidationChartProps): JSX.Element {
  const { loading, error, queryValue, onRetry, sampleData, setAsTooManyMetrics, isQueryExecuted = false } = props
  const { getString } = useStrings()
  const isTooManyMetrics = Boolean(
    sampleData?.series?.length && sampleData.series.length > 1 && queryValue?.includes(GroupByClause)
  )
 
  useEffect(() => {
    setAsTooManyMetrics?.(isTooManyMetrics)
  }, [sampleData])
 
  if (!queryValue?.length) {
    return (
      <Container className={cx(css.chartContainer, css.noDataContainer)}>
        <NoDataCard
          icon="main-notes"
          message={getString('cv.monitoringSources.gco.mapMetricsToServicesPage.enterQueryForValidation')}
        />
      </Container>
    )
  }
 
  if (!isQueryExecuted) {
    return (
      <Container className={cx(css.chartContainer, css.noDataContainer)}>
        <NoDataCard
          icon="timeline-line-chart"
          message={getString('cv.monitoringSources.gcoLogs.submitQueryToSeeRecords')}
        />
      </Container>
    )
  }
 
  if (loading) {
    return <Icon name="steps-spinner" size={32} color={Color.GREY_600} className={css.sampleDataSpinner} />
  }
 
  if (error) {
    return (
      <Container className={css.chartContainer}>
        <PageError message={error} onClick={() => onRetry()} />
      </Container>
    )
  }
 
  if (!sampleData?.series?.length) {
    return (
      <Container className={cx(css.chartContainer, css.noDataContainer)}>
        <NoDataCard
          icon="warning-sign"
          message={getString('cv.monitoringSources.gco.mapMetricsToServicesPage.noDataForQuery')}
          buttonText={getString('retry')}
          onClick={() => onRetry()}
        />
      </Container>
    )
  }
 
  return (
    <Container className={css.chartContainer}>
      <HighchartsReact highcharts={Highcharts} options={sampleData} />
      {isTooManyMetrics && (
        <Text
          intent="danger"
          font={{ size: 'small' }}
          className={css.tooManyRecords}
          icon="warning-sign"
          iconProps={{ intent: 'danger' }}
        >
          {getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.tooManyMetrics')}
        </Text>
      )}
    </Container>
  )
}
 
export function GCOMetricsHealthSource(props: GCOMetricsHealthSourceProps): JSX.Element {
  const { data, onSubmit } = props
 
  const { onPrevious, sourceData } = useContext(SetupSourceTabsContext)
 
  const { existingMetricDetails, selectedDashboards: selectedDashboardsContextValue = [] } = sourceData || {}
 
  const metricDefinitions = existingMetricDetails?.spec?.metricDefinitions
 
  const { getString } = useStrings()
  const transformedData = useMemo(() => transformGCOMetricHealthSourceToGCOMetricSetupSource(data), [data])
  const [updatedData, setUpdatedData] = useState(
    initializeSelectedMetrics(selectedDashboardsContextValue, transformedData.metricDefinition)
  )
  const [shouldShowChart, setShouldShowChart] = useState(false)
  const [isIdentifierEdited, setIsIdentifierEdited] = useState(false)
  const [selectedMetric, setSelectedMetric] = useState<string>()
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const [error, setError] = useState<string | undefined>()
  const [loading, setLoading] = useState(false)
  const queryParams = useMemo(
    () => ({
      orgIdentifier,
      projectIdentifier,
      accountId,
      tracingId: Utils.randomId(),
      connectorIdentifier: data.connectorRef as string
    }),
    [data?.connectorRef, projectIdentifier, orgIdentifier, accountId]
  )
 
  const { mutate, cancel } = useGetStackdriverSampleData({ queryParams })
 
  useEffect(() => {
    setIsIdentifierEdited(false)
  }, [selectedMetric])
 
  const [isQueryExpanded, setIsQueryExpanded] = useState(false)
  const [sampleData, setSampleData] = useState<Highcharts.Options | undefined>()
 
  const onQueryChange = useCallback(
    async (updatedQueryValue: string | undefined, onError?: () => void) => {
      cancel()
      try {
        Eif (updatedQueryValue?.length) {
          setLoading(true)
          setError(undefined)
          const response = await mutate(JSON.parse(updatedQueryValue), {
            queryParams: { ...queryParams, tracingId: Utils.randomId() }
          })
          Eif (response?.data) {
            setError(undefined)
            setSampleData(transformSampleDataIntoHighchartOptions(response?.data || []))
          }
          setLoading(false)
        } else {
          setError(undefined)
          setSampleData(transformSampleDataIntoHighchartOptions([]))
        }
      } catch (e) {
        Iif (e.message?.includes('The user aborted a request.')) {
          return
        }
        Iif (e.name === 'SyntaxError') {
          setError(getErrorMessage(e))
          setSampleData(transformSampleDataIntoHighchartOptions([]))
          onError?.()
        } else Eif (e?.data) {
          setError(getErrorMessage(e))
          setSampleData(transformSampleDataIntoHighchartOptions([]))
        }
        setLoading(false)
      }
    },
    [mutate, cancel]
  )
 
  const stackDriverDashBoardRequest = useGetStackdriverDashboardDetail({ lazy: true })
 
  const { loading: loadingDashBoardData } = stackDriverDashBoardRequest
 
  const metricPackResponse = useGetMetricPacks({
    queryParams: { projectIdentifier, orgIdentifier, accountId, dataSourceType: 'STACKDRIVER' }
  })
 
  const formInitialValues: GCOMetricInfo = updatedData.get(selectedMetric || '') || {}
 
  return (
    <Formik<GCOMetricInfo>
      enableReinitialize={true}
      formName="mapGCOMetrics"
      initialValues={formInitialValues}
      onSubmit={noop}
      validate={values => {
        const newMap = new Map(updatedData)
        if (selectedMetric) {
          newMap.set(selectedMetric, { ...values })
        }
 
        return validate(values, newMap, getString)
      }}
    >
      {formikProps => {
        const {
          sli = false,
          healthScore = false,
          continuousVerification = false,
          riskCategory = ''
        } = formikProps?.values
 
        const currentSelectedMetricDetail = metricDefinitions?.find(
          (metricDefinition: StackdriverDefinition) =>
            metricDefinition.metricName === updatedData.get(selectedMetric as string)?.metricName
        )
 
        const shouldShowIdentifierPlaceholder =
          !currentSelectedMetricDetail?.identifier && !formikProps.values?.identifier
 
        if (shouldShowIdentifierPlaceholder && !isIdentifierEdited) {
          formikProps.setFieldValue(
            FieldNames.IDENTIFIER,
            getPlaceholderForIdentifier(formikProps.values?.metricName, getString)
          )
          setIsIdentifierEdited(true)
        }
 
        const dashboard: { itemId: string; title: string }[] = selectedDashboardsContextValue.map(
          (item: { id: string; name: string }) => {
            return { itemId: item.id, title: item.name }
          }
        )
 
        const isDashdoardEmpty = !Object.values(dashboard).filter(item => item.title).length
 
        return (
          <SetupSourceLayout
            content={
              <FormikForm className={css.setupContainer}>
                <Heading level={3} color={Color.BLACK} className={css.sectionHeading}>
                  {getString('cv.monitoringSources.gco.mapMetricsToServicesPage.querySpecifications')}
                </Heading>
 
                <MetricErrorAndLoading isEmpty={isEmpty(formInitialValues)} loading={loadingDashBoardData}>
                  <>
                    <Container className={css.nameAndMetricTagContainer}>
                      <FormInput.KVTagInput
                        label={getString('cv.monitoringSources.gco.mapMetricsToServicesPage.metricTagsLabel')}
                        name={FieldNames.METRIC_TAGS}
                        tagsProps={{
                          addOnBlur: true,
                          addOnPaste: true,
                          onChange: values => {
                            const newTagObj: { [key: string]: any } = {}
                            ;(values as string[])?.forEach(val => {
                              newTagObj[val as string] = ''
                            })
                            formikProps.setFieldValue(FieldNames.METRIC_TAGS, newTagObj)
                          }
                        }}
                      />
                      <FormError name="metricTags" errorMessage={formikProps.errors['metricTags']} />
                      <NameId
                        nameLabel={getString('cv.monitoringSources.metricNameLabel')}
                        identifierProps={{
                          inputName: FieldNames.METRIC_NAME,
                          idName: FieldNames.IDENTIFIER,
                          isIdentifierEditable: Boolean(!currentSelectedMetricDetail?.identifier)
                        }}
                      />
                    </Container>
 
                    <Container className={css.validationContainer}>
                      <QueryContent
                        handleFetchRecords={async () => {
                          if (!shouldShowChart) {
                            setShouldShowChart(true)
                          }
                          onQueryChange(formikProps.values.query)
                        }}
                        onClickExpand={setIsQueryExpanded}
                        isDialogOpen={isQueryExpanded}
                        query={formikProps.values.query}
                        loading={loading}
                        textAreaName={FieldNames.QUERY}
                      />
 
                      <ValidationChart
                        loading={loading}
                        error={error}
                        sampleData={sampleData}
                        queryValue={formikProps.values.query}
                        setAsTooManyMetrics={isTooMany => {
                          if (isTooMany) {
                            formikProps.setFieldError('tooManyMetrics', 'invalid')
                          } else {
                            formikProps.setFieldError('tooManyMetrics', '')
                          }
                        }}
                        isQueryExecuted={shouldShowChart}
                        onRetry={async () => {
                          Iif (!formikProps.values.query?.length) return
                          onQueryChange(formikProps.values.query)
                        }}
                      />
 
                      {isQueryExpanded && (
                        <Drawer
                          {...DrawerOptions}
                          onClose={() => {
                            setIsQueryExpanded(false)
                          }}
                        >
                          <MonacoEditor
                            language="javascript"
                            value={formatJSON(formikProps.values.query)}
                            data-testid="monaco-editor"
                            onChange={val => formikProps.setFieldValue(FieldNames.QUERY, val)}
                            options={
                              {
                                readOnly: false,
                                wordBasedSuggestions: false,
                                fontFamily: "'Roboto Mono', monospace",
                                fontSize: 13
                              } as any
                            }
                          />
                        </Drawer>
                      )}
                    </Container>
                    <SelectHealthSourceServices
                      values={{
                        sli,
                        healthScore,
                        riskCategory,
                        continuousVerification
                      }}
                      metricPackResponse={metricPackResponse}
                      hideServiceIdentifier
                    />
                    {formikProps.values.continuousVerification && (
                      <FormInput.Text
                        name={FieldNames.SERVICE_INSTANCE_FIELD}
                        label={getString('cv.monitoringSources.serviceInstanceIdentifier')}
                      />
                    )}
                    <FormInput.Text name={OVERALL} className={css.hiddenField} />
                  </>
                </MetricErrorAndLoading>
                <DrawerFooter
                  onPrevious={onPrevious}
                  isSubmit
                  onNext={async () => {
                    formikProps.setTouched({
                      ...formikProps.touched,
                      [OVERALL]: true,
                      [FieldNames.SLI]: true,
                      [FieldNames.RISK_CATEGORY]: true,
                      [FieldNames.HIGHER_BASELINE_DEVIATION]: true,
                      [FieldNames.LOWER_BASELINE_DEVIATION]: true,
                      [FieldNames.SERVICE_INSTANCE_FIELD]: true
                    } as any)
 
                    const errors = validate(formikProps.values, updatedData, getString)
                    Eif (!isEmpty(errors)) {
                      formikProps.setErrors({ ...errors })
                      return
                    }
 
                    if (selectedMetric) {
                      updatedData.set(selectedMetric, { ...formikProps.values })
                    }
                    const filteredData = new Map()
                    for (const metric of updatedData) {
                      const [metricName, metricInfo] = metric
                      if (isEmpty(ensureFieldsAreFilled(metricInfo, getString, new Map(updatedData)))) {
                        filteredData.set(metricName, metricInfo)
                      }
                    }
 
                    await onSubmit(
                      data,
                      transformGCOMetricSetupSourceToGCOHealthSource({
                        ...transformedData,
                        metricDefinition: filteredData
                      })
                    )
                  }}
                />
              </FormikForm>
            }
            leftPanelContent={
              <MetricDashboardWidgetNav
                dashboards={isDashdoardEmpty ? [] : dashboard}
                dashboardWidgetMapper={mapstackdriverDashboardDetailToMetricWidget}
                dashboardDetailsRequest={stackDriverDashBoardRequest}
                addManualQueryTitle={'cv.monitoringSources.gco.manualInputQueryModal.modalTitle'}
                connectorIdentifier={data.connectorRef as string}
                manuallyInputQueries={getManuallyCreatedQueries(updatedData)}
                showSpinnerOnLoad={!selectedMetric}
                onSelectMetric={(id, metricName, query, widget, dashboardId, dashboardTitle) => {
                  onSelectNavItem({
                    id,
                    metricName,
                    query,
                    widget,
                    dashboardId,
                    dashboardTitle,
                    updatedData,
                    setUpdatedData,
                    selectedMetric,
                    formikProps
                  })
                  setSelectedMetric(metricName)
                  setShouldShowChart(false)
                  setError(undefined)
                  setSampleData(transformSampleDataIntoHighchartOptions([]))
 
                  formikProps.resetForm()
                }}
              />
            }
          />
        )
      }}
    </Formik>
  )
}