Class: Doppler::Client

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

Constant Summary collapse

MAX_RETRIES =
10
ENVIRONMENT_SEGMENT =
'/environments/'

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



11
12
13
# File 'lib/doppler/client.rb', line 11

def initialize()
  startup()
end

Instance Method Details

#_request(endpoint, body, retry_count = 0) ⇒ Object

Raises:

  • (ArgumentError)


56
57
58
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
# File 'lib/doppler/client.rb', line 56

def _request(endpoint, body, retry_count=0)
  raise ArgumentError, 'endpoint not string' unless endpoint.is_a? String

  raw_url = Doppler.host_url + ENVIRONMENT_SEGMENT + Doppler.environment + endpoint
  uri = URI.parse(raw_url)
  header = {
    'Content-Type': 'application/json',
    'api-key': Doppler.api_key,
    'pipeline': Doppler.pipeline,
    'client-sdk': 'ruby',
    'client-version': Doppler::VERSION

  }
  http = ::Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  begin
    response = http.post(uri.path, body.to_json, header)
    response_data = JSON.parse(response.body)
    if response_data['success'] == false
      raise RuntimeError, response_data["messages"].join(". ")
    end
  rescue => e
    retry_count += 1

    if retry_count > MAX_RETRIES
      raise e
    else
      return _request(endpoint, body, retry_count)
    end
  end

  return response_data
end

#get(key_name, priority = Doppler.priority) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/doppler/client.rb', line 26

def get(key_name, priority = Doppler.priority)
  value =
    if priority == Doppler::PRIORITY_LOCAL
      ENV[key_name] || @remote_keys[key_name]
    else
      @remote_keys[key_name] || ENV[key_name]
    end

  unless Doppler.ignore_keys.include?(key_name)
    # TODO: Move this to a background job or thread once we get more customers!
    upload_key_to_server(key_name, value)
  end

  value
end

#startupObject



15
16
17
18
19
20
21
22
23
24
# File 'lib/doppler/client.rb', line 15

def startup
  local_keys = ENV.to_hash
  keys_to_send = local_keys.select { |k, _| Doppler.track_keys.include?(k) }

  resp = self._request('/fetch_keys', {
                         'local_keys' => keys_to_send
                       })

  @remote_keys = resp['keys']
end

#upload_key_to_server(key_name, value) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/doppler/client.rb', line 42

def upload_key_to_server(key_name, value)
  if value
    if ENV[key_name] != @remote_keys[key_name]
      _request('/track_key', {
                 'local_keys' => {key_name: ENV[key_name]}
               })
    end
  else
    _request('/missing_key', {
               'key_name' => key_name
             })
  end
end