All files / modules/10-common/hooks useFeatures.ts

99.04% Statements 103/104
97.37% Branches 74/76
100% Functions 20/20
99.03% Lines 102/103

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              590x 590x 590x 590x 590x   590x                       590x 590x 590x                         5194x 5194x 5194x     590x   1637x   1637x   1637x 1637x   1637x 1637x           1637x   1637x 572x 309x 3x       306x             1637x 753x       884x     590x   3557x   3557x   3557x 3557x   3557x   3557x     3557x 3557x 3557x 485x           485x 485x 4x     481x     3557x   3557x   3557x 1380x 68x   2x 2x     68x   2x             3557x 788x 236x 236x 291x     788x       2769x 181x 181x 194x 4x   194x 8x         2769x     590x 43x 43x     590x 705x       705x 705x     705x 705x 705x     705x 705x 705x     705x     590x 47x   47x     47x 47x       47x 47x           47x 47x       47x 47x 46x     1x 3x 3x 1x   2x     2x 2x     1x     590x               3x    
/*
 * 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 { useMemo } from 'react'
import { capitalize } from 'lodash-es'
import { Editions, RestrictionType } from '@common/constants/SubscriptionTypes'
import { useDeepCompareEffect } from '@common/hooks'
import { useFeaturesContext } from 'framework/featureStore/FeaturesContext'
import type { AvailabilityRestrictionDTO } from 'services/cd-ng'
import { FeatureFlag } from '@common/featureFlags'
import type {
  FeatureRequestOptions,
  FeatureRequest,
  CheckFeatureReturn,
  FeaturesRequest,
  CheckFeaturesReturn,
  ModuleType,
  RestrictionMetadataMap,
  FirstDisabledFeatureReturn
} from 'framework/featureStore/featureStoreUtil'
import type { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import { useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import { useCommunity } from 'framework/LicenseStore/useCommunity'
import { useFeatureFlag } from './useFeatureFlag'
 
interface FeatureProps {
  featureRequest?: FeatureRequest
  options?: FeatureRequestOptions
}
 
interface FeaturesProps {
  featuresRequest?: FeaturesRequest
  options?: FeatureRequestOptions
}
 
function useGetFeatureEnforced(): boolean {
  const featureEnforced = useFeatureFlag(FeatureFlag.FEATURE_ENFORCEMENT_ENABLED)
  const isCommunity = useCommunity()
  return featureEnforced || isCommunity
}
 
export function useFeature(props: FeatureProps): CheckFeatureReturn {
  const { requestFeatures, checkFeature, requestLimitFeature, checkLimitFeature, getRestrictionType } =
    useFeaturesContext()
  const { licenseInformation, CI_LICENSE_STATE, CD_LICENSE_STATE, FF_LICENSE_STATE, CCM_LICENSE_STATE } =
    useLicenseStore()
 
  const featureEnforced = useGetFeatureEnforced()
  const isCommunity = useCommunity()
 
  const { featureRequest, options } = props
  const restrictionType = getRestrictionType({
    featureRequest,
    licenseInformation,
    licenseState: { CI_LICENSE_STATE, CD_LICENSE_STATE, FF_LICENSE_STATE, CCM_LICENSE_STATE },
    isCommunity
  })
  const isLimit = restrictionType && restrictionType !== RestrictionType.AVAILABILITY
 
  useDeepCompareEffect(() => {
    if (featureEnforced && featureRequest) {
      if (isLimit) {
        requestLimitFeature(featureRequest)
      } else {
        // cache enabled availability feature list in the context
        // restrictionType could be undefined, we don't do anything
        restrictionType && requestFeatures(featureRequest, options)
      }
    }
 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [featureRequest, options, isLimit, featureEnforced, restrictionType])
 
  if (!featureEnforced || featureRequest === undefined) {
    return { enabled: true }
  }
 
  // rate limit feature always calls the api in real time
  return isLimit ? checkLimitFeature(featureRequest.featureName) : checkFeature(featureRequest.featureName)
}
 
export function useFeatures(props: FeaturesProps): CheckFeaturesReturn {
  const { requestFeatures, checkFeature, requestLimitFeature, checkLimitFeature, getRestrictionType } =
    useFeaturesContext()
  const { licenseInformation, CI_LICENSE_STATE, CD_LICENSE_STATE, FF_LICENSE_STATE, CCM_LICENSE_STATE } =
    useLicenseStore()
 
  const featureEnforced = useGetFeatureEnforced()
  const isCommunity = useCommunity()
 
  const features = new Map<FeatureIdentifier, CheckFeatureReturn>()
 
  const { featuresRequest, options } = props
 
  function groupFeatures(): { limitFeatures: FeatureIdentifier[]; availFeatures: FeatureIdentifier[] } {
    const accLimitFeatures: FeatureIdentifier[] = []
    const accAvailFeatures: FeatureIdentifier[] = []
    featuresRequest?.featureNames.forEach(featureName => {
      const restrictionType = getRestrictionType({
        featureRequest: { featureName },
        licenseInformation,
        licenseState: { CI_LICENSE_STATE, CD_LICENSE_STATE, FF_LICENSE_STATE, CCM_LICENSE_STATE },
        isCommunity
      })
      const isLimit = restrictionType && restrictionType !== RestrictionType.AVAILABILITY
      if (isLimit) {
        accLimitFeatures.push(featureName)
      } else {
        // restrictionType could be undefined, we don't do anything
        restrictionType && accAvailFeatures.push(featureName)
      }
    })
    return { limitFeatures: accLimitFeatures, availFeatures: accAvailFeatures }
  }
  const { limitFeatures, availFeatures } = groupFeatures()
 
  useDeepCompareEffect(() => {
    if (featureEnforced && featuresRequest) {
      if (limitFeatures.length > 0) {
        // every limit feature needs real time inquiry
        limitFeatures.forEach(featureName => {
          requestLimitFeature({ featureName })
        })
      }
      if (availFeatures.length > 0) {
        // cache enabled availability feature list in the context
        requestFeatures(featuresRequest, options)
      }
    }
 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [options, featureEnforced, limitFeatures, availFeatures])
 
  if (!featureEnforced) {
    if (featuresRequest) {
      const { featureNames } = featuresRequest
      featureNames.forEach(featureName => {
        features.set(featureName, { enabled: true })
      })
    }
    return { features }
  }
 
  // re-order the returned features by the order they are passed in
  if (featuresRequest) {
    const { featureNames } = featuresRequest
    featureNames.forEach(featureName => {
      if (limitFeatures.includes(featureName)) {
        features.set(featureName, checkLimitFeature(featureName))
      }
      if (availFeatures.includes(featureName)) {
        features.set(featureName, checkFeature(featureName))
      }
    })
  }
 
  return { features }
}
 
export function useFeatureModule(featureName?: FeatureIdentifier): ModuleType {
  const { featureMap } = useFeaturesContext()
  return featureName && featureMap.get(featureName)?.moduleType
}
 
export function useGetFirstDisabledFeature(featuresRequest?: FeaturesRequest): FirstDisabledFeatureReturn {
  const { features } = useFeatures({
    featuresRequest
  })
 
  const keys = useMemo(() => {
    return [...features.keys()]
  }, [features])
 
  const firstDisabledFeatureIndex: number = useMemo(() => {
    const values = [...features.values()]
    return values.findIndex(feature => !feature.enabled)
  }, [features])
 
  const featureEnabled = firstDisabledFeatureIndex === -1
  const disabledFeatureName = useMemo(() => {
    return !featureEnabled ? keys[firstDisabledFeatureIndex] : undefined
  }, [featureEnabled, keys, firstDisabledFeatureIndex])
 
  return { featureEnabled, disabledFeatureName }
}
 
export function useFeatureRequiredPlans(featureName?: FeatureIdentifier): string[] {
  const { featureMap, getEdition } = useFeaturesContext()
  const { licenseInformation, CI_LICENSE_STATE, CD_LICENSE_STATE, FF_LICENSE_STATE, CCM_LICENSE_STATE } =
    useLicenseStore()
 
  // for community, do not return plans
  const isCommunity = useCommunity()
  Iif (isCommunity) {
    return []
  }
 
  const moduleType = featureName && featureMap.get(featureName)?.moduleType
  const currentEdition = getEdition({
    moduleType,
    licenseInformation,
    licenseState: { CI_LICENSE_STATE, CD_LICENSE_STATE, FF_LICENSE_STATE, CCM_LICENSE_STATE },
    isCommunity
  })
  const restrictionMetadataMap = featureName && featureMap.get(featureName)?.restrictionMetadataMap
  return getRequiredPlans(currentEdition, restrictionMetadataMap)
}
 
function getRequiredPlans(currentEdition?: Editions, map?: RestrictionMetadataMap): string[] {
  const editions: string[] = []
  if (!map || !currentEdition) {
    return editions
  }
 
  Object.entries(map).forEach(([key, value]) => {
    const edition = key as Editions
    if (lowerThanCurrentPlan(currentEdition, edition)) {
      return
    }
    const { enabled } = value as AvailabilityRestrictionDTO
    // for plans when it's AVAILABILITY feature, when enabled is true, push it into the bucket
    // for plans when it's LIMIT feature, enabled is undefined, just push it into the bucket
    Eif (enabled !== false) {
      editions.push(capitalize(edition.toString()))
    }
  })
  return editions
}
 
const orders = {
  ENTERPRISE: 0,
  TEAM: 1,
  FREE: 2,
  COMMUNITY: 2
}
 
function lowerThanCurrentPlan(currentEdition: Editions, edition: Editions): boolean {
  return orders[currentEdition] <= orders[edition]
}