From 2459500c23f0f3d82f914a3fa5546235bfb58b7a Mon Sep 17 00:00:00 2001 From: Matthew Keeler Date: Wed, 20 Mar 2024 12:17:36 -0400 Subject: [PATCH 1/3] feat: Add initial support for hooks --- lib/ldclient-rb/config.rb | 13 +++ lib/ldclient-rb/interfaces.rb | 84 +++++++++++++++++++ lib/ldclient-rb/ldclient.rb | 130 ++++++++++++++++++++++++++++- spec/ldclient_hooks_spec.rb | 152 ++++++++++++++++++++++++++++++++++ spec/mock_components.rb | 21 +++++ 5 files changed, 398 insertions(+), 2 deletions(-) create mode 100644 spec/ldclient_hooks_spec.rb diff --git a/lib/ldclient-rb/config.rb b/lib/ldclient-rb/config.rb index 052d4ce0..28b8cc08 100644 --- a/lib/ldclient-rb/config.rb +++ b/lib/ldclient-rb/config.rb @@ -43,6 +43,7 @@ class Config # @option opts [BigSegmentsConfig] :big_segments See {#big_segments}. # @option opts [Hash] :application See {#application} # @option opts [String] :payload_filter_key See {#payload_filter_key} + # @option hooks [Array] + # @param hook_context [EvaluationContext] + # + # @return [Array] + # + private def execute_before_evaluation(hooks, hook_context) + hooks.map do |hook| + try_execute_stage(:before_evaluation, hook.metadata.name) do + hook.before_evaluation(hook_context, {}) + end + end + end + + # + # Execute the :after_evaluation stage of the evaluation series. + # + # This method will return the results of each hook, indexed into an array in the same order as the hooks. If a hook + # raised an uncaught exception, the value will be nil. + # + # @param hooks [Array] + # @param hook_context [EvaluationContext] + # @param hook_data [Array] + # @param evaluation_detail [EvaluationDetail] + # + # @return [Array] + # + private def execute_after_evaluation(hooks, hook_context, hook_data, evaluation_detail) + hooks.zip(hook_data).reverse.map do |(hook, data)| + try_execute_stage(:after_evaluation, hook.metadata.name) do + hook.after_evaluation(hook_context, data, evaluation_detail) + end + end + end + + # + # Try to execute the provided block. If execution raises an exception, catch and log it, then move on with + # execution. + # + # @return [any] + # + private def try_execute_stage(method, hook_name) + begin + yield + rescue => e + @config.logger.error { "[LDClient] An error occurred in #{method} of the hook #{hook_name}: #{e}" } + nil + end + end + + # + # Return a copy of the existing hooks and a few instance of the EvaluationContext used for the evaluation series. + # + # @param key [String] + # @param context [LDContext] + # @param default [any] + # @param method [Symbol] + # @return [Array[Array, Interfaces::Hooks::EvaluationContext]] + # + private def prepare_hooks(key, context, default, method) + # Copy the hooks to use a consistent set during the evaluation series. + # + # Hooks can be added and we want to ensure all correct stages for a given hook execute. For example, we do not + # want to trigger the after_evaluation method without also triggering the before_evaluation method. + hooks = @hooks.dup + hook_context = Interfaces::Hooks::EvaluationContext.new(key, context, default, method) + + [hooks, hook_context] + end + # # This method returns the migration stage of the migration feature flag for the given evaluation context. # @@ -508,7 +632,9 @@ def create_default_data_source(sdk_key, config, diagnostic_accumulator) # @return [Array] # def variation_with_flag(key, context, default) - evaluate_internal(key, context, default, false) + evaluate_with_hooks(key, context, default, :variation_detail) do + evaluate_internal(key, context, default, false) + end end # diff --git a/spec/ldclient_hooks_spec.rb b/spec/ldclient_hooks_spec.rb new file mode 100644 index 00000000..887bd829 --- /dev/null +++ b/spec/ldclient_hooks_spec.rb @@ -0,0 +1,152 @@ +require "ldclient-rb" + +require "mock_components" +require "model_builders" +require "spec_helper" + +module LaunchDarkly + describe "LDClient hooks tests" do + context "registration" do + it "can register a hook on the config" do + count = 0 + hook = MockHook.new(->(_, _) { count += 1 }, ->(_, _, _) { count += 2 }) + with_client(test_config(hooks: [hook])) do |client| + client.variation("doesntmatter", basic_context, "default") + expect(count).to eq 3 + end + end + + it "can register a hook on the client" do + count = 0 + hook = MockHook.new(->(_, _) { count += 1 }, ->(_, _, _) { count += 2 }) + with_client(test_config()) do |client| + client.add_hook(hook) + client.variation("doesntmatter", basic_context, "default") + + expect(count).to eq 3 + end + end + + it "can register hooks on both" do + count = 0 + config_hook = MockHook.new(->(_, _) { count += 1 }, ->(_, _, _) { count += 2 }) + client_hook = MockHook.new(->(_, _) { count += 4 }, ->(_, _, _) { count += 8 }) + + with_client(test_config(hooks: [config_hook])) do |client| + client.add_hook(client_hook) + client.variation("doesntmatter", basic_context, "default") + + expect(count).to eq 15 + end + end + + it "will drop invalid hooks on config" do + config = test_config(hooks: [true, nil, "example thing"]) + expect(config.hooks.count).to eq 0 + end + + it "will drop invalid hooks on client" do + with_client(test_config) do |client| + client.add_hook(true) + client.add_hook(nil) + client.add_hook("example thing") + + expect(client.instance_variable_get("@hooks").count).to eq 0 + end + + config = test_config(hooks: [true, nil, "example thing"]) + expect(config.hooks.count).to eq 0 + end + end + + context "execution order" do + it "config order is preserved" do + order = [] + first_hook = MockHook.new(->(_, _) { order << "first before" }, ->(_, _, _) { order << "first after" }) + second_hook = MockHook.new(->(_, _) { order << "second before" }, ->(_, _, _) { order << "second after" }) + + with_client(test_config(hooks: [first_hook, second_hook])) do |client| + client.variation("doesntmatter", basic_context, "default") + expect(order).to eq ["first before", "second before", "second after", "first after"] + end + end + + it "client order is preserved" do + order = [] + first_hook = MockHook.new(->(_, _) { order << "first before" }, ->(_, _, _) { order << "first after" }) + second_hook = MockHook.new(->(_, _) { order << "second before" }, ->(_, _, _) { order << "second after" }) + + with_client(test_config()) do |client| + client.add_hook(first_hook) + client.add_hook(second_hook) + client.variation("doesntmatter", basic_context, "default") + + expect(order).to eq ["first before", "second before", "second after", "first after"] + end + end + + it "config hooks precede client hooks" do + order = [] + config_hook = MockHook.new(->(_, _) { order << "config before" }, ->(_, _, _) { order << "config after" }) + client_hook = MockHook.new(->(_, _) { order << "client before" }, ->(_, _, _) { order << "client after" }) + + with_client(test_config(hooks: [config_hook])) do |client| + client.add_hook(client_hook) + client.variation("doesntmatter", basic_context, "default") + + expect(order).to eq ["config before", "client before", "client after", "config after"] + end + end + end + + context "passing data" do + it "hook receives EvaluationDetail" do + td = Integrations::TestData.data_source + td.update(td.flag("flagkey").variations("value").variation_for_all(0)) + + detail = nil + config_hook = MockHook.new(->(_, _) { }, ->(_, _, d) { detail = d }) + with_client(test_config(data_source: td, hooks: [config_hook])) do |client| + client.variation("flagkey", basic_context, "default") + + expect(detail.value).to eq "value" + expect(detail.variation_index).to eq 0 + expect(detail.reason).to eq EvaluationReason::fallthrough + end + end + + it "from before evaluation to after evaluation" do + actual = nil + config_hook = MockHook.new(->(_, _) { "example string returned" }, ->(_, hook_data, _) { actual = hook_data }) + with_client(test_config(hooks: [config_hook])) do |client| + client.variation("doesntmatter", basic_context, "default") + + expect(actual).to eq "example string returned" + end + end + + it "exception receives nil value" do + actual = nil + config_hook = MockHook.new(->(_, _) { raise "example string returned" }, ->(_, hook_data, _) { actual = hook_data }) + with_client(test_config(hooks: [config_hook])) do |client| + client.variation("doesntmatter", basic_context, "default") + + expect(actual).to be_nil + end + end + + it "exceptions do not mess up data passing order" do + data = [] + first_hook = MockHook.new(->(_, _) { "first hook" }, ->(_, hook_data, _) { data << hook_data }) + second_hook = MockHook.new(->(_, _) { raise "second hook" }, ->(_, hook_data, _) { data << hook_data }) + third_hook = MockHook.new(->(_, _) { "third hook" }, ->(_, hook_data, _) { data << hook_data }) + with_client(test_config(hooks: [first_hook, second_hook, third_hook])) do |client| + client.variation("doesntmatter", basic_context, "default") + + # NOTE: These are reversed since the push happens in the after_evaluation (when hooks are reversed) + expect(data).to eq ["third hook", nil, "first hook"] + end + end + end + end +end diff --git a/spec/mock_components.rb b/spec/mock_components.rb index 3866b9f3..77663767 100644 --- a/spec/mock_components.rb +++ b/spec/mock_components.rb @@ -97,4 +97,25 @@ def self.adding_to_queue(q) new(->(value) { q << value }) end end + + class MockHook + include Interfaces::Hooks::Hook + + def initialize(before_evaluation, after_evaluation) + @before_evaluation = before_evaluation + @after_evaluation = after_evaluation + end + + def metadata + Interfaces::Hooks::Metadata.new("mock hook") + end + + def before_evaluation(hook_context, data) + @before_evaluation.call(hook_context, data) + end + + def after_evaluation(hook_context, data, detail) + @after_evaluation.call(hook_context, data, detail) + end + end end From 8028633ad6e69d993044fe3ce6a9893195c7e65d Mon Sep 17 00:00:00 2001 From: Matthew Keeler Date: Thu, 21 Mar 2024 09:20:50 -0400 Subject: [PATCH 2/3] Concurrent array --- lib/ldclient-rb/ldclient.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index 47199419..b3cf5753 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -7,6 +7,7 @@ require "ldclient-rb/impl/flag_tracker" require "ldclient-rb/impl/store_client_wrapper" require "ldclient-rb/impl/migrations/tracker" +require "concurrent" require "concurrent/atomics" require "digest/sha1" require "forwardable" @@ -54,7 +55,7 @@ def initialize(sdk_key, config = Config.default, wait_for_sec = 5) end @sdk_key = sdk_key - @hooks = config.hooks + @hooks = Concurrent::Array.new(config.hooks) @shared_executor = Concurrent::SingleThreadExecutor.new From aea01b5476a96f04dd20ba5ea3d7fdd51f8aa291 Mon Sep 17 00:00:00 2001 From: Matthew Keeler Date: Thu, 21 Mar 2024 10:32:25 -0400 Subject: [PATCH 3/3] Renames --- lib/ldclient-rb/interfaces.rb | 19 ++++++++++--------- lib/ldclient-rb/ldclient.rb | 26 +++++++++++++------------- spec/mock_components.rb | 8 ++++---- 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/lib/ldclient-rb/interfaces.rb b/lib/ldclient-rb/interfaces.rb index 57853236..c76683a9 100644 --- a/lib/ldclient-rb/interfaces.rb +++ b/lib/ldclient-rb/interfaces.rb @@ -902,35 +902,36 @@ module Hook # @return [Metadata] # def metadata - Metadata('UNDEFINED') + Metadata.new('UNDEFINED') end # # The before method is called during the execution of a variation method before the flag value has been # determined. The method is executed synchronously. # - # @param hook_context [EvaluationContext] Contains information about the evaluation being performed. This is not - # mutable. + # @param evaluation_series_context [EvaluationSeriesContext] Contains information about the evaluation being + # performed. This is not mutable. # @param data [Hash] A record associated with each stage of hook invocations. Each stage is called with the data # of the previous stage for a series. The input record should not be modified. # @return [Hash] Data to use when executing the next state of the hook in the evaluation series. # - def before_evaluation(hook_context, data) + def before_evaluation(evaluation_series_context, data) {} end # - # The after method is called during the execution of the variation method - # after the flag value has been determined. The method is executed synchronously. + # The after method is called during the execution of the variation method # after the flag value has been + # determined. The method is executed synchronously. # - # @param hook_context [EvaluationContext] Contains read-only information about the evaluation being performed. + # @param evaluation_series_context [EvaluationSeriesContext] Contains read-only information about the evaluation + # being performed. # @param data [Hash] A record associated with each stage of hook invocations. Each stage is called with the data # of the previous stage for a series. # @param detail [LaunchDarkly::EvaluationDetail] The result of the evaluation. This value should not be # modified. # @return [Hash] Data to use when executing the next state of the hook in the evaluation series. # - def after_evaluation(hook_context, data, detail) + def after_evaluation(evaluation_series_context, data, detail) data end end @@ -949,7 +950,7 @@ def initialize(name) # # Contextual information that will be provided to handlers during evaluation series. # - class EvaluationContext + class EvaluationSeriesContext attr_reader :key attr_reader :context attr_reader :value diff --git a/lib/ldclient-rb/ldclient.rb b/lib/ldclient-rb/ldclient.rb index b3cf5753..3495dce3 100644 --- a/lib/ldclient-rb/ldclient.rb +++ b/lib/ldclient-rb/ldclient.rb @@ -272,10 +272,10 @@ def variation_detail(key, context, default) private def evaluate_with_hooks(key, context, default, method) return yield if @hooks.empty? - hooks, hook_context = prepare_hooks(key, context, default, method) - hook_data = execute_before_evaluation(hooks, hook_context) + hooks, evaluation_series_context = prepare_hooks(key, context, default, method) + hook_data = execute_before_evaluation(hooks, evaluation_series_context) evaluation_detail, flag, error = yield - execute_after_evaluation(hooks, hook_context, hook_data, evaluation_detail) + execute_after_evaluation(hooks, evaluation_series_context, hook_data, evaluation_detail) [evaluation_detail, flag, error] end @@ -287,14 +287,14 @@ def variation_detail(key, context, default) # raised an uncaught exception, the value will be nil. # # @param hooks [Array] - # @param hook_context [EvaluationContext] + # @param evaluation_series_context [EvaluationSeriesContext] # # @return [Array] # - private def execute_before_evaluation(hooks, hook_context) + private def execute_before_evaluation(hooks, evaluation_series_context) hooks.map do |hook| try_execute_stage(:before_evaluation, hook.metadata.name) do - hook.before_evaluation(hook_context, {}) + hook.before_evaluation(evaluation_series_context, {}) end end end @@ -306,16 +306,16 @@ def variation_detail(key, context, default) # raised an uncaught exception, the value will be nil. # # @param hooks [Array] - # @param hook_context [EvaluationContext] + # @param evaluation_series_context [EvaluationSeriesContext] # @param hook_data [Array] # @param evaluation_detail [EvaluationDetail] # # @return [Array] # - private def execute_after_evaluation(hooks, hook_context, hook_data, evaluation_detail) + private def execute_after_evaluation(hooks, evaluation_series_context, hook_data, evaluation_detail) hooks.zip(hook_data).reverse.map do |(hook, data)| try_execute_stage(:after_evaluation, hook.metadata.name) do - hook.after_evaluation(hook_context, data, evaluation_detail) + hook.after_evaluation(evaluation_series_context, data, evaluation_detail) end end end @@ -336,13 +336,13 @@ def variation_detail(key, context, default) end # - # Return a copy of the existing hooks and a few instance of the EvaluationContext used for the evaluation series. + # Return a copy of the existing hooks and a few instance of the EvaluationSeriesContext used for the evaluation series. # # @param key [String] # @param context [LDContext] # @param default [any] # @param method [Symbol] - # @return [Array[Array, Interfaces::Hooks::EvaluationContext]] + # @return [Array[Array, Interfaces::Hooks::EvaluationSeriesContext]] # private def prepare_hooks(key, context, default, method) # Copy the hooks to use a consistent set during the evaluation series. @@ -350,9 +350,9 @@ def variation_detail(key, context, default) # Hooks can be added and we want to ensure all correct stages for a given hook execute. For example, we do not # want to trigger the after_evaluation method without also triggering the before_evaluation method. hooks = @hooks.dup - hook_context = Interfaces::Hooks::EvaluationContext.new(key, context, default, method) + evaluation_series_context = Interfaces::Hooks::EvaluationSeriesContext.new(key, context, default, method) - [hooks, hook_context] + [hooks, evaluation_series_context] end # diff --git a/spec/mock_components.rb b/spec/mock_components.rb index 77663767..4eb0e7a8 100644 --- a/spec/mock_components.rb +++ b/spec/mock_components.rb @@ -110,12 +110,12 @@ def metadata Interfaces::Hooks::Metadata.new("mock hook") end - def before_evaluation(hook_context, data) - @before_evaluation.call(hook_context, data) + def before_evaluation(evaluation_series_context, data) + @before_evaluation.call(evaluation_series_context, data) end - def after_evaluation(hook_context, data, detail) - @after_evaluation.call(hook_context, data, detail) + def after_evaluation(evaluation_series_context, data, detail) + @after_evaluation.call(evaluation_series_context, data, detail) end end end