-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathConditionEvaluator.java
More file actions
345 lines (307 loc) · 13.6 KB
/
ConditionEvaluator.java
File metadata and controls
345 lines (307 loc) · 13.6 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
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
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.remoteconfig;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.firebase.internal.NonNull;
import com.google.firebase.internal.Nullable;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.IntPredicate;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class ConditionEvaluator {
private static final int MAX_CONDITION_RECURSION_DEPTH = 10;
private static final Logger logger = LoggerFactory.getLogger(ConditionEvaluator.class);
private static final BigInteger MICRO_PERCENT_MODULO = BigInteger.valueOf(100_000_000L);
/**
* Evaluates server conditions and assigns a boolean value to each condition.
*
* @param conditions List of conditions which are to be evaluated.
* @param context A map with additional metadata used during evaluation.
* @return A map of condition to evaluated value.
*/
@NonNull
Map<String, Boolean> evaluateConditions(
@NonNull List<ServerCondition> conditions, @Nullable KeysAndValues context) {
checkNotNull(conditions, "List of conditions must not be null.");
checkArgument(!conditions.isEmpty(), "List of conditions must not be empty.");
if (context == null || conditions.isEmpty()) {
return ImmutableMap.of();
}
KeysAndValues evaluationContext =
context != null ? context : new KeysAndValues.Builder().build();
Map<String, Boolean> evaluatedConditions =
conditions.stream()
.collect(
ImmutableMap.toImmutableMap(
ServerCondition::getName,
condition ->
evaluateCondition(
condition.getCondition(), evaluationContext, /* nestingLevel= */ 0)));
return evaluatedConditions;
}
private boolean evaluateCondition(
OneOfCondition condition, KeysAndValues context, int nestingLevel) {
if (nestingLevel > MAX_CONDITION_RECURSION_DEPTH) {
logger.warn("Maximum condition recursion depth exceeded.");
return false;
}
if (condition.getOrCondition() != null) {
return evaluateOrCondition(condition.getOrCondition(), context, nestingLevel + 1);
} else if (condition.getAndCondition() != null) {
return evaluateAndCondition(condition.getAndCondition(), context, nestingLevel + 1);
} else if (condition.isTrue() != null) {
return true;
} else if (condition.isFalse() != null) {
return false;
} else if (condition.getCustomSignal() != null) {
return evaluateCustomSignalCondition(condition.getCustomSignal(), context);
} else if (condition.getPercent() != null) {
return evaluatePercentCondition(condition.getPercent(), context);
}
logger.atWarn().log("Received invalid condition for evaluation.");
return false;
}
private boolean evaluateOrCondition(
OrCondition condition, KeysAndValues context, int nestingLevel) {
return condition.getConditions().stream()
.anyMatch(subCondition -> evaluateCondition(subCondition, context, nestingLevel + 1));
}
private boolean evaluateAndCondition(
AndCondition condition, KeysAndValues context, int nestingLevel) {
return condition.getConditions().stream()
.allMatch(subCondition -> evaluateCondition(subCondition, context, nestingLevel + 1));
}
private boolean evaluateCustomSignalCondition(
CustomSignalCondition condition, KeysAndValues context) {
CustomSignalOperator customSignalOperator = condition.getCustomSignalOperator();
String customSignalKey = condition.getCustomSignalKey();
ImmutableList<String> targetCustomSignalValues =
ImmutableList.copyOf(condition.getTargetCustomSignalValues());
if (targetCustomSignalValues.isEmpty()) {
logger.warn(
String.format(
"Values must be assigned to all custom signal fields. Operator:%s, Key:%s, Values:%s",
customSignalOperator, customSignalKey, targetCustomSignalValues));
return false;
}
String customSignalValue = context.get(customSignalKey);
if (customSignalValue == null) {
return false;
}
switch (customSignalOperator) {
// String operations.
case STRING_CONTAINS:
return compareStrings(
targetCustomSignalValues,
customSignalValue,
(customSignal, targetSignal) -> customSignal.contains(targetSignal));
case STRING_DOES_NOT_CONTAIN:
return !compareStrings(
targetCustomSignalValues,
customSignalValue,
(customSignal, targetSignal) -> customSignal.contains(targetSignal));
case STRING_EXACTLY_MATCHES:
return compareStrings(
targetCustomSignalValues,
customSignalValue,
(customSignal, targetSignal) -> customSignal.equals(targetSignal));
case STRING_CONTAINS_REGEX:
return compareStrings(
targetCustomSignalValues,
customSignalValue,
(customSignal, targetSignal) -> compareStringRegex(customSignal, targetSignal));
// Numeric operations.
case NUMERIC_LESS_THAN:
return compareNumbers(targetCustomSignalValues, customSignalValue, (result) -> result < 0);
case NUMERIC_LESS_EQUAL:
return compareNumbers(targetCustomSignalValues, customSignalValue, (result) -> result <= 0);
case NUMERIC_EQUAL:
return compareNumbers(targetCustomSignalValues, customSignalValue, (result) -> result == 0);
case NUMERIC_NOT_EQUAL:
return compareNumbers(targetCustomSignalValues, customSignalValue, (result) -> result != 0);
case NUMERIC_GREATER_THAN:
return compareNumbers(targetCustomSignalValues, customSignalValue, (result) -> result > 0);
case NUMERIC_GREATER_EQUAL:
return compareNumbers(targetCustomSignalValues, customSignalValue, (result) -> result >= 0);
// Semantic operations.
case SEMANTIC_VERSION_EQUAL:
return compareSemanticVersions(
targetCustomSignalValues, customSignalValue, (result) -> result == 0);
case SEMANTIC_VERSION_GREATER_EQUAL:
return compareSemanticVersions(
targetCustomSignalValues, customSignalValue, (result) -> result >= 0);
case SEMANTIC_VERSION_GREATER_THAN:
return compareSemanticVersions(
targetCustomSignalValues, customSignalValue, (result) -> result > 0);
case SEMANTIC_VERSION_LESS_EQUAL:
return compareSemanticVersions(
targetCustomSignalValues, customSignalValue, (result) -> result <= 0);
case SEMANTIC_VERSION_LESS_THAN:
return compareSemanticVersions(
targetCustomSignalValues, customSignalValue, (result) -> result < 0);
case SEMANTIC_VERSION_NOT_EQUAL:
return compareSemanticVersions(
targetCustomSignalValues, customSignalValue, (result) -> result != 0);
default:
return false;
}
}
private boolean evaluatePercentCondition(PercentCondition condition, KeysAndValues context) {
if (!context.containsKey("randomizationId")) {
logger.warn("Percentage operation must not be performed without randomizationId");
return false;
}
PercentConditionOperator operator = condition.getPercentConditionOperator();
// The micro-percent interval to be used with the BETWEEN operator.
MicroPercentRange microPercentRange = condition.getMicroPercentRange();
int microPercentUpperBound =
microPercentRange != null ? microPercentRange.getMicroPercentUpperBound() : 0;
int microPercentLowerBound =
microPercentRange != null ? microPercentRange.getMicroPercentLowerBound() : 0;
// The limit of percentiles to target in micro-percents when using the
// LESS_OR_EQUAL and GREATER_THAN operators. The value must be in the range [0
// and 100000000].
int microPercent = condition.getMicroPercent();
BigInteger microPercentile =
getMicroPercentile(condition.getSeed(), context.get("randomizationId"));
switch (operator) {
case LESS_OR_EQUAL:
return microPercentile.compareTo(BigInteger.valueOf(microPercent)) <= 0;
case GREATER_THAN:
return microPercentile.compareTo(BigInteger.valueOf(microPercent)) > 0;
case BETWEEN:
return microPercentile.compareTo(BigInteger.valueOf(microPercentLowerBound)) > 0
&& microPercentile.compareTo(BigInteger.valueOf(microPercentUpperBound)) <= 0;
case UNSPECIFIED:
default:
return false;
}
}
private BigInteger getMicroPercentile(String seed, String randomizationId) {
String seedPrefix = seed != null && !seed.isEmpty() ? seed + "." : "";
String stringToHash = seedPrefix + randomizationId;
BigInteger hash = hashSeededRandomizationId(stringToHash);
BigInteger microPercentile = hash.mod(MICRO_PERCENT_MODULO);
return microPercentile;
}
private BigInteger hashSeededRandomizationId(String seededRandomizationId) {
try {
// Create a SHA-256 hash.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(seededRandomizationId.getBytes(StandardCharsets.UTF_8));
// Convert the hash bytes to a BigInteger
return new BigInteger(1, hashBytes);
} catch (NoSuchAlgorithmException e) {
logger.error("SHA-256 algorithm not found", e);
throw new RuntimeException("SHA-256 algorithm not found", e);
}
}
private boolean compareStrings(
ImmutableList<String> targetValues,
String customSignal,
BiPredicate<String, String> compareFunction) {
return targetValues.stream()
.anyMatch(targetValue -> compareFunction.test(customSignal, targetValue));
}
private boolean compareStringRegex(String customSignal, String targetSignal) {
try {
return Pattern.compile(targetSignal).matcher(customSignal).matches();
} catch (PatternSyntaxException e) {
return false;
}
}
private boolean compareNumbers(
ImmutableList<String> targetValues, String customSignal, IntPredicate compareFunction) {
if (targetValues.size() != 1) {
logger.warn(
String.format(
"Target values must contain 1 element for numeric operations. Target Value: %s",
targetValues));
return false;
}
try {
double customSignalDouble = Double.parseDouble(customSignal);
double targetValue = Double.parseDouble(targetValues.get(0));
int comparisonResult = Double.compare(customSignalDouble, targetValue);
return compareFunction.test(comparisonResult);
} catch (NumberFormatException e) {
logger.warn(
"Error parsing numeric values: customSignal=%s, targetValue=%s",
customSignal, targetValues.get(0), e);
return false;
}
}
private boolean compareSemanticVersions(
ImmutableList<String> targetValues, String customSignal, IntPredicate compareFunction) {
if (targetValues.size() != 1) {
logger.warn(String.format("Target values must contain 1 element for semantic operation."));
return false;
}
String targetValueString = targetValues.get(0);
if (!validateSemanticVersion(targetValueString) || !validateSemanticVersion(customSignal)) {
return false;
}
List<Integer> targetVersion = parseSemanticVersion(targetValueString);
List<Integer> customSignalVersion = parseSemanticVersion(customSignal);
int maxLength = 5;
if (targetVersion.size() > maxLength || customSignalVersion.size() > maxLength) {
logger.warn(
"Semantic version max length(%s) exceeded. Target: %s, Custom Signal: %s",
maxLength, targetValueString, customSignal);
return false;
}
int comparison = compareSemanticVersions(customSignalVersion, targetVersion);
return compareFunction.test(comparison);
}
private int compareSemanticVersions(List<Integer> version1, List<Integer> version2) {
int maxLength = Math.max(version1.size(), version2.size());
int version1Size = version1.size();
int version2Size = version2.size();
for (int i = 0; i < maxLength; i++) {
// Default to 0 if segment is missing
int v1 = i < version1Size ? version1.get(i) : 0;
int v2 = i < version2Size ? version2.get(i) : 0;
int comparison = Integer.compare(v1, v2);
if (comparison != 0) {
return comparison;
}
}
// Versions are equal
return 0;
}
private List<Integer> parseSemanticVersion(String versionString) {
return Arrays.stream(versionString.split("\\."))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private boolean validateSemanticVersion(String version) {
Pattern pattern = Pattern.compile("^[0-9]+(?:\\.[0-9]+){0,4}$");
return pattern.matcher(version).matches();
}
}