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
2 changes: 2 additions & 0 deletions dd-openfeature/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,8 @@ tracing remain active. Previously recorded or queued data is not removed.
* The provider moved to `com.datadog.openfeature.Provider`, and the exposure hook to `com.datadog.openfeature.ExposureHook`. `datadog.trace.api.openfeature.Provider` and `datadog.trace.api.openfeature.ExposureHook` are kept as deprecated aliases.
* The SDK no longer requires `dd-java-agent` and no longer links against agent classes.
* `dd-openfeature` releases before 1.69.0 link to agent classes that `dd-java-agent` 1.69.0 removes: with `dd-java-agent` 1.69.0 or later, they return the caller default values. Upgrade `dd-openfeature` to 1.69.0 or later together with `dd-java-agent`.
* JSON flag values are now shared and read-only. Changing the returned structure, list, or `asObjectMap()` map throws `UnsupportedOperationException`. Copy the value before you change it, for example with `asMap()` or `new HashMap<>(structure.asObjectMap())`. The copy is shallow: also copy each nested map or list that you change. A hook that changes the value in `after` makes the evaluation return the default value with the `GENERAL` error code.
* Integers in JSON flag values are now `Integer` or `Long` (for example `5`, not `5.0`), and integers up to `Long.MAX_VALUE` keep their exact value. This also applies to `Value.asObject()` and `Value.equals`. To read a number as a double, use `Value.asDouble()` or `((Number) map.get("n")).doubleValue()`.

## Design notes for contributors

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,11 @@ private <T> ProviderEvaluation<T> resolveVariant(

final T mappedValue;
try {
mappedValue = mapValue(target, variant.value);
// An object or array variant is converted once, at parse time: share it, not a new copy.
mappedValue =
target == Value.class && variant.frozenValue != null
? target.cast(variant.frozenValue)
: mapValue(target, variant.value);
} catch (final NumberFormatException e) {
return error(
defaultValue,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package com.datadog.openfeature.internal.ufc;

import dev.openfeature.sdk.MutableStructure;
import dev.openfeature.sdk.Structure;
import dev.openfeature.sdk.Value;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Builds the OpenFeature {@link Value} of a JSON variant once, when the configuration is parsed, so
* that each evaluation returns the same instance instead of a new deep copy.
*
* <p>Each JSON object becomes a {@link FrozenStructure}: a {@link MutableStructure} over an
* unmodifiable map, so {@code getValue} returns the shared child without a copy and {@code add}
* throws {@link UnsupportedOperationException}. It keeps the equality of {@link
* Value#objectToValue}. Each JSON array becomes an unmodifiable list.
*/
final class FrozenValues {
/** Tells whether the loaded OpenFeature SDK accepts {@link Long} values (1.22.0 or later). */
static final boolean LONG_VALUES = hasLongValues();

private FrozenValues() {}

private static boolean hasLongValues() {
try {
Value.class.getConstructor(Long.class);
return true;
} catch (final NoSuchMethodException e) {
return false;
}
}

/** Tells whether the value is a JSON object or array, the values that are frozen. */
static boolean isContainer(final Object value) {
return value instanceof Map || value instanceof List;
}

/**
* Converts a parsed JSON tree to a {@link Value} that cannot change. The result is equal to
* {@code Value.objectToValue(tree)}.
*/
static Value freeze(final Object tree) {
if (tree instanceof Map) {
final Map<?, ?> source = (Map<?, ?>) tree;
final Map<String, Value> attributes = new HashMap<>(capacity(source.size()));
for (final Map.Entry<?, ?> entry : source.entrySet()) {
attributes.put((String) entry.getKey(), freeze(entry.getValue()));
}
return new Value(new FrozenStructure(Collections.unmodifiableMap(attributes)));
}
if (tree instanceof List) {
final List<?> source = (List<?>) tree;
final List<Value> items = new ArrayList<>(source.size());
for (final Object element : source) {
items.add(freeze(element));
}
return new Value(Collections.unmodifiableList(items));
}
return Value.objectToValue(tree);
}

/** Returns the plain form of a frozen value, equal to the tree that was frozen. */
static Object plain(final Value frozen) {
return frozen.isStructure()
? frozen.asStructure().asObjectMap()
: FrozenStructure.toObject(frozen);
}

private static int capacity(final int size) {
return (int) Math.min(Integer.MAX_VALUE, ((long) size * 4 + 2) / 3);
}

/**
* A structure that cannot change. It also keeps its plain-map form, because applications often
* read a JSON flag with {@link #asObjectMap()}.
*/
static final class FrozenStructure extends MutableStructure {
private volatile Map<String, Object> objectMap;

FrozenStructure(final Map<String, Value> attributes) {
super(attributes);
}

/**
* Returns the plain-map form, built on the first call and then shared. The map and its nested
* maps and lists cannot change.
*/
@Override
public Map<String, Object> asObjectMap() {
Map<String, Object> map = this.objectMap;
if (map == null) {
map = toObjectMap(this);
// A race builds equal immutable maps; any of them can be kept.
this.objectMap = map;
}
return map;
}

private static Map<String, Object> toObjectMap(final Structure structure) {
final Map<String, Value> attributes = structure.asUnmodifiableMap();
final Map<String, Object> map = new HashMap<>(capacity(attributes.size()));
for (final Map.Entry<String, Value> entry : attributes.entrySet()) {
map.put(entry.getKey(), toObject(entry.getValue()));
}
return Collections.unmodifiableMap(map);
}

/**
* The same conversion as {@link Structure#convertValue}, with unmodifiable containers. {@link
* #freeze} gives each child a non-null {@link Value}, and each nested structure is frozen.
*/
private static Object toObject(final Value value) {
if (value.isStructure()) {
return value.asStructure().asObjectMap();
}
if (value.isList()) {
final List<Value> source = value.asList();
final List<Object> items = new ArrayList<>(source.size());
for (final Value item : source) {
items.add(toObject(item));
}
return Collections.unmodifiableList(items);
}
return value.asObject();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import dev.openfeature.sdk.Value;
import java.io.IOException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
Expand All @@ -23,7 +24,8 @@
* Parses Universal Flag Configuration (UFC) documents.
*
* <p>The document is first read as a generic JSON tree (objects, arrays, strings, {@link Double}
* numbers, booleans and nulls), then mapped onto the UFC model. Malformed flags are dropped
* numbers, booleans and nulls; an integer in a variant value that fits in a long is read as {@link
* Integer} or {@link Long}), then mapped onto the UFC model. Malformed flags are dropped
* individually and reported through {@link ServerConfiguration#invalidFlags}; a malformed envelope
* fails the whole document.
*/
Expand Down Expand Up @@ -85,15 +87,51 @@ private static Object readDocument(final byte[] content) throws IOException {
if (parser.nextToken() == null) {
throw new JsonParseException(parser, "Empty document");
}
final Object document = readValue(parser, 1);
final Object document = readValue(parser, 1, Scope.UFC);
if (parser.nextToken() != null) {
throw new JsonParseException(parser, "Unexpected content after the document");
}
return document;
}
}

private static Object readValue(final JsonParser parser, final int depth) throws IOException {
/**
* Where the reader is in the document. Numbers are read as {@link Double}, except integers in
* {@code flags.<flag>.variations.<key>.value} that fit in a long: those are read as {@link
* Integer} or {@link Long}, so JSON variants keep exact integers.
*/
private enum Scope {
UFC,
FLAGS,
FLAG,
VARIATIONS,
VARIANT,
VARIANT_VALUE;

Scope field(final String name) {
switch (this) {
case UFC:
return "flags".equals(name) ? FLAGS : UFC;
case FLAGS:
return FLAG;
case FLAG:
return "variations".equals(name) ? VARIATIONS : UFC;
case VARIATIONS:
return VARIANT;
case VARIANT:
return "value".equals(name) ? VARIANT_VALUE : UFC;
default:
return VARIANT_VALUE;
}
}

Scope element() {
return this == VARIANT_VALUE ? VARIANT_VALUE : UFC;
}
}

private static Object readValue(final JsonParser parser, final int depth, final Scope scope)
throws IOException {
final JsonToken token = parser.currentToken();
if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY)
&& depth > MAX_NESTING_DEPTH) {
Expand All @@ -105,24 +143,36 @@ private static Object readValue(final JsonParser parser, final int depth) throws
while (parser.nextToken() == JsonToken.FIELD_NAME) {
final String name = parser.currentName();
parser.nextToken();
object.put(name, readValue(parser, depth + 1));
object.put(name, readValue(parser, depth + 1, scope.field(name)));
}
return object;
case START_ARRAY:
final List<Object> array = new ArrayList<>();
while (parser.nextToken() != JsonToken.END_ARRAY) {
array.add(readValue(parser, depth + 1));
array.add(readValue(parser, depth + 1, scope.element()));
}
return array;
case VALUE_STRING:
return parser.getText();
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
final double number = parser.getDoubleValue();
if (!Double.isFinite(number)) {
throw new JsonParseException(parser, "Non-finite JSON number");
if (scope == Scope.VARIANT_VALUE) {
// OpenFeature values hold Integer, Long or Double: larger integers stay doubles.
switch (parser.getNumberType()) {
case INT:
return parser.getIntValue();
case LONG:
// OpenFeature SDKs before 1.22.0 have no Long values: keep the double there.
if (FrozenValues.LONG_VALUES) {
return parser.getLongValue();
}
break;
default:
break;
}
}
return number;
return finiteDouble(parser);
case VALUE_NUMBER_FLOAT:
return finiteDouble(parser);
case VALUE_TRUE:
return Boolean.TRUE;
case VALUE_FALSE:
Expand All @@ -134,6 +184,14 @@ private static Object readValue(final JsonParser parser, final int depth) throws
}
}

private static double finiteDouble(final JsonParser parser) throws IOException {
final double number = parser.getDoubleValue();
if (!Double.isFinite(number)) {
throw new JsonParseException(parser, "Non-finite JSON number");
}
return number;
}

@Nullable
private static ServerConfiguration toServerConfiguration(@Nullable final Object value)
throws IOException {
Expand Down Expand Up @@ -200,33 +258,66 @@ private static Flag toFlag(@Nullable final Object value) {
return null;
}
final Map<?, ?> json = asObject(value, "flag");
final ValueType variationType =
asEnum(json.get("variationType"), ValueType.class, "variationType");
return new Flag(
asString(json.get("key"), "key"),
strictBoolean(json, "enabled"),
asEnum(json.get("variationType"), ValueType.class, "variationType"),
toVariants(json.get("variations")),
variationType,
toVariants(json.get("variations"), variationType),
toList(json.get("allocations"), "allocations", UniversalFlagConfigParser::toAllocation));
}

@Nullable
private static Map<String, Variant> toVariants(@Nullable final Object value) {
private static Map<String, Variant> toVariants(
@Nullable final Object value, @Nullable final ValueType variationType) {
if (value == null) {
return null;
}
final Map<String, Variant> variants = new HashMap<>();
for (final Map.Entry<?, ?> entry : asObject(value, "variations").entrySet()) {
variants.put((String) entry.getKey(), toVariant(entry.getValue()));
variants.put((String) entry.getKey(), toVariant(entry.getValue(), variationType));
}
return variants;
}

@Nullable
private static Variant toVariant(@Nullable final Object value) {
private static Variant toVariant(
@Nullable final Object value, @Nullable final ValueType variationType) {
if (value == null) {
return null;
}
final Map<?, ?> json = asObject(value, "variant");
return new Variant(asString(json.get("key"), "key"), json.get("value"));
final String key = asString(json.get("key"), "key");
final Object variantValue = json.get("value");
if (variationType != ValueType.JSON) {
// Only JSON flags keep exact integers.
return new Variant(key, withDoubles(variantValue), null);
}
if (!FrozenValues.isContainer(variantValue)) {
return new Variant(key, variantValue, null);
}
// Freeze once and share it. Keep its plain form instead of the parsed tree.
final Value frozen = FrozenValues.freeze(variantValue);
return new Variant(key, FrozenValues.plain(frozen), frozen);
}

/** Replaces each Integer or Long in a variant value with the equal Double. */
private static Object withDoubles(@Nullable final Object value) {
if (value instanceof Integer || value instanceof Long) {
return ((Number) value).doubleValue();
}
if (value instanceof Map) {
final Map<Object, Object> map = new LinkedHashMap<>();
((Map<?, ?>) value).forEach((k, v) -> map.put(k, withDoubles(v)));
return map;
}
if (value instanceof List) {
final List<Object> list = new ArrayList<>();
((List<?>) value).forEach(v -> list.add(withDoubles(v)));
return list;
}
return value;
}

@Nullable
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
package com.datadog.openfeature.internal.ufc;

import dev.openfeature.sdk.Value;

public final class Variant {
public final String key;
public final Object value;

/** The shared, read-only value of a JSON object or array variant; otherwise {@code null}. */
public final Value frozenValue;

public Variant(final String key, final Object value) {
this(key, value, null);
}

public Variant(final String key, final Object value, final Value frozenValue) {
this.key = key;
this.value = value;
this.frozenValue = frozenValue;
}
}
Loading
Loading