#include "evaluator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "absl/log/log.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "flagd/sync/sync.h" #include "flagd_ops.h" #include "openfeature/error_code.h" #include "openfeature/evaluation_context.h" #include "openfeature/flag_metadata.h" #include "openfeature/reason.h" #include "openfeature/resolution_details.h" #include "openfeature/value.h" namespace flagd { namespace { openfeature::Value JsonToValue(const nlohmann::json& json_val) { if (json_val.is_boolean()) { return openfeature::Value(json_val.get()); } if (json_val.is_number_integer()) { return openfeature::Value(json_val.get()); } if (json_val.is_number_float()) { return openfeature::Value(json_val.get()); } if (json_val.is_string()) { return openfeature::Value(json_val.get()); } if (json_val.is_object()) { std::map map; for (const auto& [key, value] : json_val.items()) { map.emplace(key, JsonToValue(value)); } return openfeature::Value(map); } if (json_val.is_array()) { std::vector vec; vec.reserve(json_val.size()); for (const auto& item : json_val) { vec.push_back(JsonToValue(item)); } return openfeature::Value(vec); } LOG(ERROR) << "Failed to map JSON value to openfeature::Value: " << json_val.dump(); return {}; } nlohmann::json ValueToJson(const openfeature::Value& value) { if (value.IsBool()) { return value.AsBool().value(); } if (value.IsString()) { return value.AsString().value(); } if (value.IsNumber()) { std::optional val_i = value.AsInt(); std::optional val_d = value.AsDouble(); if (val_i && val_d && static_cast(*val_i) == *val_d) { return *val_i; } return val_d.value_or(0.0); } if (value.IsStructure()) { nlohmann::json obj = nlohmann::json::object(); const auto* structure = value.AsStructure(); if (structure != nullptr) { for (const auto& [key, val] : *structure) { obj[key] = ValueToJson(val); } } return obj; } if (value.IsList()) { nlohmann::json arr = nlohmann::json::array(); const auto* list = value.AsList(); if (list != nullptr) { for (const auto& val : *list) { arr.push_back(ValueToJson(val)); } } return arr; } return nullptr; } std::optional JsonToMetadataValue( const nlohmann::json& json) { if (json.is_boolean()) { return json.get(); } if (json.is_string()) { return json.get(); } if (json.is_number_integer()) { return json.get(); } if (json.is_number_float()) { return json.get(); } LOG(ERROR) << "Failed to map JSON value to openfeature::FlagMetadataValue: " << json.dump(); return std::nullopt; } void EnrichMetadata(openfeature::FlagMetadata& metadata, const nlohmann::json& metadata_json) { if (!metadata_json.is_object()) return; for (const auto& [key, value] : metadata_json.items()) { std::optional metadata_value = JsonToMetadataValue(value); if (metadata_value.has_value()) { metadata.data[key] = std::move(metadata_value.value()); } } } // binary is reserved for resolve results, so context can't forge one nlohmann::json WithoutBinary(const nlohmann::json& json) { if (json.is_binary()) return nullptr; if (json.is_object()) { nlohmann::json obj = nlohmann::json::object(); for (const auto& [key, value] : json.items()) { obj[key] = WithoutBinary(value); } return obj; } if (json.is_array()) { nlohmann::json arr = nlohmann::json::array(); for (const auto& item : json) { arr.push_back(WithoutBinary(item)); } return arr; } return json; } // Reason is a closed enum, so non-standard reasons keep the default reason std::optional ReasonFromString(std::string_view reason) { for (openfeature::Reason candidate : {openfeature::Reason::kStatic, openfeature::Reason::kDefault, openfeature::Reason::kTargetingMatch, openfeature::Reason::kSplit, openfeature::Reason::kCached, openfeature::Reason::kDisabled, openfeature::Reason::kUnknown, openfeature::Reason::kStale, openfeature::Reason::kError}) { if (openfeature::ToString(candidate) == reason) return candidate; } return std::nullopt; } nlohmann::json ContextToJson(const openfeature::EvaluationContext& ctx) { nlohmann::json json = nlohmann::json::object(); std::optional targeting_key = ctx.GetTargetingKey(); if (targeting_key.has_value()) { json["targetingKey"] = targeting_key.value(); } for (const auto& [key, value] : ctx.GetAttributes()) { if (const auto* str_val = std::any_cast(&value)) { json[key] = *str_val; } else if (const auto* i64_val = std::any_cast(&value)) { json[key] = *i64_val; } else if (const auto* u64_val = std::any_cast(&value)) { json[key] = *u64_val; } else if (const auto* int_val = std::any_cast(&value)) { json[key] = *int_val; } else if (const auto* dbl_val = std::any_cast(&value)) { json[key] = *dbl_val; } else if (const auto* bool_val = std::any_cast(&value)) { json[key] = *bool_val; } else if (const auto* of_val = std::any_cast(&value)) { json[key] = ValueToJson(*of_val); } else if (const auto* json_val = std::any_cast(&value)) { json[key] = WithoutBinary(*json_val); } else { LOG(WARNING) << "Unsupported attribute type for key: " << key; } } return json; } } // namespace JsonLogicEvaluator::JsonLogicEvaluator(std::shared_ptr sync) : sync_(std::move(sync)) { json_logic_.RegisterOperation("starts_with", StartsWith); json_logic_.RegisterOperation("ends_with", EndsWith); json_logic_.RegisterOperation("sem_ver", SemVer); json_logic_.RegisterOperation("fractional", Fractional); json_logic_.RegisterOperation("resolve", Resolve); } template std::unique_ptr> JsonLogicEvaluator::ResolveAny(std::string_view flag_key, T default_value, const openfeature::EvaluationContext& ctx) { std::shared_ptr flags = sync_->GetFlags(); std::shared_ptr global_metadata_json = sync_->GetMetadata(); openfeature::FlagMetadata flag_metadata; if (global_metadata_json) { EnrichMetadata(flag_metadata, *global_metadata_json); } if (flags == nullptr) { return std::make_unique>( std::move(default_value), openfeature::Reason::kError, "", flag_metadata, openfeature::ErrorCode::kParseError, "No flags available"); } auto flag_it = flags->find(flag_key); if (flag_it == flags->end()) { return std::make_unique>( std::move(default_value), openfeature::Reason::kError, "", flag_metadata, openfeature::ErrorCode::kFlagNotFound, absl::StrCat("flag: ", flag_key, " not found")); } const nlohmann::json& flag_config = *flag_it; if (flag_config.contains("metadata")) { EnrichMetadata(flag_metadata, flag_config["metadata"]); } if (flag_config["state"] == "DISABLED") { return std::make_unique>( std::move(default_value), openfeature::Reason::kDisabled, "", flag_metadata, openfeature::ErrorCode::kFlagNotFound, absl::StrCat("flag: ", flag_key, " is disabled")); } std::optional variant; bool has_targeting = false; std::optional resolved; if (flag_config.contains("targeting") && !flag_config["targeting"].empty()) { has_targeting = true; nlohmann::json data = ContextToJson(ctx); // flagd also injects some special variables data["$flagd"] = { {"flagKey", flag_key}, { "timestamp", std::chrono::system_clock::to_time_t( std::chrono::system_clock::now()), }, }; absl::StatusOr result = json_logic_.Apply(flag_config["targeting"], data); if (result.ok()) { resolved = DecodeResolveResult(result.value()); if (resolved.has_value()) { // a null variant falls back exactly like a plain null result variant = resolved->variant; EnrichMetadata(flag_metadata, resolved->metadata); } else if (result.value().is_string()) { variant = result.value().get(); } else if (result.value().is_boolean()) { variant = result.value().get() ? "true" : "false"; } else { // According to the flagd spec, targeting rules must return a string // (the variant name). Booleans are a special case to support logical // operations in boolean flags, which we map to "true"/"false" strings. // Other types are not valid variant identifiers. LOG(WARNING) << "Targeting rule for flag '" << flag_key << "' returned an unsupported type: " << result.value().type_name() << ". Expected string or boolean."; } } else { LOG(ERROR) << "JsonLogic evaluation failed for flag " << flag_key << ": " << result.status().message(); } } openfeature::Reason reason; std::string variant_name; if (variant.has_value()) { variant_name = std::move(*variant); reason = openfeature::Reason::kTargetingMatch; } else { // targeting that returned null reports DEFAULT; no targeting is STATIC reason = has_targeting ? openfeature::Reason::kDefault : openfeature::Reason::kStatic; if (!flag_config.value("defaultVariant", nlohmann::json()).is_null()) { variant_name = flag_config["defaultVariant"]; } } // a resolve reason replaces the reason the plain result would report if (resolved.has_value() && resolved->reason.has_value()) { std::optional rule_reason = ReasonFromString(*resolved->reason); if (rule_reason.has_value()) reason = *rule_reason; } // no variant means no value; reasons only affect telemetry and side effects if (variant_name.empty()) { return std::make_unique>( std::move(default_value), reason == openfeature::Reason::kStatic ? openfeature::Reason::kDefault : reason, "", flag_metadata, std::nullopt, std::nullopt); } const nlohmann::json& variants = flag_config["variants"]; if (!variants.contains(variant_name)) { return std::make_unique>( std::move(default_value), openfeature::Reason::kError, variant_name, flag_metadata, openfeature::ErrorCode::kGeneral, absl::StrCat("flag: ", flag_key, " doesn't contain evaluated variant: ", variant_name, ".")); } // TODO(#29): Currently this function doesn't differentiate between int and // float, We might need to verify those castings once #flagd/1481 issue is // resolved. T value; try { if constexpr (std::is_same_v) { value = JsonToValue(variants.at(variant_name)); } else { value = variants.at(variant_name).get(); } } catch (const nlohmann::json::exception& err) { return std::make_unique>( std::move(default_value), openfeature::Reason::kError, variant_name, flag_metadata, openfeature::ErrorCode::kTypeMismatch, err.what()); } return std::make_unique>( std::move(value), reason, variant_name, flag_metadata, std::nullopt, std::nullopt); } std::unique_ptr JsonLogicEvaluator::ResolveBoolean(std::string_view flag_key, bool default_value, const openfeature::EvaluationContext& ctx) { return ResolveAny(flag_key, default_value, ctx); } std::unique_ptr JsonLogicEvaluator::ResolveString(std::string_view flag_key, std::string_view default_value, const openfeature::EvaluationContext& ctx) { return ResolveAny(flag_key, std::string(default_value), ctx); } std::unique_ptr JsonLogicEvaluator::ResolveInteger(std::string_view flag_key, int64_t default_value, const openfeature::EvaluationContext& ctx) { return ResolveAny(flag_key, default_value, ctx); } std::unique_ptr JsonLogicEvaluator::ResolveDouble(std::string_view flag_key, double default_value, const openfeature::EvaluationContext& ctx) { return ResolveAny(flag_key, default_value, ctx); } std::unique_ptr JsonLogicEvaluator::ResolveObject(std::string_view flag_key, openfeature::Value default_value, const openfeature::EvaluationContext& ctx) { return ResolveAny(flag_key, std::move(default_value), ctx); } } // namespace flagd