diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 773e1d09..2440fef0 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -56,19 +56,23 @@ def flush end if !events.empty? - res = log_timings("Flush events") { - next @client.post (@config.base_uri + "/api/events/bulk") do |req| - req.headers['Authorization'] = 'api_key ' + @api_key - req.headers['User-Agent'] = 'RubyClient/' + LaunchDarkly::VERSION - req.headers['Content-Type'] = 'application/json' - req.body = events.to_json - req.options.timeout = @config.read_timeout - req.options.open_timeout = @config.connect_timeout - end - } - if res.status != 200 - @config.logger.error("[LDClient] Unexpected status code while processing events: #{res.status}") + post_flushed_events(events) + end + end + + def post_flushed_events(events) + res = log_timings("Flush events") { + next @client.post (@config.base_uri + "/api/events/bulk") do |req| + req.headers['Authorization'] = 'api_key ' + @api_key + req.headers['User-Agent'] = 'RubyClient/' + LaunchDarkly::VERSION + req.headers['Content-Type'] = 'application/json' + req.body = events.to_json + req.options.timeout = @config.read_timeout + req.options.open_timeout = @config.connect_timeout end + } + if res.status/100 != 2 + @config.logger.error("[LDClient] Unexpected status code while processing events: #{res.status}") end end @@ -122,9 +126,7 @@ def get_flag?(key, user, default=false) # # @return [Boolean] whether or not the flag should be enabled, or the default value if the flag is disabled on the LaunchDarkly control panel def toggle?(key, user, default=false) - if @offline - return default - end + return default if @offline unless user @config.logger.error("[LDClient] Must specify user") @@ -136,14 +138,7 @@ def toggle?(key, user, default=false) end if @config.stream? and @stream_processor.initialized? - feature = get_flag_stream(key) - if @config.debug_stream? - polled = get_flag_int(key) - diff = HashDiff.diff(feature, polled) - if not diff.empty? - @config.logger.error("Streamed flag differs from polled flag " + diff.to_s) - end - end + feature = get_streamed_flag(key) else feature = get_flag_int(key) end @@ -159,9 +154,8 @@ def toggle?(key, user, default=false) end def add_event(event) - if @offline - return - end + return if @offline + if @queue.length < @config.capacity event[:creationDate] = (Time.now.to_f * 1000).to_i @queue.push(event) @@ -220,13 +214,25 @@ def feature_keys def get_features res = make_request '/api/features' - if res.status == 200 then + if res.status/100 == 2 return JSON.parse(res.body, symbolize_names: true)[:items] else @config.logger.error("[LDClient] Unexpected status code #{res.status}") end end + def get_streamed_flag(key) + feature = get_flag_stream(key) + if @config.debug_stream? + polled = get_flag_int(key) + diff = HashDiff.diff(feature, polled) + if not diff.empty? + @config.logger.error("Streamed flag differs from polled flag " + diff.to_s) + end + end + feature + end + def get_flag_stream(key) @stream_processor.get_feature(key) end @@ -246,7 +252,7 @@ def get_flag_int(key) return nil end - if res.status != 200 + if res.status/100 != 2 @config.logger.error("[LDClient] Unexpected status code #{res.status}") return nil end @@ -265,13 +271,10 @@ def make_request(path) end def param_for_user(feature, user) - if !! user[:key] - id_hash = user[:key] - else - return nil - end + return nil unless user[:key] - if !! user[:secondary] + id_hash = user[:key] + if user[:secondary] id_hash += '.' + user[:secondary] end @@ -285,19 +288,14 @@ def match_target?(target, user) attrib = target[:attribute].to_sym if BUILTINS.include?(attrib) - if user[attrib] - u_value = user[attrib] - return target[:values].include? u_value - else - return false - end + return false unless user[attrib] + + u_value = user[attrib] + return target[:values].include? u_value else # custom attribute - unless !! user[:custom] - return false - end - unless user[:custom].include? attrib - return false - end + return false unless user[:custom] + return false unless user[:custom].include? attrib + u_value = user[:custom][attrib] if u_value.is_a? Array return ! ((target[:values] & u_value).empty?) @@ -311,12 +309,19 @@ def match_target?(target, user) end def match_user?(variation, user) - if !!variation[:userTarget] + if variation[:userTarget] return match_target?(variation[:userTarget], user) end return false end + def find_user_match(feature, user) + feature[:variations].each do |variation| + return variation[:value] if match_user?(variation, user) + end + return nil + end + def match_variation?(variation, user) variation[:targets].each do |target| if !!variation[:userTarget] and target[:attribute].to_sym == :key @@ -330,46 +335,42 @@ def match_variation?(variation, user) return false end - def evaluate(feature, user) - if feature.nil? || !feature[:on] - return nil - end - - param = param_for_user(feature, user) - - if param.nil? - return nil - end - - feature[:variations].each do |variation| - if match_user?(variation, user) - return variation[:value] - end - end - + def find_target_match(feature, user) feature[:variations].each do |variation| - if match_variation?(variation, user) - return variation[:value] - end + return variation[:value] if match_variation?(variation, user) end + return nil + end + def find_weight_match(feature, param) total = 0.0 feature[:variations].each do |variation| total += variation[:weight].to_f / 100.0 - if param < total - return variation[:value] - end + return variation[:value] if param < total end return nil + end + + def evaluate(feature, user) + return nil if feature.nil? + return nil unless feature[:on] + + param = param_for_user(feature, user) + return nil if param.nil? + + value = find_user_match(feature, user) + return value if !value.nil? + value = find_target_match(feature, user) + return value if !value.nil? + + find_weight_match(feature, param) end def log_timings(label, &block) - if !@config.log_timings? || !@config.logger.debug? - return block.call - end + return block.call unless @config.log_timings? && @config.logger.debug? res = nil exn = nil bench = Benchmark.measure { @@ -380,13 +381,11 @@ def log_timings(label, &block) end } @config.logger.debug { "[LDClient] #{label} timing: #{bench}".chomp } - if exn - raise exn - end + raise exn if exn return res end - private :add_event, :get_flag_stream, :get_flag_int, :make_request, :param_for_user, :match_target?, :match_user?, :match_variation?, :evaluate, :create_worker, :log_timings + private :post_flushed_events, :add_event, :get_streamed_flag, :get_flag_stream, :get_flag_int, :make_request, :param_for_user, :match_target?, :match_user?, :match_variation?, :evaluate, :create_worker, :log_timings end end diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 0cfd5a39..59e517d6 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -104,14 +104,10 @@ def start_reactor def start # Try to start the reactor. If it's not started, we shouldn't start # the stream processor - if not start_reactor - return - end + return if not start_reactor # If someone else booted the stream processor connection, just return - if not @started.make_true - return - end + return unless @started.make_true # If we're the first and only thread to set started, boot # the stream processor connection @@ -126,9 +122,9 @@ def boot_event_manager {'Accept' => 'text/event-stream', 'Authorization' => 'api_key ' + @api_key, 'User-Agent' => 'RubyClient/' + LaunchDarkly::VERSION}) - source.on PUT { |message| process_message(message, PUT) } - source.on PATCH { |message| process_message(message, PATCH) } - source.on DELETE { |message| process_message(message, DELETE) } + source.on(PUT) { |message| process_message(message, PUT) } + source.on(PATCH) { |message| process_message(message, PATCH) } + source.on(DELETE) { |message| process_message(message, DELETE) } source.error do |error| @config.logger.info("[LDClient] Error subscribing to stream API: #{error}") set_disconnected diff --git a/spec/fixtures/feature.json b/spec/fixtures/feature.json new file mode 100644 index 00000000..3b347ca7 --- /dev/null +++ b/spec/fixtures/feature.json @@ -0,0 +1,67 @@ +{ + "name":"New recommendations engine", + "key":"engine.enable", + "kind":"flag", + "salt":"ZW5naW5lLmVuYWJsZQ==", + "on":true, + "variations":[ + { + "value":true, + "weight":31, + "targets":[ + { + "attribute":"groups", + "op":"in", + "values":[ + "Microsoft" + ] + } + ], + "userTarget":{ + "attribute":"key", + "op":"in", + "values":[ + "foo@bar.com", + "Abbey.Orkwis@example.com", + "Abbie.Stolte@example.com", + "44d2781c-5985-4d89-b07a-0dffbd24126f", + "0ffe4f0c-7aa9-4621-a87c-abe1c051abd8", + "f52d99be-6a40-4cdd-a7b4-0548834fcbe5", + "Vernetta.Belden@example.com", + "c9d591bd-ea1f-465f-86d2-239ea41d0f0f", + "870745092" + ] + } + }, + { + "value":false, + "weight":69, + "targets":[ + { + "attribute":"key", + "op":"in", + "values":[ + "Alida.Caples@example.com" + ] + }, + { + "attribute":"groups", + "op":"in", + "values":[ + + ] + } + ], + "userTarget":{ + "attribute":"key", + "op":"in", + "values":[ + "Alida.Caples@example.com" + ] + } + } + ], + "ttl":0, + "commitDate":"2015-05-10T06:06:45.381Z", + "creationDate":"2014-09-02T20:39:18.61Z" +} diff --git a/spec/fixtures/user.json b/spec/fixtures/user.json new file mode 100644 index 00000000..f31855e0 --- /dev/null +++ b/spec/fixtures/user.json @@ -0,0 +1,9 @@ +{ + "key":"user@test.com", + "custom":{ + "groups":[ + "microsoft", + "google" + ] + } +} diff --git a/spec/ldclient_spec.rb b/spec/ldclient_spec.rb index da433046..ab207af1 100644 --- a/spec/ldclient_spec.rb +++ b/spec/ldclient_spec.rb @@ -6,41 +6,99 @@ expect_any_instance_of(LaunchDarkly::LDClient).to receive :create_worker subject.new('api_key') end + let(:feature) do + data = File.read(File.join('spec', 'fixtures', 'feature.json')) + JSON.parse(data, symbolize_names: true) + end + let(:user) do + data = File.read(File.join('spec', 'fixtures', 'user.json')) + JSON.parse(data, symbolize_names: true) + end describe '#flush' do it 'will flush and post all events' do client.instance_variable_get(:@queue).push 'asdf' client.instance_variable_get(:@queue).push 'asdf' + expect(client).to receive(:post_flushed_events) + client.flush + expect(client.instance_variable_get(:@queue).length).to eq 0 + end + it 'will not do anything if there are no events' do + expect(client).to_not receive(:post_flushed_events) + expect(client.instance_variable_get(:@config).logger).to_not receive :error + client.flush + end + end + + describe '#post_flushed_events' do + let(:events) { ['event'] } + it 'will flush and post all events' do result = double('result', status: 200) expect(client.instance_variable_get(:@client)).to receive(:post).and_return result - client.flush + expect(client.instance_variable_get(:@config).logger).to_not receive :error + client.send(:post_flushed_events, events) expect(client.instance_variable_get(:@queue).length).to eq 0 end + it 'will allow any 2XX response' do + result = double('result', status: 202) + expect(client.instance_variable_get(:@client)).to receive(:post).and_return result + expect(client.instance_variable_get(:@config).logger).to_not receive :error + client.send(:post_flushed_events, events) + end it 'will work with unexpected post results' do - client.instance_variable_get(:@queue).push 'asdf' - client.instance_variable_get(:@queue).push 'asdf' - result = double('result', status: 500) + result = double('result', status: 418) expect(client.instance_variable_get(:@client)).to receive(:post).and_return result expect(client.instance_variable_get(:@config).logger).to receive :error - client.flush + client.send(:post_flushed_events, events) expect(client.instance_variable_get(:@queue).length).to eq 0 end - it 'will not do anything if there are no events' do - expect(client.instance_variable_get(:@client)).to_not receive(:post) - expect(client.instance_variable_get(:@config).logger).to_not receive :error - client.flush - end end describe '#toggle?' do - let(:key) { 'ld-key' } - let(:user) { {user: 'user1'} } it 'will not fail' do expect(client.instance_variable_get(:@config)).to receive(:stream?).and_raise RuntimeError expect(client.instance_variable_get(:@config).logger).to receive(:error) - result = client.toggle?(key, user, 'default') + result = client.toggle?(feature[:key], user, 'default') expect(result).to eq 'default' end + it 'requires user' do + expect(client.instance_variable_get(:@config).logger).to receive(:error) + result = client.toggle?(feature[:key], nil, 'default') + expect(result).to eq 'default' + end + it 'returns value from streamed flag if available' do + expect(client.instance_variable_get(:@config)).to receive(:stream?).and_return(true).twice + expect(client.instance_variable_get(:@stream_processor)).to receive(:started?).and_return true + expect(client.instance_variable_get(:@stream_processor)).to receive(:initialized?).and_return true + expect(client).to receive(:add_event) + expect(client).to receive(:get_streamed_flag).and_return feature + result = client.toggle?(feature[:key], user, 'default') + expect(result).to eq false + end + it 'returns value from normal request if streamed flag is not available' do + expect(client.instance_variable_get(:@config)).to receive(:stream?).and_return(false).twice + expect(client).to receive(:add_event) + expect(client).to receive(:get_flag_int).and_return feature + result = client.toggle?(feature[:key], user, 'default') + expect(result).to eq false + end + end + + describe '#get_streamed_flag' do + it 'will not check the polled flag normally' do + expect(client).to receive(:get_flag_stream).and_return true + expect(client).to_not receive(:get_flag_int) + expect(client.send(:get_streamed_flag, 'key')).to eq true + end + context 'debug stream' do + it 'will log an error if the streamed and polled flag do not match' do + expect(client.instance_variable_get(:@config)).to receive(:debug_stream?).and_return true + expect(client).to receive(:get_flag_stream).and_return true + expect(client).to receive(:get_flag_int).and_return false + expect(client.instance_variable_get(:@config).logger).to receive(:error) + expect(client.send(:get_streamed_flag, 'key')).to eq true + end + end end describe '#get_features' do @@ -51,7 +109,7 @@ expect(data).to eq ['asdf'] end it 'will log errors' do - result = double('Faraday::Response', status: 500) + result = double('Faraday::Response', status: 418) expect(client).to receive(:make_request).with('/api/features').and_return(result) expect(client.instance_variable_get(:@config).logger).to receive(:error) client.send(:get_features) @@ -80,7 +138,7 @@ expect(data).to be_nil end it 'will accept non-standard statuses' do - result = double('Faraday::Response', status: 500) + result = double('Faraday::Response', status: 418) expect(client).to receive(:make_request).with('/api/eval/features/key').and_return(result) expect(client.instance_variable_get(:@config).logger).to receive(:error) data = client.send(:get_flag_int, 'key') @@ -94,4 +152,64 @@ client.send(:make_request, '/asdf') end end + + describe '#param_for_user' do + it 'will return a consistent hash of a user key, feature key, and feature salt' do + param = client.send(:param_for_user, feature, user) + expect(param).to be_between(0.0, 1.0).inclusive + end + end + + describe '#evaluate' do + it 'will return nil if there is no feature' do + expect(client.send(:evaluate, nil, user)).to eq nil + end + it 'will return nil unless the feature is on' do + feature[:on] = false + expect(client.send(:evaluate, feature, user)).to eq nil + end + it 'will return value if it matches the user' do + user = {key: 'Alida.Caples@example.com'} + expect(client.send(:evaluate, feature, user)).to eq false + user = {key: 'foo@bar.com'} + expect(client.send(:evaluate, feature, user)).to eq true + end + it 'will return value if the target matches' do + user = {key: 'asdf@asdf.com', custom: {groups: 'Microsoft'}} + expect(client.send(:evaluate, feature, user)).to eq true + end + it 'will return value if the weight matches' do + expect(client).to receive(:param_for_user).and_return 0.1 + expect(client.send(:evaluate, feature, user)).to eq true + expect(client).to receive(:param_for_user).and_return 0.9 + expect(client.send(:evaluate, feature, user)).to eq false + end + end + + describe '#log_timings' do + let(:block) { lambda { 'result' } } + let(:label) { 'label' } + it 'will not measure if not configured to do so' do + expect(Benchmark).to_not receive(:measure) + client.send(:log_timings, label, &block) + end + context 'logging enabled' do + before do + expect(client.instance_variable_get(:@config)).to receive(:log_timings?).and_return true + expect(client.instance_variable_get(:@config).logger).to receive(:debug?).and_return true + end + it 'will benchmark timings and return result' do + expect(Benchmark).to receive(:measure).and_call_original + expect(client.instance_variable_get(:@config).logger).to receive(:debug) + result = client.send(:log_timings, label, &block) + expect(result).to eq 'result' + end + it 'will raise exceptions if the block has them' do + block = lambda { raise RuntimeError } + expect(Benchmark).to receive(:measure).and_call_original + expect(client.instance_variable_get(:@config).logger).to receive(:debug) + expect{client.send(:log_timings, label, &block)}.to raise_error RuntimeError + end + end + end end diff --git a/spec/store_spec.rb b/spec/store_spec.rb index 02a83c5b..146c6f76 100644 --- a/spec/store_spec.rb +++ b/spec/store_spec.rb @@ -1,5 +1,11 @@ require 'spec_helper' describe LaunchDarkly::ThreadSafeMemoryStore do - subject { LaunchDarkly::LDNewRelic } + subject { LaunchDarkly::ThreadSafeMemoryStore } + let(:store) { subject.new } + it 'can read and write' do + store.write('key', 'value') + value = store.read 'key' + expect(store.read('key')).to eq 'value' + end end