|
| 1 | +package com.featurevisor.openfeature; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 4 | +import com.featurevisor.sdk.Evaluation; |
| 5 | +import com.featurevisor.sdk.Emitter; |
| 6 | +import com.featurevisor.sdk.Featurevisor; |
| 7 | +import com.featurevisor.sdk.FeaturevisorDiagnosticHandler; |
| 8 | +import com.featurevisor.sdk.VariableType; |
| 9 | +import dev.openfeature.sdk.ErrorCode; |
| 10 | +import dev.openfeature.sdk.EvaluationContext; |
| 11 | +import dev.openfeature.sdk.FeatureProvider; |
| 12 | +import dev.openfeature.sdk.ImmutableMetadata; |
| 13 | +import dev.openfeature.sdk.Metadata; |
| 14 | +import dev.openfeature.sdk.ProviderEvaluation; |
| 15 | +import dev.openfeature.sdk.Reason; |
| 16 | +import dev.openfeature.sdk.Structure; |
| 17 | +import dev.openfeature.sdk.TrackingEventDetails; |
| 18 | +import dev.openfeature.sdk.Value; |
| 19 | +import java.time.Instant; |
| 20 | +import java.util.ArrayList; |
| 21 | +import java.util.HashMap; |
| 22 | +import java.util.List; |
| 23 | +import java.util.Map; |
| 24 | + |
| 25 | +/** OpenFeature provider backed by the Featurevisor v3 SDK. */ |
| 26 | +public final class FeaturevisorOpenFeatureProvider implements FeatureProvider { |
| 27 | + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); |
| 28 | + |
| 29 | + @FunctionalInterface |
| 30 | + public interface TrackingHandler { |
| 31 | + void track(String eventName, EvaluationContext context, TrackingEventDetails details); |
| 32 | + } |
| 33 | + |
| 34 | + public static final class Options { |
| 35 | + private Featurevisor featurevisor; |
| 36 | + private Featurevisor.FeaturevisorOptions featurevisorOptions = new Featurevisor.FeaturevisorOptions(); |
| 37 | + private String targetingKeyField = "userId"; |
| 38 | + private String keySeparator = ":"; |
| 39 | + private String variationKey = "variation"; |
| 40 | + private TrackingHandler onTrack; |
| 41 | + |
| 42 | + public Options featurevisor(Featurevisor value) { this.featurevisor = value; return this; } |
| 43 | + public Options featurevisorOptions(Featurevisor.FeaturevisorOptions value) { this.featurevisorOptions = value; return this; } |
| 44 | + public Options targetingKeyField(String value) { this.targetingKeyField = value; return this; } |
| 45 | + public Options keySeparator(String value) { this.keySeparator = value; return this; } |
| 46 | + public Options variationKey(String value) { this.variationKey = value; return this; } |
| 47 | + public Options onTrack(TrackingHandler value) { this.onTrack = value; return this; } |
| 48 | + } |
| 49 | + |
| 50 | + private final Featurevisor featurevisor; |
| 51 | + private final String targetingKeyField; |
| 52 | + private final String keySeparator; |
| 53 | + private final String variationKey; |
| 54 | + private final TrackingHandler onTrack; |
| 55 | + private final Emitter.UnsubscribeFunction datafileUnsubscribe; |
| 56 | + private final boolean ownsFeaturevisor; |
| 57 | + private String datafileError; |
| 58 | + |
| 59 | + public FeaturevisorOpenFeatureProvider(Options options) { |
| 60 | + Options resolved = options != null ? options : new Options(); |
| 61 | + this.targetingKeyField = nonEmpty(resolved.targetingKeyField, "userId"); |
| 62 | + this.keySeparator = nonEmpty(resolved.keySeparator, ":"); |
| 63 | + this.variationKey = nonEmpty(resolved.variationKey, "variation"); |
| 64 | + this.onTrack = resolved.onTrack; |
| 65 | + this.ownsFeaturevisor = resolved.featurevisor == null; |
| 66 | + if (resolved.featurevisor != null) { |
| 67 | + this.featurevisor = resolved.featurevisor; |
| 68 | + } else { |
| 69 | + Featurevisor.FeaturevisorOptions fvOptions = resolved.featurevisorOptions != null |
| 70 | + ? resolved.featurevisorOptions : new Featurevisor.FeaturevisorOptions(); |
| 71 | + if (fvOptions.getDatafileString() != null) { |
| 72 | + try { |
| 73 | + com.featurevisor.sdk.DatafileContent.fromJson(fvOptions.getDatafileString()); |
| 74 | + } catch (Exception ignored) { |
| 75 | + datafileError = "Could not parse datafile"; |
| 76 | + } |
| 77 | + } |
| 78 | + FeaturevisorDiagnosticHandler original = fvOptions.getOnDiagnostic(); |
| 79 | + fvOptions.onDiagnostic(diagnostic -> { |
| 80 | + if ("invalid_datafile".equals(diagnostic.getCode())) datafileError = diagnostic.getMessage(); |
| 81 | + if ("datafile_set".equals(diagnostic.getCode())) datafileError = null; |
| 82 | + if (original != null) original.handle(diagnostic); |
| 83 | + }); |
| 84 | + this.featurevisor = Featurevisor.createFeaturevisor(fvOptions); |
| 85 | + } |
| 86 | + this.datafileUnsubscribe = this.featurevisor.on(Emitter.EventName.DATAFILE_SET, details -> datafileError = null); |
| 87 | + } |
| 88 | + |
| 89 | + public FeaturevisorOpenFeatureProvider(Featurevisor.FeaturevisorOptions options) { |
| 90 | + this(new Options().featurevisorOptions(options)); |
| 91 | + } |
| 92 | + |
| 93 | + public FeaturevisorOpenFeatureProvider(Featurevisor featurevisor) { |
| 94 | + this(new Options().featurevisor(featurevisor)); |
| 95 | + } |
| 96 | + |
| 97 | + public Featurevisor getFeaturevisor() { return featurevisor; } |
| 98 | + @Override public Metadata getMetadata() { return () -> "Featurevisor"; } |
| 99 | + @Override public void shutdown() { |
| 100 | + datafileUnsubscribe.unsubscribe(); |
| 101 | + if (ownsFeaturevisor) featurevisor.close(); |
| 102 | + } |
| 103 | + @Override public void track(String name, EvaluationContext context, TrackingEventDetails details) { |
| 104 | + if (onTrack != null) onTrack.track(name, context, details); |
| 105 | + } |
| 106 | + |
| 107 | + @Override public ProviderEvaluation<Boolean> getBooleanEvaluation(String key, Boolean defaultValue, EvaluationContext context) { |
| 108 | + return cast(resolve(key, defaultValue, context, "boolean"), defaultValue, Boolean.class); |
| 109 | + } |
| 110 | + @Override public ProviderEvaluation<String> getStringEvaluation(String key, String defaultValue, EvaluationContext context) { |
| 111 | + return cast(resolve(key, defaultValue, context, "string"), defaultValue, String.class); |
| 112 | + } |
| 113 | + @Override public ProviderEvaluation<Integer> getIntegerEvaluation(String key, Integer defaultValue, EvaluationContext context) { |
| 114 | + ProviderEvaluation<Object> result = resolve(key, defaultValue, context, "integer"); |
| 115 | + Integer value = result.getValue() instanceof Number ? ((Number) result.getValue()).intValue() : defaultValue; |
| 116 | + return copy(result, value); |
| 117 | + } |
| 118 | + @Override public ProviderEvaluation<Double> getDoubleEvaluation(String key, Double defaultValue, EvaluationContext context) { |
| 119 | + ProviderEvaluation<Object> result = resolve(key, defaultValue, context, "number"); |
| 120 | + Double value = result.getValue() instanceof Number ? ((Number) result.getValue()).doubleValue() : defaultValue; |
| 121 | + return copy(result, value); |
| 122 | + } |
| 123 | + @Override public ProviderEvaluation<Value> getObjectEvaluation(String key, Value defaultValue, EvaluationContext context) { |
| 124 | + ProviderEvaluation<Object> result = resolve(key, defaultValue, context, "object"); |
| 125 | + try { |
| 126 | + return copy(result, toValue(result.getValue())); |
| 127 | + } catch (Exception exception) { |
| 128 | + return error(defaultValue, ErrorCode.TYPE_MISMATCH, "Flag \"" + key + "\" did not resolve to an object value", result.getFlagMetadata()); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + private ProviderEvaluation<Object> resolve(String flagKey, Object defaultValue, EvaluationContext context, String expectedType) { |
| 133 | + if (datafileError != null) return error(defaultValue, ErrorCode.PARSE_ERROR, datafileError, ImmutableMetadata.EMPTY); |
| 134 | + int separatorIndex = flagKey.indexOf(keySeparator); |
| 135 | + String featureKey = separatorIndex < 0 ? flagKey : flagKey.substring(0, separatorIndex); |
| 136 | + String selector = separatorIndex < 0 ? null : flagKey.substring(separatorIndex + keySeparator.length()); |
| 137 | + Map<String, Object> fvContext = context != null ? normalizeMap(context.asObjectMap()) : new HashMap<>(); |
| 138 | + if (context != null && context.getTargetingKey() != null && !context.getTargetingKey().isEmpty()) { |
| 139 | + fvContext.put(targetingKeyField, context.getTargetingKey()); |
| 140 | + } |
| 141 | + |
| 142 | + Evaluation evaluation; |
| 143 | + Object value; |
| 144 | + if (selector == null || selector.isEmpty()) { |
| 145 | + if (!"boolean".equals(expectedType)) return typeMismatch(flagKey, defaultValue, expectedType, ImmutableMetadata.EMPTY); |
| 146 | + evaluation = featurevisor.evaluateFlag(featureKey, fvContext); |
| 147 | + value = evaluation.getEnabled(); |
| 148 | + } else if (selector.equals(variationKey)) { |
| 149 | + evaluation = featurevisor.evaluateVariation(featureKey, fvContext); |
| 150 | + value = evaluation.getVariationValue() != null ? evaluation.getVariationValue() |
| 151 | + : evaluation.getVariation() != null ? evaluation.getVariation().getValue() : null; |
| 152 | + } else { |
| 153 | + evaluation = featurevisor.evaluateVariable(featureKey, selector, fvContext); |
| 154 | + value = evaluation.getVariableValue(); |
| 155 | + if (evaluation.getVariableSchema() != null |
| 156 | + && evaluation.getVariableSchema().getType() == VariableType.JSON |
| 157 | + && value instanceof String) { |
| 158 | + try { value = OBJECT_MAPPER.readValue((String) value, Object.class); } catch (Exception ignored) { } |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + ImmutableMetadata metadata = metadata(evaluation); |
| 163 | + ErrorCode errorCode = errorCode(evaluation.getReason()); |
| 164 | + if (errorCode != null) return error(defaultValue, errorCode, errorMessage(evaluation), metadata); |
| 165 | + if (value == null) return success(defaultValue, evaluation, metadata); |
| 166 | + if (!matches(value, expectedType)) return typeMismatch(flagKey, defaultValue, expectedType, metadata); |
| 167 | + return success(value, evaluation, metadata); |
| 168 | + } |
| 169 | + |
| 170 | + private ProviderEvaluation<Object> success(Object value, Evaluation evaluation, ImmutableMetadata metadata) { |
| 171 | + return ProviderEvaluation.builder().value(value).variant(variant(evaluation)).reason(reason(evaluation.getReason()).name()).flagMetadata(metadata).build(); |
| 172 | + } |
| 173 | + |
| 174 | + private ImmutableMetadata metadata(Evaluation evaluation) { |
| 175 | + ImmutableMetadata.ImmutableMetadataBuilder builder = ImmutableMetadata.builder() |
| 176 | + .addString("featureKey", evaluation.getFeatureKey()) |
| 177 | + .addString("featurevisorReason", evaluation.getReason()) |
| 178 | + .addString("schemaVersion", featurevisor.getSchemaVersion()); |
| 179 | + if (featurevisor.getRevision() != null) builder.addString("revision", featurevisor.getRevision()); |
| 180 | + if (evaluation.getVariableKey() != null) builder.addString("variableKey", evaluation.getVariableKey()); |
| 181 | + if (evaluation.getRuleKey() != null) builder.addString("ruleKey", evaluation.getRuleKey()); |
| 182 | + if (evaluation.getBucketKey() != null) builder.addString("bucketKey", evaluation.getBucketKey()); |
| 183 | + if (evaluation.getBucketValue() != null) builder.addInteger("bucketValue", evaluation.getBucketValue()); |
| 184 | + if (evaluation.getForceIndex() != null) builder.addInteger("forceIndex", evaluation.getForceIndex()); |
| 185 | + if (evaluation.getVariableOverrideIndex() != null) builder.addInteger("variableOverrideIndex", evaluation.getVariableOverrideIndex()); |
| 186 | + return builder.build(); |
| 187 | + } |
| 188 | + |
| 189 | + private static Reason reason(String reason) { |
| 190 | + if (List.of(Evaluation.REASON_FEATURE_NOT_FOUND, Evaluation.REASON_VARIABLE_NOT_FOUND, Evaluation.REASON_NO_VARIATIONS, Evaluation.REASON_ERROR).contains(reason)) return Reason.ERROR; |
| 191 | + if (List.of(Evaluation.REASON_REQUIRED, Evaluation.REASON_FORCED, Evaluation.REASON_STICKY, Evaluation.REASON_RULE, Evaluation.REASON_VARIABLE_OVERRIDE_RULE, Evaluation.REASON_VARIABLE_OVERRIDE_VARIATION).contains(reason)) return Reason.TARGETING_MATCH; |
| 192 | + if (Evaluation.REASON_ALLOCATED.equals(reason)) return Reason.SPLIT; |
| 193 | + if (List.of(Evaluation.REASON_DISABLED, Evaluation.REASON_VARIATION_DISABLED, Evaluation.REASON_VARIABLE_DISABLED).contains(reason)) return Reason.DISABLED; |
| 194 | + return Reason.DEFAULT; |
| 195 | + } |
| 196 | + |
| 197 | + private static ErrorCode errorCode(String reason) { |
| 198 | + if (List.of(Evaluation.REASON_FEATURE_NOT_FOUND, Evaluation.REASON_VARIABLE_NOT_FOUND, Evaluation.REASON_NO_VARIATIONS).contains(reason)) return ErrorCode.FLAG_NOT_FOUND; |
| 199 | + if (Evaluation.REASON_ERROR.equals(reason)) return ErrorCode.GENERAL; |
| 200 | + return null; |
| 201 | + } |
| 202 | + |
| 203 | + private static String errorMessage(Evaluation evaluation) { |
| 204 | + if (evaluation.getError() != null) return evaluation.getError().getMessage(); |
| 205 | + if (Evaluation.REASON_FEATURE_NOT_FOUND.equals(evaluation.getReason())) return "Feature \"" + evaluation.getFeatureKey() + "\" was not found"; |
| 206 | + if (Evaluation.REASON_VARIABLE_NOT_FOUND.equals(evaluation.getReason())) return "Variable \"" + evaluation.getVariableKey() + "\" was not found for feature \"" + evaluation.getFeatureKey() + "\""; |
| 207 | + if (Evaluation.REASON_NO_VARIATIONS.equals(evaluation.getReason())) return "Feature \"" + evaluation.getFeatureKey() + "\" has no variations"; |
| 208 | + return "Featurevisor evaluation failed"; |
| 209 | + } |
| 210 | + |
| 211 | + private static String variant(Evaluation evaluation) { |
| 212 | + if (evaluation.getVariationValue() != null) return evaluation.getVariationValue(); |
| 213 | + return evaluation.getVariation() != null ? evaluation.getVariation().getValue() : null; |
| 214 | + } |
| 215 | + |
| 216 | + private static boolean matches(Object value, String expected) { |
| 217 | + if ("boolean".equals(expected)) return value instanceof Boolean; |
| 218 | + if ("string".equals(expected)) return value instanceof String; |
| 219 | + if ("integer".equals(expected)) return value instanceof Number && Math.rint(((Number) value).doubleValue()) == ((Number) value).doubleValue(); |
| 220 | + if ("number".equals(expected)) return value instanceof Number && Double.isFinite(((Number) value).doubleValue()); |
| 221 | + return value instanceof Map || value instanceof List; |
| 222 | + } |
| 223 | + |
| 224 | + private static Map<String, Object> normalizeMap(Map<String, Object> input) { |
| 225 | + Map<String, Object> result = new HashMap<>(); |
| 226 | + input.forEach((key, value) -> result.put(key, normalize(value))); |
| 227 | + return result; |
| 228 | + } |
| 229 | + private static Object normalize(Object value) { |
| 230 | + if (value instanceof Instant) return value.toString(); |
| 231 | + if (value instanceof Map) return normalizeMap((Map<String, Object>) value); |
| 232 | + if (value instanceof List) { List<Object> result = new ArrayList<>(); for (Object item : (List<?>) value) result.add(normalize(item)); return result; } |
| 233 | + return value; |
| 234 | + } |
| 235 | + private static Value toValue(Object value) throws InstantiationException { |
| 236 | + if (value instanceof Value) return (Value) value; |
| 237 | + if (value instanceof Map) return new Value(Structure.mapToStructure((Map<String, Object>) value)); |
| 238 | + if (value instanceof List) { List<Value> result = new ArrayList<>(); for (Object item : (List<?>) value) result.add(toValue(item)); return new Value(result); } |
| 239 | + return new Value(value); |
| 240 | + } |
| 241 | + private static ProviderEvaluation<Object> typeMismatch(String key, Object fallback, String expected, ImmutableMetadata metadata) { |
| 242 | + return error(fallback, ErrorCode.TYPE_MISMATCH, "Flag \"" + key + "\" did not resolve to a " + expected + " value", metadata); |
| 243 | + } |
| 244 | + private static <T> ProviderEvaluation<T> error(T value, ErrorCode code, String message, ImmutableMetadata metadata) { |
| 245 | + return ProviderEvaluation.<T>builder().value(value).reason(Reason.ERROR.name()).errorCode(code).errorMessage(message).flagMetadata(metadata).build(); |
| 246 | + } |
| 247 | + private static <T> ProviderEvaluation<T> cast(ProviderEvaluation<Object> source, T fallback, Class<T> type) { |
| 248 | + T value = type.isInstance(source.getValue()) ? type.cast(source.getValue()) : fallback; |
| 249 | + return copy(source, value); |
| 250 | + } |
| 251 | + private static <T> ProviderEvaluation<T> copy(ProviderEvaluation<Object> source, T value) { |
| 252 | + return ProviderEvaluation.<T>builder().value(value).variant(source.getVariant()).reason(source.getReason()).errorCode(source.getErrorCode()).errorMessage(source.getErrorMessage()).flagMetadata(source.getFlagMetadata()).build(); |
| 253 | + } |
| 254 | + private static String nonEmpty(String value, String fallback) { return value == null || value.isEmpty() ? fallback : value; } |
| 255 | +} |
0 commit comments