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
# 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) do
      _load_feature_flags
  end

  # 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
64
# 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


  unless @loaded_flags_successfully_once
    return default_result
  end

  feature_flag = nil

  # puts @feature_flags

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

  if !feature_flag
    return default_result
  end

  flag_rollout_pctg = feature_flag['rollout_percentage'] ? feature_flag['rollout_percentage'] : 100
  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



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

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



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

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

#shutdown_pollerObject



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

def shutdown_poller()
  @task.shutdown
end