Skip to content

Commit dab5ef0

Browse files
committed
gotta go fast
1 parent 6098940 commit dab5ef0

6 files changed

Lines changed: 138 additions & 15 deletions

File tree

‎.github/workflows/sdk-spec.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ permissions:
1111
jobs:
1212
sdk-spec:
1313
# Keep the ref in `uses:` and `spec-ref` in sync.
14-
uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.3.0
14+
uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.7.0
1515
with:
16-
spec-ref: v0.3.0
16+
spec-ref: v0.7.0
1717
language: java

‎sdk-spec/Steps.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import com.flagsmith.FlagsmithClient;
2+
import com.flagsmith.config.FlagsmithConfig;
23
import com.flagsmith.exceptions.FlagsmithClientError;
34
import com.flagsmith.models.BaseFlag;
45
import com.flagsmith.models.Flags;
@@ -35,6 +36,17 @@ static FlagsmithClient createClient(String environmentKey, String apiUrl) {
3536
return FlagsmithClient.newBuilder().setApiKey(environmentKey).withApiUrl(apiUrl).build();
3637
}
3738

39+
// Create the SDK client with local evaluation
40+
static FlagsmithClient createClientWithLocalEvaluation(String environmentKey, String apiUrl) {
41+
return FlagsmithClient.newBuilder()
42+
.setApiKey(environmentKey)
43+
.withConfiguration(FlagsmithConfig.newBuilder()
44+
.baseUri(apiUrl)
45+
.withLocalEvaluation(true)
46+
.build())
47+
.build();
48+
}
49+
3850
// When the application gets the environment flags
3951
static List<SpecFlag> getEnvironmentFlags(FlagsmithClient flagsmith)
4052
throws FlagsmithClientError {

‎src/main/java/com/flagsmith/FlagsmithClient.java‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,11 @@
3232
import java.util.stream.Collectors;
3333
import lombok.AccessLevel;
3434
import lombok.Data;
35+
import lombok.EqualsAndHashCode;
3536
import lombok.Getter;
3637
import lombok.NonNull;
3738
import lombok.Setter;
39+
import lombok.ToString;
3840
import org.apache.commons.lang3.StringUtils;
3941
import org.slf4j.Logger;
4042
import org.slf4j.LoggerFactory;
@@ -51,6 +53,11 @@ public class FlagsmithClient {
5153
private final FlagsmithLogger logger = new FlagsmithLogger();
5254
private FlagsmithSdk flagsmithSdk;
5355
private EvaluationContext evaluationContext;
56+
@Getter(AccessLevel.NONE)
57+
@Setter(AccessLevel.NONE)
58+
@EqualsAndHashCode.Exclude
59+
@ToString.Exclude
60+
private EvaluationContext environmentEvaluationContext;
5461
private PollingManager pollingManager;
5562
@Getter(AccessLevel.PACKAGE)
5663
@Setter(AccessLevel.NONE)
@@ -63,6 +70,19 @@ public static FlagsmithClient.Builder newBuilder() {
6370
return new FlagsmithClient.Builder();
6471
}
6572

73+
/**
74+
* Set the evaluation context, and derive the one environment flags evaluate against.
75+
*
76+
* @param evaluationContext the evaluation context
77+
*/
78+
public void setEvaluationContext(EvaluationContext evaluationContext) {
79+
this.environmentEvaluationContext = evaluationContext == null
80+
? null
81+
: new EvaluationContext(evaluationContext)
82+
.withSegments(getIdentityFreeSegments(evaluationContext.getSegments()));
83+
this.evaluationContext = evaluationContext;
84+
}
85+
6686
/**
6787
* Load the environment flags in the environment variable from the API.
6888
*/
@@ -73,7 +93,7 @@ public void updateEnvironment() {
7393
// if we didn't get an environment from the API,
7494
// then don't overwrite the copy we already have.
7595
if (updatedEvaluationContext != null) {
76-
this.evaluationContext = updatedEvaluationContext;
96+
setEvaluationContext(updatedEvaluationContext);
7797
} else {
7898
logger.error(getEnvironmentUpdateErrorMessage());
7999
}
@@ -416,17 +436,15 @@ private EventProcessor requireEventProcessor(String action) {
416436
}
417437

418438
private Flags getEnvironmentFlagsFromEvaluationContext() throws FlagsmithClientError {
419-
if (evaluationContext == null) {
439+
final EvaluationContext context = environmentEvaluationContext;
440+
if (context == null) {
420441
if (getConfig().getFlagsmithFlagDefaults() == null) {
421442
throw new FlagsmithClientError("Unable to get flags. No environment present.");
422443
}
423444
return getDefaultFlags();
424445
}
425446

426-
final EvaluationResult result = Engine.getEvaluationResult(
427-
new EvaluationContext(evaluationContext)
428-
.withSegments(getIdentityFreeSegments(evaluationContext.getSegments()))
429-
);
447+
final EvaluationResult result = Engine.getEvaluationResult(context);
430448

431449
return Flags.fromEvaluationResult(
432450
result,
@@ -779,8 +797,8 @@ public FlagsmithClient build() {
779797
throw new FlagsmithRuntimeError(
780798
"Cannot use both default flag handler and offline handler.");
781799
}
782-
client.evaluationContext = EngineMappers.mapEnvironmentToContext(
783-
configuration.getOfflineHandler().getEnvironment());
800+
client.setEvaluationContext(EngineMappers.mapEnvironmentToContext(
801+
configuration.getOfflineHandler().getEnvironment()));
784802
}
785803

786804
EventProcessor processor = null;

‎src/main/java/com/flagsmith/flagengine/segments/SegmentEvaluator.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import java.io.IOException;
1717
import java.util.ArrayList;
1818
import java.util.Arrays;
19+
import java.util.Collections;
1920
import java.util.List;
2021
import java.util.Map;
2122
import java.util.function.Predicate;
@@ -249,6 +250,9 @@ private static Object getContextValue(EvaluationContext context, String property
249250
Map<String, Object> contextMap;
250251
if (property.startsWith("$.flags.") || property.startsWith("$.flags[")) {
251252
contextMap = Map.of("flags", flags); // Spares serialising a context the path can't reach.
253+
} else if (property.startsWith("$.environment.") || property.startsWith("$.environment[")) {
254+
contextMap = Collections.singletonMap("environment",
255+
mapper.convertValue(context.getEnvironment(), contextMapTypeRef));
252256
} else {
253257
contextMap = mapper.convertValue(context, contextMapTypeRef);
254258
contextMap.put("flags", flags); // Replaces any client-supplied flags.

‎src/main/java/com/flagsmith/flagengine/utils/types/TypeCasting.java‎

Lines changed: 53 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,50 @@ public static Boolean compare(SegmentConditions condition, Comparable value1, Co
6262
return value1.compareTo(value2) == 0;
6363
}
6464

65+
/*
66+
* Whether a string may parse as a decimal, sparing a failed parse's exception when it can't.
67+
* Accepts a superset of Float.parseFloat and Double.parseDouble inputs.
68+
*/
69+
private static boolean mayBeDecimal(String value) {
70+
int index = 0;
71+
while (index < value.length() && value.charAt(index) <= ' ') {
72+
index++; // Skips the whitespace the parsers trim.
73+
}
74+
if (index == value.length()) {
75+
return false;
76+
}
77+
char first = value.charAt(index);
78+
return Character.isDigit(first)
79+
|| first == '+' || first == '-' || first == '.' || first == 'N' || first == 'I';
80+
}
81+
82+
/*
83+
* Whether a string may parse as an integer, sparing a failed parse's exception when it can't.
84+
* Accepts a superset of Integer.valueOf inputs.
85+
*/
86+
private static boolean mayBeInteger(String value) {
87+
if (value.isEmpty()) {
88+
return false;
89+
}
90+
char first = value.charAt(0);
91+
return Character.isDigit(first) || first == '+' || first == '-';
92+
}
93+
6594
/**
6695
* Convert the object to Double.
6796
*
6897
* @param number Object to convert to Double.
6998
*/
7099
public static Double toDouble(Object number) {
100+
if (number instanceof Double) {
101+
return (Double) number;
102+
}
103+
String asString = String.valueOf(number);
104+
if (!mayBeDecimal(asString)) {
105+
return null;
106+
}
71107
try {
72-
String asString = String.valueOf(number);
73-
return number instanceof Double ? ((Double) number) : Double.parseDouble(asString);
108+
return Double.parseDouble(asString);
74109
} catch (Exception nfe) {
75110
return null;
76111
}
@@ -91,8 +126,15 @@ public static Boolean isDouble(Object number) {
91126
* @param number Object to convert to Float.
92127
*/
93128
public static Float toFloat(Object number) {
129+
if (number instanceof Float) {
130+
return (Float) number;
131+
}
132+
String asString = String.valueOf(number);
133+
if (!mayBeDecimal(asString)) {
134+
return null;
135+
}
94136
try {
95-
return number instanceof Float ? ((Float) number) : Float.parseFloat(String.valueOf(number));
137+
return Float.parseFloat(asString);
96138
} catch (Exception nfe) {
97139
return null;
98140
}
@@ -113,9 +155,15 @@ public static Boolean isFloat(Object number) {
113155
* @param number Object to convert to Integer.
114156
*/
115157
public static Integer toInteger(Object number) {
158+
if (number instanceof Integer) {
159+
return (Integer) number;
160+
}
161+
String asString = String.valueOf(number);
162+
if (!mayBeInteger(asString)) {
163+
return null;
164+
}
116165
try {
117-
String asString = String.valueOf(number);
118-
return number instanceof Integer ? ((Integer) number) : Integer.valueOf(asString);
166+
return Integer.valueOf(asString);
119167
} catch (Exception nfe) {
120168
return null;
121169
}

‎src/test/java/com/flagsmith/flagengine/unit/segments/SegmentEvaluatorTest.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import java.util.ArrayList;
2121
import java.util.Arrays;
2222
import java.util.List;
23+
import java.util.Map;
2324
import java.util.stream.Stream;
2425

2526
public class SegmentEvaluatorTest {
@@ -62,6 +63,46 @@ public void testContextInSegment(SegmentContext segment, List<TraitModel> identi
6263
Assertions.assertEquals(expectedResponse, actualResult);
6364
}
6465

66+
private static Stream<Arguments> numericTraitComparisons() {
67+
return Stream.of(
68+
Arguments.of(7, SegmentConditions.EQUAL, "7", true),
69+
Arguments.of("7", SegmentConditions.EQUAL, "7", true),
70+
Arguments.of("+7", SegmentConditions.EQUAL, "7", true),
71+
Arguments.of("007", SegmentConditions.EQUAL, "7", true),
72+
Arguments.of("-7", SegmentConditions.LESS_THAN, "0", true),
73+
Arguments.of("7.5", SegmentConditions.GREATER_THAN, "7", true),
74+
Arguments.of(".5", SegmentConditions.LESS_THAN, "1", true),
75+
Arguments.of(" 7 ", SegmentConditions.EQUAL, "7.0", true),
76+
Arguments.of("7e2", SegmentConditions.EQUAL, "700", true),
77+
Arguments.of("NaN", SegmentConditions.EQUAL, "NaN", true),
78+
Arguments.of("-Infinity", SegmentConditions.LESS_THAN, "0", true),
79+
Arguments.of("plan-7", SegmentConditions.EQUAL, "7", false),
80+
Arguments.of("", SegmentConditions.EQUAL, "0", false),
81+
Arguments.of(" ", SegmentConditions.EQUAL, "0", false)
82+
);
83+
}
84+
85+
@ParameterizedTest
86+
@MethodSource("numericTraitComparisons")
87+
public void testTraitValuesThatReadAsNumbersAreComparedAsNumbers(Object traitValue,
88+
SegmentConditions conditionOperator, String conditionValue, Boolean expectedResult) {
89+
// Given
90+
final EvaluationContext context = EngineMappers.mapContextAndIdentityDataToContext(
91+
FlagsmithTestHelper.evaluationContext(), "foo", Map.of("score", traitValue));
92+
SegmentContext segment = new SegmentContext().withName("testSegment").withRules(
93+
Arrays.asList(new SegmentRule().withType(SegmentRule.Type.ALL).withConditions(
94+
Arrays.asList(new SegmentCondition()
95+
.withOperator(conditionOperator)
96+
.withProperty("score")
97+
.withValue(conditionValue)))));
98+
99+
// When
100+
Boolean inSegment = SegmentEvaluator.isContextInSegment(context, segment);
101+
102+
// Then
103+
Assertions.assertEquals(expectedResult, inSegment);
104+
}
105+
65106
private static Stream<Arguments> traitExistenceChecks() {
66107
return Stream.of(
67108
Arguments.of(SegmentConditions.IS_SET, "foo", new ArrayList<>(), false),

0 commit comments

Comments
 (0)