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

82.8% Statements 130/157
67.33% Branches 204/303
95% Functions 19/20
84.56% Lines 126/149

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                    32x                         32x 32x 32x 32x   32x         32x   32x 82x 76x 76x 144x 144x 1x     76x     32x 8x 8x 8x 8x           32x 5x   5x 4x     5x 5x 4x 4x           5x     32x 8x 7x     8x                       8x 1x     7x   7x 7x 7x           7x 7x 7x     7x                                   7x     32x                                                                                                                             39x       39x 76x       32x         39x 39x 2x       77x 18x     39x 2x 2x   2x 2x       39x 2x     39x     39x   39x             39x 1x   39x 1x   39x     32x         20x   20x       20x 19x 19x 19x 19x       1x 1x     1x     32x       48x 3x     45x 45x 45x 45x 45x             45x     32x 3x 2x     1x 1x 3x 3x 5x       5x               1x     32x 20x 16x     4x 4x 16x 16x 16x 6x 6x     16x     4x     32x       19x 19x             32x       16x 16x       16x                 32x                                             7x 7x 7x                     7x 7x 7x     7x    
/*
 * 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 type { Dispatch, SetStateAction } from 'react'
import type { FormikProps } from 'formik'
import type { IOptionProps } from '@blueprintjs/core'
import { isNumber, isEmpty } from 'lodash-es'
import type {
  RiskProfile,
  MetricPackDTO,
  TimeSeriesSampleDTO,
  StackdriverMetricHealthSourceSpec,
  StackdriverDefinition,
  StackdriverDashboardDetail
} from 'services/cv'
import type { MetricWidget } from '@cv/components/MetricDashboardWidgetNav/MetricDashboardWidgetNav.type'
import type { StringKeys } from 'framework/strings'
import type { GCOMetricInfo, GCOMetricSetupSource } from './GCOMetricsHealthSource.type'
import type { UpdatedHealthSource } from '../../HealthSourceDrawer/HealthSourceDrawerContent.types'
import { HealthSourceTypes } from '../../types'
import { chartsConfig } from './GCOWidgetChartConfig'
import { OVERALL } from './GCOMetricsHealthSource.constants'
import { MANUAL_INPUT_QUERY } from './components/ManualInputQueryModal/ManualInputQueryModal'
 
export const GCOProduct = {
  CLOUD_METRICS: 'Cloud Metrics',
  CLOUD_LOGS: 'Cloud Logs'
}
 
export const MANUAL_QUERY_DASHBOARD = 'Manual_Query_Dashboard'
 
export function getManuallyCreatedQueries(selectedMetrics: GCOMetricSetupSource['metricDefinition']): string[] {
  if (!selectedMetrics?.size) return []
  const manualQueries: string[] = []
  for (const entry of selectedMetrics) {
    const [metricName, metricInfo] = entry
    if (metricName && metricInfo?.isManualQuery) {
      manualQueries.push(metricName)
    }
  }
  return manualQueries
}
 
export function formatJSON(val?: string | Record<string, unknown>): string | undefined {
  try {
    Iif (!val) return
    const res = typeof val === 'string' ? JSON.parse(val) : val
    return JSON.stringify(res, null, 2)
  } catch (e) {
    return
  }
}
 
export const getSelectedDashboards = (sourceData: any) => {
  const selectedDashboards = []
 
  const healthSource: UpdatedHealthSource = sourceData?.healthSourceList?.find(
    (source: UpdatedHealthSource) => source.name === sourceData.healthSourceName
  )
 
  const gcoMetricSpec: StackdriverMetricHealthSourceSpec = healthSource?.spec || {}
  for (const metricDefinition of gcoMetricSpec.metricDefinitions || []) {
    Eif (!sourceData.selectedDashboards?.length) {
      selectedDashboards.push({
        name: metricDefinition.dashboardName,
        id: metricDefinition.dashboardPath
      })
    }
  }
  return selectedDashboards
}
 
export function transformGCOMetricHealthSourceToGCOMetricSetupSource(sourceData: any): GCOMetricSetupSource {
  const healthSource: UpdatedHealthSource = sourceData?.healthSourceList?.find(
    (source: UpdatedHealthSource) => source.name === sourceData.healthSourceName
  )
 
  const setupSource: GCOMetricSetupSource = {
    selectedDashboards: sourceData.selectedDashboards || [],
    metricDefinition:
      new Map([...(sourceData.metricDefinition || new Map()), ...(sourceData.selectedMetrics || new Map())]) ||
      new Map(),
    isEdit: sourceData.isEdit,
    healthSourceName: sourceData.healthSourceName,
    healthSourceIdentifier: sourceData.healthSourceIdentifier,
    connectorRef: sourceData.connectorRef,
    product: sourceData.product
  }
 
  if (!healthSource) {
    return setupSource
  }
 
  const gcoMetricSpec: StackdriverMetricHealthSourceSpec = healthSource.spec || {}
 
  for (const metricDefinition of gcoMetricSpec.metricDefinitions || []) {
    const manualQuery = metricDefinition?.isManualQuery
    Iif (
      !metricDefinition?.metricName ||
      ((!metricDefinition.dashboardName || !metricDefinition.dashboardPath) && !manualQuery)
    )
      continue
 
    const metricTags: any = {}
    for (const tag of metricDefinition.metricTags || []) {
      metricTags[tag] = ''
    }
 
    setupSource.metricDefinition.set(metricDefinition.metricName, {
      metricName: metricDefinition.metricName,
      identifier: metricDefinition.identifier,
      metricTags,
      dashboardName: metricDefinition.dashboardName,
      dashboardPath: metricDefinition.dashboardPath,
      isManualQuery: manualQuery,
      riskCategory: `${metricDefinition.riskProfile?.category}/${metricDefinition.riskProfile?.metricType}`,
      higherBaselineDeviation: metricDefinition.riskProfile?.thresholdTypes?.includes('ACT_WHEN_HIGHER'),
      lowerBaselineDeviation: metricDefinition.riskProfile?.thresholdTypes?.includes('ACT_WHEN_LOWER'),
      query: JSON.stringify(metricDefinition.jsonMetricDefinition, null, 2),
      sli: metricDefinition.sli?.enabled,
      continuousVerification: metricDefinition.analysis?.deploymentVerification?.enabled,
      healthScore: metricDefinition.analysis?.liveMonitoring?.enabled,
      serviceInstanceField: metricDefinition.serviceInstanceField
    })
  }
 
  return setupSource
}
 
export function transformGCOMetricSetupSourceToGCOHealthSource(setupSource: GCOMetricSetupSource): UpdatedHealthSource {
  const healthSource: UpdatedHealthSource = {
    type: HealthSourceTypes.StackdriverMetrics as UpdatedHealthSource['type'],
    identifier: setupSource.healthSourceIdentifier,
    name: setupSource.healthSourceName,
    spec: {
      connectorRef: setupSource.connectorRef,
      feature: GCOProduct.CLOUD_METRICS,
      metricDefinitions: []
    }
  }
  for (const selectedMetricInfo of setupSource.metricDefinition) {
    const [selectedMetric, metricInfo] = selectedMetricInfo
    if (!selectedMetric || !metricInfo) continue
    const [category, metricType] = metricInfo.riskCategory?.split('/') || []
 
    const thresholdTypes: RiskProfile['thresholdTypes'] = []
    if (metricInfo.lowerBaselineDeviation) {
      thresholdTypes.push('ACT_WHEN_LOWER')
    }
    if (metricInfo.higherBaselineDeviation) {
      thresholdTypes.push('ACT_WHEN_HIGHER')
    }
 
    const spec: StackdriverMetricHealthSourceSpec = healthSource.spec || []
    spec.metricDefinitions?.push({
      dashboardName: (metricInfo.dashboardName || '') as string,
      dashboardPath: (metricInfo.dashboardPath || '') as string,
      metricName: metricInfo.metricName as string,
      metricTags: Object.keys(metricInfo.metricTags || {}),
      identifier: metricInfo.identifier,
      isManualQuery: metricInfo.isManualQuery,
      jsonMetricDefinition: JSON.parse(metricInfo.query || ''),
      riskProfile: {
        metricType: metricType as RiskProfile['metricType'],
        category: category as RiskProfile['category'],
        thresholdTypes
      },
      sli: { enabled: metricInfo?.sli || false },
      serviceInstanceField: metricInfo.continuousVerification ? metricInfo.serviceInstanceField : null,
      analysis: {
        riskProfile: {
          category: category as RiskProfile['category'],
          metricType: metricType,
          thresholdTypes
        },
        liveMonitoring: { enabled: metricInfo.healthScore || false },
        deploymentVerification: {
          enabled: metricInfo.continuousVerification || false
        }
      }
    } as StackdriverDefinition)
  }
 
  return healthSource
}
 
function getIsAllIDsUnique(
  selectedMetrics: Map<string, GCOMetricInfo>,
  currentId: string,
  currentMetricName: string
): boolean {
  // to prevent error during submit
  Iif (!selectedMetrics) {
    return false
  }
 
  return ![...selectedMetrics.values()].find(
    metricData => metricData.identifier === currentId && currentMetricName !== metricData.metricName
  )
}
 
export function ensureFieldsAreFilled(
  values: GCOMetricInfo,
  getString: (key: StringKeys, vars?: Record<string, any> | undefined) => string,
  selectedMetrics: Map<string, GCOMetricInfo>
): Record<string, any> {
  const ret: any = {}
  if (!values?.query?.length) {
    ret.query = getString('cv.monitoringSources.gco.manualInputQueryModal.validation.query')
  }
 
  // values.sli, values.continuousVerification , values.healthScore
  if (![values.sli, values.continuousVerification, values.healthScore].some(i => i)) {
    ret.sli = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.baseline')
  }
 
  if (values.continuousVerification || values.healthScore) {
    Eif (!values.riskCategory) {
      ret.riskCategory = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.riskCategory')
    }
    Eif (!(values.higherBaselineDeviation || values.lowerBaselineDeviation)) {
      ret.higherBaselineDeviation = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.baseline')
    }
  }
 
  if (values.continuousVerification && !values.serviceInstanceField) {
    ret.serviceInstanceField = getString('cv.monitoringSources.prometheus.validation.serviceInstanceIdentifier')
  }
 
  Iif (!values.identifier?.trim()) {
    ret.identifier = getString('validation.identifierRequired')
  } else {
    const isAllIDsUnique = getIsAllIDsUnique(selectedMetrics, values.identifier.trim(), values.metricName || '')
 
    Iif (!isAllIDsUnique) {
      ret.identifier = getString('cv.monitoringSources.uniqueIdentifierValidation', {
        idName: values.identifier.trim()
      })
    }
  }
 
  if (!values.metricName?.length) {
    ret.metricName = getString('cv.monitoringSources.metricNameValidation')
  }
  if (isEmpty(values.metricTags)) {
    ret.metricTags = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.tags')
  }
  return ret
}
 
export function validate(
  values: GCOMetricInfo,
  selectedMetrics: Map<string, GCOMetricInfo>,
  getString: (key: StringKeys) => string
): { [key: string]: string } | undefined {
  const errors = ensureFieldsAreFilled(values, getString, selectedMetrics)
 
  Iif (selectedMetrics.size === 1) {
    return errors
  }
 
  for (const entry of selectedMetrics) {
    const [, metricInfo] = entry
    Iif (metricInfo.metricName === values.metricName) continue
    Eif (isEmpty(ensureFieldsAreFilled(metricInfo, getString, selectedMetrics))) {
      return errors
    }
  }
 
  Eif (!isEmpty(errors)) {
    errors[OVERALL] = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.mainSetupValidation')
  }
 
  return errors
}
 
export function initializeSelectedMetrics(
  selectedDashboards: GCOMetricSetupSource['selectedDashboards'],
  selectedMetrics?: GCOMetricSetupSource['metricDefinition']
): GCOMetricSetupSource['metricDefinition'] {
  if (!selectedMetrics?.size) {
    return new Map()
  }
 
  const updatedMap = new Map(selectedMetrics)
  for (const entry of updatedMap) {
    const [metricName, metricInfo] = entry
    Iif (
      !selectedDashboards.find(dashboard => dashboard?.name === metricInfo?.dashboardName) &&
      !metricInfo.isManualQuery
    ) {
      updatedMap.delete(metricName)
    }
  }
 
  return updatedMap
}
 
export function getRiskCategoryOptions(metricPacks?: MetricPackDTO[]): IOptionProps[] {
  if (!metricPacks?.length) {
    return []
  }
 
  const riskCategoryOptions: IOptionProps[] = []
  for (const metricPack of metricPacks) {
    Eif (metricPack?.identifier && metricPack.metrics?.length) {
      for (const metric of metricPack.metrics) {
        Iif (!metric?.name) {
          continue
        }
 
        riskCategoryOptions.push({
          label: metricPack.category !== metric.name ? `${metricPack.category}/${metric.name}` : metricPack.category,
          value: `${metricPack.category}/${metric.type}`
        })
      }
    }
  }
 
  return riskCategoryOptions
}
 
export function transformSampleDataIntoHighchartOptions(sampleData?: TimeSeriesSampleDTO[]): Highcharts.Options {
  if (!sampleData?.length) {
    return {}
  }
 
  const seriesData = new Map<string, Highcharts.SeriesLineOptions>()
  for (const data of sampleData) {
    Iif (!data || !data.timestamp || !data.txnName || !isNumber(data.metricValue)) continue
    let highchartsOptions = seriesData.get(data.txnName)
    if (!highchartsOptions) {
      highchartsOptions = { name: data.txnName, data: [], type: 'line' }
      seriesData.set(data.txnName, highchartsOptions)
    }
 
    highchartsOptions.data?.push([data.timestamp, data.metricValue])
  }
 
  return chartsConfig(Array.from(seriesData.values()).slice(0, 5))
}
 
export function getPlaceholderForIdentifier(
  metricName = '',
  getString?: (key: StringKeys, vars?: Record<string, any> | undefined) => string
): string {
  Eif (!metricName.length && getString) {
    return getString('cv.identifierPlaceholder')
  }
 
  // Default maxInput for InputWithIdentifier is 63
  return metricName.substr(-63).replace(/[^a-zA-Z_ ]/g, '')
}
 
export function mapstackdriverDashboardDetailToMetricWidget(
  _: string,
  stackdriverDashboardDetail: StackdriverDashboardDetail
): MetricWidget {
  const widgetName = stackdriverDashboardDetail.widgetName
  return {
    widgetName: widgetName || '',
    dataSets:
      stackdriverDashboardDetail.dataSetList?.map(dataSet => {
        return {
          id: `${dataSet.metricName}`,
          name: `${dataSet.metricName}`,
          query: dataSet.timeSeriesQuery || ''
        }
      }) || []
  }
}
 
export const onSelectNavItem = ({
  id,
  metricName,
  query,
  widget,
  dashboardId,
  dashboardTitle,
  updatedData,
  setUpdatedData,
  selectedMetric,
  formikProps
}: {
  id: string
  metricName: string
  query: string
  widget?: string
  dashboardId?: string
  dashboardTitle?: string
  updatedData: Map<string, GCOMetricInfo>
  setUpdatedData: Dispatch<SetStateAction<Map<string, GCOMetricInfo>>>
  selectedMetric?: string
  formikProps: FormikProps<GCOMetricInfo>
}): void => {
  let metricInfo: GCOMetricInfo | undefined = updatedData.get(metricName)
  Eif (!metricInfo) {
    metricInfo = {
      metricName,
      identifier: id,
      query,
      metricTags: widget ? { [widget]: '' } : {},
      isManualQuery: query === MANUAL_INPUT_QUERY,
      dashboardName: dashboardTitle,
      dashboardPath: dashboardId
    }
  }
 
  metricInfo.query = formatJSON(metricInfo.query) || ''
  updatedData.set(metricName, metricInfo)
  Iif (selectedMetric) {
    updatedData.set(selectedMetric as string, { ...formikProps.values })
  }
  setUpdatedData(new Map(updatedData))
}