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.rb b/lib/ldclient-rb.rb index 1c585f5a..01ab529e 100644 --- a/lib/ldclient-rb.rb +++ b/lib/ldclient-rb.rb @@ -1,7 +1,12 @@ require "ldclient-rb/version" require "ldclient-rb/settings" +require "ldclient-rb/evaluation" 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..074bda6b 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 # @@ -79,13 +84,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 # @@ -95,6 +96,11 @@ def debug_stream? # @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. @@ -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/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/events.rb b/lib/ldclient-rb/events.rb new file mode 100644 index 00000000..e495290e --- /dev/null +++ b/lib/ldclient-rb/events.rb @@ -0,0 +1,79 @@ +require "thread" +require "faraday/http_cache" + +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 + + 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) + 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" + 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 + @config.logger.debug("[LDClient] Enqueueing event: #{event.to_json}") + @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 +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..f9ee2927 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -1,15 +1,10 @@ -require "faraday/http_cache" -require "json" require "digest/sha1" -require "thread" require "logger" -require "net/http/persistent" require "benchmark" -require "hashdiff" +require "waitutil" +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. @@ -17,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, @@ -27,70 +23,36 @@ class LDClient # @param config [Config] an optional client configuration object # # @return [LDClient] The LaunchDarkly client instance - def initialize(api_key, config = Config.default) - @queue = Queue.new + def initialize(api_key, config = Config.default, wait_for_sec = 0) @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 - - if @config.stream? - @stream_processor = StreamProcessor.new(api_key, config) - end - - @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) - 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 + @store = config.feature_store + requestor = Requestor.new(api_key, config) + + 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 - 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 + @event_processor = EventProcessor.new(api_key, config) - sleep(@config.flush_interval) - rescue StandardError => exn - log_exception(__method__.to_s, exn) + 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 - def get_flag?(key, user, default = false) - toggle?(key, user, default) + def flush + @event_processor.flush end # @@ -128,7 +90,7 @@ def get_flag?(key, user, default = false) # @return [Boolean] whether or not the flag should be enabled, or the # default value if the flag is disabled on the LaunchDarkly control panel def toggle?(key, user, default = false) - return default if @offline + return default if @config.offline? unless user @config.logger.error("[LDClient] Must specify user") @@ -136,19 +98,11 @@ def toggle?(key, user, default = false) end sanitize_user(user) - if @config.stream? && !@stream_processor.started? - @stream_processor.start - end - - if @config.stream? && @stream_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 - 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 @@ -156,21 +110,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 # @@ -178,19 +117,7 @@ def add_event(event) # def identify(user) sanitize_user(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 + @event_processor.add_event(kind: "identify", key: user[:key], user: user) end # @@ -203,204 +130,18 @@ def is_offline? # @return [void] def track(event_name, user, data) sanitize_user(user) - 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 + @event_processor.add_event(kind: "custom", key: event_name, user: user, data: data) end # # Returns all feature flags # - def all_flags - return Hash.new if @offline - - if @config.stream? && !@stream_processor.started? - @stream_processor.start - end - - if @config.stream? && @stream_processor.initialized? - @stream_processor.get_all_features - else - res = make_request "/api/eval/features" - - 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 - 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) - @stream_processor.get_feature(key) - end + def all_flags(user) + return Hash.new if @config.offline? - def get_flag_int(key) - res = log_timings("Feature request") do - next make_request "/api/eval/features/" + key - end - - 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 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] - - 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 + features = @store.all - 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) - return nil if feature.nil? - return nil unless feature[:on] - - param = param_for_user(feature, user) - return nil if param.nil? - - value = find_user_match(feature, user) - return value if !value.nil? - - value = find_target_match(feature, user) - return value if !value.nil? - - find_weight_match(feature, param) - end - - def log_timings(label, &block) - 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 + Hash[features{|k,f| [k, evaluate(f, user)] }] end def log_exception(caller, exn) @@ -415,9 +156,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_timings, :log_exception, :sanitize_user + private :param_for_user, :match_target?, :match_user?, :match_variation?, :evaluate, + :log_exception, :sanitize_user, :find_weight_match, :find_target_match, :find_user_match end end diff --git a/lib/ldclient-rb/polling.rb b/lib/ldclient-rb/polling.rb new file mode 100644 index 00000000..f3e3bf69 --- /dev/null +++ b/lib/ldclient-rb/polling.rb @@ -0,0 +1,56 @@ +require "concurrent/atomics" +require "thread" + +module LaunchDarkly + class PollingProcessor + + def initialize(config, requestor) + @config = config + @requestor = requestor + @initialized = Concurrent::AtomicBoolean.new(false) + @started = Concurrent::AtomicBoolean.new(false) + end + + def initialized? + @initialized.value + end + + def start + return unless @started.make_true + @config.logger.info("[LDClient] Initializing polling connection") + create_worker + end + + def poll + flags = @requestor.request_all_flags + if flags + @config.feature_store.init(flags) + if @initialized.make_true + @config.logger.info("[LDClient] Polling connection initialized") + end + end + end + + def create_worker + Thread.new do + @config.logger.debug("[LDClient] Starting polling worker") + 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 + @config.logger.error("[LDClient] Exception while polling: #{exn.inspect}") + # 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/requestor.rb b/lib/ldclient-rb/requestor.rb new file mode 100644 index 00000000..f26373d4 --- /dev/null +++ b/lib/ldclient-rb/requestor.rb @@ -0,0 +1,56 @@ +require "json" +require "net/http/persistent" +require "faraday/http_cache" + +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("/api/eval/latest-features") + end + + def request_flag(key) + make_request("/api/eval/latest-features/" + 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..f694cd04 100644 --- a/lib/ldclient-rb/stream.rb +++ b/lib/ldclient-rb/stream.rb @@ -6,96 +6,27 @@ module LaunchDarkly PUT = "put" 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 + 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) + @store = config.feature_store + @requestor = requestor + @initialized = 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 return unless @started.make_true + + @config.logger.info("[LDClient] Initializing stream connection") headers = { @@ -104,50 +35,39 @@ 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 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.info("[LDClient] Stream initialized") 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 + @config.logger.info("[LDClient] Stream initialized (via indirect message)") + 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