Skip to content

Commit

Permalink
(feat) - WIP - embed the proxy client in the main SDK.
Browse files Browse the repository at this point in the history
To allow code re-use.
Need to add unit tests, and more methods in the proxy SDK to mirror the general client.

consider caching results, if the context is unchanged
  • Loading branch information
rarruda committed Mar 4, 2022
1 parent c745ed4 commit cf7d61b
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/unleash/context.rb
Expand Up @@ -22,6 +22,23 @@ def to_s
",app_name=#{@app_name},environment=#{@environment}>"
end

# TODO(rarruda): add unit test
def as_uri_params
[*ATTRS, :properties]
.flatten
.reject{ |k| self.send(k).nil? }
.map do |k|
if k == :properties
self.properties
.map{ |property,pval| "properties[#{property}]=#{pval}" }
.join("&")
else
"#{k}=#{self.send(k)}"
end
end
.join("&")
end

def get_by_name(name)
normalized_name = underscore(name).to_sym

Expand Down
60 changes: 60 additions & 0 deletions lib/unleash/proxy/client.rb
@@ -0,0 +1,60 @@
require 'unleash/util/http'
require 'unleash/context'

module Unleash
module Proxy
class Client
attr_accessor :proxy_url, :proxy_http_headers, :toggles

def initialize(opts)
self.proxy_url = opts[:proxy_url]
self.proxy_http_headers = opts[:proxy_http_headers]
end

def is_enabled?(feature, context = nil, default_value_param = false, &fallback_blk)
Unleash.logger.debug "Unleash::Client.is_enabled? feature: #{feature} with context #{context}"

retrieve_toggles

default_value = if block_given?
default_value_param || !!fallback_blk.call(feature, context)
else
default_value_param
end

toggle_as_hash = toggles.select{ |toggle| toggle['name'] == feature}&.first

if toggle_as_hash.nil?
Unleash.logger.debug "Unleash::Client.is_enabled? feature: #{feature} not found"
return default_value
end

!!toggle['enabled']
end

def get_variant(feature, context = Unleash::Context.new, fallback_variant = disabled_variant)
retrieve_toggles

toggle_as_hash = toggles.select{ |toggle| toggle['name'] == feature}&.first

return Unleash::Variant.new(toggle_as_hash['variant']) if toggle_as_hash.is_a?(Hash) && toggle_as_hash.has_key?('variant')

fallback_variant
end

private

def retrieve_toggles
request_url = self.proxy_url.dup
request_url += "?#{context.as_uri_params}" unless context.nil?

toggles_response = Unleash::Util::Http.get(request_url, nil, self.proxy_http_headers)
# TODO(): handle non-200 responses.

self.toggles = JSON.parse(toggles_response)['toggles']
# TODO(rarruda): handle malformed responses
end

end
end
end

0 comments on commit cf7d61b

Please sign in to comment.