diff --git a/Gemfile.lock b/Gemfile.lock index bed803f..249a91e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -4,6 +4,7 @@ PATH flagsmith (4.3.0) faraday (>= 2.0.1) faraday-retry + jsonpath (~> 1.1) semantic GEM @@ -21,8 +22,11 @@ GEM faraday (~> 2.0) gem-release (2.2.2) json (2.7.1) + jsonpath (1.1.5) + multi_json language_server-protocol (3.17.0.3) method_source (1.0.0) + multi_json (1.17.0) net-http (0.4.1) uri parallel (1.24.0) diff --git a/flagsmith.gemspec b/flagsmith.gemspec index a4b950d..a1e9459 100644 --- a/flagsmith.gemspec +++ b/flagsmith.gemspec @@ -34,6 +34,7 @@ Gem::Specification.new do |spec| spec.add_dependency 'faraday', '>= 2.0.1' spec.add_dependency 'faraday-retry' + spec.add_dependency 'jsonpath', '~> 1.1' spec.add_dependency 'semantic' spec.metadata['rubygems_mfa_required'] = 'true' end diff --git a/lib/flagsmith/engine/core.rb b/lib/flagsmith/engine/core.rb index 530a3f4..cb872b0 100644 --- a/lib/flagsmith/engine/core.rb +++ b/lib/flagsmith/engine/core.rb @@ -12,6 +12,7 @@ require_relative 'segments/models' require_relative 'utils/hash_func' require_relative 'evaluation/mappers' +require_relative 'evaluation/core' module Flagsmith module Engine diff --git a/lib/flagsmith/engine/evaluation/core.rb b/lib/flagsmith/engine/evaluation/core.rb index 2b510cc..e0d4eb1 100644 --- a/lib/flagsmith/engine/evaluation/core.rb +++ b/lib/flagsmith/engine/evaluation/core.rb @@ -1,20 +1,173 @@ # frozen_string_literal: true +require_relative '../utils/hash_func' +require_relative '../features/constants' +require_relative '../segments/evaluator' + module Flagsmith module Engine module Evaluation + # Core evaluation logic module module Core + extend self + include Flagsmith::Engine::Utils::HashFunc + include Flagsmith::Engine::Features::TargetingReasons + include Flagsmith::Engine::Segments::Evaluator # Get evaluation result from evaluation context # # @param evaluation_context [Hash] The evaluation context # @return [Hash] Evaluation result with flags and segments - def self.get_evaluation_result(_evaluation_context) - # TODO: Implement core evaluation logic + # returns EvaluationResultWithMetadata + def get_evaluation_result(evaluation_context) + segments, segment_overrides = evaluate_segments(evaluation_context) + flags = evaluate_features(evaluation_context, segment_overrides) { - flags: {}, - segments: [] + flags: flags, + segments: segments } end + + # Returns { segments: EvaluationResultSegments; segmentOverrides: Record; } + def evaluate_segments(evaluation_context) + return [], {} if evaluation_context[:identity].nil? || evaluation_context[:segments].nil? + + identity_segments = get_identity_segments_from_context(evaluation_context) + + segments = identity_segments.map do |segment| + result = { + name: segment[:name] + } + + result[:metadata] = segment[:metadata] if segment[:metadata] + + result + end + + segment_overrides = process_segment_overrides(identity_segments) + + [segments, segment_overrides] + end + + # Returns Record + def process_segment_overrides(identity_segments) + segment_overrides = {} + + identity_segments.each do |segment| + next unless segment[:overrides] + + overrides_list = segment[:overrides].is_a?(Array) ? segment[:overrides] : [] + + overrides_list.each do |override| + next unless should_apply_override(override, segment_overrides) + + segment_overrides[override[:name]] = { + feature: override, + segment_name: segment[:name] + } + end + end + + segment_overrides + end + + # returns EvaluationResultFlags + def evaluate_features(evaluation_context, segment_overrides) + flags = {} + + (evaluation_context[:features] || {}).each_value do |feature| + segment_override = segment_overrides[feature[:name]] + final_feature = segment_override ? segment_override[:feature] : feature + has_override = !segment_override.nil? + + # Evaluate feature value + evaluated = if has_override + { value: final_feature[:value], reason: nil } + else + evaluate_feature_value(final_feature, get_identity_key(evaluation_context)) + end + + # Build flag result + flag_result = { + name: final_feature[:name], + enabled: final_feature[:enabled], + value: evaluated[:value] + } + + # Add metadata if present + flag_result[:metadata] = final_feature[:metadata] if final_feature[:metadata] + + # Set reason + flag_result[:reason] = evaluated[:reason] || + get_targeting_match_reason({ type: 'SEGMENT', override: segment_override }) + + flags[final_feature[:name].to_sym] = flag_result + end + + flags + end + + # Returns {value: any; reason?: string} + def evaluate_feature_value(feature, identity_key = nil) + return get_multivariate_feature_value(feature, identity_key) if feature[:variants]&.any? && identity_key + + { value: feature[:value], reason: nil } + end + + # Returns {value: any; reason?: string} + def get_multivariate_feature_value(feature, identity_key) + percentage_value = hashed_percentage_for_object_ids([feature[:key], identity_key]) + sorted_variants = (feature[:variants] || []).sort_by { |v| v[:priority] || Float::INFINITY } + + start_percentage = 0 + sorted_variants.each do |variant| + limit = start_percentage + variant[:weight] + if start_percentage <= percentage_value && percentage_value < limit + return { + value: variant[:value], + reason: get_targeting_match_reason({ type: 'SPLIT', weight: variant[:weight] }) + } + end + start_percentage = limit + end + + { value: feature[:value], reason: nil } + end + + # returns boolean + def should_apply_override(override, existing_overrides) + current_override = existing_overrides[override[:name]] + !current_override || higher_priority?(override[:priority], current_override[:feature][:priority]) + end + + private + + # Extract identity key from evaluation context + # + # @param evaluation_context [Hash] The evaluation context + # @return [String, nil] The identity key or nil if no identity + def get_identity_key(evaluation_context) + return nil unless evaluation_context[:identity] + + evaluation_context[:identity][:key] || + "#{evaluation_context[:environment][:key]}_#{evaluation_context[:identity][:identifier]}" + end + + # returns boolean + def higher_priority?(priority_a, priority_b) + (priority_a || Float::INFINITY) < (priority_b || Float::INFINITY) + end + + def get_targeting_match_reason(match_object) + type = match_object[:type] + + if type == 'SEGMENT' + return match_object[:override] ? "#{TARGETING_REASON_TARGETING_MATCH}; segment=#{match_object[:override][:segment_name]}" : TARGETING_REASON_DEFAULT + end + + return "#{TARGETING_REASON_SPLIT}; weight=#{match_object[:weight]}" if type == 'SPLIT' + + TARGETING_REASON_DEFAULT + end end end end diff --git a/lib/flagsmith/engine/evaluation/mappers.rb b/lib/flagsmith/engine/evaluation/mappers.rb index 81ba85e..745e9c0 100644 --- a/lib/flagsmith/engine/evaluation/mappers.rb +++ b/lib/flagsmith/engine/evaluation/mappers.rb @@ -161,7 +161,7 @@ def self.map_identity_overrides_to_segments(identity_overrides) features_to_identifiers = {} identity_overrides.each do |identity| - next if identity.identity_features.nil? || !identity.identity_features.any? + next if identity.identity_features.nil? || identity.identity_features.none? # Sort features by name for consistent hashing sorted_features = identity.identity_features.to_a.sort_by { |fs| fs.feature.name } diff --git a/lib/flagsmith/engine/features/constants.rb b/lib/flagsmith/engine/features/constants.rb new file mode 100644 index 0000000..b3baa08 --- /dev/null +++ b/lib/flagsmith/engine/features/constants.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +module Flagsmith + module Engine + module Features + # Targeting reason constants for evaluation results + module TargetingReasons + TARGETING_REASON_DEFAULT = 'DEFAULT' + TARGETING_REASON_TARGETING_MATCH = 'TARGETING_MATCH' + TARGETING_REASON_SPLIT = 'SPLIT' + end + end + end +end diff --git a/lib/flagsmith/engine/segments/evaluator.rb b/lib/flagsmith/engine/segments/evaluator.rb index cc4a2f0..d4342f8 100644 --- a/lib/flagsmith/engine/segments/evaluator.rb +++ b/lib/flagsmith/engine/segments/evaluator.rb @@ -1,6 +1,9 @@ # frozen_string_literal: true +require 'json' +require 'jsonpath' require_relative 'constants' +require_relative 'models' require_relative '../utils/hash_func' module Flagsmith @@ -11,6 +14,24 @@ module Evaluator include Flagsmith::Engine::Segments::Constants include Flagsmith::Engine::Utils::HashFunc + module_function + # Context-based segment evaluation (new approach) + # Returns all segments that the identity belongs to based on segment rules evaluation + # + # @param context [Hash] Evaluation context containing identity and segment definitions + # @return [Array] Array of segments that the identity matches + def get_identity_segments_from_context(context) + return [] unless context[:identity] && context[:segments] + + context[:segments].values.select do |segment| + next false if segment[:rules].nil? || segment[:rules].empty? + + matches = segment[:rules].all? { |rule| traits_match_segment_rule_from_context(rule, segment[:key], context) } + matches + end + end + + # Model-based segment evaluation (existing approach) def get_identity_segments(environment, identity, override_traits = nil) environment.project.segments.select do |s| evaluate_identity_in_segment(identity, s, override_traits) @@ -70,6 +91,151 @@ def traits_match_segment_condition(identity_traits, condition, segment_id, ident false end + # Context-based helper functions (new approach) + + # Evaluates whether a segment rule matches using context + # + # @param rule [Hash] The rule to evaluate + # @param segment_key [String] The segment key (used for percentage split) + # @param context [Hash] The evaluation context + # @return [Boolean] True if the rule matches + def traits_match_segment_rule_from_context(rule, segment_key, context) + matches_conditions = evaluate_conditions_from_context(rule, segment_key, context) + matches_sub_rules = evaluate_sub_rules_from_context(rule, segment_key, context) + + matches_conditions && matches_sub_rules + end + + # Evaluates rule conditions based on rule type (ALL/ANY/NONE) + # + # @param rule [Hash] The rule containing conditions and type + # @param segment_key [String] The segment key + # @param context [Hash] The evaluation context + # @return [Boolean] True if conditions match according to rule type + def evaluate_conditions_from_context(rule, segment_key, context) + return true unless rule[:conditions]&.any? + + condition_results = rule[:conditions].map do |condition| + traits_match_segment_condition_from_context(condition, segment_key, context) + end + + evaluate_rule_conditions(rule[:type], condition_results) + end + + # Evaluates nested sub-rules + # + # @param rule [Hash] The rule containing nested rules + # @param segment_key [String] The segment key + # @param context [Hash] The evaluation context + # @return [Boolean] True if all sub-rules match + def evaluate_sub_rules_from_context(rule, segment_key, context) + return true if rule[:rules].nil? || rule[:rules].empty? + + rule[:rules].all? do |sub_rule| + traits_match_segment_rule_from_context(sub_rule, segment_key, context) + end + end + + # Evaluates a single segment condition using context + # + # @param condition [Hash] The condition to evaluate + # @param segment_key [String] The segment key (used for percentage split hashing) + # @param context [Hash] The evaluation context + # @return [Boolean] True if the condition matches + def traits_match_segment_condition_from_context(condition, segment_key, context) + if condition[:operator] == PERCENTAGE_SPLIT + context_value_key = get_context_value(condition[:property], context) || get_identity_key_from_context(context) + hashed_percentage = hashed_percentage_for_object_ids([segment_key, context_value_key]) + return hashed_percentage <= condition[:value].to_f + end + + return false if condition[:property].nil? + + trait_value = get_trait_value(condition[:property], context) + + return !trait_value.nil? if condition[:operator] == IS_SET + return trait_value.nil? if condition[:operator] == IS_NOT_SET + + unless trait_value.nil? + # Reuse existing Condition class logic + condition_obj = Flagsmith::Engine::Segments::Condition.new( + operator: condition[:operator], + value: condition[:value], + property: condition[:property] + ) + return condition_obj.match_trait_value?(trait_value) + end + + false + end + + # Evaluate rule conditions based on type (ALL/ANY/NONE) + # + # @param rule_type [String] The rule type + # @param condition_results [Array] Array of condition evaluation results + # @return [Boolean] True if conditions match according to rule type + def evaluate_rule_conditions(rule_type, condition_results) + case rule_type + when 'ALL' + condition_results.empty? || condition_results.all? + when 'ANY' + !condition_results.empty? && condition_results.any? + when 'NONE' + condition_results.empty? || condition_results.none? + else + false + end + end + + # Get trait value from context, supporting JSONPath expressions + # + # @param property [String] The property name or JSONPath + # @param context [Hash] The evaluation context + # @return [Object, nil] The trait value or nil + def get_trait_value(property, context) + if property.start_with?('$.') + context_value = get_context_value(property, context) + return context_value if !context_value.nil? && !non_primitive?(context_value) + end + + traits = context.dig(:identity, :traits) || {} + traits[property] || traits[property.to_sym] + end + + # Get value from context using JSONPath syntax + # + # @param json_path [String] JSONPath expression (e.g., '$.identity.identifier') + # @param context [Hash] The evaluation context + # @return [Object, nil] The value at the path or nil + def get_context_value(json_path, context) + return nil unless context && json_path&.start_with?('$.') + results = JsonPath.new(json_path, use_symbols: true).on(context) + results.first + rescue StandardError + nil + end + + # Get identity key from context + # + # @param context [Hash] The evaluation context + # @return [String, nil] The identity key or generated composite key + def get_identity_key_from_context(context) + return nil unless context[:identity] + + context[:identity][:key] || + "#{context[:environment][:key]}_#{context[:identity][:identifier]}" + end + + # Check if value is non-primitive (object or array) + # + # @param value [Object] The value to check + # @return [Boolean] True if value is an object or array + def non_primitive?(value) + return false if value.nil? + + value.is_a?(Hash) || value.is_a?(Array) + end + private def handle_trait_existence_conditions(matching_trait, operator) diff --git a/lib/flagsmith/engine/segments/models.rb b/lib/flagsmith/engine/segments/models.rb index f339112..756c905 100644 --- a/lib/flagsmith/engine/segments/models.rb +++ b/lib/flagsmith/engine/segments/models.rb @@ -45,7 +45,7 @@ class Condition CONTAINS => ->(other_value, self_value) { (other_value || false) && other_value.include?(self_value) }, NOT_CONTAINS => ->(other_value, self_value) { (other_value || false) && !other_value.include?(self_value) }, - REGEX => ->(other_value, self_value) { (other_value || false) && other_value.match?(self_value) } + REGEX => ->(other_value, self_value) { (other_value || false) && other_value.to_s.match?(self_value) } }.freeze def initialize(operator:, value:, property: nil) @@ -55,11 +55,17 @@ def initialize(operator:, value:, property: nil) end def match_trait_value?(trait_value) - # handle some exceptions - trait_value = Semantic::Version.new(trait_value.gsub(/:semver$/, '')) if @value.is_a?(String) && @value.match?(/:semver$/) + if @value.is_a?(String) && @value.match?(/:semver$/) + begin + trait_value = Semantic::Version.new(trait_value.to_s.gsub(/:semver$/, '')) + rescue ArgumentError, Semantic::Version::ValidationFailed => _e + return false + end + end return match_in_value(trait_value) if @operator == IN return match_modulo_value(trait_value) if @operator == MODULO + return MATCHING_FUNCTIONS[REGEX]&.call(trait_value, @value) if @operator == REGEX type_as_trait_value = format_to_type_of(trait_value) formatted_value = type_as_trait_value ? type_as_trait_value.call(@value) : @value @@ -72,10 +78,17 @@ def format_to_type_of(input) { 'String' => ->(v) { v.to_s }, 'Semantic::Version' => ->(v) { Semantic::Version.new(v.to_s.gsub(/:semver$/, '')) }, + # Double check this is the desired behavior between SDKs 'TrueClass' => ->(v) { ['True', 'true', 'TRUE', true, 1, '1'].include?(v) }, - 'FalseClass' => ->(v) { !['False', 'false', 'FALSE', false, 0, '0'].include?(v) }, - 'Integer' => ->(v) { v.to_i }, - 'Float' => ->(v) { v.to_f } + 'FalseClass' => ->(v) { !['False', 'false', 'FALSE', false].include?(v) }, + 'Integer' => lambda { |v| + i = v.to_i + i.to_s == v.to_s ? i : v + }, + 'Float' => lambda { |v| + f = v.to_f + f.to_s == v.to_s ? f : v + } }[input.class.to_s] end # rubocop:enable Metrics/AbcSize @@ -88,9 +101,19 @@ def match_modulo_value(trait_value) end def match_in_value(trait_value) - return @value.split(',').include?(trait_value.to_s) if trait_value.is_a?(String) || trait_value.is_a?(Integer) + return false if trait_value.nil? || trait_value.is_a?(TrueClass) || trait_value.is_a?(FalseClass) - false + return @value.include?(trait_value.to_s) if @value.is_a?(Array) + + if @value.is_a?(String) + begin + parsed = JSON.parse(@value) + return parsed.include?(trait_value.to_s) if parsed.is_a?(Array) + rescue JSON::ParserError + end + end + + @value.to_s.split(',').include?(trait_value.to_s) end class << self diff --git a/spec/engine-test-data b/spec/engine-test-data index 41c2021..218757f 160000 --- a/spec/engine-test-data +++ b/spec/engine-test-data @@ -1 +1 @@ -Subproject commit 41c202145e375c712600e318c439456de5b221d7 +Subproject commit 218757fd23f932760be681a09c686c9d6ef55fad diff --git a/spec/engine/e2e/engine_spec.rb b/spec/engine/e2e/engine_spec.rb index 77c9f92..0a40dbe 100644 --- a/spec/engine/e2e/engine_spec.rb +++ b/spec/engine/e2e/engine_spec.rb @@ -35,11 +35,12 @@ def load_test_file(filepath) test_expected_result = test_case[:result] # TODO: Implement evaluation logic - evaluation_result = {} + evaluation_result = Flagsmith::Engine::Evaluation::Core.get_evaluation_result(test_evaluation_context) # TODO: Uncomment when evaluation is implemented - # expect(evaluation_result).to eq(test_expected_result) + expect(evaluation_result[:flags]).to eq(test_expected_result[:flags]) + expect(evaluation_result[:segments]).to eq(test_expected_result[:segments]) end end end