Class: Statsig::Network

Inherits:
Object
  • Object
show all
Defined in:
lib/network.rb

Instance Method Summary collapse

Constructor Details

#initialize(server_secret, api, local_mode, backoff_mult = 10) ⇒ Network

Returns a new instance of Network.



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/network.rb', line 9

def initialize(server_secret, api, local_mode, backoff_mult = 10)
  super()
  unless api.end_with?('/')
    api += '/'
  end
  @server_secret = server_secret
  @api = api
  @local_mode = local_mode
  @backoff_multiplier = backoff_mult
  @session_id = SecureRandom.uuid
end

Instance Method Details

#check_gate(user, gate_name) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/network.rb', line 46

def check_gate(user, gate_name)
  begin
    request_body = JSON.generate({'user' => user&.serialize(false), 'gateName' => gate_name})
    response, _ = post_helper('check_gate', request_body)
    return JSON.parse(response.body) unless response.nil?
    false
  rescue
    return false
  end
end

#get_config(user, dynamic_config_name) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/network.rb', line 57

def get_config(user, dynamic_config_name)
  begin
    request_body = JSON.generate({'user' => user&.serialize(false), 'configName' => dynamic_config_name})
    response, _ = post_helper('get_config', request_body)
    return JSON.parse(response.body) unless response.nil?
    nil
  rescue
    return nil
  end
end

#post_helper(endpoint, body, retries = 0, backoff = 1) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/network.rb', line 21

def post_helper(endpoint, body, retries = 0, backoff = 1)
  if @local_mode
    return nil, nil
  end
  http = HTTP.headers(
    {"STATSIG-API-KEY" => @server_secret,
    "STATSIG-CLIENT-TIME" => (Time.now.to_f * 1000).to_i.to_s,
     "STATSIG-SERVER-SESSION-ID" => @session_id,
    "Content-Type" => "application/json; charset=UTF-8"
    }).accept(:json)
  begin
    res = http.post(@api + endpoint, body: body)
  rescue StandardError => e
    ## network error retry
    return nil, e unless retries > 0
    sleep backoff
    return post_helper(endpoint, body, retries - 1, backoff * @backoff_multiplier)
  end
  return res, nil unless !res.status.success?
  return nil, StandardError.new("Got an exception when making request to #{@api + endpoint}: #{res.to_s}") unless retries > 0 && $retry_codes.include?(res.code)
  ## status code retry
  sleep backoff
  post_helper(endpoint, body, retries - 1, backoff * @backoff_multiplier)
end

#post_logs(events) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/network.rb', line 68

def post_logs(events)
  begin
    json_body = JSON.generate({'events' => events, 'statsigMetadata' => Statsig.})
    post_helper('log_event', json_body, 5)
  rescue
  end
end