All files / modules/70-pipeline/components/PipelineStudio/ExecutionStrategy ExecutionStrategy.tsx

88.24% Statements 90/102
73.04% Branches 84/115
80.95% Functions 17/21
89.9% Lines 89/99

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              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                                           13x           13x 13x 13x 13x 13x 13x   13x 38x 38x         38x     13x   13x               13x               13x     13x 13x   13x 13x 2x     2x     2x 2x 2x 2x     2x       13x 6x 6x 4x       13x               13x 6x     6x       13x 9x 9x   9x 9x 9x       9x         13x 5x             13x 1x   1x 1x 1x     1x       13x         13x 41x     13x                 28x         3x                                                                                                                                                                                                     4x 4x 4x 4x 4x         4x 4x 4x                       24x  
/*
 * 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, { useState, useEffect, useCallback } from 'react'
import YAML from 'yaml'
import { Classes, Switch } from '@blueprintjs/core'
import { Text, Icon, Layout, Button, Card, IconName, ButtonVariation, Container } from '@wings-software/uicore'
import { defaultTo, get, isEmpty, set, startCase } from 'lodash-es'
import { Color } from '@harness/design-system'
import cx from 'classnames'
import produce from 'immer'
import {
  DeploymentStageConfig,
  GetExecutionStrategyYamlQueryParams,
  StageElementConfig,
  StageElementWrapperConfig,
  useGetExecutionStrategyList,
  useGetExecutionStrategyYaml
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import type { DeploymentStageElementConfig } from '@pipeline/utils/pipelineTypes'
import { usePipelineContext } from '../PipelineContext/PipelineContext'
import { DrawerTypes } from '../PipelineContext/PipelineActions'
import Default from './resources/BlankCanvas.png'
import Steps from './Steps'
import RollingUpdateVideo from './resources/Rolling-Update-deployment.mp4'
import HelmDeploymentBasic from './resources/Helm-Deployment-basic.mp4'
import BlueGreenVideo from './resources/Blue-Green-deployment.mp4'
import CanaryVideo from './resources/Canary-deployment.mp4'
import Rolling from './resources/Rolling-Update-deployment.png'
import BlueGreen from './resources/Blue-Green-deployment.png'
import Canary from './resources/Canary-deployment.png'
import css from './ExecutionStrategy.module.scss'
 
export interface ExecutionStrategyProps {
  selectedStage: StageElementWrapperConfig
  ref?: ExecutionStrategyForwardRef
}
 
const iconMap: { [key: string]: IconName } = {
  Rolling: 'rolling-update',
  Canary: 'canary-icon',
  BlueGreen: 'blue-green',
  Default: 'blank-canvas-card-icon',
  Basic: 'basic-deployment'
}
 
const imageByType: { [key: string]: string } = {
  BlueGreen,
  Rolling,
  Canary,
  Default,
  Basic: Rolling
}
 
const videoByType: { [key: string]: string } = {
  BlueGreen: BlueGreenVideo,
  Rolling: RollingUpdateVideo,
  Canary: CanaryVideo,
  Basic: HelmDeploymentBasic
}
 
type StrategyType = GetExecutionStrategyYamlQueryParams['strategyType'] | 'BlankCanvas'
 
export interface ExecutionStrategyRefInterface {
  cancelExecutionStrategySelection: () => void
}
 
export type ExecutionStrategyForwardRef =
  | ((instance: ExecutionStrategyRefInterface | null) => void)
  | React.MutableRefObject<ExecutionStrategyRefInterface | null>
  | null
 
function ExecutionStrategyRef(
  props: ExecutionStrategyProps,
  executionStrategyRef: ExecutionStrategyForwardRef
): JSX.Element {
  const { selectedStage } = props
  const {
    state: { pipelineView },
    updateStage,
    updatePipelineView,
    getStageFromPipeline
  } = usePipelineContext()
  const { getString } = useStrings()
  const [strategiesByDeploymentType, setStrategies] = useState([])
  const [isSubmitDisabled, disableSubmit] = useState(false)
  const [isVerifyEnabled, setIsVerifyEnabled] = useState(false)
  const [showPlayButton, setShowPlayButton] = useState<boolean>(false)
 
  const serviceDefinitionType = useCallback((): GetExecutionStrategyYamlQueryParams['serviceDefinitionType'] => {
    const isPropagating = get(selectedStage, 'stage.spec.serviceConfig.useFromStage', null)
    Iif (isPropagating) {
      const parentStageId = isPropagating.stage
      const parentStage = getStageFromPipeline<DeploymentStageElementConfig>(parentStageId || '')
      return get(parentStage, 'stage.stage.spec.serviceConfig.serviceDefinition.type', null)
    }
    return get(selectedStage, 'stage.spec.serviceConfig.serviceDefinition.type', null)
  }, [getStageFromPipeline, selectedStage])
 
  const [selectedStrategy, setSelectedStrategy] = useState<StrategyType>('Rolling')
 
  const infoByType: { [key: string]: string } = {
    BlueGreen: getString('pipeline.executionStrategy.strategies.blueGreen.description'),
    Rolling: getString('pipeline.executionStrategy.strategies.rolling.description'),
    Canary: getString('pipeline.executionStrategy.strategies.canary.description'),
    Default: getString('pipeline.executionStrategy.strategies.default.description'),
    Basic: getString('pipeline.executionStrategy.strategies.basic.description')
  }
 
  const learnMoreLinkByType: { [key: string]: string } = {
    BlueGreen: getString('pipeline.executionStrategy.strategies.blueGreen.learnMoreLink'),
    Rolling: getString('pipeline.executionStrategy.strategies.rolling.learnMoreLink'),
    Canary: getString('pipeline.executionStrategy.strategies.canary.learnMoreLink'),
    Default: getString('pipeline.executionStrategy.strategies.default.learnMoreLink'),
    Basic: getString('pipeline.executionStrategy.strategies.default.learnMoreLink')
  }
 
  const { data: strategies } = useGetExecutionStrategyList({})
 
  // Video related
  let vidWrapper: HTMLElement | null = document.querySelector('[data-testid="player"]')
  let videoPlayer: HTMLVideoElement | undefined | null = vidWrapper?.querySelector('[data-testid="videoPlayer"]')
 
  useEffect(() => {
    if (!executionStrategyRef) return
    Iif (typeof executionStrategyRef === 'function') {
      return
    }
    executionStrategyRef.current = {
      cancelExecutionStrategySelection: cancelSelection
    }
    vidWrapper = document.querySelector('[data-testid="player"]')
    videoPlayer = vidWrapper?.querySelector('[data-testid="videoPlayer"]')
    videoPlayer?.addEventListener('ended', () => setShowPlayButton(true), false)
    Iif (videoPlayer?.ended) {
      setShowPlayButton(true)
    } else {
      setShowPlayButton(false)
    }
  })
 
  useEffect(() => {
    const _strategies = strategies?.data
    /* istanbul ignore else */ if (_strategies) {
      setStrategies(_strategies[serviceDefinitionType()] as any)
    }
  }, [strategies?.data, serviceDefinitionType])
 
  const { data: yamlSnippet, error } = useGetExecutionStrategyYaml({
    queryParams: {
      serviceDefinitionType: serviceDefinitionType(),
      strategyType: selectedStrategy !== 'BlankCanvas' ? selectedStrategy : 'Rolling',
      ...(isVerifyEnabled && { includeVerify: true })
    }
  })
 
  useEffect(() => {
    Iif (error) {
      disableSubmit(true)
    } else {
      disableSubmit(false)
    }
  }, [error])
 
  useEffect(() => {
    Eif (yamlSnippet?.data) {
      updateStage(
        produce(selectedStage, draft => {
          const jsonFromYaml = YAML.parse(defaultTo(yamlSnippet?.data, '{}')) as StageElementConfig
          set(draft, 'stage.failureStrategies', jsonFromYaml.failureStrategies)
          set(draft, 'stage.spec.execution', defaultTo((jsonFromYaml.spec as DeploymentStageConfig)?.execution, {}))
        }).stage as StageElementConfig
      )
    }
    Iif (selectedStrategy === getString('pipeline.executionStrategy.strategies.default.actualName')) {
      setIsVerifyEnabled(false)
    }
  }, [yamlSnippet?.data, selectedStrategy])
 
  const updatePipelineViewState = (): void => {
    updatePipelineView({
      ...pipelineView,
      isDrawerOpened: false,
      drawerData: { type: DrawerTypes.ExecutionStrategy }
    })
  }
 
  const cancelSelection = (): void => {
    updateStage(
      produce(selectedStage, draft => {
        const jsonFromYaml = YAML.parse(defaultTo(yamlSnippet?.data, '{}')) as StageElementConfig
        set(draft, 'stage.failureStrategies', jsonFromYaml.failureStrategies)
        set(draft, 'stage.spec.execution', { steps: [], rollbackSteps: [] })
      }).stage as StageElementConfig
    ).then(() => {
      updatePipelineViewState()
    })
  }
 
  const toggleVideo = (): void => {
    videoPlayer?.play()
    setShowPlayButton(false)
  }
 
  const getStrategyNameByType = (type: string): string => {
    return type === 'Default' ? getString('pipeline.executionStrategy.strategies.default.displayName') : startCase(type)
  }
 
  return (
    <Layout.Horizontal>
      <Layout.Vertical width={448} className={css.strategySelectionPanel}>
        <Layout.Horizontal className={css.header}>
          <Text className={css.headerText}>{getString('pipeline.executionStrategy.executionStrategies')}</Text>
        </Layout.Horizontal>
        <section className={css.patterns}>
          <section className={css.strategies} data-section-id="strategy-selection">
            {strategiesByDeploymentType?.map((v: StrategyType) => (
              <Card
                className={cx(css.card, selectedStrategy === v && css.active)}
                elevation={0}
                key={v}
                interactive={true}
                onClick={() => setSelectedStrategy(v)}
                data-testid={`${v}-Card`}
              >
                <Icon name={iconMap[v] as IconName} size={40} border={false} />
                <section className={css.strategyName}>{getStrategyNameByType(v)}</section>
                <section className={css.strategyType}>
                  {v !== 'Default' ? startCase(serviceDefinitionType()) : null}
                </section>
              </Card>
            ))}
          </section>
        </section>
      </Layout.Vertical>
 
      <Layout.Vertical width={688} className={css.strategyDetailsPanel}>
        <Container className={css.strategyDetailsBody}>
          <Layout.Horizontal className={css.header} flex>
            <Layout.Horizontal>
              <Text
                className={css.headerText}
                data-testid={`${selectedStrategy}DetailsHeader`}
                tooltipProps={{ dataTooltipId: `${selectedStrategy}DetailsHeader` }}
              >
                {getStrategyNameByType(selectedStrategy)}
              </Text>
              {selectedStrategy === 'Default' && (
                <Icon name="blank-canvas-header-icon" size={24} color={Color.PRIMARY_6} />
              )}
            </Layout.Horizontal>
            <Button
              variation={ButtonVariation.LINK}
              href={learnMoreLinkByType[selectedStrategy]}
              target="_blank"
              withoutBoxShadow={true}
            >
              {getString('learnMore')}
            </Button>
          </Layout.Horizontal>
          <section className={css.preview}>
            <section className={css.previewContainer}>
              <section className={css.info} data-testid="info">
                {infoByType[selectedStrategy]}
              </section>
              {!isEmpty(videoByType[selectedStrategy]) ? (
                <section className={css.player} data-testid="player">
                  <video
                    key={selectedStrategy}
                    className={css.videoPlayer}
                    autoPlay
                    poster={imageByType[selectedStrategy]}
                    data-testid="videoPlayer"
                  >
                    <source src={videoByType[selectedStrategy]} type="video/mp4"></source>
                    <Text tooltipProps={{ dataTooltipId: 'videoNotSupportedError' }}>
                      {getString('common.videoNotSupportedError')}
                    </Text>
                  </video>
                  {showPlayButton && (
                    <div className={css.playerControls}>
                      <Button
                        minimal
                        variation={ButtonVariation.ICON}
                        className={css.playButton}
                        onClick={toggleVideo}
                        data-testid="playButton"
                        icon="play-circle"
                        iconProps={{ size: 42 }}
                        withoutCurrentColor
                      />
                    </div>
                  )}
                </section>
              ) : (
                <section className={css.image}>
                  <img src={imageByType[selectedStrategy]} data-testid="blank-canvas-image" />
                </section>
              )}
              {selectedStrategy !== 'Default' && (
                <>
                  <Steps strategy={selectedStrategy} />
                  <section className={css.enableVerificationSection}>
                    <Switch
                      checked={isVerifyEnabled}
                      onChange={() => setIsVerifyEnabled(prevIsVerifyEnabled => !prevIsVerifyEnabled)}
                      className={cx(Classes.SMALL, css.toggleVerify)}
                      data-testid="enable-verification-options-switch"
                    />
                    <Text className={css.enableVerification}>{getString('pipeline.enableVerificationOptions')}</Text>
                  </section>
                </>
              )}
            </section>
          </section>
        </Container>
        <Container className={css.strategyDetailsFooter}>
          <Button
            variation={ButtonVariation.PRIMARY}
            text={getString('pipeline.executionStrategy.useStrategy')}
            onClick={() => {
              const newStage = produce(selectedStage, draft => {
                const jsonFromYaml = YAML.parse(yamlSnippet?.data || '') as StageElementConfig
                Eif (draft.stage && draft.stage.spec) {
                  draft.stage.failureStrategies = jsonFromYaml?.failureStrategies
                  ;(draft.stage.spec as DeploymentStageConfig).execution = (jsonFromYaml?.spec as DeploymentStageConfig)
                    ?.execution ?? { steps: [], rollbackSteps: [] }
                }
              }).stage
 
              Eif (newStage) {
                updateStage(newStage).then(() => {
                  updatePipelineViewState()
                })
              }
            }}
            disabled={isSubmitDisabled}
          />
        </Container>
      </Layout.Vertical>
    </Layout.Horizontal>
  )
}
 
export const ExecutionStrategy = React.forwardRef(ExecutionStrategyRef)