-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTreatmentManagerImpl.java
More file actions
394 lines (342 loc) · 17.3 KB
/
TreatmentManagerImpl.java
File metadata and controls
394 lines (342 loc) · 17.3 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package io.split.android.client.validators;
import static io.split.android.client.utils.Utils.checkNotNull;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.split.android.client.EvaluationResult;
import io.split.android.client.Evaluator;
import io.split.android.client.FlagSetsFilter;
import io.split.android.client.SplitResult;
import io.split.android.client.TreatmentLabels;
import io.split.android.client.attributes.AttributesManager;
import io.split.android.client.attributes.AttributesMerger;
import io.split.android.client.events.ListenableEventsManager;
import io.split.android.client.events.SplitEvent;
import io.split.android.client.impressions.DecoratedImpression;
import io.split.android.client.impressions.Impression;
import io.split.android.client.impressions.ImpressionListener;
import io.split.android.client.storage.splits.SplitsStorage;
import io.split.android.client.telemetry.model.Method;
import io.split.android.client.telemetry.storage.TelemetryStorageProducer;
import io.split.android.client.utils.logger.Logger;
import io.split.android.grammar.Treatments;
public class TreatmentManagerImpl implements TreatmentManager {
private final Evaluator mEvaluator;
private final KeyValidator mKeyValidator;
private final SplitValidator mSplitValidator;
private final ImpressionListener.FederatedImpressionListener mImpressionListener;
private final String mMatchingKey;
private final String mBucketingKey;
private final boolean mLabelsEnabled;
private final ValidationMessageLogger mValidationLogger;
private final ListenableEventsManager mEventsManager;
@NonNull
private final AttributesManager mAttributesManager;
@NonNull
private final AttributesMerger mAttributesMerger;
private final TelemetryStorageProducer mTelemetryStorageProducer;
private final FlagSetsFilter mFlagSetsFilter;
private final SplitsStorage mSplitsStorage;
private final SplitFilterValidator mFlagSetsValidator;
public TreatmentManagerImpl(String matchingKey,
String bucketingKey,
Evaluator evaluator,
KeyValidator keyValidator,
SplitValidator splitValidator,
ImpressionListener.FederatedImpressionListener impressionListener,
boolean labelsEnabled,
ListenableEventsManager eventsManager,
@NonNull AttributesManager attributesManager,
@NonNull AttributesMerger attributesMerger,
@NonNull TelemetryStorageProducer telemetryStorageProducer,
@Nullable FlagSetsFilter flagSetsFilter,
@NonNull SplitsStorage splitsStorage,
@NonNull ValidationMessageLogger validationLogger,
@NonNull SplitFilterValidator flagSetsValidator) {
mEvaluator = evaluator;
mKeyValidator = keyValidator;
mSplitValidator = splitValidator;
mMatchingKey = matchingKey;
mBucketingKey = bucketingKey;
mImpressionListener = impressionListener;
mLabelsEnabled = labelsEnabled;
mEventsManager = eventsManager;
mValidationLogger = checkNotNull(validationLogger);
mAttributesManager = checkNotNull(attributesManager);
mAttributesMerger = checkNotNull(attributesMerger);
mTelemetryStorageProducer = checkNotNull(telemetryStorageProducer);
mFlagSetsFilter = flagSetsFilter;
mSplitsStorage = checkNotNull(splitsStorage);
mFlagSetsValidator = checkNotNull(flagSetsValidator);
}
@Override
public String getTreatment(String split, Map<String, Object> attributes, boolean isClientDestroyed) {
try {
String treatment = getTreatmentsWithConfigGeneric(
Collections.singletonList(split),
null,
attributes,
isClientDestroyed,
SplitResult::treatment,
Method.TREATMENT
).get(split);
return (treatment == null) ? Treatments.CONTROL : treatment;
} catch (Exception ex) {
// In case get fails for some reason
Logger.e("Client " + Method.TREATMENT.getMethod() + " exception", ex);
mTelemetryStorageProducer.recordException(Method.TREATMENT);
return Treatments.CONTROL;
}
}
@Override
public SplitResult getTreatmentWithConfig(String split, Map<String, Object> attributes, boolean isClientDestroyed) {
try {
SplitResult splitResult = getTreatmentsWithConfigGeneric(
Collections.singletonList(split),
null,
attributes,
isClientDestroyed,
ResultTransformer::identity,
Method.TREATMENT_WITH_CONFIG
).get(split);
return (splitResult == null) ? new SplitResult(Treatments.CONTROL) : splitResult;
} catch (Exception ex) {
// In case get fails for some reason
Logger.e("Client " + Method.TREATMENT_WITH_CONFIG.getMethod() + " exception", ex);
mTelemetryStorageProducer.recordException(Method.TREATMENT_WITH_CONFIG);
return new SplitResult(Treatments.CONTROL);
}
}
@Override
public Map<String, String> getTreatments(List<String> splits, Map<String, Object> attributes, boolean isClientDestroyed) {
return getTreatmentsWithConfigGeneric(
splits,
null,
attributes,
isClientDestroyed,
SplitResult::treatment,
Method.TREATMENTS);
}
@Override
public Map<String, SplitResult> getTreatmentsWithConfig(List<String> splits, Map<String, Object> attributes, boolean isClientDestroyed) {
return getTreatmentsWithConfigGeneric(
splits,
null,
attributes,
isClientDestroyed,
ResultTransformer::identity,
Method.TREATMENTS_WITH_CONFIG);
}
@Override
public Map<String, String> getTreatmentsByFlagSet(@NonNull String flagSet, @Nullable Map<String, Object> attributes, boolean isClientDestroyed) {
return getTreatmentsWithConfigGeneric(
null,
Collections.singletonList(flagSet),
attributes,
isClientDestroyed,
SplitResult::treatment,
Method.TREATMENTS_BY_FLAG_SET);
}
@Override
public Map<String, String> getTreatmentsByFlagSets(@NonNull List<String> flagSets, @Nullable Map<String, Object> attributes, boolean isClientDestroyed) {
return getTreatmentsWithConfigGeneric(
null,
flagSets,
attributes,
isClientDestroyed,
SplitResult::treatment,
Method.TREATMENTS_BY_FLAG_SETS);
}
@Override
public Map<String, SplitResult> getTreatmentsWithConfigByFlagSet(@NonNull String flagSet, @Nullable Map<String, Object> attributes, boolean isClientDestroyed) {
return getTreatmentsWithConfigGeneric(
null,
Collections.singletonList(flagSet),
attributes,
isClientDestroyed,
ResultTransformer::identity,
Method.TREATMENTS_WITH_CONFIG_BY_FLAG_SET);
}
@Override
public Map<String, SplitResult> getTreatmentsWithConfigByFlagSets(@NonNull List<String> flagSets, @Nullable Map<String, Object> attributes, boolean isClientDestroyed) {
return getTreatmentsWithConfigGeneric(
null,
flagSets,
attributes,
isClientDestroyed,
ResultTransformer::identity,
Method.TREATMENTS_WITH_CONFIG_BY_FLAG_SETS);
}
private <T> Map<String, T> getTreatmentsWithConfigGeneric(@Nullable List<String> names,
@Nullable List<String> flagSets,
@Nullable Map<String, Object> attributes,
boolean isClientDestroyed,
ResultTransformer<T> resultTransformer,
Method telemetryMethodName) {
// This flag will be modified if there are any exceptions caught in getTreatmentWithConfigWithoutMetrics,
// in which case an exception will be recorded in telemetry
boolean exceptionsOccurred = false;
String validationTag = telemetryMethodName.getMethod();
try {
// Check if client is destroyed. If so, return control treatments or empty map in the case of flag sets
if (isClientDestroyed) {
mValidationLogger.e("Client has already been destroyed - no calls possible", validationTag);
return getControlTreatmentsForSplitsWithConfig(names, validationTag, resultTransformer);
}
// Validate Key
ValidationErrorInfo errorInfo = mKeyValidator.validate(mMatchingKey, mBucketingKey);
if (errorInfo != null) {
mValidationLogger.e(errorInfo, validationTag);
return getControlTreatmentsForSplitsWithConfig(names, validationTag, resultTransformer);
}
// If there are no names but we have flag sets, get the names from the flag sets
if (names == null) {
if (flagSets != null) {
names = getNamesFromSet(validationTag, flagSets);
} else {
names = new ArrayList<>();
}
}
// Mark the start timestamp of the evaluation, to use for telemetry
long start = System.currentTimeMillis();
try {
// Merge the stored attributes with the attributes passed in for this evaluation
final Map<String, Object> mergedAttributes = mAttributesMerger.merge(mAttributesManager.getAllAttributes(), attributes);
// Create the result map
Map<String, T> result = new HashMap<>();
// Perform evaluations for every feature flag
for (String featureFlagName : names) {
TreatmentResult evaluationResult = getTreatmentWithConfigWithoutMetrics(featureFlagName, mergedAttributes, validationTag);
result.put(featureFlagName, resultTransformer.transform(evaluationResult.getSplitResult()));
if (evaluationResult.isException()) {
exceptionsOccurred = true;
}
}
return result;
} finally {
recordLatency(telemetryMethodName, start);
if (exceptionsOccurred) {
mTelemetryStorageProducer.recordException(telemetryMethodName);
}
}
} catch (Exception exception) {
Logger.e("Client " + validationTag + " exception", exception);
mTelemetryStorageProducer.recordException(telemetryMethodName);
return getControlTreatmentsForSplitsWithConfig(names, validationTag, resultTransformer);
}
}
private TreatmentResult getTreatmentWithConfigWithoutMetrics(String split, Map<String, Object> mergedAttributes, String validationTag) {
EvaluationResult evaluationResult = null;
try {
// Validate feature flag name
String splitName = split;
ValidationErrorInfo errorInfo = mSplitValidator.validateName(split);
if (errorInfo != null) {
if (errorInfo.isError()) {
mValidationLogger.e(errorInfo, validationTag);
return new TreatmentResult(new SplitResult(Treatments.CONTROL), false);
}
mValidationLogger.w(errorInfo, validationTag);
splitName = split.trim();
}
// Perform evaluation and create SplitResult object
evaluationResult = evaluateIfReady(splitName, mergedAttributes, validationTag);
SplitResult splitResult = new SplitResult(evaluationResult.getTreatment(), evaluationResult.getConfigurations());
// If the feature flag was not found, log the message and return the result
if (evaluationResult.getLabel().equals(TreatmentLabels.DEFINITION_NOT_FOUND)) {
mValidationLogger.w(mSplitValidator.splitNotFoundMessage(splitName), validationTag);
return new TreatmentResult(splitResult, false);
}
// Log impression
logImpression(
mMatchingKey,
mBucketingKey,
splitName,
evaluationResult.getTreatment(),
mLabelsEnabled ? evaluationResult.getLabel() : null,
evaluationResult.getChangeNumber(),
mergedAttributes,
evaluationResult.isImpressionsDisabled());
return new TreatmentResult(splitResult, false);
} catch (Exception ex) {
// Since this only logs an impression with EXCEPTION label, we don't log anything if labels are disabled
if (mLabelsEnabled) {
logImpression(
mMatchingKey,
mBucketingKey,
split,
Treatments.CONTROL,
TreatmentLabels.EXCEPTION,
(evaluationResult != null) ? evaluationResult.getChangeNumber() : null,
mergedAttributes,
evaluationResult != null && evaluationResult.isImpressionsDisabled());
}
return new TreatmentResult(new SplitResult(Treatments.CONTROL), true);
}
}
private void logImpression(String matchingKey, String bucketingKey, String splitName, String result, String label, Long changeNumber, Map<String, Object> attributes, boolean impressionsDisabled) {
try {
Impression impression = new Impression(matchingKey, bucketingKey, splitName, result, System.currentTimeMillis(), label, changeNumber, attributes);
DecoratedImpression decoratedImpression = new DecoratedImpression(impression, impressionsDisabled);
mImpressionListener.log(decoratedImpression);
mImpressionListener.log(impression);
} catch (Throwable t) {
Logger.e("An error occurred logging impression: " + t.getLocalizedMessage());
}
}
@NonNull
private <T> Map<String, T> getControlTreatmentsForSplitsWithConfig(@Nullable List<String> names, String validationTag, ResultTransformer<T> resultTransformer) {
return TreatmentManagerHelper.controlTreatmentsForSplitsWithConfig(
mSplitValidator,
mValidationLogger,
(names != null) ? names : new ArrayList<>(),
validationTag,
resultTransformer);
}
private EvaluationResult evaluateIfReady(String featureFlagName,
Map<String, Object> attributes, String validationTag) {
if (!mEventsManager.eventAlreadyTriggered(SplitEvent.SDK_READY) &&
!mEventsManager.eventAlreadyTriggered(SplitEvent.SDK_READY_FROM_CACHE)) {
mValidationLogger.w("the SDK is not ready, results may be incorrect for feature flag " + featureFlagName + ". Make sure to wait for SDK readiness before using this method", validationTag);
mTelemetryStorageProducer.recordNonReadyUsage();
return new EvaluationResult(Treatments.CONTROL, TreatmentLabels.NOT_READY, null, null, false);
}
return mEvaluator.getTreatment(mMatchingKey, mBucketingKey, featureFlagName, attributes);
}
private void recordLatency(Method treatment, long startTime) {
mTelemetryStorageProducer.recordLatency(treatment, System.currentTimeMillis() - startTime);
}
@NonNull
private List<String> getNamesFromSet(@NonNull String method, @NonNull List<String> flagSets) {
Set<String> setsToEvaluate = mFlagSetsValidator.items(method, flagSets, mFlagSetsFilter);
if (setsToEvaluate.isEmpty()) {
return new ArrayList<>();
}
return new ArrayList<>(mSplitsStorage.getNamesByFlagSets(setsToEvaluate));
}
interface ResultTransformer<T> {
T transform(SplitResult splitResult);
static SplitResult identity(SplitResult splitResult) {
return splitResult;
}
}
private static class TreatmentResult {
private final SplitResult mSplitResult;
private final boolean mException;
TreatmentResult(SplitResult splitResult, boolean exception) {
mSplitResult = splitResult;
mException = exception;
}
SplitResult getSplitResult() {
return mSplitResult;
}
boolean isException() {
return mException;
}
}
}