-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathComparisonStrategy.java
More file actions
164 lines (150 loc) · 6.41 KB
/
ComparisonStrategy.java
File metadata and controls
164 lines (150 loc) · 6.41 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
package dev.openfeature.sdk.multiprovider;
import dev.openfeature.sdk.ErrorCode;
import dev.openfeature.sdk.EvaluationContext;
import dev.openfeature.sdk.FeatureProvider;
import dev.openfeature.sdk.ProviderEvaluation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiConsumer;
import java.util.function.Function;
import lombok.Getter;
/**
* Comparison strategy.
*
* <p>Evaluates all providers and compares successful results.
*/
public class ComparisonStrategy implements Strategy {
@Getter
private final String fallbackProvider;
private final BiConsumer<String, Map<String, ProviderEvaluation<?>>> onMismatch;
/**
* Constructs a comparison strategy with a fallback provider.
*
* @param fallbackProvider provider name to use as fallback when successful providers disagree
*/
public ComparisonStrategy(String fallbackProvider) {
this(fallbackProvider, null);
}
/**
* Constructs a comparison strategy with fallback provider and mismatch callback.
*
* @param fallbackProvider provider name to use as fallback when successful providers disagree
* @param onMismatch callback invoked with all successful evaluations when they disagree
*/
public ComparisonStrategy(
String fallbackProvider,
BiConsumer<String, Map<String, ProviderEvaluation<?>>> onMismatch) {
this.fallbackProvider = Objects.requireNonNull(fallbackProvider, "fallbackProvider must not be null");
this.onMismatch = onMismatch;
}
@Override
public <T> ProviderEvaluation<T> evaluate(
Map<String, FeatureProvider> providers,
String key,
T defaultValue,
EvaluationContext ctx,
Function<FeatureProvider, ProviderEvaluation<T>> providerFunction) {
if (providers.isEmpty()) {
return ProviderEvaluation.<T>builder()
.errorCode(ErrorCode.GENERAL)
.errorMessage("No providers configured")
.build();
}
if (!providers.containsKey(fallbackProvider)) {
throw new IllegalArgumentException("fallbackProvider not found in providers: " + fallbackProvider);
}
Map<String, ProviderEvaluation<T>> successfulResults = new ConcurrentHashMap<>(providers.size());
Map<String, String> providerErrors = new ConcurrentHashMap<>(providers.size());
ExecutorService executorService = Executors.newFixedThreadPool(providers.size());
try {
List<Callable<Void>> tasks = new ArrayList<>(providers.size());
for (Map.Entry<String, FeatureProvider> entry : providers.entrySet()) {
String providerName = entry.getKey();
FeatureProvider provider = entry.getValue();
tasks.add(() -> {
try {
ProviderEvaluation<T> evaluation = providerFunction.apply(provider);
if (evaluation == null) {
providerErrors.put(providerName, "null evaluation");
} else if (evaluation.getErrorCode() == null) {
successfulResults.put(providerName, evaluation);
} else {
providerErrors.put(
providerName,
evaluation.getErrorCode() + ": " + String.valueOf(evaluation.getErrorMessage()));
}
} catch (Exception e) {
providerErrors.put(providerName, e.getClass().getSimpleName() + ": " + e.getMessage());
}
return null;
});
}
List<Future<Void>> futures = executorService.invokeAll(tasks);
for (Future<Void> future : futures) {
future.get();
}
} catch (Exception e) {
return ProviderEvaluation.<T>builder()
.errorCode(ErrorCode.GENERAL)
.errorMessage("Comparison strategy failed: " + e.getMessage())
.build();
} finally {
executorService.shutdown();
}
if (!providerErrors.isEmpty()) {
return ProviderEvaluation.<T>builder()
.errorCode(ErrorCode.GENERAL)
.errorMessage("Provider errors: " + buildErrorSummary(providerErrors))
.build();
}
ProviderEvaluation<T> fallbackResult = successfulResults.get(fallbackProvider);
if (fallbackResult == null) {
return ProviderEvaluation.<T>builder()
.errorCode(ErrorCode.GENERAL)
.errorMessage("Fallback provider did not return a successful evaluation: " + fallbackProvider)
.build();
}
if (allEvaluationsMatch(successfulResults)) {
return fallbackResult;
}
if (onMismatch != null) {
Map<String, ProviderEvaluation<?>> mismatchPayload = new LinkedHashMap<>(successfulResults);
onMismatch.accept(key, Collections.unmodifiableMap(mismatchPayload));
}
return fallbackResult;
}
private String buildErrorSummary(Map<String, String> providerErrors) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : providerErrors.entrySet()) {
if (!first) {
builder.append("; ");
}
first = false;
builder.append(entry.getKey()).append(" -> ").append(entry.getValue());
}
return builder.toString();
}
private <T> boolean allEvaluationsMatch(Map<String, ProviderEvaluation<T>> results) {
ProviderEvaluation<T> baseline = null;
for (ProviderEvaluation<T> evaluation : results.values()) {
if (baseline == null) {
baseline = evaluation;
continue;
}
if (!Objects.equals(baseline.getValue(), evaluation.getValue())) {
return false;
}
}
return true;
}
}