-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathffe-evaluator.js
More file actions
278 lines (254 loc) · 9.68 KB
/
Copy pathffe-evaluator.js
File metadata and controls
278 lines (254 loc) · 9.68 KB
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
'use strict'
const SEMVER_OPERATORS = new Set([
'SEMVER_EQ', 'SEMVER_NEQ', 'SEMVER_LT', 'SEMVER_LTE', 'SEMVER_GT', 'SEMVER_GTE',
])
const OPERATORS = new Set([
'LT', 'LTE', 'GT', 'GTE', 'MATCHES', 'NOT_MATCHES', 'ONE_OF', 'NOT_ONE_OF', 'IS_NULL',
...SEMVER_OPERATORS,
])
const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
const UINT64_MAX = '18446744073709551615'
/**
* Validates flags independently and converts SemVer conditions into rules the
* upstream evaluator can execute with per-request synthetic attributes.
*
* @param {import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1 | undefined} [configuration]
* @returns {{
* configuration: import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1 | undefined,
* rejected: Set<string>,
* sourceConfiguration: import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1 | undefined,
* semverConditions: Map<string, Array<{
* attribute: string,
* comparand: string,
* operator: string,
* syntheticAttribute: string
* }>>
* }}
*/
function sanitizeConfiguration (configuration) {
const rejected = new Set()
const semverConditions = new Map()
if (!configuration?.flags || typeof configuration.flags !== 'object' || Array.isArray(configuration.flags)) {
return { configuration, rejected, semverConditions, sourceConfiguration: configuration }
}
const flags = { ...configuration.flags }
for (const [key, flag] of Object.entries(configuration.flags)) {
try {
const conditions = []
flags[key] = prepareFlag(key, flag, conditions)
if (conditions.length) semverConditions.set(key, conditions)
} catch {
rejected.add(key)
}
}
return {
configuration: rejected.size || semverConditions.size ? { ...configuration, flags } : configuration,
rejected,
semverConditions,
sourceConfiguration: configuration,
}
}
/**
* Adds the precomputed attributes used by transformed SemVer rules.
*
* @param {Array<{
* attribute: string,
* comparand: string,
* operator: string,
* syntheticAttribute: string
* }> | undefined} conditions
* @param {import('@openfeature/server-sdk').EvaluationContext} context
* @returns {import('@openfeature/server-sdk').EvaluationContext}
*/
function addSemverContext (conditions, context) {
if (!conditions) return context
const semverContext = { ...context }
for (const condition of conditions) {
const matches = compareSemverOperator(
condition.operator,
context?.[condition.attribute],
condition.comparand
)
semverContext[condition.syntheticAttribute] = matches ? 'true' : 'false'
}
return semverContext
}
function prepareFlag (key, flag, semverConditions) {
if (!flag || flag.key !== key || typeof flag.enabled !== 'boolean' ||
!['BOOLEAN', 'INTEGER', 'NUMERIC', 'STRING', 'JSON'].includes(flag.variationType)) {
throw new Error('invalid flag')
}
if (!flag.variations || typeof flag.variations !== 'object' || Array.isArray(flag.variations)) {
throw new Error('missing variations')
}
for (const [variationKey, variation] of Object.entries(flag.variations)) {
if (!variation || variation.key !== variationKey || !matchesType(variation.value, flag.variationType)) {
throw new Error('invalid variation')
}
}
if (!Array.isArray(flag.allocations)) throw new Error('invalid allocations')
let transformed = false
const allocations = []
for (const allocation of flag.allocations) {
if (!allocation || !Array.isArray(allocation.splits)) throw new Error('invalid allocation')
for (const split of allocation.splits) validateSplit(split, flag.variations)
if (allocation.rules === undefined) {
allocations.push(allocation)
continue
}
if (!Array.isArray(allocation.rules)) throw new Error('invalid rules')
let allocationTransformed = false
const rules = []
for (const rule of allocation.rules) {
if (!rule || !Array.isArray(rule.conditions)) throw new Error('invalid rule')
let ruleTransformed = false
const conditions = []
for (const condition of rule.conditions) {
validateCondition(condition)
if (!SEMVER_OPERATORS.has(condition.operator)) {
conditions.push(condition)
continue
}
const syntheticAttribute = `__datadog_semver_condition_${semverConditions.length}`
semverConditions.push({
attribute: condition.attribute,
comparand: condition.value,
operator: condition.operator,
syntheticAttribute,
})
conditions.push({
...condition,
attribute: syntheticAttribute,
operator: 'ONE_OF',
value: ['true'],
})
ruleTransformed = true
}
rules.push(ruleTransformed ? { ...rule, conditions } : rule)
allocationTransformed ||= ruleTransformed
}
allocations.push(allocationTransformed ? { ...allocation, rules } : allocation)
transformed ||= allocationTransformed
}
return transformed ? { ...flag, allocations } : flag
}
function validateSplit (split, variations) {
if (!split || !Array.isArray(split.shards) || !Object.hasOwn(variations, split.variationKey)) {
throw new Error('invalid split')
}
for (const shard of split.shards) {
if (!shard || !Number.isSafeInteger(shard.totalShards) || shard.totalShards <= 0 ||
shard.totalShards > 0xFF_FF_FF_FF || !Array.isArray(shard.ranges)) {
throw new Error('invalid shard')
}
for (const range of shard.ranges) {
if (!range || !Number.isSafeInteger(range.start) || !Number.isSafeInteger(range.end) ||
range.start < 0 || range.start >= range.end || range.end > shard.totalShards) {
throw new Error('invalid shard range')
}
}
}
}
function validateCondition (condition) {
if (!condition || typeof condition.attribute !== 'string' || !OPERATORS.has(condition.operator)) {
throw new Error('invalid condition')
}
switch (condition.operator) {
case 'MATCHES':
case 'NOT_MATCHES':
if (typeof condition.value !== 'string') throw new Error('invalid regex')
compileRegex(condition.value)
break
case 'LT':
case 'LTE':
case 'GT':
case 'GTE':
if (typeof condition.value !== 'number' || !Number.isFinite(condition.value)) throw new Error('invalid number')
break
case 'ONE_OF':
case 'NOT_ONE_OF':
if (!Array.isArray(condition.value) || condition.value.some(value => typeof value !== 'string')) {
throw new Error('invalid membership')
}
break
case 'IS_NULL':
if (typeof condition.value !== 'boolean') throw new Error('invalid null check')
break
default:
parseSemver(condition.value)
}
}
function matchesType (value, type) {
if (type === 'BOOLEAN') return typeof value === 'boolean'
if (type === 'STRING') return typeof value === 'string'
if (type === 'INTEGER') return Number.isSafeInteger(value)
if (type === 'NUMERIC') return typeof value === 'number' && Number.isFinite(value)
return value !== undefined
}
function compileRegex (pattern) {
const inlineFlags = pattern.match(/^\(\?([imsu]+)\)/)
const flags = inlineFlags ? [...new Set(inlineFlags[1])].join('') : ''
const source = (inlineFlags ? pattern.slice(inlineFlags[0].length) : pattern)
.replaceAll('[:alnum:]', 'A-Za-z0-9')
return new RegExp(source, flags)
}
function parseSemver (value) {
if (typeof value !== 'string') throw new Error('invalid semantic version')
const match = SEMVER.exec(value)
if (!match) throw new Error('invalid semantic version')
const core = match.slice(1, 4)
if (core.some(part => compareNumeric(part, UINT64_MAX) > 0)) throw new Error('invalid semantic version')
const prerelease = match[4]?.split('.')
if (prerelease?.some(part => /^\d+$/.test(part) && compareNumeric(part, UINT64_MAX) > 0)) {
throw new Error('invalid semantic version')
}
return { core, prerelease }
}
function compareSemverOperator (operator, left, right) {
let comparison
try {
comparison = compareSemver(parseSemver(left), parseSemver(right))
} catch {
return false
}
if (operator === 'SEMVER_EQ') return comparison === 0
if (operator === 'SEMVER_NEQ') return comparison !== 0
if (operator === 'SEMVER_LT') return comparison < 0
if (operator === 'SEMVER_LTE') return comparison <= 0
if (operator === 'SEMVER_GT') return comparison > 0
return comparison >= 0
}
function compareSemver (left, right) {
for (let index = 0; index < 3; index++) {
const result = compareNumeric(left.core[index], right.core[index])
if (result) return result
}
if (!left.prerelease && !right.prerelease) return 0
if (!left.prerelease) return 1
if (!right.prerelease) return -1
for (let index = 0; index < Math.min(left.prerelease.length, right.prerelease.length); index++) {
const leftPart = left.prerelease[index]
const rightPart = right.prerelease[index]
const leftNumeric = /^\d+$/.test(leftPart)
const rightNumeric = /^\d+$/.test(rightPart)
let result
if (leftNumeric && rightNumeric) {
result = compareNumeric(leftPart, rightPart)
} else if (leftNumeric) {
result = -1
} else if (rightNumeric) {
result = 1
} else {
result = compareLexical(leftPart, rightPart)
}
if (result) return result
}
return Math.sign(left.prerelease.length - right.prerelease.length)
}
function compareNumeric (left, right) {
return Math.sign(left.length - right.length) || compareLexical(left, right)
}
function compareLexical (left, right) {
return left === right ? 0 : left < right ? -1 : 1
}
module.exports = { addSemverContext, sanitizeConfiguration }