Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file modified mvnw
100644 → 100755
Empty file.
39 changes: 38 additions & 1 deletion src/main/java/dev/openfeature/sdk/EventProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

import dev.openfeature.sdk.internal.ConfigurableThreadFactory;
import dev.openfeature.sdk.internal.TriConsumer;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import lombok.extern.slf4j.Slf4j;

/**
Expand All @@ -22,6 +25,7 @@
@Slf4j
public abstract class EventProvider implements FeatureProvider {
private EventProviderListener eventProviderListener;
private final List<BiConsumer<ProviderEvent, ProviderEventDetails>> eventObservers = new CopyOnWriteArrayList<>();
private final ExecutorService emitterExecutor =
Executors.newCachedThreadPool(new ConfigurableThreadFactory("openfeature-event-emitter-thread", true));

Expand Down Expand Up @@ -54,6 +58,31 @@ void detach() {
this.onEmit = null;
}

/**
* Add a provider event observer.
*
* <p>Observers are invoked whenever this provider emits an event and are intended for advanced
* provider composition scenarios.
*
* @param observer observer callback
*/
public void addEventObserver(BiConsumer<ProviderEvent, ProviderEventDetails> observer) {
if (observer != null) {
eventObservers.add(observer);
}
}

/**
* Remove a previously registered provider event observer.
*
* @param observer observer callback
*/
public void removeEventObserver(BiConsumer<ProviderEvent, ProviderEventDetails> observer) {
if (observer != null) {
eventObservers.remove(observer);
}
}

/**
* Stop the event emitter executor and block until either termination has completed
* or timeout period has elapsed.
Expand Down Expand Up @@ -81,8 +110,9 @@ public void shutdown() {
public Awaitable emit(final ProviderEvent event, final ProviderEventDetails details) {
final var localEventProviderListener = this.eventProviderListener;
final var localOnEmit = this.onEmit;
final var localEventObservers = this.eventObservers;

if (localEventProviderListener == null && localOnEmit == null) {
if (localEventProviderListener == null && localOnEmit == null && localEventObservers.isEmpty()) {
return Awaitable.FINISHED;
}

Expand All @@ -98,6 +128,13 @@ public Awaitable emit(final ProviderEvent event, final ProviderEventDetails deta
if (localOnEmit != null) {
localOnEmit.accept(this, event, details);
}
for (BiConsumer<ProviderEvent, ProviderEventDetails> observer : localEventObservers) {
try {
observer.accept(event, details);
} catch (Exception e) {
log.error("Exception in provider event observer {}", observer, e);
}
}
} finally {
awaitable.wakeup();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,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(

Check failure on line 57 in src/main/java/dev/openfeature/sdk/multiprovider/ComparisonStrategy.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=open-feature_java-sdk&issues=AZzCyuDysEzTo8HIlnsQ&open=AZzCyuDysEzTo8HIlnsQ&pullRequest=1883
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());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The evaluate method creates a new FixedThreadPool for every flag evaluation, which is inefficient and can lead to a Denial of Service (DoS) vulnerability. High traffic could exhaust system resources, causing an OutOfMemoryError and a DoS for the application. It is highly recommended to use a shared, managed ExecutorService instead of creating a new one for every evaluation to prevent performance issues and resource exhaustion.

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()));

Check warning on line 91 in src/main/java/dev/openfeature/sdk/multiprovider/ComparisonStrategy.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Directly append the argument of String.valueOf().

See more on https://sonarcloud.io/project/issues?id=open-feature_java-sdk&issues=AZzCyuDysEzTo8HIlnsP&open=AZzCyuDysEzTo8HIlnsP&pullRequest=1883
}
} 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) {

Check warning on line 103 in src/main/java/dev/openfeature/sdk/multiprovider/ComparisonStrategy.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.

See more on https://sonarcloud.io/project/issues?id=open-feature_java-sdk&issues=AZzCyuDysEzTo8HIlnsR&open=AZzCyuDysEzTo8HIlnsR&pullRequest=1883
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;
}
}
Loading
Loading