All files / modules/85-cv/pages/health-source/connectors/PrometheusHealthSource/components/PrometheusQueryViewer PrometheusQueryViewer.tsx

79.25% Statements 42/53
50.53% Branches 48/95
55.56% Functions 5/9
80.77% Lines 42/52

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              24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x 24x       24x                                     24x                       24x 1x 1x   1x 1x 1x   1x                                   1x                         24x 1x 1x 1x 1x 1x 1x     1x                   1x 1x 1x 1x     1x 1x                 1x   1x                                                                                                     1x               1x              
/*
 * 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, { useEffect, useMemo, useState } from 'react'
import HighchartsReact from 'highcharts-react-official'
import Highcharts from 'highcharts'
import { IDrawerProps, Position, Drawer } from '@blueprintjs/core'
import cx from 'classnames'
import { Container, Text, Utils, useConfirmationDialog } from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { useStrings } from 'framework/strings'
import { ResponseListPrometheusSampleData, useGetSampleData } from 'services/cv'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { Records } from '@cv/components/Records/Records'
import { QueryContent } from '@cv/components/QueryViewer/QueryViewer'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import { transformPrometheusSampleData, createPrometheusQuery } from './PrometheusQueryViewer.utils'
import {
  MapPrometheusQueryToService,
  PrometheusMonitoringSourceFieldNames
} from '../../PrometheusHealthSource.constants'
import css from './PrometheusQueryViewer.module.scss'
 
export interface PrometheusQueryViewerProps {
  values?: MapPrometheusQueryToService
  className?: string
  connectorIdentifier?: string
  onChange: (fieldName: string, value: any) => void
}
 
interface ChartAndRecordsProps {
  query?: string
  error?: string | null
  loading?: boolean
  data?: ResponseListPrometheusSampleData | null
  isQueryExecuted?: boolean
  fetchData: () => void
  onChange: PrometheusQueryViewerProps['onChange']
}
 
const DrawerProps: IDrawerProps = {
  autoFocus: true,
  canEscapeKeyClose: true,
  canOutsideClickClose: true,
  enforceFocus: true,
  isOpen: false,
  hasBackdrop: true,
  position: Position.RIGHT,
  usePortal: true,
  size: '50%'
}
 
export function ChartAndRecords(props: ChartAndRecordsProps): JSX.Element {
  const { query, error, loading, data, onChange, isQueryExecuted, fetchData } = props
  const { getString } = useStrings()
 
  const { options: highchartsOptions, records } = useMemo(() => {
    onChange(PrometheusMonitoringSourceFieldNames.RECORD_COUNT, data?.data?.length)
    return transformPrometheusSampleData(data?.data)
  }, [data])
  Iif (!error && !loading && records?.length) {
    return (
      <>
        <Container className={css.chart}>
          {query?.length ? <HighchartsReact highcharts={Highcharts} options={highchartsOptions} /> : null}
        </Container>
        <Records
          fetchRecords={fetchData}
          loading={loading}
          data={!query?.length ? null : records}
          error={error}
          query={query}
          isQueryExecuted={isQueryExecuted}
          queryNotExecutedMessage={getString('cv.monitoringSources.prometheus.submitQueryToSeeRecords')}
        />
      </>
    )
  }
  return (
    <Records
      fetchRecords={fetchData}
      loading={loading}
      data={records}
      error={error}
      query={query}
      isQueryExecuted={isQueryExecuted}
      queryNotExecutedMessage={getString('cv.monitoringSources.prometheus.submitQueryToSeeRecords') as string}
    />
  )
}
 
export function PrometheusQueryViewer(props: PrometheusQueryViewerProps): JSX.Element {
  const { values, className, connectorIdentifier, onChange } = props
  const { getString } = useStrings()
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const [isQueryExecuted, setIsQueryExecuted] = useState(false)
  const query = useMemo(() => {
    Iif (values?.isManualQuery) {
      return values.query?.length ? values.query : ''
    }
    return createPrometheusQuery(values)
  }, [
    values?.isManualQuery,
    values?.envFilter,
    values?.serviceFilter,
    values?.additionalFilter,
    values?.aggregator,
    values?.query,
    values?.prometheusMetric
  ])
  const { data, refetch, cancel, error, loading } = useGetSampleData({ lazy: true })
  useEffect(() => {
    Eif (!isManualQuery) {
      onChange(PrometheusMonitoringSourceFieldNames.QUERY, query)
    }
  }, [query])
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const { openDialog } = useConfirmationDialog({
    titleText: getString('cv.monitoringSources.prometheus.querySettingsNotEditable'),
    contentText: getString('cv.monitoringSources.prometheus.querySettingsSubtext'),
    confirmButtonText: getString('cv.proceedToEdit'),
    cancelButtonText: getString('cancel'),
    onCloseDialog: (proceed: boolean) => {
      if (proceed) onChange(PrometheusMonitoringSourceFieldNames.IS_MANUAL_QUERY, true)
    }
  })
  const isManualQuery = Boolean(values?.isManualQuery)
  let content = (
    <>
      <QueryContent
        handleFetchRecords={async () => {
          cancel()
          await refetch({
            queryParams: {
              accountId,
              projectIdentifier,
              orgIdentifier,
              query: query || '',
              tracingId: Utils.randomId(),
              connectorIdentifier: connectorIdentifier as string
            }
          })
          if (!isQueryExecuted) {
            setIsQueryExecuted(true)
          }
        }}
        query={query}
        loading={loading}
        textAreaName={PrometheusMonitoringSourceFieldNames.QUERY}
        onClickExpand={setIsDrawerOpen}
        onEditQuery={!isManualQuery ? openDialog : undefined}
        isDialogOpen={isDrawerOpen}
        textAreaProps={{ readOnly: !isManualQuery }}
        mandatoryFields={[values?.prometheusMetric]}
        isAutoFetch={!isManualQuery}
      />
      <ChartAndRecords
        fetchData={async () =>
          refetch({
            queryParams: {
              accountId,
              projectIdentifier,
              orgIdentifier,
              query: query || '',
              tracingId: Utils.randomId(),
              connectorIdentifier: connectorIdentifier as string
            }
          })
        }
        query={query}
        isQueryExecuted={isQueryExecuted}
        onChange={onChange}
        data={data}
        error={getErrorMessage(error)}
        loading={loading}
      />
    </>
  )
 
  Iif (isDrawerOpen) {
    content = (
      <Drawer {...DrawerProps} isOpen={true} onClose={() => setIsDrawerOpen(false)} className={css.queryViewDialog}>
        {content}
      </Drawer>
    )
  }
 
  return (
    <Container className={cx(css.main, className)}>
      <Text className={css.labelText}>{getString('cv.query')}</Text>
      {content}
    </Container>
  )
}