Class: PostHog::Client
- Inherits:
-
Object
- Object
- PostHog::Client
- Defined in:
- lib/posthog/client.rb
Direct Known Subclasses
Constant Summary
Constants included from Utils
Utils::UTC_OFFSET_WITHOUT_COLON, Utils::UTC_OFFSET_WITH_COLON
Instance Attribute Summary collapse
-
#emails ⇒ PostHog::Emails
readonly
Sends transactional email from email templates made in PostHog or from content your code rendered, and reads the status of each email sent.
Class Method Summary collapse
- ._decrement_instance_count(api_key) ⇒ Object
- ._increment_instance_count(api_key) ⇒ Object
-
.reset_instance_tracking! ⇒ Object
Resets instance tracking.
Instance Method Summary collapse
-
#alias(attrs) ⇒ Boolean
Aliases a user from one id to another.
-
#capture(attrs) ⇒ Boolean
Captures an event.
-
#capture_exception(exception, distinct_id = nil, additional_properties = {}, flags: nil, mechanism: nil) ⇒ Boolean?
Captures an exception as an event.
-
#clear ⇒ void
Clears the queue without waiting.
-
#dequeue_last_message ⇒ Hash
Pops the last message from the queue.
-
#enabled? ⇒ Boolean
Whether the client will actually send events.
-
#evaluate_flags(distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, disable_geoip: nil, flag_keys: nil) ⇒ PostHog::FeatureFlagEvaluations
Evaluate feature flags for a distinct id and return a snapshot.
-
#feature_flags_loaded? ⇒ Boolean
Whether feature flag definitions for local evaluation are currently loaded.
-
#flush(timeout: nil) ⇒ Boolean
When sync_mode is enabled, waits until any in-flight request completes or timeout is hit.
-
#get_all_flags(distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false) ⇒ Hash
Returns all flags for a given user.
-
#get_all_flags_and_payloads(distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false) ⇒ Hash
Returns all flags and payloads for a given user.
-
#get_feature_flag(key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true) ⇒ String, ...
deprecated
Deprecated.
Use #evaluate_flags and FeatureFlagEvaluations#get_flag instead.
-
#get_feature_flag_payload(key, distinct_id, match_value: nil, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false) ⇒ Object?
deprecated
Deprecated.
Use #get_feature_flag_result instead, which returns both the flag value and payload and properly raises the $feature_flag_called event.
- #get_feature_flag_result(key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true) ⇒ PostHog::FeatureFlagResult? deprecated Deprecated.
-
#get_remote_config_payload(flag_key) ⇒ Hash
The parsed remote config payload response.
-
#group_identify(attrs) ⇒ Boolean
Identifies a group.
-
#identify(attrs) ⇒ Boolean
Identifies a user.
-
#initialize(opts = {}) ⇒ Client
constructor
A new instance of Client.
-
#is_feature_enabled(flag_key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true) ⇒ Boolean?
deprecated
Deprecated.
Use #evaluate_flags and FeatureFlagEvaluations#enabled? instead.
-
#queued_messages ⇒ Integer
Number of messages in the queue.
-
#reload_feature_flags ⇒ void
Reload locally cached feature flag definitions synchronously on the calling thread.
-
#shutdown(timeout: nil) ⇒ Boolean
Flush pending events and stop background resources.
Methods included from Logging
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
Constructor Details
#initialize(opts = {}) ⇒ Client
Returns a new instance of Client.
142 143 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/posthog/client.rb', line 142 def initialize(opts = {}) symbolize_keys!(opts) opts[:api_key] = normalize_string_option(opts[:api_key]) opts[:secret_key] = normalize_string_option(opts[:secret_key], blank_as_nil: true) opts[:personal_api_key] = normalize_string_option(opts[:personal_api_key], blank_as_nil: true) opts[:host] = normalize_host_option(opts[:host]) if opts[:secret_key].nil? && !opts[:personal_api_key].nil? logger.warn( 'The :personal_api_key option is deprecated; use :secret_key instead. It accepts either a ' \ 'Personal API Key (phx_...) or a Project Secret API Key (phs_...).' ) end secret_key = opts[:secret_key] || opts[:personal_api_key] @queue = Queue.new @queue_mutex = Mutex.new @api_key = opts[:api_key] @disabled = @api_key.nil? || @api_key.empty? @max_queue_size = opts[:max_queue_size] || Defaults::Queue::MAX_SIZE @lib = opts[:_lib] || 'posthog-ruby' @lib_version = (opts[:_lib_version] || PostHog::VERSION).to_s @headers = Defaults::Request::HEADERS.merge('User-Agent' => "#{@lib}/#{@lib_version}") # Built before the worker, the instance count and the flags poller start, so a bad email option raises # before anything runs or sends the secret key. @emails = Emails.new( secret_key: secret_key, host: opts[:host], app_host: opts[:app_host], timeout: opts[:email_request_timeout_seconds] || Defaults::Emails::REQUEST_TIMEOUT_SECONDS, max_retries: opts[:email_request_max_retries] || Defaults::Emails::REQUEST_MAX_RETRIES, migrated_from: opts[:migrated_from], user_agent: @headers['User-Agent'], disabled: @disabled, skip_ssl_verification: opts[:skip_ssl_verification] == true ) @worker_mutex = Mutex.new @shutdown_mutex = Mutex.new @shutdown_condition = ConditionVariable.new @shutdown = false @shutdown_complete = false @shutdown_result = false @sync_mode = opts[:sync_mode] == true && !opts[:test_mode] && !@disabled @on_error = opts[:on_error] || proc { |status, error| } @worker = if opts[:test_mode] || @disabled NoopWorker.new(@queue) elsif @sync_mode nil else SendWorker.new(@queue, @api_key, opts.merge(headers: @headers)) end if @sync_mode @transport = Transport.new( api_host: opts[:host], headers: @headers, skip_ssl_verification: opts[:skip_ssl_verification], retries: opts.key?(:max_retries) ? opts[:max_retries].to_i + 1 : 3, compress_request: opts[:compress_request] ) @sync_lock = Mutex.new end @worker_thread = nil @feature_flags_poller = nil @secret_key = secret_key @personal_api_key = secret_key @flag_definition_cache_provider = opts[:flag_definition_cache_provider] if @disabled && !opts[:silence_disabled_client_error] logger.error('api_key is missing or empty after trimming whitespace; check your project API key') end # Warn when multiple clients are created with the same API key (can cause dropped events) unless @disabled || opts[:test_mode] || opts[:disable_singleton_warning] previous_count = PostHog::Client._increment_instance_count(@api_key) @instance_registered = true if previous_count >= 1 logger.warn( 'Multiple PostHog client instances detected for the same API key. ' \ 'This can cause dropped events and inconsistent behavior. ' \ 'Use a singleton pattern: instantiate once and reuse the client. ' \ 'See https://posthog.com/docs/libraries/ruby' ) end end # Initialize tracking before the poller can load definitions (including async loads). @distinct_id_has_sent_flag_calls_mutex = Mutex.new @distinct_id_has_sent_flag_calls = SizeLimitedHash.new(Defaults::MAX_HASH_SIZE) do |hash, key| hash[key] = SizeLimitedArray.new(Defaults::MAX_HASH_SIZE) end unless @disabled @feature_flags_poller = FeatureFlagsPoller.new( opts[:feature_flags_polling_interval], secret_key, @api_key, opts[:host], opts[:feature_flag_request_timeout_seconds] || Defaults::FeatureFlags::FLAG_REQUEST_TIMEOUT_SECONDS, opts[:on_error], flag_definition_cache_provider: @flag_definition_cache_provider, feature_flag_request_max_retries: opts[:feature_flag_request_max_retries], async_load: opts[:feature_flags_async_load] == true, user_agent: @headers['User-Agent'], flag_definitions_update_mutex: @distinct_id_has_sent_flag_calls_mutex, on_flag_definitions_updated: -> { @distinct_id_has_sent_flag_calls.clear } ) end @before_send = opts[:before_send] @is_server = opts.fetch(:is_server, true) != false @release_id = normalize_string_option(ENV.fetch(RELEASE_ID_ENV_VAR, nil), blank_as_nil: true) @deprecation_emitted_for = Concurrent::Set.new end |
Instance Attribute Details
#emails ⇒ PostHog::Emails (readonly)
Sends transactional email from email templates made in PostHog or from content your code rendered, and reads
the status of each email sent. Needs :secret_key, a project secret API key with the
transactional_email:write scope.
263 264 265 |
# File 'lib/posthog/client.rb', line 263 def emails @emails end |
Class Method Details
._decrement_instance_count(api_key) ⇒ Object
82 83 84 85 86 87 |
# File 'lib/posthog/client.rb', line 82 def _decrement_instance_count(api_key) @instances_mutex.synchronize do count = (@instances_by_api_key[api_key] || 1) - 1 @instances_by_api_key[api_key] = [count, 0].max end end |
._increment_instance_count(api_key) ⇒ Object
74 75 76 77 78 79 80 |
# File 'lib/posthog/client.rb', line 74 def _increment_instance_count(api_key) @instances_mutex.synchronize do count = @instances_by_api_key[api_key] || 0 @instances_by_api_key[api_key] = count + 1 count end end |
.reset_instance_tracking! ⇒ Object
Resets instance tracking. Used primarily for testing. In production, instance counts persist for the lifetime of the process.
68 69 70 71 72 |
# File 'lib/posthog/client.rb', line 68 def reset_instance_tracking! @instances_mutex.synchronize do @instances_by_api_key = {} end end |
Instance Method Details
#alias(attrs) ⇒ Boolean
Aliases a user from one id to another
506 507 508 509 510 511 512 513 514 |
# File 'lib/posthog/client.rb', line 506 def alias(attrs) return false if @disabled symbolize_keys! attrs attrs[:is_server] = @is_server attrs[:lib] = @lib attrs[:lib_version] = @lib_version enqueue(FieldParser.parse_for_alias(attrs)) end |
#capture(attrs) ⇒ Boolean
If :distinct_id is omitted, request/context distinct_id is used when
available; otherwise a UUID is generated and the event is marked personless
with $process_person_profile: false.
Captures an event
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 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 |
# File 'lib/posthog/client.rb', line 337 def capture(attrs) return false if @disabled symbolize_keys! attrs minimal_flag_called_event = attrs.delete(:_minimal_flag_called_event) == true # Integrations that ride on a host application's client (e.g. PostHog::MCP) # may relabel a single event's `$lib`/`$lib_version` without relabeling the # client or its User-Agent. lib_override = attrs.delete(:_lib) lib_version_override = attrs.delete(:_lib_version) enrich_capture_attrs_with_context(attrs) # Precedence: an explicit `flags` snapshot always wins, regardless of # `send_feature_flags`. The snapshot guarantees the event carries the same # values the developer branched on with no additional network call. if attrs[:flags] if attrs[:flags].is_a?(FeatureFlagEvaluations) if attrs[:send_feature_flags] logger.warn( '[FEATURE FLAGS] Both `flags` and `send_feature_flags` were passed to ' \ 'capture(); using `flags` and ignoring `send_feature_flags`.' ) end snapshot_props = attrs[:flags]._get_event_properties attrs[:properties] = snapshot_props.merge(attrs[:properties] || {}) attrs.delete(:flags) attrs.delete(:send_feature_flags) else logger.warn( '[FEATURE FLAGS] capture(flags:) expects a PostHog::FeatureFlagEvaluations snapshot ' \ "from `client.evaluate_flags(...)`; got #{attrs[:flags].class}. Ignoring." ) attrs.delete(:flags) end end send_feature_flags_param = attrs[:send_feature_flags] if send_feature_flags_param && !@disabled _emit_deprecation( :capture_send_feature_flags, '`send_feature_flags` on `capture` is deprecated and will be removed in a future major ' \ 'version. Pass a `flags` snapshot from `client.evaluate_flags(...)` instead — it ' \ 'avoids a second `/flags` request per capture and guarantees the event carries the ' \ 'exact flag values your code branched on.' ) # Handle different types of send_feature_flags parameter case send_feature_flags_param when true # Backward compatibility: simple boolean feature_variants = @feature_flags_poller.get_feature_variants(attrs[:distinct_id], attrs[:groups] || {}) when Hash # Hash with options = SendFeatureFlagsOptions.from_hash(send_feature_flags_param) feature_variants = @feature_flags_poller.get_feature_variants( attrs[:distinct_id], attrs[:groups] || {}, ? .person_properties : {}, ? .group_properties : {}, ? .only_evaluate_locally : false ) when SendFeatureFlagsOptions # SendFeatureFlagsOptions object feature_variants = @feature_flags_poller.get_feature_variants( attrs[:distinct_id], attrs[:groups] || {}, send_feature_flags_param.person_properties, send_feature_flags_param.group_properties, send_feature_flags_param.only_evaluate_locally || false ) else # Invalid type, treat as false feature_variants = nil end attrs[:feature_variants] = feature_variants if feature_variants end attrs[:is_server] = @is_server attrs[:lib] = lib_override || @lib attrs[:lib_version] = (lib_version_override || @lib_version).to_s = FieldParser.parse_for_capture(attrs) # Minimal events are built from the allowlist after full assembly so # context properties and parser-added metadata can never leak in. if minimal_flag_called_event [:properties] = [:properties].slice(*MINIMAL_FLAG_CALLED_EVENT_PROPERTIES) end enqueue() end |
#capture_exception(exception, distinct_id = nil, additional_properties = {}, flags: nil, mechanism: nil) ⇒ Boolean?
Captures an exception as an event
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 |
# File 'lib/posthog/client.rb', line 439 def capture_exception(exception, distinct_id = nil, additional_properties = {}, flags: nil, mechanism: nil) return false if @disabled || exception_captured?(exception) exception_list = ExceptionCapture.build_exception_list(exception, mechanism: mechanism) return if exception_list.nil? properties = { '$exception_list' => exception_list }.merge(active_trace_properties) properties.merge!(additional_properties) if additional_properties && !additional_properties.empty? event_data = { distinct_id: distinct_id, event: '$exception', properties: properties, timestamp: Time.now } event_data[:flags] = flags if flags capture(event_data).tap do |captured| mark_exception_captured(exception) if captured end end |
#clear ⇒ void
This method returns an undefined value.
Clears the queue without waiting.
Use only in test mode.
301 302 303 |
# File 'lib/posthog/client.rb', line 301 def clear @queue_mutex.synchronize { @queue.clear } end |
#dequeue_last_message ⇒ Hash
Returns Pops the last message from the queue. Intended for test mode.
517 518 519 |
# File 'lib/posthog/client.rb', line 517 def @queue.pop end |
#enabled? ⇒ Boolean
Whether the client will actually send events. It is disabled when the api_key is missing or blank, in which case every capture call no-ops.
951 952 953 |
# File 'lib/posthog/client.rb', line 951 def enabled? !@disabled end |
#evaluate_flags(distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, disable_geoip: nil, flag_keys: nil) ⇒ PostHog::FeatureFlagEvaluations
Evaluate feature flags for a distinct id and return a snapshot.
The returned FeatureFlagEvaluations can be queried with
is_enabled / get_flag / get_flag_payload, narrowed with
only_accessed / only, and passed to #capture via the flags: option
to attach $feature/<key> and $active_feature_flags without an extra
/flags request.
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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 |
# File 'lib/posthog/client.rb', line 675 def evaluate_flags( distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, disable_geoip: nil, flag_keys: nil ) host = _feature_flag_evaluations_host if distinct_id.nil? || distinct_id.to_s.empty? return FeatureFlagEvaluations.new(host: host, distinct_id: '', flags: {}) end return FeatureFlagEvaluations.new(host: host, distinct_id: distinct_id, flags: {}, groups: groups) if @disabled if flag_keys && flag_keys.empty? return FeatureFlagEvaluations.new( host: host, distinct_id: distinct_id, flags: {}, groups: groups, disable_geoip: disable_geoip ) end groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) records = {} locally_evaluated_keys = Set.new unresolved_flags = {} flag_keys_set = flag_keys&.to_set(&:to_s) @feature_flags_poller.load_feature_flags definition_snapshot = @feature_flags_poller._evaluation_snapshot poller_flags_by_key = definition_snapshot[:flags_by_key] || {} poller_flags_by_key.each do |key, definition| next if flag_keys_set && !flag_keys_set.include?(key.to_s) begin match = @feature_flags_poller.send( :_compute_flag_locally, definition, distinct_id, groups, person_properties, group_properties, snapshot: definition_snapshot ) rescue PostHog::RequiresServerEvaluation, PostHog::InconclusiveMatchError => e unresolved_flags[key.to_s] = e.reason next rescue StandardError next end next if match.nil? records[key.to_s] = FeatureFlagEvaluations::EvaluatedFlagRecord.new( key: key.to_s, enabled: match.is_a?(String) || (match ? true : false), variant: match.is_a?(String) ? match : nil, payload: FeatureFlagResult.parse_payload( @feature_flags_poller.send(:_compute_flag_payload_locally, key, match, snapshot: definition_snapshot) ), id: definition[:id], version: nil, reason: FeatureFlagEvaluations::EVALUATED_LOCALLY_REASON, locally_evaluated: true, has_experiment: definition[:has_experiment] ) locally_evaluated_keys << key.to_s end request_id = nil evaluated_at = nil errors_while_computing = false quota_limited = false # Server-controlled gate for minimal `$feature_flag_called` events. When # the snapshot uses a remote /flags response, the response's top-level # `minimalFlagCalledEvents` field governs; a local-only snapshot reads # the gate polled with the flag definitions. minimal_flag_called_events = definition_snapshot[:minimal_flag_called_events] # Skip the remote `/flags` round-trip when the caller scoped the request # to a fixed set of `flag_keys` and we've already resolved every one of # them locally. Without `flag_keys` set, we can't know whether the server # has flags we don't have definitions for, so we still hit `/flags`. all_requested_flags_resolved_locally = flag_keys_set && (flag_keys_set - locally_evaluated_keys).empty? if !only_evaluate_locally && !all_requested_flags_resolved_locally # The gate is team-level, so the /flags response gate supersedes the # poller gate for mixed snapshots — both signals come from the same # server and agree in steady state. When the response omits the gate, # the whole snapshot fails safe to full events. minimal_flag_called_events = false begin flags_response = @feature_flags_poller.get_flags( distinct_id, groups, person_properties, group_properties, flag_keys, disable_geoip ) minimal_flag_called_events = flags_response[:minimalFlagCalledEvents] == true request_id = flags_response[:requestId] evaluated_at = flags_response[:evaluatedAt] errors_while_computing = flags_response[:errorsWhileComputingFlags] == true quota_limited = (flags_response[:quotaLimited] || []).include?('feature_flags') remote_flags = flags_response[:flags] || {} remote_flags.each do |key, ff| key_str = key.to_s next if locally_evaluated_keys.include?(key_str) = ff. reason = ff.reason enabled = ff.enabled ? true : false # nil marks no evaluated value; retain the record only for failure diagnostics. enabled = nil if ff.failed == true records[key_str] = FeatureFlagEvaluations::EvaluatedFlagRecord.new( key: key_str, enabled: enabled, variant: ff.failed == true ? nil : ff.variant, payload: ff.failed == true ? nil : FeatureFlagResult.parse_payload(ff.payload), id: &.id, version: &.version, reason: reason ? (reason.description || reason.code) : nil, locally_evaluated: false, has_experiment: &.has_experiment ) end rescue StandardError => e @on_error&.call(-1, "Error evaluating flags remotely: #{e}") end end FeatureFlagEvaluations.new( host: host, distinct_id: distinct_id, flags: records, groups: groups, disable_geoip: disable_geoip, request_id: request_id, evaluated_at: evaluated_at, flag_definitions_loaded_at: @feature_flags_poller.flag_definitions_loaded_at, errors_while_computing: errors_while_computing, quota_limited: quota_limited, minimal_flag_called_events: minimal_flag_called_events, unresolved_flags: unresolved_flags.reject { |key, _reason| records.key?(key) && !records[key].enabled.nil? } ) end |
#feature_flags_loaded? ⇒ Boolean
Whether feature flag definitions for local evaluation are currently loaded. False until the first successful load, and false again if a quota-limited (402) response discards the definitions.
941 942 943 944 945 |
# File 'lib/posthog/client.rb', line 941 def feature_flags_loaded? return false if @disabled @feature_flags_poller.definitions_loaded? end |
#flush(timeout: nil) ⇒ Boolean
When sync_mode is enabled, waits until any in-flight request completes or timeout is hit.
Otherwise, waits until the worker has cleared the queue or timeout is hit. Note: The asynchronous wait polls and can be starved if another thread is actively continuing to enqueue new events.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
# File 'lib/posthog/client.rb', line 276 def flush(timeout: nil) deadline = timeout && (monotonic_time + timeout) return synchronized_within?(deadline) {} if @sync_mode # rubocop:disable Lint/EmptyBlock if @worker.is_a?(NoopWorker) clear return true end while !@queue.empty? || @worker.is_requesting? ensure_worker_running @worker.request_flush remaining = deadline && (deadline - monotonic_time) return false if remaining && remaining <= 0 sleep(remaining ? remaining.clamp(0, 0.1) : 0.1) end true end |
#get_all_flags(distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false) ⇒ Hash
Returns all flags for a given user
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 |
# File 'lib/posthog/client.rb', line 827 def get_all_flags( distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false ) return {} if @disabled groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) @feature_flags_poller.get_all_flags(distinct_id, groups, person_properties, group_properties, only_evaluate_locally) end |
#get_all_flags_and_payloads(distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false) ⇒ Hash
Returns all flags and payloads for a given user
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 |
# File 'lib/posthog/client.rb', line 896 def get_all_flags_and_payloads( distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false ) return { featureFlags: {}, featureFlagPayloads: {} } if @disabled groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) response = @feature_flags_poller.get_all_flags_and_payloads( distinct_id, groups, person_properties, group_properties, only_evaluate_locally ) # Remove internal information response.delete(:requestId) response.delete(:evaluatedAt) response.delete(:flagDetails) response.delete(:minimalFlagCalledEvents) response end |
#get_feature_flag(key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true) ⇒ String, ...
Use #evaluate_flags and FeatureFlagEvaluations#get_flag instead.
Returns whether the given feature flag is enabled for the given user or not
The provided properties are used to calculate feature flags locally, if possible.
groups are a mapping from group type to group key. So, if you have a group type of "organization"
and a group key of "5",
you would pass groups="5".
group_properties take the format: { group_type_name: { group_properties } }
So, for example, if you have the group type "organization" and the group key "5", with the properties name,
and employee count, you'll send these as:
group_properties: {"organization": {"name": "PostHog", "employees": 11}}
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/posthog/client.rb', line 596 def get_feature_flag( key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true ) _emit_deprecation( :get_feature_flag, '`get_feature_flag` is deprecated and will be removed in a future major version. ' \ 'Use `client.evaluate_flags(distinct_id, ...)` and call `flags.get_flag(key)` instead — ' \ 'this consolidates flag evaluation into a single `/flags` request per incoming request.' ) # Bypass the public `get_feature_flag_result` so the user only sees one deprecation warning. result = _get_feature_flag_result( key, distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties, only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events ) result&.value end |
#get_feature_flag_payload(key, distinct_id, match_value: nil, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false) ⇒ Object?
Use #get_feature_flag_result instead, which returns both the flag value and payload and properly raises the $feature_flag_called event.
Returns payload for a given feature flag
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 |
# File 'lib/posthog/client.rb', line 858 def get_feature_flag_payload( key, distinct_id, match_value: nil, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false ) _emit_deprecation( :get_feature_flag_payload, '`get_feature_flag_payload` is deprecated and will be removed in a future major version. ' \ 'Use `client.evaluate_flags(distinct_id, ...)` and call `flags.get_flag_payload(key)` ' \ 'instead — this consolidates flag evaluation into a single `/flags` request per ' \ 'incoming request.' ) return nil if @disabled key = key.to_s groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) @feature_flags_poller.get_feature_flag_payload(key, distinct_id, match_value, groups, person_properties, group_properties, only_evaluate_locally) end |
#get_feature_flag_result(key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true) ⇒ PostHog::FeatureFlagResult?
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
# File 'lib/posthog/client.rb', line 630 def get_feature_flag_result( key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true ) _emit_deprecation( :get_feature_flag_result, '`get_feature_flag_result` is deprecated and will be removed in a future major version. ' \ 'Use `client.evaluate_flags(distinct_id, ...)` and call `flags.get_flag(key)` / ' \ '`flags.get_flag_payload(key)` instead — this consolidates flag evaluation into a single ' \ '`/flags` request per incoming request.' ) return nil if @disabled _get_feature_flag_result( key, distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties, only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events ) end |
#get_remote_config_payload(flag_key) ⇒ Hash
Returns The parsed remote config payload response.
566 567 568 569 570 |
# File 'lib/posthog/client.rb', line 566 def get_remote_config_payload(flag_key) return nil if @disabled @feature_flags_poller.get_remote_config_payload(flag_key.to_s) end |
#group_identify(attrs) ⇒ Boolean
Identifies a group
489 490 491 492 493 494 495 496 497 |
# File 'lib/posthog/client.rb', line 489 def group_identify(attrs) return false if @disabled symbolize_keys! attrs attrs[:is_server] = @is_server attrs[:lib] = @lib attrs[:lib_version] = @lib_version enqueue(FieldParser.parse_for_group_identify(attrs)) end |
#identify(attrs) ⇒ Boolean
Identifies a user
469 470 471 472 473 474 475 476 477 |
# File 'lib/posthog/client.rb', line 469 def identify(attrs) return false if @disabled symbolize_keys! attrs attrs[:is_server] = @is_server attrs[:lib] = @lib attrs[:lib_version] = @lib_version enqueue(FieldParser.parse_for_identify(attrs)) end |
#is_feature_enabled(flag_key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true) ⇒ Boolean?
Use #evaluate_flags and FeatureFlagEvaluations#enabled? instead.
TODO: In future version, rename to feature_flag_enabled?
536 537 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 |
# File 'lib/posthog/client.rb', line 536 def is_feature_enabled( # rubocop:disable Naming/PredicatePrefix flag_key, distinct_id, groups: {}, person_properties: {}, group_properties: {}, only_evaluate_locally: false, send_feature_flag_events: true ) _emit_deprecation( :is_feature_enabled, '`is_feature_enabled` is deprecated and will be removed in a future major version. ' \ 'Use `client.evaluate_flags(distinct_id, ...)` and call `flags.enabled?(key)` instead — ' \ 'this consolidates flag evaluation into a single `/flags` request per incoming request.' ) # Bypass the public `get_feature_flag` so the user only sees a single deprecation # warning per call, not a cascade. result = _get_feature_flag_result( flag_key, distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties, only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events ) response = result&.value return nil if response.nil? !!response end |
#queued_messages ⇒ Integer
Returns Number of messages in the queue. Intended for test mode.
522 523 524 |
# File 'lib/posthog/client.rb', line 522 def @queue.length end |
#reload_feature_flags ⇒ void
This method returns an undefined value.
Reload locally cached feature flag definitions synchronously on the calling thread.
924 925 926 927 928 929 930 931 932 933 934 |
# File 'lib/posthog/client.rb', line 924 def reload_feature_flags return if @disabled unless @secret_key || @flag_definition_cache_provider logger.error( 'You need to specify a secret_key or flag_definition_cache_provider to locally evaluate feature flags' ) return end @feature_flags_poller.load_feature_flags(true) end |
#shutdown(timeout: nil) ⇒ Boolean
Flush pending events and stop background resources.
When sync_mode is not set, this method calls the flush method; see flush method documentation for timeout semantics. Unlike flush, this method stops the worker. So any events still queued after the timeout will not be sent. After the timeout, this method may wait up to one additional second for worker and transport cleanup, which may continue after it returns.
When sync_mode is set and the timeout elapses while a request is in flight, the connection is closed once that request completes.
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 |
# File 'lib/posthog/client.rb', line 970 def shutdown(timeout: nil) deadline = timeout && (monotonic_time + timeout) shutdown_result = @shutdown_mutex.synchronize do if @shutdown until @shutdown_complete # Avoid deadlocking when an in-flight send's on_error callback # re-enters shutdown while the original caller is waiting for it. break if Thread.current == @worker_thread || (@sync_mode && @sync_lock.owned?) remaining = deadline && (deadline - monotonic_time) break if remaining && remaining <= 0 @shutdown_condition.wait(@shutdown_mutex, remaining) end @shutdown_complete ? @shutdown_result : false else @shutdown = true nil end end return shutdown_result unless shutdown_result.nil? flushed = false begin PostHog::Client._decrement_instance_count(@api_key) if @instance_registered @feature_flags_poller&.shutdown_poller flushed = if @sync_mode # Waiting for @sync_lock lets any in-flight sync send finish before # the connection is closed. closed = synchronized_within?(deadline) { @transport&.shutdown } Thread.new { @sync_lock.synchronize { @transport&.shutdown } } unless closed closed else drained = flush(timeout: timeout) @worker&.shutdown @worker_thread&.join(1) drained end @distinct_id_has_sent_flag_calls_mutex.synchronize do @distinct_id_has_sent_flag_calls.clear end emails_settled = @emails.close(timeout: deadline && [deadline - monotonic_time, 0].max) flushed &&= emails_settled ensure @shutdown_mutex.synchronize do @shutdown_result = flushed @shutdown_complete = true @shutdown_condition.broadcast end end end |