From 658c4ecc5b5d10c6a44fc8160bb7cc835e0ff57b Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 29 Jun 2016 22:58:28 -0700 Subject: [PATCH 01/70] Work in progress on ruby v2 refactoring --- lib/ldclient-rb.rb | 6 +- lib/ldclient-rb/{store.rb => cache_store.rb} | 0 lib/ldclient-rb/config.rb | 55 ++++++------ lib/ldclient-rb/events.rb | 14 +++ lib/ldclient-rb/feature_store.rb | 60 +++++++++++++ lib/ldclient-rb/ldclient.rb | 92 ++++++-------------- lib/ldclient-rb/polling.rb | 6 ++ lib/ldclient-rb/requestor.rb | 54 ++++++++++++ lib/ldclient-rb/stream.rb | 56 ------------ 9 files changed, 192 insertions(+), 151 deletions(-) rename lib/ldclient-rb/{store.rb => cache_store.rb} (100%) create mode 100644 lib/ldclient-rb/events.rb create mode 100644 lib/ldclient-rb/feature_store.rb create mode 100644 lib/ldclient-rb/polling.rb create mode 100644 lib/ldclient-rb/requestor.rb diff --git a/lib/ldclient-rb.rb b/lib/ldclient-rb.rb index 1c585f5a..6460dbe0 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -1,7 +1,11 @@ require "ldclient-rb/version" require "ldclient-rb/settings" require "ldclient-rb/ldclient" -require "ldclient-rb/store" +require "ldclient-rb/cache_store" require "ldclient-rb/config" require "ldclient-rb/newrelic" require "ldclient-rb/stream" +require "ldclient-rb/polling" +require "ldclient-rb/events" +require "ldclient-rb/feature_store" +require "ldclient-rb/requestor" diff --git a/lib/ldclient-rb/store.rb b/lib/ldclient-rb/cache_store.rb similarity index 100% rename from lib/ldclient-rb/store.rb rename to lib/ldclient-rb/cache_store.rb diff --git a/lib/ldclient-rb/config.rb b/lib/ldclient-rb/config.rb index edcde25d..c5875437 100644 --- a/lib/ldclient-rb/config.rb +++ b/lib/ldclient-rb/config.rb @@ -31,9 +31,14 @@ class Config # connections in seconds. # @option opts [Float] :connect_timeout (2) The connect timeout for network # connections in seconds. - # @option opts [Object] :store A cache store for the Faraday HTTP caching + # @option opts [Object] :cache_store A cache store for the Faraday HTTP caching # library. Defaults to the Rails cache in a Rails environment, or a # thread-safe in-memory store otherwise. + # @option opts [Boolean] :offline (false) Whether the client should be initialized in + # offline mode. In offline mode, default values are returned for all flags and no + # remote network requests are made. + # @option opts [Float] :poll_interval (30) The number of seconds between polls for flag updates + # if streaming is off. # # @return [type] [description] def initialize(opts = {}) @@ -42,14 +47,14 @@ def initialize(opts = {}) @events_uri = (opts[:events_uri] || Config.default_events_uri).chomp("/") @capacity = opts[:capacity] || Config.default_capacity @logger = opts[:logger] || Config.default_logger - @store = opts[:store] || Config.default_store + @cache_store = opts[:cache_store] || Config.default_cache_store @flush_interval = opts[:flush_interval] || Config.default_flush_interval @connect_timeout = opts[:connect_timeout] || Config.default_connect_timeout @read_timeout = opts[:read_timeout] || Config.default_read_timeout @feature_store = opts[:feature_store] || Config.default_feature_store @stream = opts.has_key?(:stream) ? opts[:stream] : Config.default_stream - @log_timings = opts.has_key?(:log_timings) ? opts[:log_timings] : Config.default_log_timings - @debug_stream = opts.has_key?(:debug_stream) ? opts[:debug_stream] : Config.default_debug_stream + @offline = opts.has_key?(:offline) ? opts[:offline] : Config.default_offline + @poll_interval = opts.has_key?(:poll_interval) && opts[:poll_interval] > 1 ? opts[:poll_interval] : Config.default_poll_interval end # @@ -70,6 +75,11 @@ def initialize(opts = {}) # @return [String] The configured base URL for the LaunchDarkly events server. attr_reader :events_uri + + # TODO docs + attr_reader :poll_interval + + # # Whether streaming mode should be enabled. Streaming mode asynchronously updates # feature flags in real-time using server-sent events. @@ -79,13 +89,9 @@ def stream? @stream end - # - # Whether we should debug streaming mode. If set, the client will fetch features via polling - # and compare the retrieved feature with the value in the feature store - # - # @return [Boolean] True if we should debug streaming mode - def debug_stream? - @debug_stream + # TODO docs + def offline? + @offline end # @@ -117,7 +123,7 @@ def debug_stream? # 'read' and 'write' requests. # # @return [Object] The configured store for the Faraday HTTP caching library. - attr_reader :store + attr_reader :cache_store # # The read timeout for network connections in seconds. @@ -132,16 +138,7 @@ def debug_stream? attr_reader :connect_timeout # - # Whether timing information should be logged. If it is logged, it will be logged to the DEBUG - # level on the configured logger. This can be very verbose. - # - # @return [Boolean] True if timing information should be logged. - def log_timings? - @log_timings - end - - # - # TODO docs + # A store for feature flag configuration rules. # attr_reader :feature_store @@ -170,7 +167,7 @@ def self.default_events_uri "https://events.launchdarkly.com" end - def self.default_store + def self.default_cache_store defined?(Rails) && Rails.respond_to?(:cache) ? Rails.cache : ThreadSafeMemoryStore.new end @@ -190,20 +187,20 @@ def self.default_logger defined?(Rails) && Rails.respond_to?(:logger) ? Rails.logger : ::Logger.new($stdout) end - def self.default_log_timings - false - end - def self.default_stream true end def self.default_feature_store - nil + InMemoryFeatureStore.new end - def self.default_debug_stream + def self.default_offline false end + + def self.default_poll_interval + 1 + end end end diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb new file mode 100644 index 00000000..f7dbb500 --- /dev/null +++ b/lib/ldclient-rb/events.rb @@ -0,0 +1,14 @@ +module LaunchDarkly + + class EventProcessor + def initialize(api_key, config) + @api_key = api_key + @config = config + @client = Faraday.new do |builder| + builder.use :http_cache, store: @config.cache_store + builder.adapter :net_http_persistent + end + end + end + +end \ No newline at end of file diff --git a/lib/ldclient-rb/feature_store.rb b/lib/ldclient-rb/feature_store.rb new file mode 100644 index 00000000..332ed804 --- /dev/null +++ b/lib/ldclient-rb/feature_store.rb @@ -0,0 +1,60 @@ +require "concurrent/atomics" + +module LaunchDarkly + + class InMemoryFeatureStore + def initialize + @features = Hash.new + @lock = Concurrent::ReadWriteLock.new + @initialized = Concurrent::AtomicBoolean.new(false) + end + + def get(key) + @lock.with_read_lock do + f = @features[key.to_sym] + (f.nil? || f[:deleted]) ? nil : f + end + end + + def all + @lock.with_read_lock do + @features.select { |_k, f| not f[:deleted] } + end + end + + def delete(key, version) + @lock.with_write_lock do + old = @features[key.to_sym] + + if !old.nil? && old[:version] < version + old[:deleted] = true + old[:version] = version + @features[key.to_sym] = old + elsif old.nil? + @features[key.to_sym] = { deleted: true, version: version } + end + end + end + + def init(fs) + @lock.with_write_lock do + @features.replace(fs) + @initialized.make_true + end + end + + def upsert(key, feature) + @lock.with_write_lock do + old = @features[key.to_sym] + + if old.nil? || old[:version] < feature[:version] + @features[key.to_sym] = feature + end + end + end + + def initialized? + @initialized.value + end + end +end \ No newline at end of file diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index c34b16e6..a00e9248 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -27,21 +27,24 @@ class LDClient # @param config [Config] an optional client configuration object # # @return [LDClient] The LaunchDarkly client instance - def initialize(api_key, config = Config.default) + def initialize(api_key, config = Config.default, wait_for = 0) @queue = Queue.new @api_key = api_key @config = config - @client = Faraday.new do |builder| - builder.use :http_cache, store: @config.store - - builder.adapter :net_http_persistent end - @offline = false + + @store = config.feature_store + + requestor = Requestor.new(api_key, config) if @config.stream? - @stream_processor = StreamProcessor.new(api_key, config) + @update_processor = StreamProcessor.new(api_key, config, requestor) + else + @update_processor = PollingProcessor.new(config, requestor) end + @event_processor = EventProcessor.new(api_key, config) + @worker = create_worker end @@ -60,15 +63,13 @@ def flush end def post_flushed_events(events) - res = log_timings("Flush events") do - next @client.post (@config.events_uri + "/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 + @client.post (@config.events_uri + "/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}") @@ -136,11 +137,11 @@ def toggle?(key, user, default = false) end sanitize_user(user) - if @config.stream? && !@stream_processor.started? - @stream_processor.start + if @config.stream? && !@update_processor.started? + @update_processor.start end - if @config.stream? && @stream_processor.initialized? + if @config.stream? && @update_processor.initialized? feature = get_streamed_flag(key) else feature = get_flag_int(key) @@ -181,18 +182,6 @@ def identify(user) add_event(kind: "identify", key: user[:key], user: user) end - def set_offline - @offline = true - end - - def set_online - @offline = false - end - - def is_offline? - @offline - end - # # Tracks that a user performed an event # @@ -219,12 +208,12 @@ def all_keys def all_flags return Hash.new if @offline - if @config.stream? && !@stream_processor.started? - @stream_processor.start + if @config.stream? && !@update_processor.started? + @update_processor.start end - if @config.stream? && @stream_processor.initialized? - @stream_processor.get_all_features + if @config.stream? && @update_processor.initialized? + @update_processor.get_all_features else res = make_request "/api/eval/features" @@ -254,13 +243,11 @@ def get_streamed_flag(key) end def get_flag_stream(key) - @stream_processor.get_feature(key) + @update_processor.get_feature(key) end def get_flag_int(key) - res = log_timings("Feature request") do - next make_request "/api/eval/features/" + key - end + res = make_request "/api/eval/features/" + key if res.status == 401 @config.logger.error("[LDClient] Invalid API key") @@ -280,15 +267,6 @@ def get_flag_int(key) JSON.parse(res.body, symbolize_names: true) end - def make_request(path) - @client.get (@config.base_uri + path) do |req| - req.headers["Authorization"] = "api_key " + @api_key - req.headers["User-Agent"] = "RubyClient/" + LaunchDarkly::VERSION - req.options.timeout = @config.read_timeout - req.options.open_timeout = @config.connect_timeout - end - end - def param_for_user(feature, user) return nil unless user[:key] @@ -387,22 +365,6 @@ def evaluate(feature, user) find_weight_match(feature, param) end - def log_timings(label, &block) - return block.call unless @config.log_timings? && @config.logger.debug? - res = nil - exn = nil - bench = Benchmark.measure do - begin - res = block.call - rescue StandardError => e - exn = e - end - end - @config.logger.debug { "[LDClient] #{label} timing: #{bench}".chomp } - raise exn if exn - res - end - def log_exception(caller, exn) error_traceback = "#{exn.inspect} #{exn}\n\t#{exn.backtrace.join("\n\t")}" error = "[LDClient] Unexpected exception in #{caller}: #{error_traceback}" @@ -418,6 +380,6 @@ def sanitize_user(user) 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, :log_exception, :sanitize_user + :create_worker, :log_exception, :sanitize_user end end diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb new file mode 100644 index 00000000..7943f794 --- /dev/null +++ b/lib/ldclient-rb/polling.rb @@ -0,0 +1,6 @@ +module LaunchDarkly + class PollingProcessor + def initialize(api_key, config, requestor) + end + end +end \ No newline at end of file diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb new file mode 100644 index 00000000..a78d1c8a --- /dev/null +++ b/lib/ldclient-rb/requestor.rb @@ -0,0 +1,54 @@ +require "json" + +module LaunchDarkly + + class Requestor + def initialize(api_key, config) + @api_key = api_key + @config = config + @client = Faraday.new do |builder| + builder.use :http_cache, store: @config.cache_store + + builder.adapter :net_http_persistent + end + end + + def request_all_flags() + make_request("/sdk/latest-flags") + end + + def request_flag(key) + make_request("/sdk/latest-flags/" + key) + end + + def make_request(path) + res = @client.get (@config.base_uri + path) do |req| + req.headers["Authorization"] = "api_key " + @api_key + req.headers["User-Agent"] = "RubyClient/" + LaunchDarkly::VERSION + req.options.timeout = @config.read_timeout + req.options.open_timeout = @config.connect_timeout + end + + if res.status == 401 + @config.logger.error("[LDClient] Invalid API key") + return nil + end + + if res.status == 404 + @config.logger.error("[LDClient] Resource not found") + return nil + end + + if res.status / 100 != 2 + @config.logger.error("[LDClient] Unexpected status code #{res.status}") + return nil + end + + JSON.parse(res.body, symbolize_names: true) + end + + private :make_request + + end + +end \ No newline at end of file diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 7db8e555..53287d4b 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -7,62 +7,6 @@ module LaunchDarkly PATCH = "patch" DELETE = "delete" - class InMemoryFeatureStore - def initialize - @features = Hash.new - @lock = Concurrent::ReadWriteLock.new - @initialized = Concurrent::AtomicBoolean.new(false) - end - - def get(key) - @lock.with_read_lock do - f = @features[key.to_sym] - (f.nil? || f[:deleted]) ? nil : f - end - end - - def all - @lock.with_read_lock do - @features.select { |_k, f| not f[:deleted] } - end - end - - def delete(key, version) - @lock.with_write_lock do - old = @features[key.to_sym] - - if !old.nil? && old[:version] < version - old[:deleted] = true - old[:version] = version - @features[key.to_sym] = old - elsif old.nil? - @features[key.to_sym] = { deleted: true, version: version } - end - end - end - - def init(fs) - @lock.with_write_lock do - @features.replace(fs) - @initialized.make_true - end - end - - def upsert(key, feature) - @lock.with_write_lock do - old = @features[key.to_sym] - - if old.nil? || old[:version] < feature[:version] - @features[key.to_sym] = feature - end - end - end - - def initialized? - @initialized.value - end - end - class StreamProcessor def initialize(api_key, config) @api_key = api_key From 66d93780402f0d19cdc1ceca2b16e27bbeb6b482 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Tue, 5 Jul 2016 17:00:43 -0700 Subject: [PATCH 02/70] Work in progress on v1 refactoring --- ldclient-rb.gemspec | 3 +- lib/ldclient-rb/config.rb | 10 ++-- lib/ldclient-rb/events.rb | 63 ++++++++++++++++++++ lib/ldclient-rb/ldclient.rb | 116 +++--------------------------------- lib/ldclient-rb/polling.rb | 45 ++++++++++++++ lib/ldclient-rb/stream.rb | 57 +++++------------- 6 files changed, 137 insertions(+), 157 deletions(-) diff --git a/ldclient-rb.gemspec b/ldclient-rb.gemspec index 302c8d7d..ee80a8e0 100644 --- a/ldclient-rb.gemspec +++ b/ldclient-rb.gemspec @@ -30,5 +30,6 @@ Gem::Specification.new do |spec| spec.add_runtime_dependency "net-http-persistent", "~> 2.9" spec.add_runtime_dependency "concurrent-ruby", "~> 1.0.0" spec.add_runtime_dependency "hashdiff", "~> 0.2" - spec.add_runtime_dependency "ld-celluloid-eventsource", "~> 0.4" + spec.add_runtime_dependency "ld-celluloid-eventsource", "~> 0.4" + spec.add_runtime_dependency "waitutil", "0.2" end diff --git a/lib/ldclient-rb/config.rb b/lib/ldclient-rb/config.rb index c5875437..074bda6b 100644 --- a/lib/ldclient-rb/config.rb +++ b/lib/ldclient-rb/config.rb @@ -75,11 +75,6 @@ def initialize(opts = {}) # @return [String] The configured base URL for the LaunchDarkly events server. attr_reader :events_uri - - # TODO docs - attr_reader :poll_interval - - # # Whether streaming mode should be enabled. Streaming mode asynchronously updates # feature flags in real-time using server-sent events. @@ -101,6 +96,11 @@ def offline? # @return [Float] The configured number of seconds between flushes of the event buffer. attr_reader :flush_interval + # + # The number of seconds to wait before polling for feature flag updates. This option has no + # effect unless streaming is disabled + attr_reader :poll_interval + # # The configured logger for the LaunchDarkly client. The client library uses the log to # print warning and error messages. diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb index f7dbb500..ff1b3f92 100644 --- a/lib/ldclient-rb/events.rb +++ b/lib/ldclient-rb/events.rb @@ -2,13 +2,76 @@ module LaunchDarkly class EventProcessor def initialize(api_key, config) + @queue = Queue.new @api_key = api_key @config = config @client = Faraday.new do |builder| builder.use :http_cache, store: @config.cache_store builder.adapter :net_http_persistent end + + @worker = create_worker + end + end + + def create_worker + Thread.new do + loop do + begin + flush + sleep(@config.flush_interval) + rescue StandardError => exn + log_exception(__method__.to_s, exn) + end + end + end + end + + def post_flushed_events(events) + @client.post (@config.events_uri + "/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 + def flush + events = [] + begin + loop do + events << @queue.pop(true) + end + rescue ThreadError + end + + if !events.empty? + post_flushed_events(events) + end + end + + def add_event(event) + return if @offline + + if @queue.length < @config.capacity + event[:creationDate] = (Time.now.to_f * 1000).to_i + @queue.push(event) + + if !@worker.alive? + @worker = create_worker + end + else + @config.logger.warn("[LDClient] Exceeded event queue capacity. Increase capacity to avoid dropping events.") + end + end + + + + private :create_worker, :post_flushed_events + end \ No newline at end of file diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index a00e9248..7874fd47 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -28,7 +28,6 @@ class LDClient # # @return [LDClient] The LaunchDarkly client instance def initialize(api_key, config = Config.default, wait_for = 0) - @queue = Queue.new @api_key = api_key @config = config end @@ -42,56 +41,13 @@ def initialize(api_key, config = Config.default, wait_for = 0) else @update_processor = PollingProcessor.new(config, requestor) end + @update_processor.start @event_processor = EventProcessor.new(api_key, config) - - @worker = create_worker end def flush - events = [] - begin - loop do - events << @queue.pop(true) - end - rescue ThreadError - end - - if !events.empty? - post_flushed_events(events) - end - end - - def post_flushed_events(events) - @client.post (@config.events_uri + "/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 - - def create_worker - Thread.new do - loop do - begin - flush - - sleep(@config.flush_interval) - rescue StandardError => exn - log_exception(__method__.to_s, exn) - end - end - end - end - - def get_flag?(key, user, default = false) - toggle?(key, user, default) + @event_processor.flush end # @@ -149,7 +105,7 @@ def toggle?(key, user, default = false) value = evaluate(feature, user) value = value.nil? ? default : value - add_event(kind: "feature", key: key, user: user, value: value, default: default) + @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) LDNewRelic.annotate_transaction(key, value) return value rescue StandardError => error @@ -157,21 +113,6 @@ def toggle?(key, user, default = false) default end - def add_event(event) - return if @offline - - if @queue.length < @config.capacity - event[:creationDate] = (Time.now.to_f * 1000).to_i - @queue.push(event) - - if !@worker.alive? - @worker = create_worker - end - else - @config.logger.warn("[LDClient] Exceeded event queue capacity. Increase capacity to avoid dropping events.") - end - end - # # Registers the user # @@ -179,7 +120,7 @@ def add_event(event) # def identify(user) sanitize_user(user) - add_event(kind: "identify", key: user[:key], user: user) + @event_processor.add_event(kind: "identify", key: user[:key], user: user) end # @@ -192,7 +133,7 @@ def identify(user) # @return [void] def track(event_name, user, data) sanitize_user(user) - add_event(kind: "custom", key: event_name, user: user, data: data) + @event_processor.add_event(kind: "custom", key: event_name, user: user, data: data) end # @@ -226,47 +167,6 @@ def all_flags end end - def get_user_settings(user) - Hash[all_flags.map { |key, feature| [key, evaluate(feature, user)]}] - 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) - @update_processor.get_feature(key) - end - - def get_flag_int(key) - res = make_request "/api/eval/features/" + key - - if res.status == 401 - @config.logger.error("[LDClient] Invalid API key") - return nil - end - - if res.status == 404 - @config.logger.error("[LDClient] Unknown feature key: #{key}") - return nil - end - - if res.status / 100 != 2 - @config.logger.error("[LDClient] Unexpected status code #{res.status}") - return nil - end - - JSON.parse(res.body, symbolize_names: true) - end - def param_for_user(feature, user) return nil unless user[:key] @@ -377,9 +277,7 @@ def sanitize_user(user) end end - 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_exception, :sanitize_user + private :param_for_user, :match_target?, :match_user?, :match_variation?, :evaluate, + :log_exception, :sanitize_user end end diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 7943f794..64c45d8f 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -1,6 +1,51 @@ +require "concurrent/atomics" + module LaunchDarkly class PollingProcessor + def initialize(api_key, config, requestor) + @api_key = api_key + @config = config + @requestor = requestor + @initalized = Concurrent::AtomicBoolean.new(false) + @started = Concurrent::AtomicBoolean.new(false) end + + def initialized? + @initialized.value + end + + def start + return unless @started.make_true + create_worker + end + + def poll + flags = @requestor.request_all_flags + if flags + @config.store.init(flags) + @initialized.make_true + end + end + + def create_worker + Thread.new do + loop do + begin + started_at = Time.now + poll + delta = @config.poll_interval - (Time.now - started_at) + if delta > 0 + sleep(delta) + end + rescue StandardError => exn + # TODO: log_exception(__method__.to_s, exn) + end + end + end + end + + + private :poll, :create_worker end end \ No newline at end of file diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 53287d4b..f38c5f8c 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -6,36 +6,21 @@ module LaunchDarkly PUT = "put" PATCH = "patch" DELETE = "delete" + INDIRECT_PUT = "indirect/put" + INDIRECT_PATCH = "indirect/patch" class StreamProcessor - def initialize(api_key, config) + def initialize(api_key, config, requestor) @api_key = api_key @config = config @store = config.feature_store ? config.feature_store : InMemoryFeatureStore.new - @disconnected = Concurrent::AtomicReference.new(nil) + @requestor = requestor + @initalized = Concurrent::AtomicBoolean.new(false) @started = Concurrent::AtomicBoolean.new(false) end def initialized? - @store.initialized? - end - - def started? - @started.value - end - - def get_all_features - if not initialized? - throw :uninitialized - end - @store.all - end - - def get_feature(key) - if not initialized? - throw :uninitialized - end - @store.get(key) + @initialized.value end def start @@ -48,18 +33,14 @@ def start } opts = {:headers => headers, :with_credentials => true} @es = Celluloid::EventSource.new(@config.stream_uri + "/features", opts) do |conn| - conn.on_open do - set_connected - end - conn.on(PUT) { |message| process_message(message, PUT) } conn.on(PATCH) { |message| process_message(message, PATCH) } conn.on(DELETE) { |message| process_message(message, DELETE) } - + conn.on(INDIRECT_PUT) { |message| process_message(message, INDIRECT_PUT) } + conn.on(INDIRECT_PATCH) { |message| process_message(message, INDIRECT_PATCH) } conn.on_error do |message| # TODO replace this with proper logging @config.logger.error("[LDClient] Error connecting to stream. Status code: #{message[:status_code]}") - set_disconnected end end end @@ -68,30 +49,22 @@ def process_message(message, method) message = JSON.parse(message.data, symbolize_names: true) if method == PUT @store.init(message) + @initialized.make_true elsif method == PATCH @store.upsert(message[:path][1..-1], message[:data]) elsif method == DELETE @store.delete(message[:path][1..-1], message[:version]) + elsif method == INDIRECT_PUT + @store.init(@requestor.request_all_flags) + @initialized.make_true + elsif method == INDIRECT_PATCH + @store.upsert(@requestor.request_flag(message[:data])) else @config.logger.error("[LDClient] Unknown message received: #{method}") end - set_connected - end - - def set_disconnected - @disconnected.set(Time.now) - end - - def set_connected - @disconnected.set(nil) - end - - def should_fallback_update - disc = @disconnected.get - !disc.nil? && disc < (Time.now - 120) end # TODO mark private methods - private :process_message, :set_connected, :set_disconnected + private :process_message end end From 960f08a1db17014e7bde7b830e282668e0dcd204 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 10:54:47 -0700 Subject: [PATCH 03/70] Fix syntax error --- lib/ldclient-rb/ldclient.rb | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 7874fd47..860c4d38 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -30,10 +30,7 @@ class LDClient def initialize(api_key, config = Config.default, wait_for = 0) @api_key = api_key @config = config - end - @store = config.feature_store - requestor = Requestor.new(api_key, config) if @config.stream? From aeabe5f8994c6099996ffb1d865d626f0491724f Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 11:03:45 -0700 Subject: [PATCH 04/70] Fix polling processor ctor --- lib/ldclient-rb/polling.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 64c45d8f..853f7df2 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -3,8 +3,7 @@ module LaunchDarkly class PollingProcessor - def initialize(api_key, config, requestor) - @api_key = api_key + def initialize(config, requestor) @config = config @requestor = requestor @initalized = Concurrent::AtomicBoolean.new(false) From 18e7d0486c314a6bd891025342fb662c90d11d76 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 12:18:15 -0700 Subject: [PATCH 05/70] Update imports, add create_worker to EventProcessor, update toggle and all_flags implementations --- lib/ldclient-rb/events.rb | 95 ++++++++++++++++++------------------ lib/ldclient-rb/ldclient.rb | 43 ++-------------- lib/ldclient-rb/requestor.rb | 2 + lib/ldclient-rb/stream.rb | 1 - 4 files changed, 55 insertions(+), 86 deletions(-) diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb index ff1b3f92..bb5b43b2 100644 --- a/lib/ldclient-rb/events.rb +++ b/lib/ldclient-rb/events.rb @@ -1,3 +1,6 @@ +require "thread" +require "faraday/http_cache" + module LaunchDarkly class EventProcessor @@ -12,66 +15,64 @@ def initialize(api_key, config) @worker = create_worker end - end - def create_worker - Thread.new do - loop do - begin - flush - sleep(@config.flush_interval) - rescue StandardError => exn - log_exception(__method__.to_s, exn) + def create_worker + Thread.new do + loop do + begin + flush + sleep(@config.flush_interval) + rescue StandardError => exn + log_exception(__method__.to_s, exn) + end end end end - end - def post_flushed_events(events) - @client.post (@config.events_uri + "/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 - - def flush - events = [] - begin - loop do - events << @queue.pop(true) + def post_flushed_events(events) + @client.post (@config.events_uri + "/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 - rescue ThreadError - end - - if !events.empty? - post_flushed_events(events) end - end - def add_event(event) - return if @offline - - if @queue.length < @config.capacity - event[:creationDate] = (Time.now.to_f * 1000).to_i - @queue.push(event) + def flush + events = [] + begin + loop do + events << @queue.pop(true) + end + rescue ThreadError + end - if !@worker.alive? - @worker = create_worker + if !events.empty? + post_flushed_events(events) end - else - @config.logger.warn("[LDClient] Exceeded event queue capacity. Increase capacity to avoid dropping events.") end - end + def add_event(event) + return if @offline + if @queue.length < @config.capacity + event[:creationDate] = (Time.now.to_f * 1000).to_i + @queue.push(event) - private :create_worker, :post_flushed_events + if !@worker.alive? + @worker = create_worker + end + else + @config.logger.warn("[LDClient] Exceeded event queue capacity. Increase capacity to avoid dropping events.") + end + end + private :create_worker, :post_flushed_events + + end end \ No newline at end of file diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 860c4d38..e69f0930 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -1,11 +1,6 @@ -require "faraday/http_cache" -require "json" require "digest/sha1" -require "thread" require "logger" -require "net/http/persistent" require "benchmark" -require "hashdiff" module LaunchDarkly BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] @@ -90,15 +85,7 @@ def toggle?(key, user, default = false) end sanitize_user(user) - if @config.stream? && !@update_processor.started? - @update_processor.start - end - - if @config.stream? && @update_processor.initialized? - feature = get_streamed_flag(key) - else - feature = get_flag_int(key) - end + feature = @store.get(key) value = evaluate(feature, user) value = value.nil? ? default : value @@ -133,35 +120,15 @@ def track(event_name, user, data) @event_processor.add_event(kind: "custom", key: event_name, user: user, data: data) end - # - # Returns the key of every feature flag - # - def all_keys - all_flags.keys - end - # # Returns all feature flags # - def all_flags + def all_flags(user) return Hash.new if @offline - if @config.stream? && !@update_processor.started? - @update_processor.start - end - - if @config.stream? && @update_processor.initialized? - @update_processor.get_all_features - else - res = make_request "/api/eval/features" + features = @store.all - if res.status / 100 == 2 - JSON.parse(res.body, symbolize_names: true) - else - @config.logger.error("[LDClient] Unexpected status code #{res.status}") - Hash.new - end - end + Hash[features{|k,f| [k, evaluate(f, user)] }] end def param_for_user(feature, user) @@ -275,6 +242,6 @@ def sanitize_user(user) end private :param_for_user, :match_target?, :match_user?, :match_variation?, :evaluate, - :log_exception, :sanitize_user + :log_exception, :sanitize_user, :find_weight_match, :find_target_match, :find_user_match end end diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb index a78d1c8a..72c8d493 100644 --- a/lib/ldclient-rb/requestor.rb +++ b/lib/ldclient-rb/requestor.rb @@ -1,4 +1,6 @@ require "json" +require "net/http/persistent" +require "faraday/http_cache" module LaunchDarkly diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index f38c5f8c..6719f18f 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -64,7 +64,6 @@ def process_message(message, method) end end - # TODO mark private methods private :process_message end end From 100129987123a4a0781cd953f4bb12dc066d694b Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 12:26:09 -0700 Subject: [PATCH 06/70] Assign res in Event processor --- lib/ldclient-rb/events.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb index bb5b43b2..34abcc46 100644 --- a/lib/ldclient-rb/events.rb +++ b/lib/ldclient-rb/events.rb @@ -30,7 +30,7 @@ def create_worker end def post_flushed_events(events) - @client.post (@config.events_uri + "/bulk") do |req| + res = @client.post (@config.events_uri + "/bulk") do |req| req.headers["Authorization"] = "api_key " + @api_key req.headers["User-Agent"] = "RubyClient/" + LaunchDarkly::VERSION req.headers["Content-Type"] = "application/json" From c2df04004e3f87bb17c711439a7806a0d0d297be Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:00:02 -0700 Subject: [PATCH 07/70] Wait for initialization --- lib/ldclient-rb/ldclient.rb | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index e69f0930..5432abf3 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -1,6 +1,7 @@ require "digest/sha1" require "logger" require "benchmark" +require "waitutil" module LaunchDarkly BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] @@ -22,20 +23,28 @@ class LDClient # @param config [Config] an optional client configuration object # # @return [LDClient] The LaunchDarkly client instance - def initialize(api_key, config = Config.default, wait_for = 0) + def initialize(api_key, config = Config.default, wait_for_sec = 0) @api_key = api_key @config = config @store = config.feature_store requestor = Requestor.new(api_key, config) - if @config.stream? - @update_processor = StreamProcessor.new(api_key, config, requestor) - else - @update_processor = PollingProcessor.new(config, requestor) + if !@config.offline + if @config.stream? + @update_processor = StreamProcessor.new(api_key, config, requestor) + else + @update_processor = PollingProcessor.new(config, requestor) + end + @update_processor.start end - @update_processor.start @event_processor = EventProcessor.new(api_key, config) + + if !@config.offline && wait_for_sec + WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec: => .1, :verbose => true) do + @update_processor.initialized? + end + end end def flush @@ -77,7 +86,7 @@ def flush # @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) - return default if @offline + return default if @config.offline unless user @config.logger.error("[LDClient] Must specify user") @@ -124,7 +133,7 @@ def track(event_name, user, data) # Returns all feature flags # def all_flags(user) - return Hash.new if @offline + return Hash.new if @config.offline features = @store.all From 938573cf9daf1217b45bbe8d5f432b0c3a27b53e Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:00:39 -0700 Subject: [PATCH 08/70] Fix syntax error in initializer --- lib/ldclient-rb/ldclient.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 5432abf3..1e773ba9 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -41,7 +41,7 @@ def initialize(api_key, config = Config.default, wait_for_sec = 0) @event_processor = EventProcessor.new(api_key, config) if !@config.offline && wait_for_sec - WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec: => .1, :verbose => true) do + WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec => .1, :verbose => true) do @update_processor.initialized? end end From e18e27c19d46d020233f4480bdf65a502b8797c6 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:01:21 -0700 Subject: [PATCH 09/70] Use correct floating point literal syntax --- lib/ldclient-rb/ldclient.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 1e773ba9..8673744e 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -41,7 +41,7 @@ def initialize(api_key, config = Config.default, wait_for_sec = 0) @event_processor = EventProcessor.new(api_key, config) if !@config.offline && wait_for_sec - WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec => .1, :verbose => true) do + WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec => 0.1, :verbose => true) do @update_processor.initialized? end end From aae8176ab1ab4711dfd1f21235627701febf8de5 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:02:15 -0700 Subject: [PATCH 10/70] offline -> offline? --- lib/ldclient-rb/ldclient.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 8673744e..c42165d9 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -29,7 +29,7 @@ def initialize(api_key, config = Config.default, wait_for_sec = 0) @store = config.feature_store requestor = Requestor.new(api_key, config) - if !@config.offline + if !@config.offline? if @config.stream? @update_processor = StreamProcessor.new(api_key, config, requestor) else @@ -40,7 +40,7 @@ def initialize(api_key, config = Config.default, wait_for_sec = 0) @event_processor = EventProcessor.new(api_key, config) - if !@config.offline && wait_for_sec + if !@config.offline? && wait_for_sec WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec => 0.1, :verbose => true) do @update_processor.initialized? end @@ -86,7 +86,7 @@ def flush # @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) - return default if @config.offline + return default if @config.offline? unless user @config.logger.error("[LDClient] Must specify user") @@ -133,7 +133,7 @@ def track(event_name, user, data) # Returns all feature flags # def all_flags(user) - return Hash.new if @config.offline + return Hash.new if @config.offline? features = @store.all From e9d22da221f74a371e162d0bb65929944e785fbc Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:02:58 -0700 Subject: [PATCH 11/70] Fix typo in stream initialization --- lib/ldclient-rb/stream.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 6719f18f..4e0a92ca 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -15,7 +15,7 @@ def initialize(api_key, config, requestor) @config = config @store = config.feature_store ? config.feature_store : InMemoryFeatureStore.new @requestor = requestor - @initalized = Concurrent::AtomicBoolean.new(false) + @initialized = Concurrent::AtomicBoolean.new(false) @started = Concurrent::AtomicBoolean.new(false) end From 87a3302149d6dd41f10cbb57f4edaf2bbc04b049 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:09:14 -0700 Subject: [PATCH 12/70] Rescue and log timeout exception --- lib/ldclient-rb/ldclient.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index c42165d9..c0cb30fc 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -40,9 +40,13 @@ def initialize(api_key, config = Config.default, wait_for_sec = 0) @event_processor = EventProcessor.new(api_key, config) - if !@config.offline? && wait_for_sec - WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec => 0.1, :verbose => true) do - @update_processor.initialized? + if !@config.offline? && wait_for_sec > 0 + begin + WaitUtil.wait_for_condition("LaunchDarkly client initialization", :timeout_sec => wait_for_sec, :delay_sec => 0.1) do + @update_processor.initialized? + end + rescue WaitUtil::TimeoutError + @config.logger.error("[LDClient] Timeout encountered waiting for LaunchDarkly client initialization") end end end From 48a56097ee55a261ffbba6b69271a7869ea30ffb Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:13:14 -0700 Subject: [PATCH 13/70] Improve debug output in stream --- lib/ldclient-rb/stream.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 4e0a92ca..65495959 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -39,7 +39,6 @@ def start conn.on(INDIRECT_PUT) { |message| process_message(message, INDIRECT_PUT) } conn.on(INDIRECT_PATCH) { |message| process_message(message, INDIRECT_PATCH) } conn.on_error do |message| - # TODO replace this with proper logging @config.logger.error("[LDClient] Error connecting to stream. Status code: #{message[:status_code]}") end end @@ -47,9 +46,11 @@ def start def process_message(message, method) message = JSON.parse(message.data, symbolize_names: true) + @config.logger.debug("[LDClient] Stream received #{method} message") if method == PUT @store.init(message) @initialized.make_true + @config.logger.debug("[LDClient] Stream initialized") elsif method == PATCH @store.upsert(message[:path][1..-1], message[:data]) elsif method == DELETE @@ -57,6 +58,7 @@ def process_message(message, method) elsif method == INDIRECT_PUT @store.init(@requestor.request_all_flags) @initialized.make_true + @config.logger.debug("[LDClient] Stream initialized (via indirect message)") elsif method == INDIRECT_PATCH @store.upsert(@requestor.request_flag(message[:data])) else From a373bc0d1551c4292cc74474cb4098bc390ea08b Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 13:59:11 -0700 Subject: [PATCH 14/70] Add debug logging for event enqueuing --- lib/ldclient-rb/events.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb index 34abcc46..e495290e 100644 --- a/lib/ldclient-rb/events.rb +++ b/lib/ldclient-rb/events.rb @@ -62,6 +62,7 @@ def add_event(event) if @queue.length < @config.capacity event[:creationDate] = (Time.now.to_f * 1000).to_i + @config.logger.debug("[LDClient] Enqueueing event: #{event.to_json}") @queue.push(event) if !@worker.alive? From 2e3e6d9d579ebafb221eb169e44aef06f55d9023 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:06:27 -0700 Subject: [PATCH 15/70] Debug output for evaluation --- lib/ldclient-rb/ldclient.rb | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index c0cb30fc..de2b6ee7 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -227,19 +227,34 @@ def find_weight_match(feature, param) end def evaluate(feature, user) - return nil if feature.nil? - return nil unless feature[:on] + if feature.nil? + @config.logger.debug("[LDClient] Nil feature in evaluate") + return nil + end + + if !feature[:on] + @config.logger.debug("[LDClient] Feature #{feature[:key]} is off") + return nil + end param = param_for_user(feature, user) return nil if param.nil? value = find_user_match(feature, user) - return value if !value.nil? + if !value.nil? + @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from user targeting match") + return value + end value = find_target_match(feature, user) - return value if !value.nil? + if !value.nil? + @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from rule match") + return value + end - find_weight_match(feature, param) + value = find_weight_match(feature, param) + @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from percentage rollout") + value end def log_exception(caller, exn) From e61a05ec509ef6768db920cab32c176816a42731 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:11:43 -0700 Subject: [PATCH 16/70] More debug output from streaming connection --- lib/ldclient-rb/stream.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 65495959..2039574b 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -25,6 +25,8 @@ def initialized? def start return unless @started.make_true + + @config.logger.info("[LDClient] Initializing stream connection") headers = { @@ -50,7 +52,7 @@ def process_message(message, method) if method == PUT @store.init(message) @initialized.make_true - @config.logger.debug("[LDClient] Stream initialized") + @config.logger.info("[LDClient] Stream initialized") elsif method == PATCH @store.upsert(message[:path][1..-1], message[:data]) elsif method == DELETE @@ -58,7 +60,7 @@ def process_message(message, method) elsif method == INDIRECT_PUT @store.init(@requestor.request_all_flags) @initialized.make_true - @config.logger.debug("[LDClient] Stream initialized (via indirect message)") + @config.logger.info("[LDClient] Stream initialized (via indirect message)") elsif method == INDIRECT_PATCH @store.upsert(@requestor.request_flag(message[:data])) else From e4d0a48dd492ad45769b525a0eeb3cef5b80eafb Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:21:47 -0700 Subject: [PATCH 17/70] Debug output for polling update processor --- lib/ldclient-rb/polling.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 853f7df2..fbbd5ddf 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -16,6 +16,8 @@ def initialized? def start return unless @started.make_true + @config.logger.info("[LDClient] Initializing polling connection") + create_worker end @@ -23,7 +25,11 @@ def poll flags = @requestor.request_all_flags if flags @config.store.init(flags) - @initialized.make_true + if @initialized.make_true + @config.logger.info("[LDClient] Polling connection initialized") + else + @config.logger.debug("[LDClient] Received polling updated") + end end end From 99645f0fabb5a595a8fdb342c3ad5fd02969bee8 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:23:07 -0700 Subject: [PATCH 18/70] Fix typo in polling processor initialization --- lib/ldclient-rb/polling.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index fbbd5ddf..df3d171a 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -6,7 +6,7 @@ class PollingProcessor def initialize(config, requestor) @config = config @requestor = requestor - @initalized = Concurrent::AtomicBoolean.new(false) + @initialized = Concurrent::AtomicBoolean.new(false) @started = Concurrent::AtomicBoolean.new(false) end From 771c42ee9cc884c010d51d878d1701f66c0ebdd0 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:24:42 -0700 Subject: [PATCH 19/70] Import thread package --- lib/ldclient-rb/polling.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index df3d171a..74b4368b 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -1,4 +1,5 @@ require "concurrent/atomics" +require "thread" module LaunchDarkly class PollingProcessor From 8b5bc52861706312a3a619914b7e7641060d6907 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:26:11 -0700 Subject: [PATCH 20/70] More debug output for polling --- lib/ldclient-rb/polling.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 74b4368b..551c8cc7 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -36,6 +36,7 @@ def poll def create_worker Thread.new do + @config.logger.debug("[LDClient] Starting polling worker") loop do begin started_at = Time.now From c50b832c3441ec65e54e98631b9b83db57cac266 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:27:33 -0700 Subject: [PATCH 21/70] Debug output for requestor --- lib/ldclient-rb/requestor.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb index 72c8d493..36c3f7b2 100644 --- a/lib/ldclient-rb/requestor.rb +++ b/lib/ldclient-rb/requestor.rb @@ -24,6 +24,7 @@ def request_flag(key) end def make_request(path) + @config.logger.debug("[LDClient] Making remote request to #{@config.base_uri + path}") res = @client.get (@config.base_uri + path) do |req| req.headers["Authorization"] = "api_key " + @api_key req.headers["User-Agent"] = "RubyClient/" + LaunchDarkly::VERSION From a8da405cd52553438edc21dd7b922133fb60d533 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:29:32 -0700 Subject: [PATCH 22/70] Debug the sleep time in polling processor --- lib/ldclient-rb/polling.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 551c8cc7..9cf822bf 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -43,9 +43,11 @@ def create_worker poll delta = @config.poll_interval - (Time.now - started_at) if delta > 0 + @config.logger.debug("[LDClient] Polling processor sleeping for #{delta} milliseconds") sleep(delta) end rescue StandardError => exn + @config.logger.error("[LDClient] Exception while polling: #{exn.inspect}") # TODO: log_exception(__method__.to_s, exn) end end From 2264d0c728f8795bbdccc8026d1dc0922245b96c Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:31:23 -0700 Subject: [PATCH 23/70] Clean up feature store definition --- lib/ldclient-rb/polling.rb | 2 +- lib/ldclient-rb/stream.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 9cf822bf..0be0cce1 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -25,7 +25,7 @@ def start def poll flags = @requestor.request_all_flags if flags - @config.store.init(flags) + @config.feature_store.init(flags) if @initialized.make_true @config.logger.info("[LDClient] Polling connection initialized") else diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 2039574b..f694cd04 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -13,7 +13,7 @@ class StreamProcessor def initialize(api_key, config, requestor) @api_key = api_key @config = config - @store = config.feature_store ? config.feature_store : InMemoryFeatureStore.new + @store = config.feature_store @requestor = requestor @initialized = Concurrent::AtomicBoolean.new(false) @started = Concurrent::AtomicBoolean.new(false) From 1106ff31305239bf8e8204d69da9abeef4f6f2bf Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:32:01 -0700 Subject: [PATCH 24/70] Improve debug output --- lib/ldclient-rb/polling.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index 0be0cce1..c2d67f08 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -29,7 +29,7 @@ def poll if @initialized.make_true @config.logger.info("[LDClient] Polling connection initialized") else - @config.logger.debug("[LDClient] Received polling updated") + @config.logger.debug("[LDClient] Received polling update") end end end @@ -43,7 +43,7 @@ def create_worker poll delta = @config.poll_interval - (Time.now - started_at) if delta > 0 - @config.logger.debug("[LDClient] Polling processor sleeping for #{delta} milliseconds") + @config.logger.debug("[LDClient] Polling processor sleeping for #{delta} seconds") sleep(delta) end rescue StandardError => exn From 79bd9255add42484aa272a783c88cc2ab62eebcd Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:35:09 -0700 Subject: [PATCH 25/70] More debug output changes --- lib/ldclient-rb/ldclient.rb | 3 +++ lib/ldclient-rb/polling.rb | 4 ---- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index de2b6ee7..89586729 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -2,6 +2,7 @@ require "logger" require "benchmark" require "waitutil" +require "json" module LaunchDarkly BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] @@ -232,6 +233,8 @@ def evaluate(feature, user) return nil end + @config.logger.debug("[LDClient] Evaluating feature: #{feature.to_json}") + if !feature[:on] @config.logger.debug("[LDClient] Feature #{feature[:key]} is off") return nil diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb index c2d67f08..f3e3bf69 100644 --- a/lib/ldclient-rb/polling.rb +++ b/lib/ldclient-rb/polling.rb @@ -18,7 +18,6 @@ def initialized? def start return unless @started.make_true @config.logger.info("[LDClient] Initializing polling connection") - create_worker end @@ -28,8 +27,6 @@ def poll @config.feature_store.init(flags) if @initialized.make_true @config.logger.info("[LDClient] Polling connection initialized") - else - @config.logger.debug("[LDClient] Received polling update") end end end @@ -43,7 +40,6 @@ def create_worker poll delta = @config.poll_interval - (Time.now - started_at) if delta > 0 - @config.logger.debug("[LDClient] Polling processor sleeping for #{delta} seconds") sleep(delta) end rescue StandardError => exn From 314c6749cb472ba6d959af4829308225381fa1a0 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:41:25 -0700 Subject: [PATCH 26/70] Remove more debugging --- lib/ldclient-rb/requestor.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb index 36c3f7b2..72c8d493 100644 --- a/lib/ldclient-rb/requestor.rb +++ b/lib/ldclient-rb/requestor.rb @@ -24,7 +24,6 @@ def request_flag(key) end def make_request(path) - @config.logger.debug("[LDClient] Making remote request to #{@config.base_uri + path}") res = @client.get (@config.base_uri + path) do |req| req.headers["Authorization"] = "api_key " + @api_key req.headers["User-Agent"] = "RubyClient/" + LaunchDarkly::VERSION From c903e6695088af447d66d9f8dc99f379695a675c Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 14:48:49 -0700 Subject: [PATCH 27/70] Fix endpoint for v1 --- lib/ldclient-rb/requestor.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb index 72c8d493..f26373d4 100644 --- a/lib/ldclient-rb/requestor.rb +++ b/lib/ldclient-rb/requestor.rb @@ -16,11 +16,11 @@ def initialize(api_key, config) end def request_all_flags() - make_request("/sdk/latest-flags") + make_request("/api/eval/latest-features") end def request_flag(key) - make_request("/sdk/latest-flags/" + key) + make_request("/api/eval/latest-features/" + key) end def make_request(path) From 13f041efcbbb01940ee036977cf1d179461b5461 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 15:17:59 -0700 Subject: [PATCH 28/70] Move evaluation methods into a separate sub-module --- lib/ldclient-rb.rb | 1 + lib/ldclient-rb/evaluation.rb | 122 ++++++++++++++++++++++++++++++++++ lib/ldclient-rb/ldclient.rb | 118 +------------------------------- 3 files changed, 124 insertions(+), 117 deletions(-) create mode 100644 lib/ldclient-rb/evaluation.rb diff --git a/lib/ldclient-rb.rb b/lib/ldclient-rb.rb index 6460dbe0..c9b7403c 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -9,3 +9,4 @@ require "ldclient-rb/events" require "ldclient-rb/feature_store" require "ldclient-rb/requestor" +require "ldclient-rb/evaluation" diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb new file mode 100644 index 00000000..e1d74b60 --- /dev/null +++ b/lib/ldclient-rb/evaluation.rb @@ -0,0 +1,122 @@ +module LaunchDarkly + + module Evaluation + BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] + + def param_for_user(feature, user) + return nil unless user[:key] + + id_hash = user[:key] + if user[:secondary] + id_hash += "." + user[:secondary] + end + + hash_key = "%s.%s.%s" % [feature[:key], feature[:salt], id_hash] + + hash_val = (Digest::SHA1.hexdigest(hash_key))[0..14] + hash_val.to_i(16) / Float(0xFFFFFFFFFFFFFFF) + end + + def match_target?(target, user) + attrib = target[:attribute].to_sym + + if BUILTINS.include?(attrib) + return false unless user[attrib] + + u_value = user[attrib] + return target[:values].include? u_value + else # custom attribute + 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?) + else + return target[:values].include? u_value + end + + return false + end + end + + def match_user?(variation, user) + if variation[:userTarget] + return match_target?(variation[:userTarget], user) + end + false + end + + def find_user_match(feature, user) + feature[:variations].each do |variation| + return variation[:value] if match_user?(variation, user) + end + nil + end + + def match_variation?(variation, user) + variation[:targets].each do |target| + if !!variation[:userTarget] && target[:attribute].to_sym == :key + next + end + + if match_target?(target, user) + return true + end + end + false + end + + def find_target_match(feature, user) + feature[:variations].each do |variation| + return variation[:value] if match_variation?(variation, user) + end + nil + end + + def find_weight_match(feature, param) + total = 0.0 + feature[:variations].each do |variation| + total += variation[:weight].to_f / 100.0 + + return variation[:value] if param < total + end + + nil + end + + def evaluate(feature, user) + if feature.nil? + @config.logger.debug("[LDClient] Nil feature in evaluate") + return nil + end + + @config.logger.debug("[LDClient] Evaluating feature: #{feature.to_json}") + + if !feature[:on] + @config.logger.debug("[LDClient] Feature #{feature[:key]} is off") + return nil + end + + param = param_for_user(feature, user) + return nil if param.nil? + + value = find_user_match(feature, user) + if !value.nil? + @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from user targeting match") + return value + end + + value = find_target_match(feature, user) + if !value.nil? + @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from rule match") + return value + end + + value = find_weight_match(feature, param) + @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from percentage rollout") + value + end + end + +end \ No newline at end of file diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 89586729..f9ee2927 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -5,8 +5,6 @@ require "json" module LaunchDarkly - BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] - # # A client for the LaunchDarkly API. Client instances are thread-safe. Users # should create a single client instance for the lifetime of the application. @@ -14,6 +12,7 @@ module LaunchDarkly # class LDClient include Settings + include Evaluation # # Creates a new client instance that connects to LaunchDarkly. A custom # configuration parameter can also supplied to specify advanced options, @@ -145,121 +144,6 @@ def all_flags(user) Hash[features{|k,f| [k, evaluate(f, user)] }] end - def param_for_user(feature, user) - return nil unless user[:key] - - id_hash = user[:key] - if user[:secondary] - id_hash += "." + user[:secondary] - end - - hash_key = "%s.%s.%s" % [feature[:key], feature[:salt], id_hash] - - hash_val = (Digest::SHA1.hexdigest(hash_key))[0..14] - hash_val.to_i(16) / Float(0xFFFFFFFFFFFFFFF) - end - - def match_target?(target, user) - attrib = target[:attribute].to_sym - - if BUILTINS.include?(attrib) - return false unless user[attrib] - - u_value = user[attrib] - return target[:values].include? u_value - else # custom attribute - 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?) - else - return target[:values].include? u_value - end - - return false - end - end - - def match_user?(variation, user) - if variation[:userTarget] - return match_target?(variation[:userTarget], user) - end - false - end - - def find_user_match(feature, user) - feature[:variations].each do |variation| - return variation[:value] if match_user?(variation, user) - end - nil - end - - def match_variation?(variation, user) - variation[:targets].each do |target| - if !!variation[:userTarget] && target[:attribute].to_sym == :key - next - end - - if match_target?(target, user) - return true - end - end - false - end - - def find_target_match(feature, user) - feature[:variations].each do |variation| - return variation[:value] if match_variation?(variation, user) - end - nil - end - - def find_weight_match(feature, param) - total = 0.0 - feature[:variations].each do |variation| - total += variation[:weight].to_f / 100.0 - - return variation[:value] if param < total - end - - nil - end - - def evaluate(feature, user) - if feature.nil? - @config.logger.debug("[LDClient] Nil feature in evaluate") - return nil - end - - @config.logger.debug("[LDClient] Evaluating feature: #{feature.to_json}") - - if !feature[:on] - @config.logger.debug("[LDClient] Feature #{feature[:key]} is off") - return nil - end - - param = param_for_user(feature, user) - return nil if param.nil? - - value = find_user_match(feature, user) - if !value.nil? - @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from user targeting match") - return value - end - - value = find_target_match(feature, user) - if !value.nil? - @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from rule match") - return value - end - - value = find_weight_match(feature, param) - @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from percentage rollout") - value - end - def log_exception(caller, exn) error_traceback = "#{exn.inspect} #{exn}\n\t#{exn.backtrace.join("\n\t")}" error = "[LDClient] Unexpected exception in #{caller}: #{error_traceback}" From dbad74f8d0e5488f0c6fa7554431d1be6bf47d8c Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 6 Jul 2016 15:19:04 -0700 Subject: [PATCH 29/70] Move evaluation sub-module --- lib/ldclient-rb.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb.rb b/lib/ldclient-rb.rb index c9b7403c..01ab529e 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -1,5 +1,6 @@ require "ldclient-rb/version" require "ldclient-rb/settings" +require "ldclient-rb/evaluation" require "ldclient-rb/ldclient" require "ldclient-rb/cache_store" require "ldclient-rb/config" @@ -9,4 +10,3 @@ require "ldclient-rb/events" require "ldclient-rb/feature_store" require "ldclient-rb/requestor" -require "ldclient-rb/evaluation" From 8f9c213dbe1a0ebd2e25f89ff010516fdd9768d0 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 14:50:06 -0700 Subject: [PATCH 30/70] First cut at v2 evaluation --- lib/ldclient-rb.rb | 1 + lib/ldclient-rb/evaluation.rb | 224 ++++++++++++++++++++++------------ lib/ldclient-rb/ldclient.rb | 43 +++++-- lib/ldclient-rb/operators.rb | 56 +++++++++ lib/ldclient-rb/requestor.rb | 4 +- lib/ldclient-rb/stream.rb | 2 +- 6 files changed, 239 insertions(+), 91 deletions(-) create mode 100644 lib/ldclient-rb/operators.rb diff --git a/lib/ldclient-rb.rb b/lib/ldclient-rb.rb index 01ab529e..ebe170bc 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -1,5 +1,6 @@ require "ldclient-rb/version" require "ldclient-rb/settings" +require "ldclient-rb/operators" require "ldclient-rb/evaluation" require "ldclient-rb/ldclient" require "ldclient-rb/cache_store" diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index e1d74b60..2d5a1c8a 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -1,122 +1,194 @@ module LaunchDarkly module Evaluation + include Operators BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] - def param_for_user(feature, user) - return nil unless user[:key] + class EvaluationError < StandardError + end - id_hash = user[:key] - if user[:secondary] - id_hash += "." + user[:secondary] + # Evaluates a feature flag, returning a hash containing the evaluation result and any events + # generated during prerequisite evaluation. Raises EvaluationError if the flag is not well-formed + # Will return nil, but not raise an exception, indicating that the rules (including fallthrough) did not match + # In that case, the caller should return the default value. + def evaluate(flag, user, store) + if flag.nil? + raise EvaluationError, "Flag does not exist" end - hash_key = "%s.%s.%s" % [feature[:key], feature[:salt], id_hash] - - hash_val = (Digest::SHA1.hexdigest(hash_key))[0..14] - hash_val.to_i(16) / Float(0xFFFFFFFFFFFFFFF) - end + if user.nil? || user[:key].nil? + raise EvaluationError, "Invalid user" + end - def match_target?(target, user) - attrib = target[:attribute].to_sym + events = [] - if BUILTINS.include?(attrib) - return false unless user[attrib] + if feature[:on] + res = eval_internal(flag, user, store, events) - u_value = user[attrib] - return target[:values].include? u_value - else # custom attribute - return false unless user[:custom] - return false unless user[:custom].include? attrib + return res if !res[:value].nil? + end - u_value = user[:custom][attrib] - if u_value.is_a? Array - return ! ((target[:values] & u_value).empty?) - else - return target[:values].include? u_value - end - return false + if !feature[:off_variation].nil? && feature[:off_variation] < feature[:variations].length + value = feature[:variations][:off_variation] + @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) + return {value: value, events: events} end - end - def match_user?(variation, user) - if variation[:userTarget] - return match_target?(variation[:userTarget], user) - end - false + {value: nil, events: events} end - def find_user_match(feature, user) - feature[:variations].each do |variation| - return variation[:value] if match_user?(variation, user) + def eval_internal(flag, user, store, events) + failed_prereq = false + # Evaluate prerequisites, if any + if !flag[:prerequisites].nil? + flag[:prerequisites].each do |prerequisite| + + prereq_flag = store.get(prerequisite[:key]) + + if !prereq_flag[:on] + failed_prereq = true + end + + begin + prereq_res = eval_internal(prereq_flag, user, store, events) + events.push(kind: "feature", key: key, value: default, default: default) + variation = get_variation(prereq_flag, prerequisite[:variation]) + if prereq_res.nil? || prereq_res != variation + failed_prereq = true + end + rescue => exn + @config.logger.error("[LDClient] Error evaluating prerequisite: #{exn.inspect}") + failed_prereq = true + end + + end + + if failed_prereq + return {value: nil, events: events} + end end - nil + # The prerequisites were satisfied. + # Now walk through the evaluation steps and get the correct + # variation index + {value: eval_rules(flag, user), events: events} end - def match_variation?(variation, user) - variation[:targets].each do |target| - if !!variation[:userTarget] && target[:attribute].to_sym == :key - next + def eval_rules(flag, user) + # Check user target matches + if !flag[:targets].nil? + flag[:targets].each do |target| + if !target[:values].nil? + target[:values].each do |value| + return get_variation(flag, target[:variation]) if value == user[:key] + end + end end + end - if match_target?(target, user) - return true + # Check custom rules + if !flag[:rules].nil? + flag[:rules].each do |rule| + return variation_for_user(rule, user, flag) if rule_match_user(rule, user) end end - false - end - def find_target_match(feature, user) - feature[:variations].each do |variation| - return variation[:value] if match_variation?(variation, user) + # Check the fallthrough rule + if !flag[:fallthrough].nil? + return variation_for_user(flag[:fallthrough], user, flag]) end + + # Not even the fallthrough matched-- return the off variation or default nil end - def find_weight_match(feature, param) - total = 0.0 - feature[:variations].each do |variation| - total += variation[:weight].to_f / 100.0 + def get_variation(flag, index) + if index >= flag[:variations].length + raise EvaluationError, "Invalid variation index" + end + flag[:variations][index] + end + + def rule_match_user(rule, user) + return false if !r[:clauses] - return variation[:value] if param < total + rule[:clauses].each do |clause| + return false if !clause_match_user(clause, user) end - nil + return true end - def evaluate(feature, user) - if feature.nil? - @config.logger.debug("[LDClient] Nil feature in evaluate") - return nil - end + def clause_match_user(clause, user) + val = user_value(user, clause[:attribute]) + return false if val.nil? - @config.logger.debug("[LDClient] Evaluating feature: #{feature.to_json}") + op = operators[clause[:op]] - if !feature[:on] - @config.logger.debug("[LDClient] Feature #{feature[:key]} is off") - return nil + if val.is_a? Enumerable + val.each do |v| + return maybe_negate(clause, true) if match_any(op, v, clause[:values]) + end + return maybe_negate(clause, false) end - param = param_for_user(feature, user) - return nil if param.nil? + maybe_negate(clause, match_any(op, val, clause[:values])) + end + + def variation_for_user(rule, user, flag) + if !rule[:variation].nil? # fixed variation + return get_variation(flag, rule[:variation]) + elsif !rule[:rollout].nil? # percentage rollout + rollout = rule[:rollout] + bucket_by = rollout[:bucketBy].nil? ? "key" : rollout[:bucketBy] + bucket = bucket_user(user, flag[:key], bucket_by, flag[:salt]) + sum = 0; + rollout[:variations].each do |variate| + sum += variate[:weight].to_f / 100000.0 + return get_variation(flag, variate[:variation]) if bucket < sum + end + nil + else # the rule isn't well-formed + raise EvaluationError, "Rule does not define a variation or rollout" + end + end + + def bucket_user(user, key, bucket_by, salt) + return nil unless user[:key] - value = find_user_match(feature, user) - if !value.nil? - @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from user targeting match") - return value + id_hash = user_value(user, bucket_by) + + if user[:secondary] + id_hash += "." + user[:secondary] end - value = find_target_match(feature, user) - if !value.nil? - @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from rule match") - return value + hash_key = "%s.%s.%s" % [key, salt, id_hash] + + hash_val = (Digest::SHA1.hexdigest(hash_key))[0..14] + hash_val.to_i(16) / Float(0xFFFFFFFFFFFFFFF) + end + + def user_value(user, attribute) + if BUILTINS[attribute] + user[attribute] + elsif !user[:custom].is_nil? + user[:custom][attribute] + else + nil end + end - value = find_weight_match(feature, param) - @config.logger.debug("[LDClient] Evaluated feature #{feature[:key]} to #{value} from percentage rollout") - value + def maybe_negate(clause, b) + clause[:negate] ? !b : b + end + + def match_any(op, value, values) + values.each do |v| + return true if op.call(value, v) + end + return false end end -end \ No newline at end of file +end + diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index f9ee2927..c46ecb76 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -94,20 +94,39 @@ def toggle?(key, user, default = false) unless user @config.logger.error("[LDClient] Must specify user") + @event_processor.add_event(kind: "feature", key: key, value: default, default: default) return default end - sanitize_user(user) + if !@update_processor.initialized? + @config.logger.error("[LDClient] Client has not finished initializing. Returning default value") + @event_processor.add_event(kind: "feature", key: key, value: default, default: default) + return default + end + + sanitize_user(user) feature = @store.get(key) - value = evaluate(feature, user) - value = value.nil? ? default : value - - @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) - LDNewRelic.annotate_transaction(key, value) - return value - rescue StandardError => error - log_exception(__method__.to_s, error) - default + + begin + res = evaluate(feature, user, @config.store) + if !res[:events].nil? + res[:events] do |event| + @event_processor.add_event(event) + end + end + if !res[:value].nil? + @event_processor.add_event(kind: "feature", key: key, user: user, value: res[:value], default: default) + return res[:value] + else + @config.logger.debug("[LDClient] Result value is null in toggle") + @event_processor.add_event(kind: "feature", key: key, value: default, default: default) + return default + end + rescue => exn + @config.logger.warn("[LDClient] Error evaluating feature flag: #{exn.inspect}") + @event_processor.add_event(kind: "feature", key: key, user: user, value: default, default: default) + return default + end end # @@ -134,14 +153,14 @@ def track(event_name, user, data) end # - # Returns all feature flags + # Returns all feature flag values for the given user # def all_flags(user) return Hash.new if @config.offline? features = @store.all - Hash[features{|k,f| [k, evaluate(f, user)] }] + Hash[features{|k,f| [k, evaluate(f, user, @config.store)[:value]] }] end def log_exception(caller, exn) diff --git a/lib/ldclient-rb/operators.rb b/lib/ldclient-rb/operators.rb new file mode 100644 index 00000000..99c107c7 --- /dev/null +++ b/lib/ldclient-rb/operators.rb @@ -0,0 +1,56 @@ +require "date" + +module LaunchDarkly + module Operators + operators = { + in: + lambda do |a, b| + a == b + end, + endsWith: + lambda do |a, b| + (a.is_a? String) && (a.end_with? b) + end, + startsWith: + lambda do |a, b| + (a.is_a? String) && (a.start_with? b) + end, + matches: + lambda do |a, b| + (a.is_a? String) && !(Regexp.new a).match(b).nil? + end, + contains: + lambda do |a, b| + (a.is_a? String) && (a.include? b) + end, + lessThan: + lambda do |a, b| + (a.is_a? Numeric) && (a < b) + end, + lessThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a <= b) + end, + greaterThan: + lambda do |a, b| + (a.is_a? Numeric) && (a > b) + end, + greaterThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a >= b) + end, + greaterThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a >= b) + end, + before: + lambda do |a, b| + ((a.is_a? Numeric) && (a < b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc < DateTime.rfc3339(b).to_time.utc)) + end, + after: + lambda do |a, b| + ((a.is_a? Numeric) && (a > b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc > DateTime.rfc3339(b).to_time.utc)) + end + } + end +end \ No newline at end of file diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb index f26373d4..b33a2804 100644 --- a/lib/ldclient-rb/requestor.rb +++ b/lib/ldclient-rb/requestor.rb @@ -16,11 +16,11 @@ def initialize(api_key, config) end def request_all_flags() - make_request("/api/eval/latest-features") + make_request("/sdk/latest-features") end def request_flag(key) - make_request("/api/eval/latest-features/" + key) + make_request("/sdk/latest-features/" + key) end def make_request(path) diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index f694cd04..13dd0a11 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -34,7 +34,7 @@ def start 'User-Agent' => 'RubyClient/' + LaunchDarkly::VERSION } opts = {:headers => headers, :with_credentials => true} - @es = Celluloid::EventSource.new(@config.stream_uri + "/features", opts) do |conn| + @es = Celluloid::EventSource.new(@config.stream_uri + "/flags", opts) do |conn| conn.on(PUT) { |message| process_message(message, PUT) } conn.on(PATCH) { |message| process_message(message, PATCH) } conn.on(DELETE) { |message| process_message(message, DELETE) } From 2571e5169a578e3774fa009c32bcdf51246271d2 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 15:53:30 -0700 Subject: [PATCH 31/70] Symbolize event names --- lib/ldclient-rb/stream.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/ldclient-rb/stream.rb b/lib/ldclient-rb/stream.rb index 13dd0a11..b0b52a2e 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -3,11 +3,11 @@ require "celluloid/eventsource" module LaunchDarkly - PUT = "put" - PATCH = "patch" - DELETE = "delete" - INDIRECT_PUT = "indirect/put" - INDIRECT_PATCH = "indirect/patch" + PUT = :put + PATCH = :patch + DELETE = :delete + INDIRECT_PUT = :'indirect/put' + INDIRECT_PATCH = :'indirect/patch' class StreamProcessor def initialize(api_key, config, requestor) From 4753b2a23c9f7f71ddc079912a4d70cfb87c7e66 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:01:34 -0700 Subject: [PATCH 32/70] Fix syntax error --- lib/ldclient-rb/evaluation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 2d5a1c8a..cf2512d3 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -95,7 +95,7 @@ def eval_rules(flag, user) # Check the fallthrough rule if !flag[:fallthrough].nil? - return variation_for_user(flag[:fallthrough], user, flag]) + return variation_for_user(flag[:fallthrough], user, flag) end # Not even the fallthrough matched-- return the off variation or default From 83805799138e375f36912bb2bfa2083e487355aa Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:02:14 -0700 Subject: [PATCH 33/70] Add each to iterator syntax --- lib/ldclient-rb/ldclient.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index c46ecb76..e37c4894 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -110,7 +110,7 @@ def toggle?(key, user, default = false) begin res = evaluate(feature, user, @config.store) if !res[:events].nil? - res[:events] do |event| + res[:events].each do |event| @event_processor.add_event(event) end end From 4f24dcc4dcf809635998978bc20a813b20335472 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:03:19 -0700 Subject: [PATCH 34/70] Remove references to obsolete private methods --- lib/ldclient-rb/ldclient.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index e37c4894..06094525 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -175,7 +175,6 @@ def sanitize_user(user) end end - private :param_for_user, :match_target?, :match_user?, :match_variation?, :evaluate, - :log_exception, :sanitize_user, :find_weight_match, :find_target_match, :find_user_match + private :evaluate, :log_exception, :sanitize_user end end From 9ef0b6015ae677741cf76bbeeb9abf9034696ba1 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:19:39 -0700 Subject: [PATCH 35/70] Pass the correct store --- lib/ldclient-rb/ldclient.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 06094525..27ab7dfa 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -108,7 +108,7 @@ def toggle?(key, user, default = false) feature = @store.get(key) begin - res = evaluate(feature, user, @config.store) + res = evaluate(feature, user, @store) if !res[:events].nil? res[:events].each do |event| @event_processor.add_event(event) @@ -160,7 +160,7 @@ def all_flags(user) features = @store.all - Hash[features{|k,f| [k, evaluate(f, user, @config.store)[:value]] }] + Hash[features{|k,f| [k, evaluate(f, user, @store)[:value]] }] end def log_exception(caller, exn) From 8309254b1b23ca0e51dd872e966bc366ab10b829 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:22:40 -0700 Subject: [PATCH 36/70] feature -> flag --- lib/ldclient-rb/evaluation.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index cf2512d3..2d0759f7 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -22,15 +22,15 @@ def evaluate(flag, user, store) events = [] - if feature[:on] + if flag[:on] res = eval_internal(flag, user, store, events) return res if !res[:value].nil? end - if !feature[:off_variation].nil? && feature[:off_variation] < feature[:variations].length - value = feature[:variations][:off_variation] + if !flag[:off_variation].nil? && flag[:off_variation] < flag[:variations].length + value = flag[:variations][:off_variation] @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) return {value: value, events: events} end From 2b0969af6150ad48fa1105200411e297b75315e5 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:27:37 -0700 Subject: [PATCH 37/70] r -> rule --- lib/ldclient-rb/evaluation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 2d0759f7..d8fe04d9 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -110,7 +110,7 @@ def get_variation(flag, index) end def rule_match_user(rule, user) - return false if !r[:clauses] + return false if !rule[:clauses] rule[:clauses].each do |clause| return false if !clause_match_user(clause, user) From e5b1dad84ae31c6053b4bcb7e7966329bba26f4e Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 16:31:40 -0700 Subject: [PATCH 38/70] Add the exception backtrace to debug output --- lib/ldclient-rb/ldclient.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 27ab7dfa..297b6520 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -123,7 +123,7 @@ def toggle?(key, user, default = false) return default end rescue => exn - @config.logger.warn("[LDClient] Error evaluating feature flag: #{exn.inspect}") + @config.logger.warn("[LDClient] Error evaluating feature flag: #{exn.inspect}. \nTrace: #{exn.backtrace}") @event_processor.add_event(kind: "feature", key: key, user: user, value: default, default: default) return default end From a76d93baab1b810c76367fc6fa69c5fa4a3e4e74 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:15:30 -0700 Subject: [PATCH 39/70] Fix builtin lookup --- lib/ldclient-rb/evaluation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index d8fe04d9..d9dda0e7 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -169,7 +169,7 @@ def bucket_user(user, key, bucket_by, salt) end def user_value(user, attribute) - if BUILTINS[attribute] + if BUILTINS.include? attribute user[attribute] elsif !user[:custom].is_nil? user[:custom][attribute] From 663fbc5eb4fa37419afd04b103eedb1c4af4ba2e Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:22:54 -0700 Subject: [PATCH 40/70] Fix prereq evaluation --- lib/ldclient-rb/evaluation.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index d9dda0e7..db4e29db 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -52,7 +52,7 @@ def eval_internal(flag, user, store, events) begin prereq_res = eval_internal(prereq_flag, user, store, events) - events.push(kind: "feature", key: key, value: default, default: default) + events.push(kind: "feature", key: prereq_flag[:key], value: default, default: default) variation = get_variation(prereq_flag, prerequisite[:variation]) if prereq_res.nil? || prereq_res != variation failed_prereq = true @@ -171,7 +171,7 @@ def bucket_user(user, key, bucket_by, salt) def user_value(user, attribute) if BUILTINS.include? attribute user[attribute] - elsif !user[:custom].is_nil? + elsif !user[:custom].nil? user[:custom][attribute] else nil From 8a5f17497f0fd72cae460f284da9013aed935064 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:31:19 -0700 Subject: [PATCH 41/70] Return the correct off variation --- lib/ldclient-rb/evaluation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index db4e29db..76fe296e 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -30,7 +30,7 @@ def evaluate(flag, user, store) if !flag[:off_variation].nil? && flag[:off_variation] < flag[:variations].length - value = flag[:variations][:off_variation] + value = flag[:variations][flag[:off_variation]] @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) return {value: value, events: events} end From 4ccf97a66abd6811e2fb00c4a258dc087a083615 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:34:28 -0700 Subject: [PATCH 42/70] Debug output for off variation --- lib/ldclient-rb/evaluation.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 76fe296e..0743be5d 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -28,6 +28,7 @@ def evaluate(flag, user, store) return res if !res[:value].nil? end + @config.logger.debug("Off variation is #{flag[:off_variation]} and flag has #{flag[:variations]} variations") if !flag[:off_variation].nil? && flag[:off_variation] < flag[:variations].length value = flag[:variations][flag[:off_variation]] From ff44f14c46d0a76c5a5bac32e810b60c254f11a1 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:36:21 -0700 Subject: [PATCH 43/70] Fix attribute name for offVariation --- lib/ldclient-rb/evaluation.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 0743be5d..8398ccea 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -28,10 +28,10 @@ def evaluate(flag, user, store) return res if !res[:value].nil? end - @config.logger.debug("Off variation is #{flag[:off_variation]} and flag has #{flag[:variations]} variations") + @config.logger.debug("Off variation is #{flag[:offVariation]} and flag has #{flag[:variations]} variations") - if !flag[:off_variation].nil? && flag[:off_variation] < flag[:variations].length - value = flag[:variations][flag[:off_variation]] + if !flag[:offVariation].nil? && flag[:offVariation] < flag[:variations].length + value = flag[:variations][flag[:offVariation]] @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) return {value: value, events: events} end From f94046c72a02847fcd14d1e0d1d7e99d2ac2fd9b Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:37:12 -0700 Subject: [PATCH 44/70] Fix flag key lookup --- lib/ldclient-rb/evaluation.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 8398ccea..12c6f955 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -28,11 +28,9 @@ def evaluate(flag, user, store) return res if !res[:value].nil? end - @config.logger.debug("Off variation is #{flag[:offVariation]} and flag has #{flag[:variations]} variations") - if !flag[:offVariation].nil? && flag[:offVariation] < flag[:variations].length value = flag[:variations][flag[:offVariation]] - @event_processor.add_event(kind: "feature", key: key, user: user, value: value, default: default) + @event_processor.add_event(kind: "feature", key: flag[:key], user: user, value: value, default: default) return {value: value, events: events} end From 9f34b9847007e33311a1aeaa052f3535ab139c7c Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Thu, 7 Jul 2016 17:38:09 -0700 Subject: [PATCH 45/70] Don't send flag request event in the internal evaluation method --- lib/ldclient-rb/evaluation.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 12c6f955..6525b1f8 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -30,7 +30,6 @@ def evaluate(flag, user, store) if !flag[:offVariation].nil? && flag[:offVariation] < flag[:variations].length value = flag[:variations][flag[:offVariation]] - @event_processor.add_event(kind: "feature", key: flag[:key], user: user, value: value, default: default) return {value: value, events: events} end From 6c6db751cf556035627ff68afc73c6b8580dd12e Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:31:03 -0700 Subject: [PATCH 46/70] Debug output for evaluation --- lib/ldclient-rb/evaluation.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 6525b1f8..c6f768ec 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -121,15 +121,19 @@ def clause_match_user(clause, user) val = user_value(user, clause[:attribute]) return false if val.nil? + @config.logger.debug("Got user value #{val} for #{clause[:attribute]} and user #{user}") + op = operators[clause[:op]] if val.is_a? Enumerable + @config.logger.debug("User value #{val} is enumerable") val.each do |v| return maybe_negate(clause, true) if match_any(op, v, clause[:values]) end return maybe_negate(clause, false) end + @config.logger.debug("Checking whether #{val} matches #{clause[:values]}") maybe_negate(clause, match_any(op, val, clause[:values])) end From ff08368557cb93341a2d3eceb225dd90a558802b Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:33:14 -0700 Subject: [PATCH 47/70] More debug output for evaluation --- lib/ldclient-rb/evaluation.rb | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index c6f768ec..338c85e8 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -74,6 +74,8 @@ def eval_internal(flag, user, store, events) def eval_rules(flag, user) # Check user target matches + @config.logger.debug("Checking user target matches for #{flag[:targets]}") + if !flag[:targets].nil? flag[:targets].each do |target| if !target[:values].nil? @@ -84,6 +86,8 @@ def eval_rules(flag, user) end end + @config.logger.debug("Checking custom rule matches for #{flag[:rules]}") + # Check custom rules if !flag[:rules].nil? flag[:rules].each do |rule| @@ -91,6 +95,9 @@ def eval_rules(flag, user) end end + @config.logger.debug("Checking fallthrough rule for #{flag[:fallthrough]}") + + # Check the fallthrough rule if !flag[:fallthrough].nil? return variation_for_user(flag[:fallthrough], user, flag) From 76bb1629d24c8980899f7b6956f926c92013cbab Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:35:16 -0700 Subject: [PATCH 48/70] More debug output --- lib/ldclient-rb/evaluation.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 338c85e8..81a927f0 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -117,7 +117,10 @@ def get_variation(flag, index) def rule_match_user(rule, user) return false if !rule[:clauses] + @config.logger.debug("Checking clauses for #{rule[:clauses]}") + rule[:clauses].each do |clause| + @config.logger.debug("Checking claus for #{clause}") return false if !clause_match_user(clause, user) end From 4aaebe502e1ebe12197837e4a22089f2e96a8c8b Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:36:48 -0700 Subject: [PATCH 49/70] More debug logging --- lib/ldclient-rb/evaluation.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 81a927f0..3c2ce8dc 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -181,6 +181,8 @@ def bucket_user(user, key, bucket_by, salt) end def user_value(user, attribute) + @config.logger.debug("Checking user value for user #{user} and attribute #{attribute}") + if BUILTINS.include? attribute user[attribute] elsif !user[:custom].nil? From 20032e2509fa5d147c0243ee1393ac2909137a3d Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:39:48 -0700 Subject: [PATCH 50/70] Symbolize attribute --- lib/ldclient-rb/evaluation.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 3c2ce8dc..becdcbf2 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -181,6 +181,7 @@ def bucket_user(user, key, bucket_by, salt) end def user_value(user, attribute) + attribute = attribute.to_sym @config.logger.debug("Checking user value for user #{user} and attribute #{attribute}") if BUILTINS.include? attribute From 1e913134256da9f6ede99b5250872650ec24407c Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:45:17 -0700 Subject: [PATCH 51/70] Scope reference to operators --- lib/ldclient-rb/evaluation.rb | 2 +- lib/ldclient-rb/ldclient.rb | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index becdcbf2..3f157f6a 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -133,7 +133,7 @@ def clause_match_user(clause, user) @config.logger.debug("Got user value #{val} for #{clause[:attribute]} and user #{user}") - op = operators[clause[:op]] + op = Operators::operators[clause[:op]] if val.is_a? Enumerable @config.logger.debug("User value #{val} is enumerable") diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 297b6520..a15a03d3 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -160,6 +160,7 @@ def all_flags(user) features = @store.all + # TODO rescue if necessary Hash[features{|k,f| [k, evaluate(f, user, @store)[:value]] }] end From b41c9121f7b405b440dccceb9597ac325f8d0afc Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:46:45 -0700 Subject: [PATCH 52/70] Inline operators --- lib/ldclient-rb/evaluation.rb | 55 +++++++++++++++++++++++++++++++++-- lib/ldclient-rb/operators.rb | 50 ------------------------------- 2 files changed, 53 insertions(+), 52 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 3f157f6a..1fb72f34 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -1,7 +1,6 @@ module LaunchDarkly module Evaluation - include Operators BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] class EvaluationError < StandardError @@ -133,7 +132,7 @@ def clause_match_user(clause, user) @config.logger.debug("Got user value #{val} for #{clause[:attribute]} and user #{user}") - op = Operators::operators[clause[:op]] + op = operators[clause[:op]] if val.is_a? Enumerable @config.logger.debug("User value #{val} is enumerable") @@ -203,6 +202,58 @@ def match_any(op, value, values) end return false end + + operators = { + in: + lambda do |a, b| + a == b + end, + endsWith: + lambda do |a, b| + (a.is_a? String) && (a.end_with? b) + end, + startsWith: + lambda do |a, b| + (a.is_a? String) && (a.start_with? b) + end, + matches: + lambda do |a, b| + (a.is_a? String) && !(Regexp.new a).match(b).nil? + end, + contains: + lambda do |a, b| + (a.is_a? String) && (a.include? b) + end, + lessThan: + lambda do |a, b| + (a.is_a? Numeric) && (a < b) + end, + lessThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a <= b) + end, + greaterThan: + lambda do |a, b| + (a.is_a? Numeric) && (a > b) + end, + greaterThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a >= b) + end, + greaterThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a >= b) + end, + before: + lambda do |a, b| + ((a.is_a? Numeric) && (a < b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc < DateTime.rfc3339(b).to_time.utc)) + end, + after: + lambda do |a, b| + ((a.is_a? Numeric) && (a > b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc > DateTime.rfc3339(b).to_time.utc)) + end + } + end end diff --git a/lib/ldclient-rb/operators.rb b/lib/ldclient-rb/operators.rb index 99c107c7..6435c37e 100644 --- a/lib/ldclient-rb/operators.rb +++ b/lib/ldclient-rb/operators.rb @@ -2,55 +2,5 @@ module LaunchDarkly module Operators - operators = { - in: - lambda do |a, b| - a == b - end, - endsWith: - lambda do |a, b| - (a.is_a? String) && (a.end_with? b) - end, - startsWith: - lambda do |a, b| - (a.is_a? String) && (a.start_with? b) - end, - matches: - lambda do |a, b| - (a.is_a? String) && !(Regexp.new a).match(b).nil? - end, - contains: - lambda do |a, b| - (a.is_a? String) && (a.include? b) - end, - lessThan: - lambda do |a, b| - (a.is_a? Numeric) && (a < b) - end, - lessThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a <= b) - end, - greaterThan: - lambda do |a, b| - (a.is_a? Numeric) && (a > b) - end, - greaterThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a >= b) - end, - greaterThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a >= b) - end, - before: - lambda do |a, b| - ((a.is_a? Numeric) && (a < b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc < DateTime.rfc3339(b).to_time.utc)) - end, - after: - lambda do |a, b| - ((a.is_a? Numeric) && (a > b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc > DateTime.rfc3339(b).to_time.utc)) - end - } end end \ No newline at end of file From 8fd7a733209e76f43f00ffc983d2e3de2ef36e7a Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:48:06 -0700 Subject: [PATCH 53/70] move and rename operators --- lib/ldclient-rb/evaluation.rb | 105 +++++++++++++++++----------------- 1 file changed, 52 insertions(+), 53 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 1fb72f34..9e5a0047 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -3,6 +3,57 @@ module LaunchDarkly module Evaluation BUILTINS = [:key, :ip, :country, :email, :firstName, :lastName, :avatar, :name, :anonymous] + OPERATORS = { + in: + lambda do |a, b| + a == b + end, + endsWith: + lambda do |a, b| + (a.is_a? String) && (a.end_with? b) + end, + startsWith: + lambda do |a, b| + (a.is_a? String) && (a.start_with? b) + end, + matches: + lambda do |a, b| + (a.is_a? String) && !(Regexp.new a).match(b).nil? + end, + contains: + lambda do |a, b| + (a.is_a? String) && (a.include? b) + end, + lessThan: + lambda do |a, b| + (a.is_a? Numeric) && (a < b) + end, + lessThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a <= b) + end, + greaterThan: + lambda do |a, b| + (a.is_a? Numeric) && (a > b) + end, + greaterThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a >= b) + end, + greaterThanOrEqual: + lambda do |a, b| + (a.is_a? Numeric) && (a >= b) + end, + before: + lambda do |a, b| + ((a.is_a? Numeric) && (a < b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc < DateTime.rfc3339(b).to_time.utc)) + end, + after: + lambda do |a, b| + ((a.is_a? Numeric) && (a > b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc > DateTime.rfc3339(b).to_time.utc)) + end + } + class EvaluationError < StandardError end @@ -132,7 +183,7 @@ def clause_match_user(clause, user) @config.logger.debug("Got user value #{val} for #{clause[:attribute]} and user #{user}") - op = operators[clause[:op]] + op = OPERATORS[clause[:op]] if val.is_a? Enumerable @config.logger.debug("User value #{val} is enumerable") @@ -202,58 +253,6 @@ def match_any(op, value, values) end return false end - - operators = { - in: - lambda do |a, b| - a == b - end, - endsWith: - lambda do |a, b| - (a.is_a? String) && (a.end_with? b) - end, - startsWith: - lambda do |a, b| - (a.is_a? String) && (a.start_with? b) - end, - matches: - lambda do |a, b| - (a.is_a? String) && !(Regexp.new a).match(b).nil? - end, - contains: - lambda do |a, b| - (a.is_a? String) && (a.include? b) - end, - lessThan: - lambda do |a, b| - (a.is_a? Numeric) && (a < b) - end, - lessThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a <= b) - end, - greaterThan: - lambda do |a, b| - (a.is_a? Numeric) && (a > b) - end, - greaterThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a >= b) - end, - greaterThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a >= b) - end, - before: - lambda do |a, b| - ((a.is_a? Numeric) && (a < b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc < DateTime.rfc3339(b).to_time.utc)) - end, - after: - lambda do |a, b| - ((a.is_a? Numeric) && (a > b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc > DateTime.rfc3339(b).to_time.utc)) - end - } - end end From 45b265859d64ec29721f7a3ad4db6c196d9744c9 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:49:41 -0700 Subject: [PATCH 54/70] Handle unsupported operators --- lib/ldclient-rb/evaluation.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 9e5a0047..101d6f1e 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -183,7 +183,11 @@ def clause_match_user(clause, user) @config.logger.debug("Got user value #{val} for #{clause[:attribute]} and user #{user}") - op = OPERATORS[clause[:op]] + op = OPERATORS[clause[:op].to_sym] + + if op.nil? + raise EvaluationError, "Unsupported operator #{clause[:op]} in evaluation" + end if val.is_a? Enumerable @config.logger.debug("User value #{val} is enumerable") From 3ccdd86c4d5e0ae1787a9a900c1f587bbd7b0af8 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 08:51:00 -0700 Subject: [PATCH 55/70] Remove operators file --- lib/ldclient-rb.rb | 1 - lib/ldclient-rb/evaluation.rb | 15 --------------- lib/ldclient-rb/operators.rb | 6 ------ 3 files changed, 22 deletions(-) delete mode 100644 lib/ldclient-rb/operators.rb diff --git a/lib/ldclient-rb.rb b/lib/ldclient-rb.rb index ebe170bc..01ab529e 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -1,6 +1,5 @@ require "ldclient-rb/version" require "ldclient-rb/settings" -require "ldclient-rb/operators" require "ldclient-rb/evaluation" require "ldclient-rb/ldclient" require "ldclient-rb/cache_store" diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 101d6f1e..8f328f7d 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -124,8 +124,6 @@ def eval_internal(flag, user, store, events) def eval_rules(flag, user) # Check user target matches - @config.logger.debug("Checking user target matches for #{flag[:targets]}") - if !flag[:targets].nil? flag[:targets].each do |target| if !target[:values].nil? @@ -136,8 +134,6 @@ def eval_rules(flag, user) end end - @config.logger.debug("Checking custom rule matches for #{flag[:rules]}") - # Check custom rules if !flag[:rules].nil? flag[:rules].each do |rule| @@ -145,9 +141,6 @@ def eval_rules(flag, user) end end - @config.logger.debug("Checking fallthrough rule for #{flag[:fallthrough]}") - - # Check the fallthrough rule if !flag[:fallthrough].nil? return variation_for_user(flag[:fallthrough], user, flag) @@ -167,10 +160,7 @@ def get_variation(flag, index) def rule_match_user(rule, user) return false if !rule[:clauses] - @config.logger.debug("Checking clauses for #{rule[:clauses]}") - rule[:clauses].each do |clause| - @config.logger.debug("Checking claus for #{clause}") return false if !clause_match_user(clause, user) end @@ -181,8 +171,6 @@ def clause_match_user(clause, user) val = user_value(user, clause[:attribute]) return false if val.nil? - @config.logger.debug("Got user value #{val} for #{clause[:attribute]} and user #{user}") - op = OPERATORS[clause[:op].to_sym] if op.nil? @@ -190,14 +178,12 @@ def clause_match_user(clause, user) end if val.is_a? Enumerable - @config.logger.debug("User value #{val} is enumerable") val.each do |v| return maybe_negate(clause, true) if match_any(op, v, clause[:values]) end return maybe_negate(clause, false) end - @config.logger.debug("Checking whether #{val} matches #{clause[:values]}") maybe_negate(clause, match_any(op, val, clause[:values])) end @@ -236,7 +222,6 @@ def bucket_user(user, key, bucket_by, salt) def user_value(user, attribute) attribute = attribute.to_sym - @config.logger.debug("Checking user value for user #{user} and attribute #{attribute}") if BUILTINS.include? attribute user[attribute] diff --git a/lib/ldclient-rb/operators.rb b/lib/ldclient-rb/operators.rb deleted file mode 100644 index 6435c37e..00000000 --- a/lib/ldclient-rb/operators.rb +++ /dev/null @@ -1,6 +0,0 @@ -require "date" - -module LaunchDarkly - module Operators - end -end \ No newline at end of file From a70cfa58ad5e712dd457b563fa350e254354b194 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 09:06:07 -0700 Subject: [PATCH 56/70] Debug operators --- lib/ldclient-rb/evaluation.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 8f328f7d..dc34c471 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -238,6 +238,7 @@ def maybe_negate(clause, b) def match_any(op, value, values) values.each do |v| + @config.logger.debug("Calling operator #{value} #{v}") return true if op.call(value, v) end return false From f6a4533e416f583d62aa7ab0ab0919fc29854b79 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 09:09:03 -0700 Subject: [PATCH 57/70] Reverse arguments for matches operator --- lib/ldclient-rb/evaluation.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index dc34c471..19537ad7 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -18,7 +18,7 @@ module Evaluation end, matches: lambda do |a, b| - (a.is_a? String) && !(Regexp.new a).match(b).nil? + (b.is_a? String) && !(Regexp.new b).match(a).nil? end, contains: lambda do |a, b| @@ -238,7 +238,6 @@ def maybe_negate(clause, b) def match_any(op, value, values) values.each do |v| - @config.logger.debug("Calling operator #{value} #{v}") return true if op.call(value, v) end return false From 7910ca73d7d5da4ed6180725b63f7d11f61e5e60 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 09:27:29 -0700 Subject: [PATCH 58/70] Change implementations of before and after to handle mixed strings / numerics --- lib/ldclient-rb/evaluation.rb | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 19537ad7..f21862ee 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -1,3 +1,5 @@ +require "date" + module LaunchDarkly module Evaluation @@ -46,11 +48,23 @@ module Evaluation end, before: lambda do |a, b| - ((a.is_a? Numeric) && (a < b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc < DateTime.rfc3339(b).to_time.utc)) + if a.is_a? String + a = DateTime.rfc3339(a).to_time.utc.to_i + end + if b.is_a? String + b = DateTime.rfc3339(b).to_time.utc.to_i + end + (a.is_a? Numeric) ? a < b : false end, after: lambda do |a, b| - ((a.is_a? Numeric) && (a > b)) || ((a.is_a? String) && (DateTime.rfc3339(a).to_time.utc > DateTime.rfc3339(b).to_time.utc)) + if a.is_a? String + a = DateTime.rfc3339(a).to_time.utc.to_i + end + if b.is_a? String + b = DateTime.rfc3339(b).to_time.utc.to_i + end + (a.is_a? Numeric) ? a > b : false end } From bd45ba56d9292dde29be1f27db9284a348e8995f Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 09:32:54 -0700 Subject: [PATCH 59/70] Fix units for date time conversion --- lib/ldclient-rb/evaluation.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index f21862ee..0e2058d1 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -49,10 +49,10 @@ module Evaluation before: lambda do |a, b| if a.is_a? String - a = DateTime.rfc3339(a).to_time.utc.to_i + a = DateTime.rfc3339(a).to_time.utc.to_i * 1000 end if b.is_a? String - b = DateTime.rfc3339(b).to_time.utc.to_i + b = DateTime.rfc3339(b).to_time.utc.to_i * 1000 end (a.is_a? Numeric) ? a < b : false end, From 53ee4fa45d5545813f9a6025081e5fb03f93a38a Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 09:36:55 -0700 Subject: [PATCH 60/70] Handle invalid date strings --- lib/ldclient-rb/evaluation.rb | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 0e2058d1..f5e8e425 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -48,23 +48,31 @@ module Evaluation end, before: lambda do |a, b| - if a.is_a? String - a = DateTime.rfc3339(a).to_time.utc.to_i * 1000 + begin + if a.is_a? String + a = DateTime.rfc3339(a).to_time.utc.to_i * 1000 + end + if b.is_a? String + b = DateTime.rfc3339(b).to_time.utc.to_i * 1000 + end + (a.is_a? Numeric) ? a < b : false + rescue => e + false end - if b.is_a? String - b = DateTime.rfc3339(b).to_time.utc.to_i * 1000 - end - (a.is_a? Numeric) ? a < b : false end, after: lambda do |a, b| - if a.is_a? String - a = DateTime.rfc3339(a).to_time.utc.to_i + begin + if a.is_a? String + a = DateTime.rfc3339(a).to_time.utc.to_i * 1000 + end + if b.is_a? String + b = DateTime.rfc3339(b).to_time.utc.to_i * 1000 + end + (a.is_a? Numeric) ? a > b : false + rescue => e + false end - if b.is_a? String - b = DateTime.rfc3339(b).to_time.utc.to_i - end - (a.is_a? Numeric) ? a > b : false end } From 50e12d21278be5039663cd0146a3e5b589beb8b0 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 09:52:15 -0700 Subject: [PATCH 61/70] A more correct approach to getting epoch millis? --- lib/ldclient-rb/evaluation.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index f5e8e425..d15815cc 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -50,10 +50,10 @@ module Evaluation lambda do |a, b| begin if a.is_a? String - a = DateTime.rfc3339(a).to_time.utc.to_i * 1000 + a = DateTime.rfc3339(a).strftime('%Q').to_i end if b.is_a? String - b = DateTime.rfc3339(b).to_time.utc.to_i * 1000 + b = DateTime.rfc3339(b).strftime('%Q').to_i end (a.is_a? Numeric) ? a < b : false rescue => e @@ -64,10 +64,10 @@ module Evaluation lambda do |a, b| begin if a.is_a? String - a = DateTime.rfc3339(a).to_time.utc.to_i * 1000 + a = DateTime.rfc3339(a).strftime('%Q').to_i end if b.is_a? String - b = DateTime.rfc3339(b).to_time.utc.to_i * 1000 + b = DateTime.rfc3339(b).strftime('%Q').to_i end (a.is_a? Numeric) ? a > b : false rescue => e From 10f8988c8fe1a49b5def3d2bf1dbf36db6a8f2cf Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 11:24:19 -0700 Subject: [PATCH 62/70] Simplify eval_internal and fix prerequisite evaluation --- lib/ldclient-rb/evaluation.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index d15815cc..6f4c63b7 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -97,7 +97,7 @@ def evaluate(flag, user, store) if flag[:on] res = eval_internal(flag, user, store, events) - return res if !res[:value].nil? + return {value: res, events: events} if !res.nil? end if !flag[:offVariation].nil? && flag[:offVariation] < flag[:variations].length @@ -122,9 +122,9 @@ def eval_internal(flag, user, store, events) begin prereq_res = eval_internal(prereq_flag, user, store, events) - events.push(kind: "feature", key: prereq_flag[:key], value: default, default: default) variation = get_variation(prereq_flag, prerequisite[:variation]) - if prereq_res.nil? || prereq_res != variation + events.push(kind: "feature", key: prereq_flag[:key], value: prereq_res, default: default) + if prereq_res.nil? || prereq_res!= variation failed_prereq = true end rescue => exn @@ -135,13 +135,13 @@ def eval_internal(flag, user, store, events) end if failed_prereq - return {value: nil, events: events} + return nil end end # The prerequisites were satisfied. # Now walk through the evaluation steps and get the correct # variation index - {value: eval_rules(flag, user), events: events} + eval_rules(flag, user) end def eval_rules(flag, user) From 69aa7c09c2c7e9863f772aba29a730ab9c25ee1e Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 11:28:41 -0700 Subject: [PATCH 63/70] Don't send a default value for prerequisite evaluation --- lib/ldclient-rb/evaluation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index 6f4c63b7..e686b9c1 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -123,7 +123,7 @@ def eval_internal(flag, user, store, events) begin prereq_res = eval_internal(prereq_flag, user, store, events) variation = get_variation(prereq_flag, prerequisite[:variation]) - events.push(kind: "feature", key: prereq_flag[:key], value: prereq_res, default: default) + events.push(kind: "feature", key: prereq_flag[:key], value: prereq_res) if prereq_res.nil? || prereq_res!= variation failed_prereq = true end From 09881cbd96df8d83d284ccdff8c1efbaa2d403eb Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 11:35:56 -0700 Subject: [PATCH 64/70] Fix control flow for failed prerequisites. Check if the store does not contain a prereq. --- lib/ldclient-rb/evaluation.rb | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index e686b9c1..e8a37ec0 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -116,22 +116,21 @@ def eval_internal(flag, user, store, events) prereq_flag = store.get(prerequisite[:key]) - if !prereq_flag[:on] + if prereq_flag.nil? || !prereq_flag[:on] failed_prereq = true - end - - begin - prereq_res = eval_internal(prereq_flag, user, store, events) - variation = get_variation(prereq_flag, prerequisite[:variation]) - events.push(kind: "feature", key: prereq_flag[:key], value: prereq_res) - if prereq_res.nil? || prereq_res!= variation + else + begin + prereq_res = eval_internal(prereq_flag, user, store, events) + variation = get_variation(prereq_flag, prerequisite[:variation]) + events.push(kind: "feature", key: prereq_flag[:key], value: prereq_res) + if prereq_res.nil? || prereq_res!= variation + failed_prereq = true + end + rescue => exn + @config.logger.error("[LDClient] Error evaluating prerequisite: #{exn.inspect}") failed_prereq = true end - rescue => exn - @config.logger.error("[LDClient] Error evaluating prerequisite: #{exn.inspect}") - failed_prereq = true end - end if failed_prereq From f400b8fae57a976ed59daa3a0c690022e3abab1f Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 12:24:04 -0700 Subject: [PATCH 65/70] Don't use http persistent for events --- lib/ldclient-rb/events.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb index e495290e..1c5029a9 100644 --- a/lib/ldclient-rb/events.rb +++ b/lib/ldclient-rb/events.rb @@ -10,7 +10,6 @@ def initialize(api_key, config) @config = config @client = Faraday.new do |builder| builder.use :http_cache, store: @config.cache_store - builder.adapter :net_http_persistent end @worker = create_worker From ff36fd3b9e3fef6e007d168d8a98bc914ea8bd36 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Fri, 8 Jul 2016 12:44:30 -0700 Subject: [PATCH 66/70] Change faraday client initialization --- lib/ldclient-rb/events.rb | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/ldclient-rb/events.rb b/lib/ldclient-rb/events.rb index 1c5029a9..47b4ac23 100644 --- a/lib/ldclient-rb/events.rb +++ b/lib/ldclient-rb/events.rb @@ -1,5 +1,5 @@ require "thread" -require "faraday/http_cache" +require "faraday" module LaunchDarkly @@ -8,10 +8,7 @@ def initialize(api_key, config) @queue = Queue.new @api_key = api_key @config = config - @client = Faraday.new do |builder| - builder.use :http_cache, store: @config.cache_store - end - + @client = Faraday.new @worker = create_worker end From eccf3c17ff2f12cb0748505f603a4b7c61141a36 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Tue, 12 Jul 2016 14:31:14 -0700 Subject: [PATCH 67/70] Latest features -> latest flags --- lib/ldclient-rb/requestor.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ldclient-rb/requestor.rb b/lib/ldclient-rb/requestor.rb index b33a2804..72c8d493 100644 --- a/lib/ldclient-rb/requestor.rb +++ b/lib/ldclient-rb/requestor.rb @@ -16,11 +16,11 @@ def initialize(api_key, config) end def request_all_flags() - make_request("/sdk/latest-features") + make_request("/sdk/latest-flags") end def request_flag(key) - make_request("/sdk/latest-features/" + key) + make_request("/sdk/latest-flags/" + key) end def make_request(path) From 6aaab915a0c93215fa6d66fd38e91896f46b37a7 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Tue, 12 Jul 2016 14:57:31 -0700 Subject: [PATCH 68/70] Send the user in the null toggle case --- lib/ldclient-rb/ldclient.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index a15a03d3..6ec1a08e 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -119,7 +119,7 @@ def toggle?(key, user, default = false) return res[:value] else @config.logger.debug("[LDClient] Result value is null in toggle") - @event_processor.add_event(kind: "feature", key: key, value: default, default: default) + @event_processor.add_event(kind: "feature", key: key, user: user, value: default, default: default) return default end rescue => exn From e639f37cefaa206a0a255cbdcb0c9478b9bda7b5 Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Tue, 19 Jul 2016 13:18:32 -0700 Subject: [PATCH 69/70] Get tests back up to baseline --- lib/ldclient-rb.rb | 1 - lib/ldclient-rb/ldclient.rb | 3 +- lib/ldclient-rb/settings.rb | 40 ------ spec/config_spec.rb | 6 +- spec/fixtures/feature.json | 85 ++++--------- spec/ldclient_spec.rb | 241 +++--------------------------------- spec/stream_spec.rb | 19 +-- 7 files changed, 48 insertions(+), 347 deletions(-) delete mode 100644 lib/ldclient-rb/settings.rb diff --git a/lib/ldclient-rb.rb b/lib/ldclient-rb.rb index 01ab529e..549ec43f 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -1,5 +1,4 @@ require "ldclient-rb/version" -require "ldclient-rb/settings" require "ldclient-rb/evaluation" require "ldclient-rb/ldclient" require "ldclient-rb/cache_store" diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 6ec1a08e..14722c32 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -11,7 +11,6 @@ module LaunchDarkly # # class LDClient - include Settings include Evaluation # # Creates a new client instance that connects to LaunchDarkly. A custom @@ -23,7 +22,7 @@ class LDClient # @param config [Config] an optional client configuration object # # @return [LDClient] The LaunchDarkly client instance - def initialize(api_key, config = Config.default, wait_for_sec = 0) + def initialize(api_key, config = Config.default, wait_for_sec = 5) @api_key = api_key @config = config @store = config.feature_store diff --git a/lib/ldclient-rb/settings.rb b/lib/ldclient-rb/settings.rb deleted file mode 100644 index fad2cfd9..00000000 --- a/lib/ldclient-rb/settings.rb +++ /dev/null @@ -1,40 +0,0 @@ -module LaunchDarkly - - # - # Module to manage user flag settings - # - module Settings - # - # Specifically enable or disable a feature flag for a user based - # on their key. - # - # @param user_key [String] the key of the user - # @param flag_key [String] the unique feature key for the feature flag, as shown - # on the LaunchDarkly dashboard - # @param setting [Boolean] the new setting, one of: - # true: the feature is always on - # false: the feature is never on - # nil: remove the setting (assign user per defined rules) - def update_user_flag_setting(user_key, flag_key, setting=nil) - unless user_key - @config.logger.error("[LDClient] Must specify user") - return - end - - res = log_timings('update_user_flag_setting') do - @client.put("#{@config.base_uri}/api/users/#{user_key}/features/#{flag_key}") do |req| - req.headers['Authorization'] = "api_key #{@api_key}" - req.headers['User-Agent'] = "RubyClient/#{LaunchDarkly::VERSION}" - req.headers['Content-Type'] = 'application/json' - req.body = {setting: setting}.to_json - req.options.timeout = @config.read_timeout - req.options.open_timeout = @config.connect_timeout - end - end - - unless res.success? - @config.logger.error("[LDClient] Failed to change setting, status: #{res.status}") - end - end - end -end \ No newline at end of file diff --git a/spec/config_spec.rb b/spec/config_spec.rb index fda9f23c..da121ced 100644 --- a/spec/config_spec.rb +++ b/spec/config_spec.rb @@ -32,14 +32,14 @@ expect(subject.new.stream_uri).to eq subject.default_stream_uri end end - describe ".default_store" do + describe ".default_cache_store" do it "uses Rails cache if it is available" do rails = instance_double("Rails", cache: :cache) stub_const("Rails", rails) - expect(subject.default_store).to eq :cache + expect(subject.default_cache_store).to eq :cache end it "uses memory store if Rails is not available" do - expect(subject.default_store).to be_an_instance_of LaunchDarkly::ThreadSafeMemoryStore + expect(subject.default_cache_store).to be_an_instance_of LaunchDarkly::ThreadSafeMemoryStore end end describe ".default_logger" do diff --git a/spec/fixtures/feature.json b/spec/fixtures/feature.json index 3b347ca7..152565f7 100644 --- a/spec/fixtures/feature.json +++ b/spec/fixtures/feature.json @@ -1,67 +1,36 @@ { - "name":"New recommendations engine", - "key":"engine.enable", - "kind":"flag", - "salt":"ZW5naW5lLmVuYWJsZQ==", + "key":"test-feature-flag", + "version":11, "on":true, - "variations":[ + "prerequisites":[ + + ], + "salt":"718ea30a918a4eba8734b57ab1a93227", + "sel":"fe1244e5378c4f99976c9634e33667c6", + "targets":[ { - "value":true, - "weight":31, - "targets":[ - { - "attribute":"groups", - "op":"in", - "values":[ - "Microsoft" - ] - } + "values":[ + "alice" ], - "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" - ] - } + "variation":0 }, { - "value":false, - "weight":69, - "targets":[ - { - "attribute":"key", - "op":"in", - "values":[ - "Alida.Caples@example.com" - ] - }, - { - "attribute":"groups", - "op":"in", - "values":[ - - ] - } + "values":[ + "bob" ], - "userTarget":{ - "attribute":"key", - "op":"in", - "values":[ - "Alida.Caples@example.com" - ] - } + "variation":1 } ], - "ttl":0, - "commitDate":"2015-05-10T06:06:45.381Z", - "creationDate":"2014-09-02T20:39:18.61Z" -} + "rules":[ + + ], + "fallthrough":{ + "variation":0 + }, + "offVariation":1, + "variations":[ + true, + false + ], + "deleted":false +} \ No newline at end of file diff --git a/spec/ldclient_spec.rb b/spec/ldclient_spec.rb index 2ed0d545..3a0a0174 100644 --- a/spec/ldclient_spec.rb +++ b/spec/ldclient_spec.rb @@ -1,10 +1,11 @@ require "spec_helper" + describe LaunchDarkly::LDClient do subject { LaunchDarkly::LDClient } + let(:config) { LaunchDarkly::Config.new({:offline => true}) } let(:client) do - expect_any_instance_of(LaunchDarkly::LDClient).to receive :create_worker - subject.new("api_key") + subject.new("api_key", config) end let(:feature) do data = File.read(File.join("spec", "fixtures", "feature.json")) @@ -23,246 +24,32 @@ JSON.parse(data, symbolize_names: true) end - context 'user flag settings' do - describe '#update_user_flag_setting' do - it 'requires user' do - expect(client.instance_variable_get(:@config).logger).to receive(:error) - client.update_user_flag_setting(nil, feature[:key], true) - end - - it 'puts the new setting' do - result = double('result', success?: true, status: 204) - expect(client.instance_variable_get(:@client)).to receive(:put).and_return(result) - client.update_user_flag_setting(user[:key], feature[:key], true) - end - end - 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).with(LaunchDarkly::Config.default_events_uri + "/bulk").and_return result - 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 - 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.send(:post_flushed_events, events) - expect(client.instance_variable_get(:@queue).length).to eq 0 - end - end - describe '#toggle?' do - 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) + it "will return the default value if the client is offline" do result = client.toggle?(feature[:key], user, "default") expect(result).to eq "default" end - it "will specify the default value in the feature request event" do - expect(client).to receive(:add_event).with(hash_including(default: "default")) - result = client.toggle?(feature[:key], user, "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 "sanitizes the user in the event" do - expect(client).to receive(:add_event).with(hash_including(user: sanitized_numeric_key_user)) - client.toggle?(feature[:key], numeric_key_user, "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 '#identify' do - it "queues up an identify event" do - expect(client).to receive(:add_event).with(hash_including(kind: "identify", key: user[:key], user: user)) - client.identify(user) - end - it "sanitizes the user in the event" do - expect(client).to receive(:add_event).with(hash_including(user: sanitized_numeric_key_user)) - client.identify(numeric_key_user) - end end describe '#track' do it "queues up an custom event" do - expect(client).to receive(:add_event).with(hash_including(kind: "custom", key: "custom_event_name", user: user, data: 42)) + expect(client.instance_variable_get(:@event_processor)).to receive(:add_event).with(hash_including(kind: "custom", key: "custom_event_name", user: user, data: 42)) client.track("custom_event_name", user, 42) end it "sanitizes the user in the event" do - expect(client).to receive(:add_event).with(hash_including(user: sanitized_numeric_key_user)) + expect(client.instance_variable_get(:@event_processor)).to receive(:add_event).with(hash_including(user: sanitized_numeric_key_user)) client.track("custom_event_name", numeric_key_user, nil) 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 '#all_flags' do - it "will parse and return the features list" do - result = double("Faraday::Response", status: 200, body: '{"asdf":"qwer"}') - expect(client).to receive(:make_request).with("/api/eval/features").and_return(result) - data = client.send(:all_flags) - expect(data).to eq(asdf: "qwer") - end - it "will log errors" do - result = double("Faraday::Response", status: 418) - expect(client).to receive(:make_request).with("/api/eval/features").and_return(result) - expect(client.instance_variable_get(:@config).logger).to receive(:error) - client.send(:all_flags) - end - end - - describe '#get_flag_int' do - it "will return the parsed flag" do - result = double("Faraday::Response", status: 200, body: '{"asdf":"qwer"}') - expect(client).to receive(:make_request).with("/api/eval/features/key").and_return(result) - data = client.send(:get_flag_int, "key") - expect(data).to eq(asdf: "qwer") - end - it "will accept 401 statuses" do - result = double("Faraday::Response", status: 401) - 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") - expect(data).to be_nil - end - it "will accept 404 statuses" do - result = double("Faraday::Response", status: 404) - 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") - expect(data).to be_nil - end - it "will accept non-standard statuses" do - 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") - expect(data).to be_nil - end - end - - describe '#make_request' do - it "will make a proper request" do - expect(client.instance_variable_get :@client).to receive(:get) - 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) + describe '#identify' do + it "queues up an identify event" do + expect(client.instance_variable_get(:@event_processor)).to receive(:add_event).with(hash_including(kind: "identify", key: user[:key], user: user)) + client.identify(user) 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 + it "sanitizes the user in the event" do + expect(client.instance_variable_get(:@event_processor)).to receive(:add_event).with(hash_including(user: sanitized_numeric_key_user)) + client.identify(numeric_key_user) end end @@ -276,4 +63,4 @@ end end end -end +end \ No newline at end of file diff --git a/spec/stream_spec.rb b/spec/stream_spec.rb index c3c8e94c..9a43355c 100644 --- a/spec/stream_spec.rb +++ b/spec/stream_spec.rb @@ -33,7 +33,8 @@ describe LaunchDarkly::StreamProcessor do subject { LaunchDarkly::StreamProcessor } let(:config) { LaunchDarkly::Config.new } - let(:processor) { subject.new("api_key", config) } + let(:requestor) { LaunchDarkly::Requestor.new("api_key", config)} + let(:processor) { subject.new("api_key", config, requestor) } describe '#process_message' do let(:put_message) { OpenStruct.new({data: '{"key": {"value": "asdf"}}'}) } @@ -57,19 +58,5 @@ processor.send(:process_message, put_message, "get") end end - - describe '#should_fallback_update' do - it "will return true if the stream is disconnected for more than 120 seconds" do - processor.send(:set_disconnected) - future_time = Time.now + 200 - expect(Time).to receive(:now).and_return(future_time) - value = processor.send(:should_fallback_update) - expect(value).to eq true - end - it "will return false otherwise" do - processor.send(:set_connected) - value = processor.send(:should_fallback_update) - expect(value).to eq false - end - end end + From acd226afb63485f141a1703b0ddda2abd8e359cd Mon Sep 17 00:00:00 2001 From: John Kodumal Date: Wed, 20 Jul 2016 16:00:09 -0700 Subject: [PATCH 70/70] Remove duplicated operator --- lib/ldclient-rb/evaluation.rb | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/ldclient-rb/evaluation.rb b/lib/ldclient-rb/evaluation.rb index e8a37ec0..03b1ee3d 100644 --- a/lib/ldclient-rb/evaluation.rb +++ b/lib/ldclient-rb/evaluation.rb @@ -42,10 +42,6 @@ module Evaluation lambda do |a, b| (a.is_a? Numeric) && (a >= b) end, - greaterThanOrEqual: - lambda do |a, b| - (a.is_a? Numeric) && (a >= b) - end, before: lambda do |a, b| begin