All files / modules/85-cv/pages/monitored-service/components/ServiceHealth ServiceHealth.tsx

94.74% Statements 54/57
73.33% Branches 77/105
91.67% Functions 11/12
96.43% Lines 54/56

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              10x 10x 10x 10x 10x 10x 10x     10x 10x 10x 10x                 10x   10x 10x 10x 10x 10x 10x 10x   10x           10x 10x         10x 10x 10x 10x 10x 10x 10x   10x   4x             10x   8x       8x               10x 4x     10x 5x     10x 4x     10x       10x   2x 2x         10x 10x                                         10x 8x       10x 1x 1x     10x                                           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, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Container, Heading, Layout, Select, SelectOption } from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import Card from '@cv/components/Card/Card'
import { useStrings } from 'framework/strings'
import ChangeTimeline from '@cv/components/ChangeTimeline/ChangeTimeline'
import TimelineSlider from '@cv/components/ChangeTimeline/components/TimelineSlider/TimelineSlider'
import type { RiskData } from 'services/cv'
import type { ChangesInfoCardData } from '@cv/components/ChangeTimeline/ChangeTimeline.types'
import ServiceDependencyGraph from '@cv/pages/monitored-service/CVMonitoredService/components/MonitoredServiceGraphView/MonitoredServiceGraphView'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import {
  calculateLowestHealthScoreBar,
  calculateStartAndEndTimes,
  getDimensionsAsPerContainerWidth,
  getTimeFormat,
  getTimePeriods,
  getTimestampsForPeriod,
  limitMaxSliderWidth
} from './ServiceHealth.utils'
import { DEFAULT_MAX_SLIDER_WIDTH, DEFAULT_MIN_SLIDER_WIDTH, TimePeriodEnum } from './ServiceHealth.constants'
import type { ServiceHealthProps } from './ServiceHealth.types'
import HealthScoreChart from './components/HealthScoreChart/HealthScoreChart'
import MetricsAndLogs from './components/MetricsAndLogs/MetricsAndLogs'
import AnomaliesCard from './components/AnomaliesCard/AnomaliesCard'
import ChangesSourceCard from './components/ChangesSourceCard/ChangesSourceCard'
import ChangesTable from './components/ChangesAndServiceDependency/components/ChangesTable/ChangesTable'
import ErrorTracking from './components/ErrorTracking/ErrorTracking'
import css from './ServiceHealth.module.scss'
 
export default function ServiceHealth({
  monitoredServiceIdentifier,
  serviceIdentifier,
  environmentIdentifier,
  hasChangeSource
}: ServiceHealthProps): JSX.Element {
  const { getString } = useStrings()
  const [selectedTimePeriod, setSelectedTimePeriod] = useState<SelectOption>({
    value: TimePeriodEnum.TWENTY_FOUR_HOURS,
    label: getString('cv.monitoredServices.serviceHealth.last24Hrs')
  })
 
  const [timestamps, setTimestamps] = useState<number[]>([])
  const [timeRange, setTimeRange] = useState<{ startTime: number; endTime: number }>()
  const [showTimelineSlider, setShowTimelineSlider] = useState(false)
  const [changeTimelineSummary, setChangeTimelineSummary] = useState<ChangesInfoCardData[] | null>(null)
  const [healthScoreData, setHealthScoreData] = useState<RiskData[]>()
  const containerRef = useRef<HTMLElement>(null)
  const isErrorTrackingEnabled = useFeatureFlag(FeatureFlag.ERROR_TRACKING_ENABLED)
 
  useEffect(() => {
    //changing timeperiod in dropdown should reset the timerange and remove the slider.
    Iif (showTimelineSlider) {
      resetSlider()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedTimePeriod?.value])
 
  // calculating the min and max width for the the timeline slider
  const sliderDimensions = useMemo(() => {
    // This is temporary change , will be removed once BE fix is done.
    const defaultMaxSliderWidth = limitMaxSliderWidth(selectedTimePeriod?.value as string)
      ? DEFAULT_MIN_SLIDER_WIDTH
      : DEFAULT_MAX_SLIDER_WIDTH
 
    return getDimensionsAsPerContainerWidth(
      defaultMaxSliderWidth,
      selectedTimePeriod,
      containerRef?.current?.offsetWidth
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [containerRef?.current, selectedTimePeriod?.value])
 
  const timeFormat = useMemo(() => {
    return getTimeFormat(selectedTimePeriod?.value as string)
  }, [selectedTimePeriod?.value])
 
  const lowestHealthScoreBarForTimeRange = useMemo(() => {
    return calculateLowestHealthScoreBar(timeRange?.startTime, timeRange?.endTime, healthScoreData)
  }, [timeRange?.startTime, timeRange?.endTime, healthScoreData])
 
  useEffect(() => {
    setTimestamps(getTimestampsForPeriod(healthScoreData))
  }, [healthScoreData])
 
  const onFocusTimeRange = useCallback((startTime: number, endTime: number) => {
    setTimeRange({ startTime, endTime })
  }, [])
 
  const onSliderDragEnd = useCallback(
    ({ startXPercentage, endXPercentage }) => {
      const startAndEndtime = calculateStartAndEndTimes(startXPercentage, endXPercentage, timestamps)
      Iif (startAndEndtime) onFocusTimeRange?.(startAndEndtime[0], startAndEndtime[1])
    },
    [onFocusTimeRange, timestamps]
  )
 
  const renderInfoCard = useCallback(() => {
    return (
      <AnomaliesCard
        timeRange={timeRange}
        changeTimelineSummary={changeTimelineSummary || []}
        lowestHealthScoreBarForTimeRange={lowestHealthScoreBarForTimeRange}
        timeFormat={timeFormat}
        serviceIdentifier={serviceIdentifier}
        environmentIdentifier={environmentIdentifier}
        monitoredServiceIdentifier={monitoredServiceIdentifier}
      />
    )
  }, [
    environmentIdentifier,
    lowestHealthScoreBarForTimeRange,
    monitoredServiceIdentifier,
    serviceIdentifier,
    timeFormat,
    timeRange,
    changeTimelineSummary
  ])
 
  const changesTableAndSourceCardStartAndEndtime = useMemo(
    () => calculateStartAndEndTimes(0, 1, timestamps) || [],
    [timestamps]
  )
 
  const resetSlider = useCallback(() => {
    setTimeRange({ startTime: 0, endTime: 0 })
    setShowTimelineSlider(false)
  }, [])
 
  return (
    <>
      <Select
        value={selectedTimePeriod}
        items={getTimePeriods(getString)}
        className={css.timePeriods}
        onChange={setSelectedTimePeriod}
      />
      <Container className={css.serviceHealthCard}>
        <Card>
          <>
            <Container className={css.tickerContainer}>
              {changesTableAndSourceCardStartAndEndtime[0] && changesTableAndSourceCardStartAndEndtime[1] && (
                <ChangesSourceCard
                  monitoredServiceIdentifier={monitoredServiceIdentifier}
                  startTime={changesTableAndSourceCardStartAndEndtime[0]}
                  endTime={changesTableAndSourceCardStartAndEndtime[1]}
                />
              )}
            </Container>
            <Container
              onClick={() => {
                Eif (!showTimelineSlider) {
                  setShowTimelineSlider(true)
                }
              }}
              className={css.main}
              data-testid={'HealthScoreChartContainer'}
              ref={containerRef}
            >
              <HealthScoreChart
                hasTimelineIntegration
                duration={selectedTimePeriod}
                setHealthScoreData={setHealthScoreData}
                monitoredServiceIdentifier={monitoredServiceIdentifier}
                timeFormat={timeFormat}
              />
              <TimelineSlider
                resetFocus={resetSlider}
                initialSliderWidth={sliderDimensions.minWidth}
                leftContainerOffset={90}
                hideSlider={!showTimelineSlider}
                className={css.slider}
                minSliderWidth={sliderDimensions.minWidth}
                maxSliderWidth={sliderDimensions.maxWidth}
                infoCard={renderInfoCard()}
                onSliderDragEnd={onSliderDragEnd}
              />
              <ChangeTimeline
                duration={selectedTimePeriod}
                useMonitoredServiceChangeTimeline
                monitoredServiceIdentifier={monitoredServiceIdentifier}
                startTime={timeRange?.startTime as number}
                endTime={timeRange?.endTime as number}
                selectedTimePeriod={selectedTimePeriod}
                onSliderMoved={setChangeTimelineSummary}
              />
            </Container>
          </>
        </Card>
 
        <Layout.Horizontal spacing="medium">
          <Container width="60%">
            <ChangesTable
              startTime={
                showTimelineSlider ? (timeRange?.startTime as number) : changesTableAndSourceCardStartAndEndtime[0]
              }
              endTime={
                showTimelineSlider ? (timeRange?.endTime as number) : changesTableAndSourceCardStartAndEndtime[1]
              }
              hasChangeSource={hasChangeSource}
              monitoredServiceIdentifier={monitoredServiceIdentifier}
            />
          </Container>
          <Container width="40%">
            <Heading level={2} font={{ variation: FontVariation.H6 }} padding={{ bottom: 'medium' }}>
              {getString('pipeline.serviceDependenciesText')}
            </Heading>
            <Card>
              <Layout.Vertical height={458}>
                <ServiceDependencyGraph monitoredServiceIdentifier={monitoredServiceIdentifier} />
              </Layout.Vertical>
            </Card>
          </Container>
        </Layout.Horizontal>
 
        <MetricsAndLogs
          monitoredServiceIdentifier={monitoredServiceIdentifier}
          serviceIdentifier={serviceIdentifier}
          environmentIdentifier={environmentIdentifier}
          startTime={timeRange?.startTime}
          endTime={timeRange?.endTime}
          showTimelineSlider={showTimelineSlider}
        />
 
        {isErrorTrackingEnabled && (
          <ErrorTracking
            monitoredServiceIdentifier={monitoredServiceIdentifier}
            serviceIdentifier={serviceIdentifier}
            environmentIdentifier={environmentIdentifier}
            startTime={timeRange?.startTime}
            endTime={timeRange?.endTime}
          />
        )}
      </Container>
    </>
  )
}