All files / modules/85-cv/components/ExecutionVerification/components/DeploymentMetrics DeploymentMetrics.tsx

91.6% Statements 109/119
66.23% Branches 51/77
78.38% Functions 29/37
93.14% Lines 95/102

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              10x 10x                               10x 10x 10x 10x 10x     10x               10x 10x 10x 10x   10x       10x                           10x 10x 10x 10x                             10x 38x 38x 38x   38x 38x     38x               38x 38x 38x 38x 38x 38x               38x                       38x                     38x             38x   38x 19x     38x 76x 76x               38x           38x 10x 10x   10x 10x 10x               38x 33x 33x 33x     3x 3x     33x     38x 9x       9x       9x   9x     38x 9x 2x   7x   7x 7x                             38x 10x           10x     38x   38x 20x 20x 20x   20x             20x     38x 1x     38x     38x 1x     38x 1x       38x 38x 3x     35x 3x     32x 10x                     22x                   220x 220x                                       38x                                                                                                                                                                                 2x 2x            
/*
 * 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, { useState, useEffect, useCallback, useRef } from 'react'
import {
  Container,
  Text,
  Pagination,
  PageError,
  NoDataCard,
  Accordion,
  AccordionHandle,
  Checkbox,
  Layout,
  Button,
  ButtonVariation,
  MultiSelectDropDown,
  MultiSelectOption,
  Icon
} from '@wings-software/uicore'
import { isEqual } from 'lodash-es'
import { FontVariation, Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import { useStrings } from 'framework/strings'
import { useQueryParams } from '@common/hooks'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import type { ExecutionNode } from 'services/pipeline-ng'
import {
  GetVerifyStepDeploymentMetricsQueryParams,
  useGetVerifyStepDeploymentMetrics,
  useGetVerifyStepHealthSources,
  useGetVerifyStepNodeNames,
  useGetVerifyStepTransactionNames
} from 'services/cv'
import type { ExecutionQueryParams } from '@pipeline/utils/executionUtils'
import { VerificationType } from '@cv/components/HealthSourceDropDown/HealthSourceDropDown.constants'
import noDataImage from '@cv/assets/noData.svg'
import { POLLING_INTERVAL, PAGE_SIZE, DEFAULT_PAGINATION_VALUEE } from './DeploymentMetrics.constants'
import { RefreshViewForNewData } from '../RefreshViewForNewDataButton/RefreshForNewData'
import type { DeploymentNodeAnalysisResult } from '../DeploymentProgressAndNodes/components/DeploymentNodes/DeploymentNodes.constants'
import {
  DeploymentMetricsAnalysisRow,
  DeploymentMetricsAnalysisRowProps
} from './components/DeploymentMetricsAnalysisRow/DeploymentMetricsAnalysisRow'
import {
  transformMetricData,
  getErrorMessage,
  getAccordionIds,
  getDropdownItems,
  getInitialNodeName,
  getQueryParamForHostname,
  getQueryParamFromFilters,
  getFilterDisplayText,
  getShouldShowSpinner,
  getShouldShowError,
  isErrorOrLoading,
  isStepRunningOrWaiting
} from './DeploymentMetrics.utils'
import MetricsAccordionPanelSummary from './components/DeploymentAccordionPanel/MetricsAccordionPanelSummary'
import { HealthSourceMultiSelectDropDown } from '../HealthSourcesMultiSelectDropdown/HealthSourceMultiSelectDropDown'
import DeploymentMetricsLables from './components/DeploymentMetricsLables'
import css from './DeploymentMetrics.module.scss'
 
interface DeploymentMetricsProps {
  step: ExecutionNode
  activityId: string
  selectedNode?: DeploymentNodeAnalysisResult
}
 
type UpdateViewState = {
  hasNewData: boolean
  shouldUpdateView: boolean
  currentViewData: DeploymentMetricsAnalysisRowProps[]
  showSpinner: boolean
}
 
export function DeploymentMetrics(props: DeploymentMetricsProps): JSX.Element {
  const { step, selectedNode, activityId } = props
  const { getString } = useStrings()
  const pageParams = useQueryParams<ExecutionQueryParams>()
 
  const { accountId } = useParams<ProjectPathProps>()
  const [anomalousMetricsFilterChecked, setAnomalousMetricsFilterChecked] = useState(
    pageParams.filterAnomalous === 'true'
  )
  const [queryParams, setQueryParams] = useState<GetVerifyStepDeploymentMetricsQueryParams>({
    accountId,
    anomalousMetricsOnly: anomalousMetricsFilterChecked,
    anomalousNodesOnly: anomalousMetricsFilterChecked,
    hostNames: getQueryParamForHostname(selectedNode?.hostName),
    pageNumber: 0,
    pageSize: PAGE_SIZE
  })
  const accordionRef = useRef<AccordionHandle>(null)
  const [pollingIntervalId, setPollingIntervalId] = useState(-1)
  const [selectedHealthSources, setSelectedHealthSources] = useState<MultiSelectOption[]>([])
  const [selectedNodeName, setSelectedNodeName] = useState<MultiSelectOption[]>(() => getInitialNodeName(selectedNode))
  const [selectedTransactionName, setSelectedTransactionName] = useState<MultiSelectOption[]>([])
  const [{ hasNewData, shouldUpdateView, currentViewData, showSpinner }, setUpdateViewInfo] = useState<UpdateViewState>(
    {
      hasNewData: false,
      showSpinner: true,
      shouldUpdateView: true,
      currentViewData: []
    }
  )
  const { loading, error, data, refetch } = useGetVerifyStepDeploymentMetrics({
    queryParams,
    verifyStepExecutionId: activityId,
    queryParamStringifyOptions: {
      arrayFormat: 'repeat'
    }
  })
 
  const {
    data: transactionNames,
    loading: transactionNameLoading,
    error: transactionNameError
  } = useGetVerifyStepTransactionNames({
    verifyStepExecutionId: activityId,
    queryParams: {
      accountId
    }
  })
 
  const {
    data: nodeNames,
    loading: nodeNamesLoading,
    error: nodeNamesError
  } = useGetVerifyStepNodeNames({
    verifyStepExecutionId: activityId,
    queryParams: {
      accountId
    }
  })
 
  const accordionIdsRef = useRef<string[]>([])
 
  useEffect(() => {
    accordionIdsRef.current = getAccordionIds(currentViewData)
  }, [currentViewData])
 
  const getFilteredText = useCallback((selectedOptions: MultiSelectOption[] = [], filterText = ' '): string => {
    const baseText = getString(filterText)
    return getFilterDisplayText(selectedOptions, baseText, getString('all'))
  }, [])
 
  const {
    data: healthSourcesData,
    error: healthSourcesError,
    loading: healthSourcesLoading,
    refetch: fetchHealthSources
  } = useGetVerifyStepHealthSources({
    queryParams: { accountId },
    verifyStepExecutionId: activityId as string,
    lazy: true
  })
 
  useEffect(() => {
    Eif (activityId) {
      fetchHealthSources()
    }
    setPollingIntervalId(-1)
    setUpdateViewInfo({ currentViewData: [], hasNewData: false, shouldUpdateView: true, showSpinner: true })
    setQueryParams(oldParams => ({
      ...oldParams,
      hostNames: undefined,
      pageNumber: 0
    }))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activityId])
 
  useEffect(() => {
    let intervalId = pollingIntervalId
    clearInterval(intervalId)
    if (isStepRunningOrWaiting(step?.status)) {
      // eslint-disable-next-line
      // @ts-ignore
      intervalId = setInterval(refetch, POLLING_INTERVAL)
      setPollingIntervalId(intervalId)
    }
 
    return () => clearInterval(intervalId)
  }, [step?.status, queryParams])
 
  useEffect(() => {
    const updatedQueryParams = {
      ...queryParams,
      hostNames: getQueryParamForHostname(selectedNode?.hostName)
    }
    Iif (!isEqual(updatedQueryParams, queryParams)) {
      setQueryParams(updatedQueryParams)
    }
 
    setSelectedNodeName(getInitialNodeName(selectedNode))
 
    setUpdateViewInfo(oldState => ({ ...oldState, shouldUpdateView: true, showSpinner: true }))
  }, [selectedNode])
 
  useEffect(() => {
    if (isErrorOrLoading(error, loading)) {
      return
    }
    const updatedProps = transformMetricData(data)
 
    Eif (shouldUpdateView) {
      setUpdateViewInfo({
        hasNewData: false,
        shouldUpdateView: false,
        currentViewData: updatedProps,
        showSpinner: false
      })
    } else {
      setUpdateViewInfo(prevState => ({
        ...prevState,
        hasNewData: !isEqual(prevState?.currentViewData, updatedProps),
        showSpinner: false
      }))
    }
  }, [data])
 
  useEffect(() => {
    setQueryParams(oldQueryParams => ({
      ...oldQueryParams,
      pageNumber: 0,
      anomalousMetricsOnly: anomalousMetricsFilterChecked,
      anomalousNodesOnly: anomalousMetricsFilterChecked
    }))
    setUpdateViewInfo(oldInfo => ({ ...oldInfo, shouldUpdateView: true, showSpinner: true }))
  }, [anomalousMetricsFilterChecked])
 
  const paginationInfo = data?.resource?.pageResponse || DEFAULT_PAGINATION_VALUEE
 
  useEffect(() => {
    const healthSourceQueryParams = selectedHealthSources.map(item => item.value) as string[]
    const transactionNameParams = selectedTransactionName.map(item => item.value) as string[]
    const nodeNameParams = selectedNodeName.map(item => item.value) as string[]
 
    setQueryParams(prevQueryParams => ({
      ...prevQueryParams,
      pageNumber: 0,
      healthSources: getQueryParamFromFilters(healthSourceQueryParams),
      transactionNames: getQueryParamFromFilters(transactionNameParams),
      hostNames: getQueryParamFromFilters(nodeNameParams)
    }))
    setUpdateViewInfo(oldInfo => ({ ...oldInfo, shouldUpdateView: true, showSpinner: true }))
  }, [selectedHealthSources, selectedTransactionName, selectedNodeName])
 
  const handleHealthSourceChange = useCallback(selectedHealthSourceFitlers => {
    setSelectedHealthSources(selectedHealthSourceFitlers)
  }, [])
 
  const handleTransactionNameChange = useCallback(selectedTransactionNameFitlers => {
    setSelectedTransactionName(selectedTransactionNameFitlers)
  }, [])
  const handleNodeNameChange = useCallback(selectedNodeNameFitlers => {
    setSelectedNodeName(selectedNodeNameFitlers)
  }, [])
 
  const updatedAnomalousMetricsFilter = useCallback(
    () => setAnomalousMetricsFilterChecked(currentFilterStatus => !currentFilterStatus),
    []
  )
 
  const renderContent = (): JSX.Element => {
    if (getShouldShowSpinner(loading, showSpinner)) {
      return <Icon name="steps-spinner" className={css.loading} color={Color.GREY_400} size={30} />
    }
 
    if (getShouldShowError(error, shouldUpdateView)) {
      return <PageError message={getErrorMessage(error)} onClick={() => refetch()} className={css.error} />
    }
 
    if (!currentViewData?.length) {
      return (
        <Container className={css.noData}>
          <NoDataCard
            onClick={() => refetch()}
            message={getString('cv.monitoredServices.noMatchingData')}
            image={noDataImage}
          />
        </Container>
      )
    }
 
    return (
      <>
        <DeploymentMetricsLables />
        <Accordion
          allowMultiOpen
          panelClassName={css.deploymentMetricsAccordionPanel}
          summaryClassName={css.deploymentMetricsAccordionSummary}
          ref={accordionRef}
        >
          {currentViewData?.map(analysisRow => {
            const { transactionName, metricName, healthSourceType } = analysisRow
            return (
              <Accordion.Panel
                key={`${transactionName}-${metricName}-${healthSourceType}`}
                id={`${transactionName}-${metricName}-${healthSourceType}`}
                summary={<MetricsAccordionPanelSummary analysisRow={analysisRow} />}
                details={
                  <DeploymentMetricsAnalysisRow
                    key={`${transactionName}-${metricName}-${healthSourceType}`}
                    {...analysisRow}
                    className={css.analysisRow}
                  />
                }
              />
            )
          })}
        </Accordion>
      </>
    )
  }
 
  return (
    <Container className={css.main}>
      <Container className={css.filters}>
        <Icon name="filter" />
        <MultiSelectDropDown
          placeholder={getFilteredText(selectedTransactionName, 'rbac.group')}
          value={selectedTransactionName}
          className={css.filterDropdown}
          items={getDropdownItems(transactionNames?.resource as string[], transactionNameLoading, transactionNameError)}
          onChange={handleTransactionNameChange}
          buttonTestId={'transaction_name_filter'}
        />
        <MultiSelectDropDown
          placeholder={getFilteredText(selectedNodeName, 'pipeline.nodesLabel')}
          value={selectedNodeName}
          className={css.filterDropdown}
          items={getDropdownItems(nodeNames?.resource as string[], nodeNamesLoading, nodeNamesError)}
          onChange={handleNodeNameChange}
          buttonTestId={'node_name_filter'}
        />
        <HealthSourceMultiSelectDropDown
          data={healthSourcesData}
          loading={healthSourcesLoading}
          error={healthSourcesError}
          onChange={handleHealthSourceChange}
          verificationType={VerificationType.TIME_SERIES}
          selectedValues={selectedHealthSources}
          className={css.filterDropdown}
        />
 
        <Checkbox
          onChange={updatedAnomalousMetricsFilter}
          checked={anomalousMetricsFilterChecked}
          label={getString('pipeline.verification.anomalousMetricsFilterLabel')}
          data-testid="anomalousFilterCheckbox"
        />
      </Container>
      <Layout.Horizontal className={css.filterSecondRow} border={{ bottom: true }}>
        <Container className={css.accordionToggleButtons}>
          {Boolean(currentViewData.length) && (
            <>
              <Button
                onClick={() => accordionRef.current?.open(accordionIdsRef.current)}
                variation={ButtonVariation.LINK}
                border={{ right: true }}
              >
                {getString('pipeline.verification.expandAll')}
              </Button>
              <Button
                onClick={() => accordionRef.current?.close(accordionIdsRef.current)}
                variation={ButtonVariation.LINK}
              >
                {getString('pipeline.verification.collapseAll')}
              </Button>
            </>
          )}
        </Container>
        <Layout.Horizontal>
          {pollingIntervalId !== -1 && hasNewData && (
            <RefreshViewForNewData
              className={css.refreshButton}
              onClick={() => {
                setUpdateViewInfo(prevState => ({
                  ...prevState,
                  hasNewData: false,
                  currentViewData: transformMetricData(data)
                }))
              }}
            />
          )}
          <Layout.Horizontal className={css.legend}>
            <span className={css.predicted} />
            <Text font={{ variation: FontVariation.SMALL }}> {getString('connectors.cdng.baseline')}</Text>
            <span className={css.actualFail} />
            <span className={css.actualWarning} />
            <span className={css.actualObserve} />
            <span className={css.actualHealthy} />
            <Text font={{ variation: FontVariation.SMALL }}>{getString('common.current')}</Text>
          </Layout.Horizontal>
        </Layout.Horizontal>
      </Layout.Horizontal>
      <Container className={css.content}>{renderContent()}</Container>
      <Pagination
        className={css.metricsPagination}
        pageSize={paginationInfo.pageSize as number}
        pageCount={paginationInfo.totalPages as number}
        itemCount={paginationInfo.totalItems as number}
        pageIndex={paginationInfo.pageIndex}
        gotoPage={selectedPage => {
          setQueryParams(oldQueryParams => ({ ...oldQueryParams, pageNumber: selectedPage }))
          setUpdateViewInfo(oldInfo => ({ ...oldInfo, shouldUpdateView: true, showSpinner: true }))
        }}
      />
    </Container>
  )
}