A platform for community discussion. Free, open, simple.
DEV: Display better output when inspecting service steps
Loïc Guitauta589b48f9aea
diff --git a/lib/service/base.rb b/lib/service/base.rbindex e3e6edd9f9c..13a59d68e08 100644--- a/lib/service/base.rb+++ b/lib/service/base.rb@@ -70,7 +70,7 @@ module Serviceenddef inspect_steps- Service::StepsInspector.new(self)+ Service::StepsInspector.new(self).inspectendprivate@@ -129,7 +129,7 @@ module Service# @!visibility privateclass Step- attr_reader :name, :method_name, :class_name+ attr_reader :name, :method_name, :class_name, :instance, :contextdef initialize(name, method_name = name, class_name: nil)@name = name@@ -138,25 +138,39 @@ module Serviceenddef call(instance, context)+ @instance, @context = instance, context+ context[result_key] = Context.build+ with_runtime { run_step }+ end++ def result_key+ "result.#{type}.#{name}"+ end++ private++ def run_stepobject = class_name&.new(context)method = object&.method(:call) || instance.method(method_name)if method.parameters.any? { _1[0] != :keyreq }raise "In #{type} '#{name}': default values in step implementations are not allowed. Maybe they could be defined in a params or options block?"endargs = context.slice(*method.parameters.select { _1[0] == :keyreq }.map(&:last))- context[result_key] = Context.build({ object: }.compact)+ context[result_key][:object] = object if objectinstance.instance_exec(**args, &method)end- def result_key- "result.#{type}.#{name}"- end-- private-def typeself.class.name.split("::").last.downcase.sub(/^(\w+)step$/, "\\1")end++ def with_runtime+ started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)+ yield.tap do+ ended_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)+ context[result_key][:__runtime__] = ended_at - started_at+ end+ endend# @!visibility private@@ -168,7 +182,7 @@ module Service@optional = optional.present?end- def call(instance, context)+ def run_stepcontext[name] = superif !optional && (!context[name] || context[name].try(:empty?))raise ArgumentError, "Model not found"@@ -185,7 +199,7 @@ module Service# @!visibility privateclass PolicyStep < Step- def call(instance, context)+ def run_stepif !supercontext[result_key].fail(reason: context[result_key].object&.reason)context.fail!@@ -202,7 +216,7 @@ module Service@default_values_from = default_values_fromend- def call(instance, context)+ def run_stepattributes = class_name.attribute_names.map(&:to_sym)default_values = {}default_values = context[default_values_from].slice(*attributes) if default_values_from@@ -212,7 +226,6 @@ module Serviceoptions: context[:options],)context[contract_name] = contract- context[result_key] = Context.buildif contract.invalid?context[result_key].fail(errors: contract.errors, parameters: contract.raw_attributes)context.fail!@@ -243,7 +256,7 @@ module Serviceinstance_exec(&block)end- def call(instance, context)+ def run_stepActiveRecord::Base.transaction { steps.each { |step| step.call(instance, context) } }endend@@ -261,8 +274,7 @@ module Serviceinstance_exec(&block)end- def call(instance, context)- context[result_key] = Context.build+ def run_stepsteps.each do |step|@current_step = stepstep.call(instance, context)@@ -270,15 +282,14 @@ module Servicerescue *exceptions => eraise e if e.is_a?(Failure)context[@current_step.result_key].fail(raised_exception?: true, exception: e)- context[result_key].fail(exception: e)+ context[result_key][:exception] = econtext.fail!endend# @!visibility privateclass OptionsStep < Step- def call(instance, context)- context[result_key] = Context.build+ def run_stepcontext[:options] = class_name.new(context[:options])endend@@ -428,7 +439,10 @@ module Service# @!visibility privatedef initialize(initial_context = {})- @context = Context.build(initial_context.merge(__steps__: self.class.steps))+ @context =+ Context.build(+ initial_context.merge(__steps__: self.class.steps, __service_class__: self.class),+ )end# @!visibility privatediff --git a/lib/service/runner.rb b/lib/service/runner.rbindex 692c2d436d3..18d73070fa2 100644--- a/lib/service/runner.rb+++ b/lib/service/runner.rb@@ -97,7 +97,7 @@ class Service::Runner},on_exceptions: {condition: ->(*exceptions) do- next unless failure_for?("result.try.default")+ next unless result["result.try.default"]&.exceptionnext true if exceptions.empty?exceptions.any? { result["result.try.default"].exception.is_a?(_1) }end,diff --git a/lib/service/steps_inspector.rb b/lib/service/steps_inspector.rbindex fcb4b79d069..5ab0c804e33 100644--- a/lib/service/steps_inspector.rb+++ b/lib/service/steps_inspector.rb@@ -9,9 +9,11 @@ class Service::StepsInspectorclass Stepattr_reader :step, :result, :nesting_level- delegate :name, to: :step+ delegate :name, :result_key, to: :stepdelegate :failure?, :success?, :error, :raised_exception?, to: :step_result, allow_nil: true+ alias error? failure?+def self.for(step, result, nesting_level: 0)class_name ="#{module_parent_name}::#{step.class.name.split("::").last.sub(/^(\w+)Step$/, "\\1")}"@@ -38,13 +40,18 @@ class Service::StepsInspectorenddef inspect- "#{" " * nesting_level}[#{inspect_type}] '#{name}' #{emoji}".rstrip+ "#{" " * nesting_level}[#{inspect_type}] #{name}#{runtime} #{emoji}".rstripendprivate+ def runtime+ return unless step_result&.__runtime__+ " (#{(step_result.__runtime__ * 1000).round(4)} ms)"+ end+def step_result- result["result.#{type}.#{name}"]+ result[result_key]enddef result_emoji@@ -59,7 +66,7 @@ class Service::StepsInspectorenddef unexpected_result_text- return " <= expected to return true but got false instead" if failure?+ return " <= expected to return true but got false instead" if error?" <= expected to return false but got true instead"endend@@ -97,11 +104,7 @@ class Service::StepsInspectorenddef inspect- "#{" " * nesting_level}[#{inspect_type}]"- end-- def step_result- nil+ "#{" " * nesting_level}[#{inspect_type}]#{runtime}#{unexpected_result_emoji}"endend@@ -111,12 +114,12 @@ class Service::StepsInspector# @!visibility privateclass Try < Transaction- def error- step_result.exception.inspect+ def error?+ step_result.exceptionend- def step_result- result["result.#{type}.#{name}"]+ def error+ step_result.exception.full_messageendend@@ -127,24 +130,40 @@ class Service::StepsInspector@result = resultend- # Inspect the provided result object.+ def inspect+ output = <<~OUTPUT+ Inspecting #{result.__service_class__} result object:++ #{execution_flow}+ OUTPUT+ output += "\nWhy it failed:\n\n#{error}" if error.present?+ output+ end+# Example output:- # [1/4] [model] 'channel' ✅- # [2/4] [params] 'default' ✅- # [3/4] [policy] 'check_channel_permission' ❌- # [4/4] [step] 'change_status'+ # [1/4] [model] channel (0.02 ms) ✅+ # [2/4] [params] default (0.1 ms) ✅+ # [3/4] [policy] check_channel_permission ❌+ # [4/4] [step] change_status# @return [String] the steps of the result object with their state- def inspect+ def execution_flowsteps- .map+ .filter_map.with_index do |step, index|+ next if @encountered_error+ @encountered_error = index + 1 if step.failure?"[#{format("%#{steps.size.to_s.size}s", index + 1)}/#{steps.size}] #{step.inspect}"end.join("\n")+ .then do |output|+ skipped_steps = steps.size - @encountered_error.to_i+ next output unless @encountered_error && skipped_steps.positive?+ "#{output}\n\n(#{skipped_steps} more steps not shown as the execution flow was stopped before reaching them)"+ endend# @return [String, nil] the first available error, if any.def error- steps.detect(&:failure?)&.error+ steps.detect(&:error?)&.errorendenddiff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rbindex 31da38f55ec..fda894c9325 100644--- a/plugins/chat/plugin.rb+++ b/plugins/chat/plugin.rb@@ -450,7 +450,7 @@ after_initialize do)if creator.failure?- Rails.logger.warn "[discourse-automation] Chat message failed to send:\n#{creator.inspect_steps.inspect}\n#{creator.inspect_steps.error}"+ Rails.logger.warn "[discourse-automation] Chat message failed to send:\n#{creator.inspect_steps}"endendenddiff --git a/plugins/chat/spec/fabricators/chat_fabricator.rb b/plugins/chat/spec/fabricators/chat_fabricator.rbindex fd12a489b7b..c9841af6b95 100644--- a/plugins/chat/spec/fabricators/chat_fabricator.rb+++ b/plugins/chat/spec/fabricators/chat_fabricator.rb@@ -114,7 +114,7 @@ Fabricator(:chat_message_with_service, class_name: "Chat::CreateMessage") doif result.failure?raise RSpec::Expectations::ExpectationNotMetError.new("Service `#{resolved_class}` failed, see below for step details:\n\n" +- result.inspect_steps.inspect,+ result.inspect_steps,)enddiff --git a/plugins/chat/spec/plugin_helper.rb b/plugins/chat/spec/plugin_helper.rbindex e7b365b7d87..9e1c2f88264 100644--- a/plugins/chat/spec/plugin_helper.rb+++ b/plugins/chat/spec/plugin_helper.rb@@ -47,7 +47,7 @@ module ChatSystemHelpers},)- raise "#{creator.inspect_steps.inspect}\n\n#{creator.inspect_steps.error}" if creator.failure?+ raise creator.inspect_steps if creator.failure?last_message = creator.message_instanceend@@ -64,7 +64,7 @@ endmodule ChatSpecHelpersdef service_failed!(result)raise RSpec::Expectations::ExpectationNotMetError.new(- "Service failed, see below for step details:\n\n" + result.inspect_steps.inspect,+ "Service failed, see below for step details:\n\n" + result.inspect_steps,)enddiff --git a/spec/lib/service/steps_inspector_spec.rb b/spec/lib/service/steps_inspector_spec.rbindex 26a185b7836..1bc577562bd 100644--- a/spec/lib/service/steps_inspector_spec.rb+++ b/spec/lib/service/steps_inspector_spec.rb@@ -45,24 +45,28 @@ RSpec.describe Service::StepsInspector doendend- describe "#inspect" do- subject(:output) { inspector.inspect.strip }+ describe "#execution_flow" do+ subject(:output) { inspector.execution_flow.strip.gsub(%r{ \(\d+\.\d+ ms\)}, "") }context "when service runs without error" doit "outputs all the steps of the service" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ✅- [ 4/10] [params] 'default' ✅+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ✅+ [ 4/10] [params] default ✅[ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1' ✅- [ 7/10] [step] 'in_transaction_step_2' ✅+ [ 6/10] [step] in_transaction_step_1 ✅+ [ 7/10] [step] in_transaction_step_2 ✅[ 8/10] [try]- [ 9/10] [step] 'might_raise' ✅- [10/10] [step] 'final_step' ✅+ [ 9/10] [step] might_raise ✅+ [10/10] [step] final_step ✅OUTPUTend++ it "outputs time taken by each step" do+ expect(inspector.execution_flow).to match(/\d+\.\d+ ms/)+ endendcontext "when the model step is failing" do@@ -76,16 +80,10 @@ RSpec.describe Service::StepsInspector doit "shows the failing step" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ❌- [ 3/10] [policy] 'policy'- [ 4/10] [params] 'default'- [ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1'- [ 7/10] [step] 'in_transaction_step_2'- [ 8/10] [try]- [ 9/10] [step] 'might_raise'- [10/10] [step] 'final_step'+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ❌++ (8 more steps not shown as the execution flow was stopped before reaching them)OUTPUTendend@@ -101,16 +99,11 @@ RSpec.describe Service::StepsInspector doit "shows the failing step" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ❌- [ 4/10] [params] 'default'- [ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1'- [ 7/10] [step] 'in_transaction_step_2'- [ 8/10] [try]- [ 9/10] [step] 'might_raise'- [10/10] [step] 'final_step'+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ❌++ (7 more steps not shown as the execution flow was stopped before reaching them)OUTPUTendend@@ -120,16 +113,12 @@ RSpec.describe Service::StepsInspector doit "shows the failing step" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ✅- [ 4/10] [params] 'default' ❌- [ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1'- [ 7/10] [step] 'in_transaction_step_2'- [ 8/10] [try]- [ 9/10] [step] 'might_raise'- [10/10] [step] 'final_step'+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ✅+ [ 4/10] [params] default ❌++ (6 more steps not shown as the execution flow was stopped before reaching them)OUTPUTendend@@ -145,16 +134,15 @@ RSpec.describe Service::StepsInspector doit "shows the failing step" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ✅- [ 4/10] [params] 'default' ✅+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ✅+ [ 4/10] [params] default ✅[ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1' ✅- [ 7/10] [step] 'in_transaction_step_2' ❌- [ 8/10] [try]- [ 9/10] [step] 'might_raise'- [10/10] [step] 'final_step'+ [ 6/10] [step] in_transaction_step_1 ✅+ [ 7/10] [step] in_transaction_step_2 ❌++ (3 more steps not shown as the execution flow was stopped before reaching them)OUTPUTendend@@ -170,16 +158,17 @@ RSpec.describe Service::StepsInspector doit "shows the failing step" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ✅- [ 4/10] [params] 'default' ✅+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ✅+ [ 4/10] [params] default ✅[ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1' ✅- [ 7/10] [step] 'in_transaction_step_2' ✅+ [ 6/10] [step] in_transaction_step_1 ✅+ [ 7/10] [step] in_transaction_step_2 ✅[ 8/10] [try]- [ 9/10] [step] 'might_raise' 💥- [10/10] [step] 'final_step'+ [ 9/10] [step] might_raise 💥++ (1 more steps not shown as the execution flow was stopped before reaching them)OUTPUTendend@@ -190,16 +179,16 @@ RSpec.describe Service::StepsInspector doit "adapts its output accordingly" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ✅ ⚠️ <= expected to return false but got true instead- [ 4/10] [params] 'default' ✅+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ✅ ⚠️ <= expected to return false but got true instead+ [ 4/10] [params] default ✅[ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1' ✅- [ 7/10] [step] 'in_transaction_step_2' ✅+ [ 6/10] [step] in_transaction_step_1 ✅+ [ 7/10] [step] in_transaction_step_2 ✅[ 8/10] [try]- [ 9/10] [step] 'might_raise' ✅- [10/10] [step] 'final_step' ✅+ [ 9/10] [step] might_raise ✅+ [10/10] [step] final_step ✅OUTPUTendend@@ -216,16 +205,11 @@ RSpec.describe Service::StepsInspector doit "adapts its output accordingly" doexpect(output).to eq <<~OUTPUT.chomp- [ 1/10] [options] 'default' ✅- [ 2/10] [model] 'model' ✅- [ 3/10] [policy] 'policy' ❌ ⚠️ <= expected to return true but got false instead- [ 4/10] [params] 'default'- [ 5/10] [transaction]- [ 6/10] [step] 'in_transaction_step_1'- [ 7/10] [step] 'in_transaction_step_2'- [ 8/10] [try]- [ 9/10] [step] 'might_raise'- [10/10] [step] 'final_step'+ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ❌ ⚠️ <= expected to return true but got false instead++ (7 more steps not shown as the execution flow was stopped before reaching them)OUTPUTendend@@ -325,8 +309,31 @@ RSpec.describe Service::StepsInspector doendit "returns an error related to the exception" do- expect(error).to match(/RuntimeError: BOOM/)+ expect(error).to match(/BOOM \([^(]*RuntimeError[^)]*\)/)endendend++ describe "#inspect" do+ let(:parameter) { nil }++ it "outputs the service class name, the steps results and the specific error" do+ expect(inspector.inspect.gsub(%r{ \(\d+\.\d+ ms\)}, "")).to eq(<<~OUTPUT)+ Inspecting DummyService result object:++ [ 1/10] [options] default ✅+ [ 2/10] [model] model ✅+ [ 3/10] [policy] policy ✅+ [ 4/10] [params] default ❌++ (6 more steps not shown as the execution flow was stopped before reaching them)++ Why it failed:++ #<ActiveModel::Errors [#<ActiveModel::Error attribute=parameter, type=blank, options={}>]>++ Provided parameters: {"parameter"=>nil}+ OUTPUT+ end+ endenddiff --git a/spec/support/service_matchers.rb b/spec/support/service_matchers.rbindex 17d328cecb2..eb4dd75cfef 100644--- a/spec/support/service_matchers.rb+++ b/spec/support/service_matchers.rb@@ -26,8 +26,7 @@ module ServiceMatchersprivatedef error_message_with_inspection(message)- inspector = Service::StepsInspector.new(result)- "#{message}\n\n#{inspector.inspect}\n\n#{inspector.error}"+ "#{message}\n\n#{result.inspect_steps}"endend@@ -88,8 +87,7 @@ module ServiceMatchersenddef error_message_with_inspection(message)- inspector = Service::StepsInspector.new(result)- "#{message}\n\n#{inspector.inspect}\n\n#{inspector.error}"+ "#{message}\n\n#{result.inspect_steps}"enddef set_unexpected_result@@ -161,7 +159,7 @@ module ServiceMatchersenddef step_failed?- super && result[step].exception.is_a?(exception)+ result[step]&.exception&.is_a?(exception)enddef step_not_existing_message@@ -211,12 +209,4 @@ module ServiceMatchersdef run_successfullyRunServiceSuccessfully.newend-- def inspect_steps(result)- inspector = Service::StepsInspector.new(result)- puts "Steps:"- puts inspector.inspect- puts "\nFirst error:"- puts inspector.error- endend