All files / src population.js

58.62% Statements 85/145
41% Branches 41/100
85.71% Functions 6/7
58.74% Lines 84/143

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      6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 24x         30x       21x   21x 8x     8x   13x 13x   13x 3x 3x 3x       3x           10x             4x   4x 2x     2x 2x   2x   2x                 2x 2x 2x   2x                         2x 2x   2x   2x   2x   2x   2x 2x                                                                                                           30x 30x 12x     18x   18x   18x 5x 5x     18x 15x       15x   15x       6x         6x 6x 18x 18x     6x       6x   6x   24x   6x 6x 17x 17x 17x       17x 6x 6x         6x   9x     3x        
import md5 from 'md5'
import {logger} from './logger'
 
export const RULE_TYPE_STRING = 'string'
export const RULE_TYPE_INT = 'int'
export const RULE_TYPE_FLOAT = 'float'
export const RULE_TYPE_BOOLEAN = 'boolean'
export const RULE_TYPE_DATE = 'date'
export const RULE_TYPE_DATETIME = 'datetime'
 
export const RULE_OPERATOR_IS = 'is'
export const RULE_OPERATOR_IS_NOT = 'is_not'
export const RULE_OPERATOR_IN = 'in'
export const RULE_OPERATOR_NOT_IN = 'not_in'
export const RULE_OPERATOR_LT = 'lt'
export const RULE_OPERATOR_LTE = 'lte'
export const RULE_OPERATOR_GT = 'gt'
export const RULE_OPERATOR_GTE = 'gte'
export const RULE_OPERATOR_FROM = 'from'
export const RULE_OPERATOR_UNTIL = 'until'
export const RULE_OPERATOR_AFTER = 'after'
export const RULE_OPERATOR_BEFORE = 'before'
 
export const getHashedValue = s => {
  return (parseInt(md5(s), 16) * 1.0) / 340282366920938463463374607431768211455
}
 
export default class Population {
  constructor(population) {
    this.population = population
  }
 
  static categorizeValueType(v) {
    Iif (v === true || v === false) {
      return 'boolean'
    } else if (typeof v === 'number') {
      Iif ((v + '').indexOf('.') >= 0) {
        return 'float'
      } else {
        return 'int'
      }
    } else Eif (typeof v === 'string') {
      const unixTimestamp = new Date(v).getTime()
 
      if (!isNaN(unixTimestamp)) {
        const isoFormat = new Date(v).toISOString()
        const timeIndex = isoFormat.lastIndexOf('T00:00:00.000Z')
        Eif (
          timeIndex !== -1 &&
          isoFormat.length - 'T00:00:00.000Z'.length === timeIndex
        ) {
          return 'date'
        } else {
          return 'datetime'
        }
      }
 
      return 'string'
    }
    logger('Unexpected attribute value type encountered')
    return null
  }
 
  _ruleMatches(rule, obj) {
    const attributes = obj.attributes || {}
 
    if (!attributes.hasOwnProperty(rule.attributeName)) {
      return false
    }
 
    const v = attributes[rule.attributeName]
    const attributeType = Population.categorizeValueType(v)
 
    const numberTypes = [RULE_TYPE_INT, RULE_TYPE_FLOAT]
 
    Eif (
      numberTypes.indexOf(attributeType) !== -1 &&
      numberTypes.indexOf(rule.attributeType) !== -1
    ) {
      // This is fine
    } else if (attributeType !== rule.attributeType) {
      return false
    }
 
    const targetVal = rule.value
    const targetValList = rule.valueList
    const op = rule.operator
 
    Iif (attributeType === RULE_TYPE_STRING) {
      if (op === RULE_OPERATOR_IS) {
        return v === targetVal
      } else if (op === RULE_OPERATOR_IS_NOT) {
        return v !== targetVal
      } else if (op === RULE_OPERATOR_IN) {
        return targetValList.indexOf(v) !== -1
      } else if (op === RULE_OPERATOR_NOT_IN) {
        return targetValList.indexOf(v) === -1
      } else {
        logger('Invalid rule operator encountered')
        return false
      }
    } else Eif (numberTypes.indexOf(attributeType) !== -1) {
      Iif (op === RULE_OPERATOR_IS) {
        return v === targetVal
      } else Iif (op === RULE_OPERATOR_IS_NOT) {
        return v !== targetVal
      } else Iif (op === RULE_OPERATOR_IN) {
        return targetValList.indexOf(v) !== -1
      } else Iif (op === RULE_OPERATOR_NOT_IN) {
        return targetValList.indexOf(v) === -1
      } else Iif (op === RULE_OPERATOR_LT) {
        return v < targetVal
      } else Eif (op === RULE_OPERATOR_LTE) {
        return v <= targetVal
      } else if (op === RULE_OPERATOR_GT) {
        return v > targetVal
      } else if (op === RULE_OPERATOR_GTE) {
        return v >= targetVal
      } else {
        logger('Invalid rule operator encountered')
        return false
      }
    } else if (attributeType === RULE_TYPE_BOOLEAN) {
      if (op === RULE_OPERATOR_IS) {
        return v === targetVal
      } else if (op === RULE_OPERATOR_IS_NOT) {
        return v !== targetVal
      } else {
        logger('Invalid rule operator encountered')
        return false
      }
    } else if (
      attributeType === RULE_TYPE_DATE ||
      attributeType === RULE_TYPE_DATETIME
    ) {
      const targetTime = targetVal && new Date(targetVal).getTime()
      const targetTimeList =
        targetValList && targetValList.map(tv => new Date(tv).getTime())
      const vTime = new Date(v).getTime()
 
      if (op === RULE_OPERATOR_IS) {
        return vTime === targetTime
      } else if (op === RULE_OPERATOR_IS_NOT) {
        return vTime !== targetTime
      } else if (op === RULE_OPERATOR_IN) {
        return targetTimeList.indexOf(vTime) !== -1
      } else if (op === RULE_OPERATOR_NOT_IN) {
        return targetTimeList.indexOf(vTime) === -1
      } else if (op === RULE_OPERATOR_FROM) {
        return vTime >= targetTime
      } else if (op === RULE_OPERATOR_UNTIL) {
        return vTime <= targetTime
      } else if (op === RULE_OPERATOR_AFTER) {
        return vTime > targetTime
      } else if (op === RULE_OPERATOR_BEFORE) {
        return vTime < targetTime
      } else {
        logger('Invalid rule operator encountered')
        return false
      }
    } else {
      logger('Invalid attribute type encountered')
      return false
    }
  }
 
  getGateValues(obj, env, flag, sticky) {
    const population = this.population
    if (this.population.entityType !== obj.type) {
      return {eligible: false}
    }
 
    const rules = population.rules
 
    let matches = true
 
    for (let i = 0; i < rules.length; i++) {
      const r = rules[i]
      matches = matches && this._ruleMatches(r, obj)
    }
 
    if (matches) {
      const samplingHashKey = `SAMPLING:control_${flag.hashKey}:env_${
        env.hashKey
      }:rule_set_${this.population.hashKey}:client_object_${obj.type}_${obj.id}`
 
      const hashedPercentage = getHashedValue(samplingHashKey)
 
      if (
        hashedPercentage <= this.population.percentage &&
        this.population.percentage > 0
      ) {
        const splits = sticky
          ? this.population.universes[
              Math.max(Math.floor(hashedPercentage * 100) - 1, 0)
            ]
          : flag.splits
        const splitsMap = {}
        for (let i = 0; i < splits.length; i++) {
          const split = splits[i]
          splitsMap[split.treatmentId] = split
        }
 
        const allocationHashKey = `DISTRIBUTION:control_${flag.hashKey}:env_${
          env.hashKey
        }:client_object_${obj.type}_${obj.id}`
 
        const allocationHashedPercentage = getHashedValue(allocationHashKey)
 
        let trailingSum = 0.0
 
        const treatments = flag.treatments.filter(t => !t.isOffTreatment)
 
        let treatment = null
        for (let i = 0; i < treatments.length; i++) {
          const t = treatments[i]
          Eif (splitsMap.hasOwnProperty(t.treatmentId)) {
            trailingSum = parseFloat(
              (trailingSum + splitsMap[t.treatmentId].percentage).toFixed(3)
            )
 
            if (allocationHashedPercentage <= trailingSum) {
              treatment = t
              break
            }
          }
        }
 
        return {treatment: treatment, eligible: true}
      } else {
        return {eligible: true}
      }
    } else {
      return {eligible: false}
    }
  }
}