Class: PostHog::FeatureFlagsPoller

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/posthog/feature_flags.rb

Instance Method Summary collapse

Methods included from Logging

included, #logger

Constructor Details

#initialize(polling_interval, personal_api_key, project_api_key, host) ⇒ FeatureFlagsPoller

Returns a new instance of FeatureFlagsPoller.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/posthog/feature_flags.rb', line 11

def initialize(polling_interval, personal_api_key, project_api_key, host)
  @polling_interval = polling_interval || 60 * 5
  @personal_api_key = personal_api_key
  @project_api_key = project_api_key
  @host = host || 'app.posthog.com'
  @feature_flags = Concurrent::Array.new
  @loaded_flags_successfully_once = Concurrent::AtomicBoolean.new

  @task =
    Concurrent::TimerTask.new(
      execution_interval: polling_interval,
      timeout_interval: 15
    ) { _load_feature_flags }

  # load once before timer
  load_feature_flags
  @task.execute
end

Instance Method Details

#is_feature_enabled(key, distinct_id, default_result = false) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/posthog/feature_flags.rb', line 30

def is_feature_enabled(key, distinct_id, default_result = false)
  # make sure they're loaded on first run
  load_feature_flags

  return default_result unless @loaded_flags_successfully_once

  feature_flag = nil


  @feature_flags.each do |flag|
    if key == flag['key']
      feature_flag = flag
      break
    end
  end

  return default_result if !feature_flag

  flag_rollout_pctg =
    if feature_flag['rollout_percentage']
      feature_flag['rollout_percentage']
    else
      100
    end
  if feature_flag['is_simple_flag']
    return is_simple_flag_enabled(key, distinct_id, flag_rollout_pctg)
  else
    data = { 'distinct_id' => distinct_id }
    res = _request('POST', 'decide', false, data)
    return res['featureFlags'].include? key
  end

  return false
end

#is_simple_flag_enabled(key, distinct_id, rollout_percentage) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/posthog/feature_flags.rb', line 65

def is_simple_flag_enabled(key, distinct_id, rollout_percentage)
  hash = Digest::SHA1.hexdigest "#{key}.#{distinct_id}"
  return(
    (Integer(hash[0..14], 16).to_f / 0xfffffffffffffff) <=
      (rollout_percentage / 100)
  )
end

#load_feature_flags(force_reload = false) ⇒ Object



73
74
75
76
77
# File 'lib/posthog/feature_flags.rb', line 73

def load_feature_flags(force_reload = false)
  if @loaded_flags_successfully_once.false? || force_reload
    _load_feature_flags
  end
end

#shutdown_pollerObject



79
80
81
# File 'lib/posthog/feature_flags.rb', line 79

def shutdown_poller()
  @task.shutdown
end