Class: PostHog::FeatureFlagsPoller Private
- Inherits:
-
Object
- Object
- PostHog::FeatureFlagsPoller
- Defined in:
- lib/posthog/feature_flags.rb
Overview
This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.
Polls and evaluates feature flag definitions for Client.
Constant Summary collapse
- UNRESOLVED_REASON_PRECEDENCE =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
When several causes apply to one flag, the spec reports the first reason in this order, so every SDK picks the same reason whatever order it inspects the filters in.
[ UnresolvedFlagReason::EXPERIENCE_CONTINUITY, UnresolvedFlagReason::UNSUPPORTED_DEFINITION, UnresolvedFlagReason::UNRESOLVED_DEPENDENCY, UnresolvedFlagReason::MISSING_CONTEXT ].freeze
- REGEX_OPERATORS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Operator groups that share one branch in both match_property_value and assert_filter_supported, so the load-time check stays in step with evaluation.
%w[regex not_regex].freeze
- NUMERIC_OPERATORS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
%w[gt gte lt lte].freeze
- DATE_OPERATORS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
%w[is_date_before is_date_after].freeze
- SEMVER_COMPARISON_OPERATORS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
%w[semver_eq semver_neq semver_gt semver_gte semver_lt semver_lte].freeze
- RETRYABLE_REQUEST_ERRORS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Transient network errors that are safe to retry. Flag requests are retry-safe (stateless reads and evaluations, no server-side mutation), so a one-off blip (TCP retransmit, TLS jitter, an edge/proxy hiccup) should be absorbed by a retry rather than surfaced to the caller.
[ Timeout::Error, # covers Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout Errno::ECONNRESET, EOFError ].freeze
- RETRYABLE_FLAGS_REQUEST_STATUS_CODES =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
[502, 504].freeze
Constants included from Utils
Utils::UTC_OFFSET_WITHOUT_COLON, Utils::UTC_OFFSET_WITH_COLON
Instance Attribute Summary collapse
- #feature_flags_by_key ⇒ Object readonly private
- #minimal_flag_called_events ⇒ Object readonly private
Class Method Summary collapse
- .compare(lhs, rhs, operator) ⇒ Object private
-
.definition_unresolved_reason(flag, flags_by_key, cohorts, group_type_mapping) ⇒ Object
private
The unresolved reason that comes from the flag's definition alone, so it is known when definitions load.
-
.flag_dependency_definition_error(property, flags_by_key) ⇒ Object
private
Why a flag dependency filter can never evaluate locally, whatever the call passes, or nil.
- .match_cohort(property, property_values, cohort_properties, property_matching_version: 1) ⇒ Object private
- .match_property(property, property_values, cohort_properties = {}, property_matching_version: 1) ⇒ Object private
- .match_property_group(property_group, property_values, cohort_properties, property_matching_version: 1) ⇒ Object private
- .matches_dependency_value(expected_value, actual_value) ⇒ Object private
-
.parse_semver(value, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) ⇒ Object
private
Parse a semver string into a comparable [major, minor, patch] integer array.
-
.parse_semver_numeric(part, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) ⇒ Object
private
Parse a single semver numeric identifier, rejecting empty, non-digit, or leading-zero values per semver 2.0.0 §2.
-
.pick_unresolved_reason(current, reason) ⇒ Object
private
Class methods.
- .relative_date_parse_for_feature_flag_matching(value) ⇒ Object private
-
.semver_caret_bounds(value) ⇒ Object
private
Returns bounds for caret (^) range per semver spec: ^X.Y.Z where X > 0 → >=X.Y.Z <(X+1).0.0 ^0.Y.Z where Y > 0 → >=0.Y.Z <0.(Y+1).0 ^0.0.Z → >=0.0.Z <0.0.(Z+1).
-
.semver_tilde_bounds(value) ⇒ Object
private
Returns bounds for tilde (~) range: ~X → >=X.0.0 <(X+1).0.0 ~X.Y → >=X.Y.0 <X.(Y+1).0 ~X.Y.Z → >=X.Y.Z <X.(Y+1).0.
-
.semver_wildcard_bounds(value) ⇒ Object
private
Returns bounds for wildcard () range: X. or X → >=X.0.0 <(X+1).0.0 X.Y.* → >=X.Y.0 <X.(Y+1).0.
Instance Method Summary collapse
- #_apply_flag_definitions(data) ⇒ Object private
- #_compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {}, group_properties = {}, snapshot: _evaluation_snapshot) ⇒ Object private
- #_compute_flag_payload_locally(key, match_value, snapshot: _evaluation_snapshot) ⇒ Object private
- #_definition_unresolved_reason(flag, snapshot) ⇒ Object private
-
#_evaluation_snapshot ⇒ Object
private
Publish/capture all matching state together so a poll cannot switch semantics (or dependency/cohort definitions) halfway through one local evaluation.
- #_fetch_and_apply_flag_definitions ⇒ Object private
-
#_hash(key, distinct_id, salt = '') ⇒ Object
private
This function takes a distinct_id and a feature flag key and returns a float between 0 and 1.
-
#_holdout_hash(bucketing_value) ⇒ Object
private
Holdout membership hashes
holdout-<bucketing value>with no separator, salt, flag key or holdout id taking part, so one identity lands in the same holdout population on every flag, the way the server buckets it. - #_load_feature_flags ⇒ Object private
- #_mask_tokens_in_url(url) ⇒ Object private
- #_request(uri, request_object, timeout = nil, include_etag: false, retry_status_codes: []) ⇒ Object private
- #_request_feature_flag_definitions(etag: nil) ⇒ Object private
- #_request_feature_flag_evaluation(data = {}) ⇒ Object private
- #_request_remote_config_payload(flag_key) ⇒ Object private
- #_store_in_cache_provider ⇒ Object private
-
#_unresolvable_flags(flags, flags_by_key, cohorts, group_type_mapping) ⇒ Object
private
Flag key => [reason, definition] for each flag that local evaluation never resolves.
- #_warn_about_unresolvable_flags(unresolvable_flags) ⇒ Object private
- #condition_match(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, snapshot: _evaluation_snapshot) ⇒ Object private
-
#condition_match_outcome(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, snapshot: _evaluation_snapshot) ⇒ Object
private
Evaluates a single condition group and returns a tri-state outcome: :match - property filters matched AND the rollout included the user :no_match - a property filter did NOT match :out_of_rollout_bound - property filters matched (or there were none) but the rollout percentage excluded the user Distinguishing :no_match from :out_of_rollout_bound lets the caller implement the early_exit behavior (mirrors the server-side Rust evaluation engine).
-
#definitions_loaded? ⇒ Boolean
private
Whether flag definitions are currently loaded.
-
#evaluate_flag_dependency(property, evaluation_cache, distinct_id, properties, cohort_properties, snapshot: _evaluation_snapshot) ⇒ Boolean
private
Evaluates a flag dependency property according to the dependency chain algorithm.
-
#flag_definitions_loaded_at ⇒ Object
private
Epoch milliseconds of the last successful definitions load, or nil.
- #get_all_flags(distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false) ⇒ Object private
- #get_all_flags_and_payloads(distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, raise_on_error = false) ⇒ Object private
- #get_feature_flag(key, distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, snapshot: nil) ⇒ Object private
- #get_feature_flag_payload(key, distinct_id, match_value = nil, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false) ⇒ Object private
- #get_feature_payloads(distinct_id, groups = {}, person_properties = {}, group_properties = {}, _only_evaluate_locally = false) ⇒ Object private
- #get_feature_variants(distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, raise_on_error = false) ⇒ Object private
- #get_flags(distinct_id, groups = {}, person_properties = {}, group_properties = {}, flag_keys = nil, disable_geoip = nil) ⇒ Object private
- #get_matching_variant(flag, distinct_id) ⇒ Object private
- #get_remote_config_payload(flag_key) ⇒ Object private
-
#holdout_variant_for(holdout, bucketing_value) ⇒ Object
private
An experiment holdout excludes an identifier from the flag's release conditions entirely, resolving it to the synthetic variant "holdout-
". -
#initialize(polling_interval, secret_key, project_api_key, host, feature_flag_request_timeout_seconds, on_error = nil, flag_definition_cache_provider: nil, feature_flag_request_max_retries: nil, async_load: false, user_agent: "posthog-ruby/#{PostHog::VERSION}", on_flag_definitions_updated: nil, flag_definitions_update_mutex: Mutex.new) ⇒ FeatureFlagsPoller
constructor
private
A new instance of FeatureFlagsPoller.
- #load_feature_flags(force_reload = false) ⇒ Object private
- #match_feature_flag_properties(flag, distinct_id, properties, evaluation_cache, cohort_properties = {}, groups: {}, group_properties: {}, snapshot: _evaluation_snapshot) ⇒ Object private
- #shutdown_poller ⇒ Object private
- #variant_lookup_table(flag) ⇒ Object private
Methods included from Utils
convert_to_datetime, date_in_iso8601, datetime_in_iso8601, deep_symbolize_keys, formatted_offset, get_by_symbol_or_string_key, is_valid_regex, isoify_dates, isoify_dates!, monotonic_time, normalize_flag_evaluation_inputs, parse_retry_after, seconds_to_utc_offset, stringify_keys, symbolize_keys, symbolize_keys!, time_in_iso8601
Methods included from Logging
Constructor Details
#initialize(polling_interval, secret_key, project_api_key, host, feature_flag_request_timeout_seconds, on_error = nil, flag_definition_cache_provider: nil, feature_flag_request_max_retries: nil, async_load: false, user_agent: "posthog-ruby/#{PostHog::VERSION}", on_flag_definitions_updated: nil, flag_definitions_update_mutex: Mutex.new) ⇒ FeatureFlagsPoller
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns a new instance of FeatureFlagsPoller.
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/posthog/feature_flags.rb', line 59 def initialize( polling_interval, secret_key, project_api_key, host, feature_flag_request_timeout_seconds, on_error = nil, flag_definition_cache_provider: nil, feature_flag_request_max_retries: nil, async_load: false, user_agent: "posthog-ruby/#{PostHog::VERSION}", on_flag_definitions_updated: nil, flag_definitions_update_mutex: Mutex.new ) @polling_interval = polling_interval || Defaults::FeatureFlags::POLLING_INTERVAL_SECONDS @secret_key = secret_key @project_api_key = project_api_key @host = host @feature_flags = Concurrent::Array.new @group_type_mapping = Concurrent::Hash.new @cohorts = Concurrent::Hash.new @loaded_flags_successfully_once = Concurrent::AtomicBoolean.new @feature_flags_by_key = nil @feature_flag_request_timeout_seconds = feature_flag_request_timeout_seconds @feature_flag_request_max_retries = feature_flag_request_max_retries || Defaults::FeatureFlags::FLAG_REQUEST_MAX_RETRIES @on_error = on_error || proc { |status, error| } @quota_limited = Concurrent::AtomicBoolean.new(false) @flags_etag = Concurrent::AtomicReference.new(nil) @flag_definitions_loaded_at = Concurrent::AtomicReference.new(nil) @async_load = async_load @user_agent = user_agent @on_flag_definitions_updated = on_flag_definitions_updated @flag_definitions_update_mutex = flag_definitions_update_mutex # Server-controlled gate for minimal `$feature_flag_called` events, read # from the top-level `minimal_flag_called_events` key of the local # evaluation definitions payload. false when the server does not send it. @minimal_flag_called_events = false # Definition fingerprint per flag key already warned about as never locally resolvable. @warned_unresolvable_flags = {} @definition_snapshot = Concurrent::AtomicReference.new({ flags: @feature_flags, flags_by_key: @feature_flags_by_key, group_type_mapping: @group_type_mapping, cohorts: @cohorts, minimal_flag_called_events: @minimal_flag_called_events, property_matching_version: 1 }.freeze) @flag_definition_cache_provider = flag_definition_cache_provider FlagDefinitionCacheProvider.validate!(@flag_definition_cache_provider) if @flag_definition_cache_provider @task = Concurrent::TimerTask.new( execution_interval: @polling_interval, run_now: @async_load ) { _load_feature_flags } # Local evaluation can load definitions from either the API or an external cache. if @secret_key.nil? && @flag_definition_cache_provider.nil? logger.info 'No secret_key or flag_definition_cache_provider provided, disabling local evaluation' @loaded_flags_successfully_once.make_true else # load once synchronously before timer, unless @async_load load_feature_flags unless @async_load @task.execute end end |
Instance Attribute Details
#feature_flags_by_key ⇒ Object (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
142 143 144 |
# File 'lib/posthog/feature_flags.rb', line 142 def feature_flags_by_key @feature_flags_by_key end |
#minimal_flag_called_events ⇒ Object (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
142 143 144 |
# File 'lib/posthog/feature_flags.rb', line 142 def minimal_flag_called_events @minimal_flag_called_events end |
Class Method Details
.compare(lhs, rhs, operator) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/posthog/feature_flags.rb', line 508 def self.compare(lhs, rhs, operator) case operator when 'gt' lhs > rhs when 'gte' lhs >= rhs when 'lt' lhs < rhs when 'lte' lhs <= rhs else raise "Invalid operator: #{operator}" end end |
.definition_unresolved_reason(flag, flags_by_key, cohorts, group_type_mapping) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The unresolved reason that comes from the flag's definition alone, so it is known when definitions load. Matches the reason local evaluation reports for the same cause.
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 |
# File 'lib/posthog/feature_flags.rb', line 1358 def self.definition_unresolved_reason(flag, flags_by_key, cohorts, group_type_mapping) return nil unless flag[:active] return UnresolvedFlagReason::EXPERIENCE_CONTINUITY if flag[:ensure_experience_continuity] flag_filters = flag[:filters] || {} aggregation = flag_filters[:aggregation_group_type_index] if !aggregation.nil? && group_type_mapping[aggregation.to_s.to_sym].nil? return UnresolvedFlagReason::UNSUPPORTED_DEFINITION end unsupported = (flag_filters[:groups] || []).any? do |condition| (condition[:properties] || []).any? do |property| unsupported_property?(property, flags_by_key, cohorts, Set.new) end end unsupported ? UnresolvedFlagReason::UNSUPPORTED_DEFINITION : nil end |
.flag_dependency_definition_error(property, flags_by_key) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Why a flag dependency filter can never evaluate locally, whatever the call passes, or nil. Evaluation and the load-time warning both use it, so the warning matches the reason evaluation reports.
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 |
# File 'lib/posthog/feature_flags.rb', line 1378 def self.flag_dependency_definition_error(property, flags_by_key) operator = property[:operator] return "Operator #{operator} not supported for flag dependencies" if operator != 'flag_evaluates_to' key = property[:key] || 'unknown' dependency_chain = property[:dependency_chain] unless property.key?(:dependency_chain) return "Flag dependency property for '#{key}' is missing required 'dependency_chain' field" end unless dependency_chain.is_a?(Array) return "Flag dependency property for '#{key}' has an invalid 'dependency_chain' field" end return "Circular dependency detected for flag '#{key}'" if dependency_chain.empty? missing_dependency = dependency_chain.find { |dep_flag_key| flags_by_key[dep_flag_key].nil? } return nil if missing_dependency.nil? "Cannot evaluate flag dependency '#{missing_dependency}' - flag not found in local flags" end |
.match_cohort(property, property_values, cohort_properties, property_matching_version: 1) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 |
# File 'lib/posthog/feature_flags.rb', line 1096 def self.match_cohort(property, property_values, cohort_properties, property_matching_version: 1) # Cohort properties are in the form of property groups like this: # { # "cohort_id" => { # "type" => "AND|OR", # "values" => [{ # "key" => "property_name", "value" => "property_value" # }] # } # } cohort_id = extract_value(property, :value).to_s property_group = find_cohort_property(cohort_properties, cohort_id) unless property_group raise RequiresServerEvaluation.new( "cohort #{cohort_id} not found in local cohorts - likely a static cohort that requires server evaluation", reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION ) end assert_cohort_flag_leaves_parse(property_group, cohort_properties, Set.new) match_property_group(property_group, property_values, cohort_properties, property_matching_version: property_matching_version) end |
.match_property(property, property_values, cohort_properties = {}, property_matching_version: 1) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 |
# File 'lib/posthog/feature_flags.rb', line 761 def self.match_property(property, property_values, cohort_properties = {}, property_matching_version: 1) # only looks for matches where key exists in property_values # Handle cohort properties if extract_value(property, :type) == 'cohort' return match_cohort(property, property_values, cohort_properties, property_matching_version: property_matching_version) end assert_property_filter_type_supported(property) begin match_property_value(property, property_values, property_matching_version) rescue InconclusiveMatchError => e # An unusable filter outranks missing context, so check the filter before blaming the context. assert_filter_supported(property) if e.reason == UnresolvedFlagReason::MISSING_CONTEXT raise end end |
.match_property_group(property_group, property_values, cohort_properties, property_matching_version: 1) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 |
# File 'lib/posthog/feature_flags.rb', line 1121 def self.match_property_group(property_group, property_values, cohort_properties, property_matching_version: 1) return true if property_group.nil? || property_group.empty? group_type = extract_value(property_group, :type) properties = extract_value(property_group, :values) return true if properties.nil? || properties.empty? if nested_property_group?(properties) property_group_items_match?(properties, group_type) do |group| match_property_group(group, property_values, cohort_properties, property_matching_version: property_matching_version) end else property_group_items_match?(properties, group_type) do |prop| matches = if cohort_flag_dependency?(prop) false else match_property(prop, property_values, cohort_properties, property_matching_version: property_matching_version) end extract_value(prop, :negation) ? !matches : matches end end end |
.matches_dependency_value(expected_value, actual_value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 |
# File 'lib/posthog/feature_flags.rb', line 1325 def self.matches_dependency_value(expected_value, actual_value) # Check if the actual flag value matches the expected dependency value. # # - String variant case: check for exact match or boolean true # - Boolean case: must match expected boolean value # # @param expected_value [Object] The expected value from the property # @param actual_value [Object] The actual value returned by the flag evaluation # @return [Boolean] True if the values match according to flag dependency rules # String variant case - check for exact match or boolean true if actual_value.is_a?(String) && !actual_value.empty? if expected_value.is_a?(TrueClass) || expected_value.is_a?(FalseClass) # Any variant matches boolean true return expected_value elsif expected_value.is_a?(String) # variants are case-sensitive, hence our comparison is too return actual_value == expected_value else return false end # Boolean case - must match expected boolean value elsif actual_value.is_a?(TrueClass) || actual_value.is_a?(FalseClass) return actual_value == expected_value if expected_value.is_a?(TrueClass) || expected_value.is_a?(FalseClass) end # Default case false end |
.parse_semver(value, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Parse a semver string into a comparable [major, minor, patch] integer array. Handles v-prefix, whitespace, pre-release suffixes. Defaults missing components to 0.
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 |
# File 'lib/posthog/feature_flags.rb', line 608 def self.parse_semver(value, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) raise InconclusiveMatchError.new('Invalid semver format', reason: reason) if value.nil? text = value.to_s.strip.sub(/^[vV]/, '') raise InconclusiveMatchError.new('Invalid semver format', reason: reason) if text.empty? # Strip pre-release and build metadata suffixes text = text.split('-')[0].split('+')[0] parts = text.split('.') raise InconclusiveMatchError.new('Invalid semver format', reason: reason) if parts.empty? || parts[0].to_s.empty? major = parse_semver_numeric(parts[0], reason: reason) minor = parts.length > 1 ? parse_semver_numeric(parts[1], reason: reason) : 0 patch = parts.length > 2 ? parse_semver_numeric(parts[2], reason: reason) : 0 [major, minor, patch] end |
.parse_semver_numeric(part, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Parse a single semver numeric identifier, rejecting empty, non-digit, or
leading-zero values per semver 2.0.0 §2. reason names the owner of the value:
UNSUPPORTED_DEFINITION for a filter value, MISSING_CONTEXT for a value the call passed.
596 597 598 599 600 601 602 603 604 |
# File 'lib/posthog/feature_flags.rb', line 596 def self.parse_semver_numeric(part, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) if part.nil? || part.empty? || part !~ /^\d+$/ raise InconclusiveMatchError.new('Invalid semver format', reason: reason) end # Semver 2.0.0 §2: numeric identifiers MUST NOT include leading zeros. raise InconclusiveMatchError.new('Invalid semver format', reason: reason) if part.length > 1 && part[0] == '0' part.to_i end |
.pick_unresolved_reason(current, reason) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Class methods
502 503 504 505 506 |
# File 'lib/posthog/feature_flags.rb', line 502 def self.pick_unresolved_reason(current, reason) return reason if current.nil? UNRESOLVED_REASON_PRECEDENCE.index(reason) < UNRESOLVED_REASON_PRECEDENCE.index(current) ? reason : current end |
.relative_date_parse_for_feature_flag_matching(value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 |
# File 'lib/posthog/feature_flags.rb', line 538 def self.relative_date_parse_for_feature_flag_matching(value) match = /^-?([0-9]+)([a-z])$/.match(value) parsed_dt = DateTime.now.new_offset(0) return unless match number = match[1].to_i if number >= 10_000 # Guard against overflow, disallow numbers greater than 10_000 return nil end interval = match[2] case interval when 'h' parsed_dt -= (number / 24.0) when 'd' parsed_dt = parsed_dt.prev_day(number) when 'w' parsed_dt = parsed_dt.prev_day(number * 7) when 'm' parsed_dt = subtract_months(parsed_dt, number) when 'y' parsed_dt = subtract_years(parsed_dt, number) else return nil end parsed_dt end |
.semver_caret_bounds(value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns bounds for caret (^) range per semver spec: ^X.Y.Z where X > 0 → >=X.Y.Z <(X+1).0.0 ^0.Y.Z where Y > 0 → >=0.Y.Z <0.(Y+1).0 ^0.0.Z → >=0.0.Z <0.0.(Z+1)
656 657 658 659 660 661 662 663 664 665 666 667 668 669 |
# File 'lib/posthog/feature_flags.rb', line 656 def self.semver_caret_bounds(value) major, minor, patch = parse_semver(value) lower = [major, minor, patch] upper = if major.positive? [major + 1, 0, 0] elsif minor.positive? [0, minor + 1, 0] else [0, 0, patch + 1] end [lower, upper] end |
.semver_tilde_bounds(value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns bounds for tilde (~) range: ~X → >=X.0.0 <(X+1).0.0 ~X.Y → >=X.Y.0 <X.(Y+1).0 ~X.Y.Z → >=X.Y.Z <X.(Y+1).0
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 |
# File 'lib/posthog/feature_flags.rb', line 632 def self.semver_tilde_bounds(value) major, minor, patch = parse_semver(value) lower = [major, minor, patch] # Determine how many components were provided text = value.to_s.strip.sub(/^[vV]/, '') text = text.split('-')[0].split('+')[0] component_count = text.split('.').length upper = if component_count == 1 # Major-only: bump major [major + 1, 0, 0] else # Major.minor or major.minor.patch: bump minor [major, minor + 1, 0] end [lower, upper] end |
.semver_wildcard_bounds(value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns bounds for wildcard () range: X. or X → >=X.0.0 <(X+1).0.0 X.Y.* → >=X.Y.0 <X.(Y+1).0
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 |
# File 'lib/posthog/feature_flags.rb', line 674 def self.semver_wildcard_bounds(value) cleaned = value.to_s.strip.sub(/^[vV]/, '').gsub('*', '').chomp('.') parts = cleaned.split('.').reject(&:empty?) if parts.empty? raise InconclusiveMatchError.new('Invalid semver wildcard format', reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) end numeric = parts.map do |part| parse_semver_numeric(part) rescue InconclusiveMatchError raise InconclusiveMatchError.new('Invalid semver wildcard format', reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) end major = numeric[0] case numeric.length when 1 [[major, 0, 0], [major + 1, 0, 0]] when 2 minor = numeric[1] [[major, minor, 0], [major, minor + 1, 0]] else minor = numeric[1] patch = numeric[2] [[major, minor, patch], [major, minor, patch + 1]] end end |
Instance Method Details
#_apply_flag_definitions(data) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 |
# File 'lib/posthog/feature_flags.rb', line 1869 def _apply_flag_definitions(data) flags = get_by_symbol_or_string_key(data, 'flags') || [] group_type_mapping = get_by_symbol_or_string_key(data, 'group_type_mapping') || {} cohorts = get_by_symbol_or_string_key(data, 'cohorts') || {} minimal_flag_called_events = get_by_symbol_or_string_key(data, 'minimal_flag_called_events') property_matching_version = get_by_symbol_or_string_key(data, 'property_matching_version') || 1 new_flags = Concurrent::Array.new(flags.map { |f| deep_symbolize_keys(f) }) new_by_key = {} new_flags.each do |flag| new_by_key[flag[:key]] = flag unless flag[:key].nil? end new_group_type_mapping = Concurrent::Hash[deep_symbolize_keys(group_type_mapping)] new_cohorts = Concurrent::Hash[deep_symbolize_keys(cohorts)] unresolvable_flags = _unresolvable_flags(new_flags, new_by_key, new_cohorts, new_group_type_mapping) unwarned_flags = nil # A read of the new definitions must not record its event before the tracker reset. @flag_definitions_update_mutex.synchronize do @definition_snapshot.value = { flags: new_flags, flags_by_key: new_by_key, group_type_mapping: new_group_type_mapping, cohorts: new_cohorts, minimal_flag_called_events: minimal_flag_called_events == true, property_matching_version: property_matching_version }.freeze @feature_flags = new_flags @feature_flags_by_key = new_by_key @group_type_mapping = new_group_type_mapping @cohorts = new_cohorts @minimal_flag_called_events = minimal_flag_called_events == true @flag_definitions_loaded_at.value = (Time.now.to_f * 1000).to_i @loaded_flags_successfully_once.make_true if @loaded_flags_successfully_once.false? # Rebuilt from the current definitions, so a flag that is deleted or becomes resolvable is # forgotten and warns again if it later returns to an unresolvable definition. unwarned_flags = unresolvable_flags.reject { |key, entry| @warned_unresolvable_flags[key] == entry } @warned_unresolvable_flags = unresolvable_flags @on_flag_definitions_updated&.call end _warn_about_unresolvable_flags(unwarned_flags) logger.debug "Loaded #{new_flags.length} feature flags and #{new_cohorts.length} cohorts" end |
#_compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {}, group_properties = {}, snapshot: _evaluation_snapshot) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 |
# File 'lib/posthog/feature_flags.rb', line 1461 def _compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {}, group_properties = {}, snapshot: _evaluation_snapshot) # An inactive flag is false whatever its experience continuity setting. return false unless flag[:active] if flag[:ensure_experience_continuity] raise RequiresServerEvaluation.new('Flag has experience continuity enabled', reason: UnresolvedFlagReason::EXPERIENCE_CONTINUITY) end # Create evaluation cache for flag dependencies evaluation_cache = {} flag_filters = flag[:filters] || {} aggregation_group_type_index = flag_filters[:aggregation_group_type_index] if aggregation_group_type_index.nil? local_person_properties = person_properties || {} unless local_person_properties.key?(:distinct_id) || local_person_properties.key?('distinct_id') local_person_properties = local_person_properties.merge(distinct_id: distinct_id) end return match_feature_flag_properties(flag, distinct_id, local_person_properties, evaluation_cache, snapshot[:cohorts], groups: groups, group_properties: group_properties, snapshot: snapshot) end group_name = snapshot[:group_type_mapping][aggregation_group_type_index.to_s.to_sym] if group_name.nil? logger.warn( "[FEATURE FLAGS] Unknown group type index #{aggregation_group_type_index} for feature flag #{flag[:key]}" ) # failover to `/flags/` raise InconclusiveMatchError.new('Flag has unknown group type index', reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) end group_name_symbol = group_name.to_sym unless groups.key?(group_name_symbol) # Group flags are never enabled if appropriate `groups` aren't passed in # don't failover to `/flags/`, since response will be the same logger.warn "[FEATURE FLAGS] Can't compute group feature flag: #{flag[:key]} without group names passed in" return false end focused_group_properties = group_properties[group_name_symbol] match_feature_flag_properties(flag, groups[group_name_symbol], focused_group_properties, evaluation_cache, snapshot[:cohorts], groups: groups, group_properties: group_properties, snapshot: snapshot) end |
#_compute_flag_payload_locally(key, match_value, snapshot: _evaluation_snapshot) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 |
# File 'lib/posthog/feature_flags.rb', line 1514 def _compute_flag_payload_locally(key, match_value, snapshot: _evaluation_snapshot) return nil if snapshot[:flags_by_key].nil? key = key.to_s response = nil if [true, false].include? match_value response = snapshot[:flags_by_key].dig(key, :filters, :payloads, match_value.to_s.to_sym) elsif match_value.is_a? String response = snapshot[:flags_by_key].dig(key, :filters, :payloads, match_value.to_sym) end response end |
#_definition_unresolved_reason(flag, snapshot) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1619 1620 1621 1622 1623 1624 1625 |
# File 'lib/posthog/feature_flags.rb', line 1619 def _definition_unresolved_reason(flag, snapshot) self.class.definition_unresolved_reason(flag, snapshot[:flags_by_key] || {}, snapshot[:cohorts], snapshot[:group_type_mapping]) rescue StandardError # A malformed definition must not stop the fallback to the server. nil end |
#_evaluation_snapshot ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Publish/capture all matching state together so a poll cannot switch semantics (or dependency/cohort definitions) halfway through one local evaluation.
1457 1458 1459 |
# File 'lib/posthog/feature_flags.rb', line 1457 def _evaluation_snapshot @definition_snapshot.value end |
#_fetch_and_apply_flag_definitions ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 |
# File 'lib/posthog/feature_flags.rb', line 1793 def _fetch_and_apply_flag_definitions unless @secret_key logger.warn '[FEATURE FLAGS] A secret_key is required to fetch flag definitions from PostHog' return end begin res = _request_feature_flag_definitions(etag: @flags_etag.value) rescue StandardError => e @on_error.call(-1, e.to_s) return end # Handle 304 Not Modified - flags haven't changed, skip processing # Only update ETag if the 304 response includes one if res[:not_modified] @flags_etag.value = res[:etag] if res[:etag] logger.debug '[FEATURE FLAGS] Flags not modified (304), using cached data' return end # Handle quota limits with 402 status if res.is_a?(Hash) && res[:status] == 402 logger.warn( '[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. ' \ 'Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts' ) @flag_definitions_update_mutex.synchronize do definitions_were_loaded = definitions_loaded? @feature_flags = Concurrent::Array.new @feature_flags_by_key = {} @group_type_mapping = Concurrent::Hash.new @cohorts = Concurrent::Hash.new @flag_definitions_loaded_at.value = nil @minimal_flag_called_events = false @definition_snapshot.value = { flags: @feature_flags, flags_by_key: @feature_flags_by_key, group_type_mapping: @group_type_mapping, cohorts: @cohorts, minimal_flag_called_events: false, property_matching_version: 1 }.freeze @loaded_flags_successfully_once.make_false @quota_limited.make_true @on_flag_definitions_updated&.call if definitions_were_loaded end return end if res.key?(:flags) # Only update ETag on successful responses with flag data @flags_etag.value = res[:etag] _apply_flag_definitions(res) _store_in_cache_provider else logger.debug "Failed to load feature flags: #{res}" end end |
#_hash(key, distinct_id, salt = '') ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This function takes a distinct_id and a feature flag key and returns a float between 0 and 1. Given the same distinct_id and key, it'll always return the same float. These floats are uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic we can do _hash(key, distinct_id) < 0.2
1699 1700 1701 1702 |
# File 'lib/posthog/feature_flags.rb', line 1699 def _hash(key, distinct_id, salt = '') hash_key = Digest::SHA1.hexdigest "#{key}.#{distinct_id}#{salt}" (Integer(hash_key[0..14], 16).to_f / 0xfffffffffffffff) end |
#_holdout_hash(bucketing_value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Holdout membership hashes holdout-<bucketing value> with no separator, salt, flag
key or holdout id taking part, so one identity lands in the same holdout population
on every flag, the way the server buckets it. The dot-separated flag hash above
selects a different population and must not be reused here.
1729 1730 1731 1732 |
# File 'lib/posthog/feature_flags.rb', line 1729 def _holdout_hash(bucketing_value) hash_key = Digest::SHA1.hexdigest "holdout-#{bucketing_value}" (Integer(hash_key[0..14], 16).to_f / 0xfffffffffffffff) end |
#_load_feature_flags ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 |
# File 'lib/posthog/feature_flags.rb', line 1756 def _load_feature_flags should_fetch = true if @flag_definition_cache_provider begin # Cache-only readers must not acquire or renew fetch leadership. should_fetch = @secret_key && @flag_definition_cache_provider.should_fetch_flag_definitions? rescue StandardError => e logger.error("[FEATURE FLAGS] Cache provider should_fetch error: #{e}") should_fetch = true end end unless should_fetch begin cached_data = @flag_definition_cache_provider.flag_definitions if cached_data unless cached_data.is_a?(Hash) && get_by_symbol_or_string_key(cached_data, 'flags').is_a?(Array) raise ArgumentError, 'Cached flag definitions must contain a flags array' end logger.debug '[FEATURE FLAGS] Using cached flag definitions from external cache' _apply_flag_definitions(cached_data) return elsif @feature_flags.empty? # Emergency fallback: cache empty and no flags loaded -> fetch from API should_fetch = true end rescue StandardError => e logger.error("[FEATURE FLAGS] Cache provider get error: #{e}") should_fetch = true end end _fetch_and_apply_flag_definitions if should_fetch end |
#_mask_tokens_in_url(url) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
2070 2071 2072 |
# File 'lib/posthog/feature_flags.rb', line 2070 def _mask_tokens_in_url(url) url.gsub(/token=([^&]{10})[^&]*/, 'token=\1...') end |
#_request(uri, request_object, timeout = nil, include_etag: false, retry_status_codes: []) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 |
# File 'lib/posthog/feature_flags.rb', line 2000 def _request(uri, request_object, timeout = nil, include_etag: false, retry_status_codes: []) request_object['User-Agent'] = @user_agent request_timeout = timeout || 10 backoff_policy = nil attempts = 0 loop do attempts += 1 Net::HTTP.start( uri.hostname, uri.port, use_ssl: uri.scheme == 'https', open_timeout: request_timeout, read_timeout: request_timeout, write_timeout: request_timeout ) do |http| res = http.request(request_object) status_code = res.code.to_i etag = include_etag ? res['ETag'] : nil if retry_status_codes.include?(status_code) && attempts <= @feature_flag_request_max_retries backoff_policy ||= BackoffPolicy.new interval = backoff_policy.next_interval.to_f / 1000 logger.debug( "Retrying request to #{_mask_tokens_in_url(uri.to_s)} after HTTP #{status_code} (attempt #{attempts})" ) sleep(interval) next end # Handle 304 Not Modified - return special response indicating no change if status_code == 304 logger.debug("#{request_object.method} #{_mask_tokens_in_url(uri.to_s)} returned 304 Not Modified") return { not_modified: true, etag: etag, status: status_code } end # Parse response body to hash begin response = JSON.parse(res.body, symbolize_names: true) # Only add status (and etag if requested) if response is a hash extra_fields = { status: status_code } extra_fields[:etag] = etag if include_etag response = response.merge(extra_fields) if response.is_a?(Hash) return response rescue JSON::ParserError # Handle case when response isn't valid JSON error_response = { error: 'Invalid JSON response', body: res.body, status: status_code } error_response[:etag] = etag if include_etag return error_response end end rescue *RETRYABLE_REQUEST_ERRORS => e if attempts <= @feature_flag_request_max_retries backoff_policy ||= BackoffPolicy.new interval = backoff_policy.next_interval.to_f / 1000 logger.debug("Retrying request to #{_mask_tokens_in_url(uri.to_s)} after #{e.class} (attempt #{attempts})") sleep(interval) next end logger.debug("Unable to complete request to #{_mask_tokens_in_url(uri.to_s)}") raise rescue Errno::EINVAL, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError logger.debug("Unable to complete request to #{_mask_tokens_in_url(uri.to_s)}") raise end end |
#_request_feature_flag_definitions(etag: nil) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1954 1955 1956 1957 1958 1959 1960 1961 1962 |
# File 'lib/posthog/feature_flags.rb', line 1954 def _request_feature_flag_definitions(etag: nil) uri = URI("#{@host}/flags/definitions") uri.query = URI.encode_www_form([['token', @project_api_key], %w[send_cohorts true]]) req = Net::HTTP::Get.new(uri) req['Authorization'] = "Bearer #{@secret_key}" req['If-None-Match'] = etag if etag _request(uri, req, nil, include_etag: true) end |
#_request_feature_flag_evaluation(data = {}) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 |
# File 'lib/posthog/feature_flags.rb', line 1964 def _request_feature_flag_evaluation(data = {}) uri = URI("#{@host}/flags/?v=2") req = Net::HTTP::Post.new(uri) req['Content-Type'] = 'application/json' data['token'] = @project_api_key req.body = data.to_json _request( uri, req, @feature_flag_request_timeout_seconds, retry_status_codes: RETRYABLE_FLAGS_REQUEST_STATUS_CODES ) end |
#_request_remote_config_payload(flag_key) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1979 1980 1981 1982 1983 1984 1985 1986 1987 |
# File 'lib/posthog/feature_flags.rb', line 1979 def _request_remote_config_payload(flag_key) uri = URI("#{@host}/api/projects/@current/feature_flags/#{flag_key}/remote_config") uri.query = URI.encode_www_form([['token', @project_api_key]]) req = Net::HTTP::Get.new(uri) req['Content-Type'] = 'application/json' req['Authorization'] = "Bearer #{@secret_key}" _request(uri, req, @feature_flag_request_timeout_seconds) end |
#_store_in_cache_provider ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 |
# File 'lib/posthog/feature_flags.rb', line 1851 def _store_in_cache_provider return unless @flag_definition_cache_provider begin snapshot = _evaluation_snapshot data = { flags: snapshot[:flags].to_a, group_type_mapping: snapshot[:group_type_mapping].to_h, cohorts: snapshot[:cohorts].to_h, minimal_flag_called_events: snapshot[:minimal_flag_called_events], property_matching_version: snapshot[:property_matching_version] } @flag_definition_cache_provider.on_flag_definitions_received(data) rescue StandardError => e logger.error("[FEATURE FLAGS] Cache provider store error: #{e}") end end |
#_unresolvable_flags(flags, flags_by_key, cohorts, group_type_mapping) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Flag key => [reason, definition] for each flag that local evaluation never resolves. Hash#== compares the definition by content and ignores key order, so a reordered copy does not warn again.
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 |
# File 'lib/posthog/feature_flags.rb', line 1913 def _unresolvable_flags(flags, flags_by_key, cohorts, group_type_mapping) flags.each_with_object({}) do |flag, unresolvable| next if flag[:evaluation_runtime] == 'client' reason = self.class.definition_unresolved_reason(flag, flags_by_key, cohorts, group_type_mapping) next if reason.nil? || flag[:key].nil? unresolvable[flag[:key]] = [reason, flag] rescue StandardError # Evaluation reports a definition this malformed when the flag is used. next end end |
#_warn_about_unresolvable_flags(unresolvable_flags) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 |
# File 'lib/posthog/feature_flags.rb', line 1927 def _warn_about_unresolvable_flags(unresolvable_flags) keys_by_reason = unresolvable_flags.keys.group_by { |key| unresolvable_flags[key].first } experience_continuity_keys = keys_by_reason[UnresolvedFlagReason::EXPERIENCE_CONTINUITY] if experience_continuity_keys logger.warn( "[FEATURE FLAGS] #{experience_continuity_keys.length} flag(s) have experience continuity enabled and " \ "can't be evaluated locally (reason: #{UnresolvedFlagReason::EXPERIENCE_CONTINUITY}): " \ "#{experience_continuity_keys.join(', ')}. Evaluating them makes a remote request, or leaves them " \ 'unresolved with only_evaluate_locally: true. To evaluate them locally, disable experience continuity ' \ 'on these flags in PostHog.' ) end unsupported_definition_keys = keys_by_reason[UnresolvedFlagReason::UNSUPPORTED_DEFINITION] return unless unsupported_definition_keys logger.warn( "[FEATURE FLAGS] #{unsupported_definition_keys.length} flag(s) use something local evaluation doesn't " \ 'support, such as a static cohort, an unknown operator or filter type, a malformed value, or a missing or ' \ "circular flag dependency (reason: #{UnresolvedFlagReason::UNSUPPORTED_DEFINITION}): " \ "#{unsupported_definition_keys.join(', ')}. Evaluating them makes a remote request when evaluation " \ 'reaches that part, or leaves them unresolved with only_evaluate_locally: true. To evaluate them ' \ 'locally, change these flags in PostHog or upgrade posthog-ruby.' ) end |
#condition_match(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, snapshot: _evaluation_snapshot) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1627 1628 1629 1630 1631 |
# File 'lib/posthog/feature_flags.rb', line 1627 def condition_match(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, snapshot: _evaluation_snapshot) condition_match_outcome(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties, snapshot: snapshot) == :match end |
#condition_match_outcome(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, snapshot: _evaluation_snapshot) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Evaluates a single condition group and returns a tri-state outcome:
:match - property filters matched AND the rollout included the user
:no_match - a property filter did NOT match
:out_of_rollout_bound - property filters matched (or there were none) but the
rollout percentage excluded the user
Distinguishing :no_match from :out_of_rollout_bound lets the caller implement the early_exit behavior (mirrors the server-side Rust evaluation engine).
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 |
# File 'lib/posthog/feature_flags.rb', line 1640 def condition_match_outcome(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, snapshot: _evaluation_snapshot) rollout_percentage = condition[:rollout_percentage] unless (condition[:properties] || []).empty? # Filters in a condition have no defined order, so an inconclusive filter does not stop the # loop: a later filter can still rule the condition out or carry a higher-precedence reason. inconclusive_reason = nil server_evaluation_error = nil condition[:properties].each do |prop| matches = if prop[:type] == 'flag' evaluate_flag_dependency(prop, evaluation_cache, distinct_id, properties, cohort_properties, snapshot: snapshot) else FeatureFlagsPoller.match_property(prop, properties, cohort_properties, property_matching_version: snapshot[:property_matching_version]) end return :no_match unless matches rescue RequiresServerEvaluation => e # Fall back to the server only when this is the first filter that could not be checked, as # when the loop stopped there. After another inconclusive filter, later conditions must still # be able to resolve the flag locally. server_evaluation_error ||= e if inconclusive_reason.nil? inconclusive_reason = FeatureFlagsPoller.pick_unresolved_reason(inconclusive_reason, e.reason) rescue InconclusiveMatchError => e inconclusive_reason = FeatureFlagsPoller.pick_unresolved_reason(inconclusive_reason, e.reason) rescue StandardError raise if inconclusive_reason.nil? # The condition is already inconclusive, so an unexpected error in a later filter must not # fail the whole flag. Later conditions can still resolve it. break end # Raise the original error type: match_feature_flag_properties stops at it and falls back to the # server instead of trying later conditions. A later filter can still carry a higher-precedence reason. unless server_evaluation_error.nil? raise RequiresServerEvaluation.new(server_evaluation_error., reason: inconclusive_reason) end unless inconclusive_reason.nil? raise InconclusiveMatchError.new("Can't determine if a condition of flag #{flag[:key]} matches", reason: inconclusive_reason) end return :match if rollout_percentage.nil? end if !rollout_percentage.nil? && (_hash(flag[:key], distinct_id) > (rollout_percentage.to_f / 100)) return :out_of_rollout_bound end :match end |
#definitions_loaded? ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Whether flag definitions are currently loaded. False until the first successful load, and false again if a quota-limited (402) response discards them.
133 134 135 |
# File 'lib/posthog/feature_flags.rb', line 133 def definitions_loaded? !@flag_definitions_loaded_at.value.nil? end |
#evaluate_flag_dependency(property, evaluation_cache, distinct_id, properties, cohort_properties, snapshot: _evaluation_snapshot) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Evaluates a flag dependency property according to the dependency chain algorithm.
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 |
# File 'lib/posthog/feature_flags.rb', line 1245 def evaluate_flag_dependency(property, evaluation_cache, distinct_id, properties, cohort_properties, snapshot: _evaluation_snapshot) if snapshot[:flags_by_key].nil? || evaluation_cache.nil? # Cannot evaluate flag dependencies without required context raise InconclusiveMatchError.new( "Cannot evaluate flag dependency on '#{property[:key] || 'unknown'}' " \ 'without feature flags loaded or evaluation_cache', reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION ) end # A dependency with no definition outranks one that is only inconclusive, so this checks the whole # chain before evaluating any of it. Nothing is cached for it, so a later lookup reports the same. definition_error = FeatureFlagsPoller.flag_dependency_definition_error(property, snapshot[:flags_by_key]) unless definition_error.nil? raise InconclusiveMatchError.new(definition_error, reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) end dependency_chain = property[:dependency_chain] # Evaluate all dependencies in the chain order dependency_chain.each do |dep_flag_key| unless evaluation_cache.key?(dep_flag_key) # Need to evaluate this dependency first dep_flag = snapshot[:flags_by_key][dep_flag_key] if !dep_flag[:active] # Check if the flag is active (same check as in _compute_flag_locally) evaluation_cache[dep_flag_key] = false elsif dep_flag[:ensure_experience_continuity] evaluation_cache[dep_flag_key] = nil raise InconclusiveMatchError.new( "Cannot evaluate flag dependency '#{dep_flag_key}' - flag has experience continuity enabled", reason: UnresolvedFlagReason::UNRESOLVED_DEPENDENCY ) else # Recursively evaluate the dependency using existing instance method begin dep_result = match_feature_flag_properties( dep_flag, distinct_id, properties, evaluation_cache, cohort_properties, snapshot: snapshot ) evaluation_cache[dep_flag_key] = dep_result rescue RequiresServerEvaluation => e # The dependent flag needs the server too. Nothing is cached, so a later lookup of this # dependency also requires the server instead of reading it as merely inconclusive. raise RequiresServerEvaluation.new("Cannot evaluate flag dependency '#{dep_flag_key}': #{e.}", reason: UnresolvedFlagReason::UNRESOLVED_DEPENDENCY) rescue InconclusiveMatchError => e # If we can't evaluate a dependency, store nil and propagate the error evaluation_cache[dep_flag_key] = nil raise InconclusiveMatchError.new("Cannot evaluate flag dependency '#{dep_flag_key}': #{e.}", reason: UnresolvedFlagReason::UNRESOLVED_DEPENDENCY) end end end # Check the cached result cached_result = evaluation_cache[dep_flag_key] if cached_result.nil? # Previously inconclusive - raise error again raise InconclusiveMatchError.new("Flag dependency '#{dep_flag_key}' was previously inconclusive", reason: UnresolvedFlagReason::UNRESOLVED_DEPENDENCY) elsif !cached_result # Definitive False result - dependency failed return false end end # Get the expected value of the immediate dependency and the actual value expected_value = property[:value] # The flag we want to evaluate is defined by :key which should ALSO be the last key in the dependency chain actual_value = evaluation_cache[property[:key]] self.class.matches_dependency_value(expected_value, actual_value) end |
#flag_definitions_loaded_at ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Epoch milliseconds of the last successful definitions load, or nil.
138 139 140 |
# File 'lib/posthog/feature_flags.rb', line 138 def flag_definitions_loaded_at @flag_definitions_loaded_at.value end |
#get_all_flags(distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/posthog/feature_flags.rb', line 338 def get_all_flags( distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false ) if @quota_limited.true? logger.debug 'Not fetching flags from server - quota limited' return {} end # returns a string hash of all flags response = get_all_flags_and_payloads( distinct_id, groups, person_properties, group_properties, only_evaluate_locally ) response[:featureFlags] end |
#get_all_flags_and_payloads(distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, raise_on_error = false) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/posthog/feature_flags.rb', line 362 def get_all_flags_and_payloads( distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, raise_on_error = false ) load_feature_flags snapshot = _evaluation_snapshot flags = {} payloads = {} fallback_to_server = snapshot[:flags].empty? request_id = nil # Only for /flags requests evaluated_at = nil # Only for /flags requests snapshot[:flags].each do |flag| match_value = _compute_flag_locally(flag, distinct_id, groups, person_properties, group_properties, snapshot: snapshot) flags[flag[:key]] = match_value match_payload = _compute_flag_payload_locally(flag[:key], match_value, snapshot: snapshot) payloads[flag[:key]] = match_payload if match_payload rescue RequiresServerEvaluation, InconclusiveMatchError fallback_to_server = true rescue StandardError => e @on_error.call(-1, "Error computing flag locally: #{e}. #{e.backtrace.join("\n")} ") fallback_to_server = true end errors_while_computing = false quota_limited = nil status_code = nil flag_details = nil minimal_flag_called_events = nil if fallback_to_server && !only_evaluate_locally begin flags_and_payloads = get_flags(distinct_id, groups, person_properties, group_properties) flag_details = flags_and_payloads[:flags] errors_while_computing = flags_and_payloads[:errorsWhileComputingFlags] || false quota_limited = flags_and_payloads[:quotaLimited] status_code = flags_and_payloads[:status] unless flags_and_payloads.key?(:featureFlags) raise StandardError, "Error flags response: #{flags_and_payloads}" end request_id = flags_and_payloads[:requestId] evaluated_at = flags_and_payloads[:evaluatedAt] minimal_flag_called_events = flags_and_payloads[:minimalFlagCalledEvents] # Check if feature_flags are quota limited if quota_limited&.include?('feature_flags') logger.warn '[FEATURE FLAGS] Quota limited for feature flags' flags = {} payloads = {} else server_flags = stringify_keys(flags_and_payloads[:featureFlags] || {}) server_payloads = stringify_keys(flags_and_payloads[:featureFlagPayloads] || {}) if errors_while_computing # Merge server results into locally-evaluated results so that flags which # failed server-side evaluation (already filtered out by get_flags) don't # overwrite valid locally-evaluated values. flags = stringify_keys(flags).merge(server_flags) payloads = stringify_keys(payloads).merge(server_payloads) else # A failed record must preserve a successful same-context local pair, # independently of the response-wide error bit. failed_keys = (flag_details || {}).select { |_, flag| flag.failed == true }.keys.map(&:to_s) flags = stringify_keys(flags).slice(*failed_keys).merge(server_flags) payloads = stringify_keys(payloads).slice(*failed_keys).merge(server_payloads) end end rescue StandardError => e @on_error.call(-1, "Error computing flag remotely: #{e}") raise if raise_on_error end end { featureFlags: flags, featureFlagPayloads: payloads, flagDetails: flag_details, requestId: request_id, evaluatedAt: evaluated_at, errorsWhileComputingFlags: errors_while_computing, quotaLimited: quota_limited, status: status_code, minimalFlagCalledEvents: minimal_flag_called_events } end |
#get_feature_flag(key, distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, snapshot: nil) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
# File 'lib/posthog/feature_flags.rb', line 237 def get_feature_flag( key, distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, snapshot: nil ) key = key.to_s # make sure they're loaded on first run load_feature_flags snapshot ||= _evaluation_snapshot response = nil payload = nil feature_flag = snapshot[:flags_by_key]&.[](key) unless feature_flag.nil? begin response = _compute_flag_locally(feature_flag, distinct_id, groups, person_properties, group_properties, snapshot: snapshot) payload = _compute_flag_payload_locally(key, response, snapshot: snapshot) unless response.nil? logger.debug "Successfully computed flag locally: #{key} -> #{response}" rescue RequiresServerEvaluation, InconclusiveMatchError => e logger.debug "Failed to compute flag #{key} locally: #{e}" rescue StandardError => e @on_error.call(-1, "Error computing flag locally: #{e}. #{e.backtrace.join("\n")}") end end flag_was_locally_evaluated = !response.nil? # Whether the flag is linked to an experiment, as reported by the server. # Locally-evaluated flags carry it in the stored definition; remotely # evaluated flags carry it in the response metadata. nil when the server # (an older deployment) does not report it. has_experiment = feature_flag[:has_experiment] if flag_was_locally_evaluated # Server-controlled gate for minimal `$feature_flag_called` events. # Locally-evaluated flags read it from the definitions payload; remotely # evaluated flags read it from the /flags response. nil when the signal # is unavailable, which fails safe to the full event. minimal_flag_called_events = snapshot[:minimal_flag_called_events] if flag_was_locally_evaluated request_id = nil evaluated_at = nil feature_flag_error = nil if !flag_was_locally_evaluated && !only_evaluate_locally begin errors = [] flags_data = get_all_flags_and_payloads(distinct_id, groups, person_properties, group_properties, only_evaluate_locally, true) if flags_data.key?(:featureFlags) flags = stringify_keys(flags_data[:featureFlags] || {}) payloads = stringify_keys(flags_data[:featureFlagPayloads] || {}) request_id = flags_data[:requestId] evaluated_at = flags_data[:evaluatedAt] else logger.debug "Missing feature flags key: #{flags_data.to_json}" flags = {} payloads = {} end status = flags_data[:status] errors << FeatureFlagError.api_error(status) if status && status >= 400 errors << FeatureFlagError::ERRORS_WHILE_COMPUTING if flags_data[:errorsWhileComputingFlags] errors << FeatureFlagError::QUOTA_LIMITED if flags_data[:quotaLimited]&.include?('feature_flags') flag_detail = flags_data[:flagDetails]&.[](key.to_sym) failed = flag_detail&.failed == true && !flags.key?(key) if failed errors << FeatureFlagError::EVALUATION_FAILED elsif !flags.key?(key) errors << FeatureFlagError::FLAG_MISSING end response = flags[key] response = false if response.nil? && !failed payload = payloads[key] feature_flag_error = errors.join(',') unless errors.empty? has_experiment = flag_detail&.&.has_experiment minimal_flag_called_events = flags_data[:minimalFlagCalledEvents] logger.debug "Successfully computed flag remotely: #{key} -> #{response}" rescue Timeout::Error => e @on_error.call(-1, "Timeout while fetching flags remotely: #{e}") feature_flag_error = FeatureFlagError::TIMEOUT rescue Errno::ECONNRESET, Errno::ECONNREFUSED, EOFError, SocketError => e @on_error.call(-1, "Connection error while fetching flags remotely: #{e}") feature_flag_error = FeatureFlagError::CONNECTION_ERROR rescue StandardError => e @on_error.call(-1, "Error computing flag remotely: #{e}. #{e.backtrace.join("\n")}") feature_flag_error = FeatureFlagError::UNKNOWN_ERROR end end [response, flag_was_locally_evaluated, request_id, evaluated_at, feature_flag_error, payload, has_experiment, minimal_flag_called_events] end |
#get_feature_flag_payload(key, distinct_id, match_value = nil, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
# File 'lib/posthog/feature_flags.rb', line 456 def get_feature_flag_payload( key, distinct_id, match_value = nil, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false ) key = key.to_s load_feature_flags snapshot = _evaluation_snapshot if match_value.nil? match_value = get_feature_flag( key, distinct_id, groups, person_properties, group_properties, true, snapshot: snapshot )[0] end response = nil response = _compute_flag_payload_locally(key, match_value, snapshot: snapshot) unless match_value.nil? if response.nil? && !only_evaluate_locally flags_payloads = get_feature_payloads(distinct_id, groups, person_properties, group_properties) response = flags_payloads[key.downcase] || nil end response end |
#get_feature_payloads(distinct_id, groups = {}, person_properties = {}, group_properties = {}, _only_evaluate_locally = false) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/posthog/feature_flags.rb', line 173 def get_feature_payloads( distinct_id, groups = {}, person_properties = {}, group_properties = {}, _only_evaluate_locally = false ) flags_data = get_all_flags_and_payloads( distinct_id, groups, person_properties, group_properties ) if flags_data.key?(:featureFlagPayloads) stringify_keys(flags_data[:featureFlagPayloads] || {}) else logger.debug "Missing feature flag payloads key: #{flags_data.to_json}" {} end end |
#get_feature_variants(distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, raise_on_error = false) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/posthog/feature_flags.rb', line 144 def get_feature_variants( distinct_id, groups = {}, person_properties = {}, group_properties = {}, only_evaluate_locally = false, raise_on_error = false ) groups, person_properties, group_properties = normalize_flag_evaluation_inputs( groups, person_properties, group_properties ) # TODO: Convert to options hash for easier argument passing flags_data = get_all_flags_and_payloads( distinct_id, groups, person_properties, group_properties, only_evaluate_locally, raise_on_error ) if flags_data.key?(:featureFlags) stringify_keys(flags_data[:featureFlags] || {}) else logger.debug "Missing feature flags key: #{flags_data.to_json}" {} end end |
#get_flags(distinct_id, groups = {}, person_properties = {}, group_properties = {}, flag_keys = nil, disable_geoip = nil) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/posthog/feature_flags.rb', line 195 def get_flags(distinct_id, groups = {}, person_properties = {}, group_properties = {}, flag_keys = nil, disable_geoip = nil) flag_keys = flag_keys.map(&:to_s) if flag_keys.is_a?(Array) request_data = { distinct_id: distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties } request_data[:flag_keys_to_evaluate] = flag_keys if flag_keys && !flag_keys.empty? # The flags endpoint treats an omitted/null value as false; serialize that same default explicitly. request_data[:geoip_disable] = disable_geoip.nil? ? false : disable_geoip flags_response = _request_feature_flag_evaluation(request_data) # Only normalize if we have flags in the response if flags_response[:flags] # v4 format flags_hash = flags_response[:flags].transform_values do |flag| FeatureFlag.new(flag) end flags_response[:flags] = flags_hash # Filter out flags that failed evaluation to avoid overwriting cached values successful_flags = flags_hash.reject { |_, flag| flag.failed == true } flags_response[:featureFlags] = successful_flags.transform_values(&:get_value).transform_keys(&:to_sym) flags_response[:featureFlagPayloads] = successful_flags.transform_values(&:payload).transform_keys(&:to_sym) elsif flags_response[:featureFlags] # v3 format flags_response[:featureFlags] = flags_response[:featureFlags] || {} flags_response[:featureFlagPayloads] = flags_response[:featureFlagPayloads] || {} flags_response[:flags] = flags_response[:featureFlags].to_h do |key, value| [key, FeatureFlag.from_value_and_payload(key, value, flags_response[:featureFlagPayloads][key])] end end flags_response end |
#get_matching_variant(flag, distinct_id) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1734 1735 1736 1737 1738 1739 1740 |
# File 'lib/posthog/feature_flags.rb', line 1734 def get_matching_variant(flag, distinct_id) hash_value = _hash(flag[:key], distinct_id, 'variant') matching_variant = variant_lookup_table(flag).find do |variant| hash_value >= variant[:value_min] and hash_value < variant[:value_max] end matching_variant.nil? ? nil : matching_variant[:key] end |
#get_remote_config_payload(flag_key) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
233 234 235 |
# File 'lib/posthog/feature_flags.rb', line 233 def get_remote_config_payload(flag_key) _request_remote_config_payload(flag_key.to_s) end |
#holdout_variant_for(holdout, bucketing_value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
An experiment holdout excludes an identifier from the flag's release conditions
entirely, resolving it to the synthetic variant "holdout-filters.multivariate.variants. Returns nil when the flag has
no usable holdout or the identifier falls outside it, leaving ordinary evaluation
unchanged.
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 |
# File 'lib/posthog/feature_flags.rb', line 1709 def holdout_variant_for(holdout, bucketing_value) return nil unless holdout.is_a?(Hash) id = holdout[:id] exclusion_percentage = holdout[:exclusion_percentage] return nil if id.nil? || !exclusion_percentage.is_a?(Numeric) # The server clamps an out-of-range percentage rather than rejecting it, and treats # 100 as everyone without hashing, so a full holdout can't miss on a hash boundary. # Fractional percentages are kept as-is. percentage = exclusion_percentage.to_f.clamp(0, 100) return nil if percentage < 100 && _holdout_hash(bucketing_value) > (percentage / 100) "holdout-#{id}" end |
#load_feature_flags(force_reload = false) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
124 125 126 127 128 |
# File 'lib/posthog/feature_flags.rb', line 124 def load_feature_flags(force_reload = false) return if (@loaded_flags_successfully_once.true? || @async_load) && !force_reload _load_feature_flags end |
#match_feature_flag_properties(flag, distinct_id, properties, evaluation_cache, cohort_properties = {}, groups: {}, group_properties: {}, snapshot: _evaluation_snapshot) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 |
# File 'lib/posthog/feature_flags.rb', line 1527 def match_feature_flag_properties(flag, distinct_id, properties, evaluation_cache, cohort_properties = {}, groups: {}, group_properties: {}, snapshot: _evaluation_snapshot) flag_filters = flag[:filters] || {} # Holdouts precede release conditions: a held-out identifier is excluded from # the flag's targeting entirely rather than bucketed into one of its variants. # The per-condition aggregation handled below never changes holdout membership, # so this uses the flag-level bucketing identity the caller resolved. holdout_variant = holdout_variant_for(flag_filters[:holdout], distinct_id) return holdout_variant unless holdout_variant.nil? flag_conditions = flag_filters[:groups] || [] flag_aggregation = flag_filters[:aggregation_group_type_index] early_exit = flag_filters[:early_exit] == true inconclusive_reason = nil result = nil # NOTE: This NEEDS to be `each` because `each_key` breaks flag_conditions.each do |condition| # Per-condition aggregation overrides only when the condition explicitly # sets its own aggregation_group_type_index (mixed targeting). When absent, # use the properties/bucketing already resolved by the caller. condition_aggregation = condition.fetch(:aggregation_group_type_index, flag_aggregation) effective_properties = properties effective_bucketing = distinct_id # Mixed-override path: condition-level aggregation differs from flag-level. # This assumes flag-level aggregation is nil for mixed flags. if condition_aggregation != flag_aggregation if condition_aggregation.nil? # Person condition under a mixed flag — caller already passed person props/bucketing. else group_name = snapshot[:group_type_mapping][condition_aggregation.to_s.to_sym] if group_name.nil? || !groups.key?(group_name.to_sym) logger.debug do "[FEATURE FLAGS] Skipping group condition for flag '#{flag[:key]}': " \ "group type index #{condition_aggregation} not available" end next end unless group_properties.key?(group_name.to_sym) inconclusive_reason = FeatureFlagsPoller.pick_unresolved_reason( inconclusive_reason, UnresolvedFlagReason::MISSING_CONTEXT ) next end effective_properties = group_properties[group_name.to_sym] effective_bucketing = groups[group_name.to_sym] end end case condition_match_outcome(flag, effective_bucketing, condition, effective_properties, evaluation_cache, cohort_properties, snapshot: snapshot) when :match variant_override = condition[:variant] flag_multivariate = flag_filters[:multivariate] || {} flag_variants = flag_multivariate[:variants] || [] variant = if flag_variants.map { |variant| variant[:key] }.include?(condition[:variant]) variant_override else get_matching_variant(flag, effective_bucketing) end result = variant || true break when :out_of_rollout_bound break if early_exit end rescue RequiresServerEvaluation => e # Static cohort or other missing server-side data - must fallback to API. Evaluation stops here and # skips filters it did not reach, so the flag's definition still counts toward the reason. reason = FeatureFlagsPoller.pick_unresolved_reason(inconclusive_reason, e.reason) definition_reason = _definition_unresolved_reason(flag, snapshot) reason = FeatureFlagsPoller.pick_unresolved_reason(reason, definition_reason) unless definition_reason.nil? raise RequiresServerEvaluation.new(e., reason: reason) rescue InconclusiveMatchError => e # Evaluation error (bad regex, invalid date, missing property, etc.) # Track that we had an inconclusive match, but try other conditions inconclusive_reason = FeatureFlagsPoller.pick_unresolved_reason(inconclusive_reason, e.reason) end if !result.nil? return result elsif !inconclusive_reason.nil? raise InconclusiveMatchError.new("Can't determine if feature flag is enabled or not with given properties", reason: inconclusive_reason) end # We can only return False when all conditions are False false end |
#shutdown_poller ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
489 490 491 492 493 494 495 496 497 498 |
# File 'lib/posthog/feature_flags.rb', line 489 def shutdown_poller @task.shutdown return unless @flag_definition_cache_provider begin @flag_definition_cache_provider.shutdown rescue StandardError => e logger.error("[FEATURE FLAGS] Cache provider shutdown error: #{e}") end end |
#variant_lookup_table(flag) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 |
# File 'lib/posthog/feature_flags.rb', line 1742 def variant_lookup_table(flag) lookup_table = [] value_min = 0 flag_filters = flag[:filters] || {} variants = flag_filters[:multivariate] || {} multivariates = variants[:variants] || [] multivariates.each do |variant| value_max = value_min + (variant[:rollout_percentage].to_f / 100) lookup_table << { value_min: value_min, value_max: value_max, key: variant[:key] } value_min = value_max end lookup_table end |