A platform for community discussion. Free, open, simple.
DEV: Simplify workflow execution and remove duplicate coverage (#43726)
Régis Hanolee099f4f5acd
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rbindex 4d4904365e3..ee0518a2818 100644--- a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rb+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rb@@ -10,19 +10,17 @@ module Jobsexecution =::DiscourseWorkflows::Execution.find_by(id: args[:execution_id],+ status: :waiting,resume_token: args[:resume_token],)- return if execution.nil? || !execution.waiting?+ return if execution.nil?return if execution.waiting_until.nil? || execution.waiting_until > Time.current+ return execution.fail_with_timeout! if execution.timeout_action == "fail"- if execution.timeout_action == "fail"- execution.fail_with_timeout!- else- claimed = ::DiscourseWorkflows::Execution.claim_for_resume(execution)- return if claimed.nil?+ claimed = ::DiscourseWorkflows::Execution.claim_for_resume(execution)+ return if claimed.nil?- ::DiscourseWorkflows::Executor.resume(claimed, claimed.waiting_step_input_items)- end+ ::DiscourseWorkflows::Executor.resume(claimed, claimed.waiting_step_input_items)endendenddiff --git a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rbindex a49fe221b75..35470c57e1f 100644--- a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb+++ b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb@@ -161,52 +161,48 @@ module DiscourseWorkflowsdef fail_with_timeout!message = I18n.t("discourse_workflows.errors.approval_timed_out")node_id = waiting_node_id- claimed = false-- transaction do- run_time_ms = execution_data && self.class.compute_run_time_ms(execution_data.steps_array)-- affected =- self- .class- .where(- id: id,- status: :waiting,- resume_token: resume_token,- waiting_until: waiting_until,- timeout_action: timeout_action,- )- .update_all(- status: self.class.statuses[:error],- error: message,- finished_at: Time.current,- run_time_ms: run_time_ms,- waiting_node_id: nil,- waiting_until: nil,- resume_token: nil,- timeout_action: nil,- updated_at: Time.current,- )-- next if affected.zero?-- claimed = true- update_step_status_in_data!(- node_id,- Executor::Step::WAITING,- Executor::Step::ERROR,- message,- )- end-- if claimed- reload- trigger_error_workflow(StandardError.new(message))- DiscourseWorkflows::ExecutionProgressPublisher.publish(self, refresh: true)- DiscourseWorkflows::WorkflowCallContinuation.child_failed!(self)- end+ claimed =+ transaction do+ run_time_ms = execution_data && self.class.compute_run_time_ms(execution_data.steps_array)++ affected =+ self+ .class+ .where(+ id: id,+ status: :waiting,+ resume_token: resume_token,+ waiting_until: waiting_until,+ timeout_action: timeout_action,+ )+ .update_all(+ status: self.class.statuses[:error],+ error: message,+ finished_at: Time.current,+ run_time_ms: run_time_ms,+ waiting_node_id: nil,+ waiting_until: nil,+ resume_token: nil,+ timeout_action: nil,+ updated_at: Time.current,+ )++ next false if affected.zero?+ update_step_status_in_data!(+ node_id,+ Executor::Step::WAITING,+ Executor::Step::ERROR,+ message,+ )+ true+ end+ return false unless claimed- claimed+ reload+ trigger_error_workflow(StandardError.new(message))+ DiscourseWorkflows::ExecutionProgressPublisher.publish(self, refresh: true)+ DiscourseWorkflows::WorkflowCallContinuation.child_failed!(self)+ trueenddef trigger_error_workflow(error, steps: execution_data&.steps_array || [])@@ -268,11 +264,11 @@ module DiscourseWorkflowsfull_data = execution_data.data.deep_dup(full_data["entries"] || {}).each_value do |steps|Array(steps).each do |step|- if step["node_id"] == node_id.to_s && step["status"] == from_status.to_s- step["status"] = to_status.to_s- step["error"] = error_msg if error_msg- step["finished_at"] = Time.current.iso8601- end+ next unless step["node_id"] == node_id.to_s && step["status"] == from_status.to_s++ step["status"] = to_status.to_s+ step["error"] = error_msg if error_msg+ step["finished_at"] = Time.current.iso8601endendexecution_data.update!(data: full_data)diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rbindex 263885e4c51..f1e90e08f66 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rb@@ -172,7 +172,7 @@ module DiscourseWorkflowsenddef async_resume?(waiting_node:)- wait_node_response_mode(waiting_node) == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED+ node_response_mode(waiting_node) == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVEDenddef sync_resume?(waiting_node:)@@ -310,7 +310,7 @@ module DiscourseWorkflowsdef enqueue_async_workflows(request_allowed_nodes:, webhook_context:)request_allowed_nodes.each do |published_trigger|node = published_trigger.trigger_node- response_mode = trigger_node_response_mode(node)+ response_mode = node_response_mode(node)next unless response_mode == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVEDDiscourseWorkflows::TriggerDispatcher.enqueue(@@ -325,7 +325,7 @@ module DiscourseWorkflowsrequest_allowed_nodes.each do |published_trigger|node = published_trigger.trigger_nodeparameters = NodeData.parameters(node)- response_mode = trigger_node_response_mode(node)+ response_mode = node_response_mode(node)next if response_mode == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVEDexecution =@@ -372,7 +372,7 @@ module DiscourseWorkflows{execution: execution,- response_mode: trigger_node_response_mode(node),+ response_mode: node_response_mode(node),response_code: parameters["response_code"],response_data: parameters["response_data"],response_parameters: parameters,@@ -408,12 +408,7 @@ module DiscourseWorkflowsendend- def wait_node_response_mode(waiting_node)- NodeData.parameters(waiting_node)["response_mode"] ||- Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED- end-- def trigger_node_response_mode(node)+ def node_response_mode(node)NodeData.parameters(node)["response_mode"] || Schemas::Webhook::RESPONSE_MODE_ON_RECEIVEDenddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rbindex b8792b0d988..c8b95261a08 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rb@@ -60,16 +60,13 @@ module DiscourseWorkflowsdef run_workflow(trigger_node:, workflow:, workflow_version:, params:, user:)options =- DiscourseWorkflows::Executor::ExecutionOptions.new(+ Executor::ExecutionOptions.new(user: user,execution_mode: params.execution_mode.to_sym,workflow_version: workflow_version,job_id: params.job_id,)- executor =- DiscourseWorkflows::Executor.new(workflow, trigger_node["id"], params.trigger_data, options)- executor.run- executor.execution+ Executor.new(workflow, trigger_node["id"], params.trigger_data, options).runendendenddiff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rbindex 43c0745732c..cc0b7c77c3e 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb@@ -57,12 +57,7 @@ module DiscourseWorkflowsoptions: @options,)@steps = []- @queue = []- @queue_index = 0- @waiting_inputs = {}- @waiting_input_sources = {}- @waiting_input_targets = {}- @input_wait_requirements = {}+ reset_queue!@sandbox = nil@waiting_node = nil@waiting_step = nil@@ -246,7 +241,7 @@ module DiscourseWorkflowsstack.last == workflow_id ? stack : stack + [workflow_id]end- def execute_flow(setup_method, *setup_args, &block)+ def execute_flow(setup_method, *setup_args)beginreturn execution if send(setup_method, *setup_args) == falseyield@@ -667,11 +662,10 @@ module DiscourseWorkflowsenddef sole_input_pair(input_groups)- pairs =- input_groups.flat_map do |input_index, items|- items.each_index.map { |item_index| pair_for(input: input_index, item: item_index) }- end- pairs.one? ? pairs.first : nil+ return unless input_groups.sum { |_input_index, items| items.size } == 1++ input_index = input_groups.find { |_input_index, items| items.one? }.first+ pair_for(input: input_index, item: 0)enddef pair_for(input:, item:, include_input: false)@@ -945,8 +939,6 @@ module DiscourseWorkflowselsebegin_timed_wait!(wait_request.waiting_until, timeout_action: wait_request.timeout_action)end- rescue => e- @store.fail!(error: e, steps: @steps)enddef store_pending_wait_state!@@ -1004,12 +996,7 @@ module DiscourseWorkflows@snapshot = @store.workflow_snapshot@steps = []- @queue = []- @queue_index = 0- @waiting_inputs = {}- @waiting_input_sources = {}- @waiting_input_targets = {}- @input_wait_requirements = {}+ reset_queue!enddef create_execution!@@ -1033,14 +1020,18 @@ module DiscourseWorkflows@store.resume!(execution)@snapshot = @store.workflow_snapshot@steps = restore_steps_from(execution)+ reset_queue!+ restore_pending_queue!+ restore_pending_input_groups!+ end++ def reset_queue!@queue = []@queue_index = 0@waiting_inputs = {}@waiting_input_sources = {}@waiting_input_targets = {}@input_wait_requirements = {}- restore_pending_queue!- restore_pending_input_groups!enddef clear_waiting!diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rbindex afc6f9803d6..84814a3ae27 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb@@ -37,7 +37,7 @@ module DiscourseWorkflows@workflow_snapshot.to_h["nodes"],workflow_name: @workflow_snapshot.workflow_name,)- @execution = create_execution!+ persist_execution!(status: :running, trigger_data: trigger_data)return false if @duplicate_jobreset_collaborators!@@ -147,12 +147,8 @@ module DiscourseWorkflowsprivate- def create_execution!- persist_execution!(status: :running, trigger_data: trigger_data)- end-def persist_execution!(status:, trigger_data:, finished_at: nil)- @execution = @options.existing_execution || DiscourseWorkflows::Execution.new+ @execution = @options.existing_execution || Execution.newcreated = @execution.new_record?@execution_context.execution = @execution if @options.existing_executionattributes = {diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rbindex def77757edc..8019dfde81e 100644--- a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb@@ -1,6 +1,10 @@# frozen_string_literal: trueRSpec.describe Jobs::DiscourseWorkflows::ResumeWaitingExecution do+ subject(:execute_job) do+ described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)+ end+fab!(:workflow) { Fabricate(:discourse_workflows_workflow, published: true) }fab!(:execution) doFabricate(@@ -14,42 +18,27 @@ RSpec.describe Jobs::DiscourseWorkflows::ResumeWaitingExecution doit "leaves the execution waiting when the plugin is disabled" doSiteSetting.enable_discourse_workflows = false- before_updated_at = execution.updated_at-- described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)- execution.reload- expect(execution.status).to eq("waiting")- expect(execution.updated_at).to eq_time(before_updated_at)+ expect { execute_job }.not_to change { execution.reload.attributes }endit "leaves the execution untouched when another worker already claimed it" doallow(::DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)- before_updated_at = execution.updated_at- described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)-- execution.reload- expect(execution.status).to eq("waiting")- expect(execution.updated_at).to eq_time(before_updated_at)+ expect { execute_job }.not_to change { execution.reload.attributes }endit "no-ops when the execution is no longer waiting" doexecution.update!(status: :running)- before_updated_at = execution.updated_at-- described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)- execution.reload- expect(execution.status).to eq("running")- expect(execution.updated_at).to eq_time(before_updated_at)+ expect { execute_job }.not_to change { execution.reload.attributes }endcontext "when the timeout action is fail" dobefore { execution.update!(timeout_action: "fail") }it "fails the execution with the existing timeout error and clears its wait state" do- described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)+ execute_jobexpect(execution.reload).to have_attributes(status: "error",diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rbindex 45f82613a78..282b1ad1604 100644--- a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rb+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rb@@ -1,6 +1,10 @@# frozen_string_literal: trueRSpec.describe Jobs::DiscourseWorkflows::ResumeWebhookWaiting do+ subject(:execute_job) do+ described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)+ end+fab!(:workflow) { Fabricate(:discourse_workflows_workflow, published: true) }fab!(:execution) doFabricate(@@ -13,23 +17,13 @@ RSpec.describe Jobs::DiscourseWorkflows::ResumeWebhookWaiting doit "leaves the execution waiting when the plugin is disabled" doSiteSetting.enable_discourse_workflows = false- before_updated_at = execution.updated_at- described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)-- execution.reload- expect(execution.status).to eq("waiting")- expect(execution.updated_at).to eq_time(before_updated_at)+ expect { execute_job }.not_to change { execution.reload.attributes }endit "leaves the execution untouched when another worker already claimed it" doallow(::DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)- before_updated_at = execution.updated_at-- described_class.new.execute(execution_id: execution.id, resume_token: execution.resume_token)- execution.reload- expect(execution.status).to eq("waiting")- expect(execution.updated_at).to eq_time(before_updated_at)+ expect { execute_job }.not_to change { execution.reload.attributes }endenddiff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rbindex cd5eb0251a9..2efd862af69 100644--- a/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb@@ -12,12 +12,12 @@ RSpec.describe DiscourseWorkflows::Execution do)end- it "transitions a waiting execution to running and returns it" do- claimed = described_class.claim_for_resume(execution, resume_token: "tok-abc")+ it "claims a waiting execution once using its current token" do+ claimed = described_class.claim_for_resume(execution)- expect(claimed).to be_present- expect(claimed.status).to eq("running")+ expect(claimed).to eq(execution)expect(execution.reload.status).to eq("running")+ expect(described_class.claim_for_resume(execution)).to be_nilendit "returns nil when the resume token does not match" do@@ -25,33 +25,6 @@ RSpec.describe DiscourseWorkflows::Execution doexpect(execution.reload.status).to eq("waiting")end- it "returns nil when the execution is no longer waiting" do- execution.update!(status: :running)-- expect(described_class.claim_for_resume(execution, resume_token: "tok-abc")).to be_nil- end-- it "returns nil when the execution does not exist" do- execution.destroy!-- expect(described_class.claim_for_resume(execution, resume_token: "tok-abc")).to be_nil- end-- it "matches without a resume token (job entry points)" do- claimed = described_class.claim_for_resume(execution)-- expect(claimed).to be_present- expect(claimed.status).to eq("running")- end-- it "is idempotent — only the first call claims the execution" do- first = described_class.claim_for_resume(execution, resume_token: "tok-abc")- second = described_class.claim_for_resume(execution, resume_token: "tok-abc")-- expect(first).to be_present- expect(second).to be_nil- end-it "preserves a newer wait when the caller holds a stale execution" dostale_execution = described_class.find(execution.id)execution.update!(resume_token: "new-wait-token")@@ -67,18 +40,13 @@ RSpec.describe DiscourseWorkflows::Execution doFabricate(:discourse_workflows_execution, workflow: workflow, status: :pending)end- it "transitions a pending execution to running and returns it" do+ it "starts a pending execution once" doclaimed = described_class.claim_pending(execution)expect(claimed).to be_presentexpect(claimed.status).to eq("running")expect(claimed.started_at).to be_presentexpect(execution.reload.status).to eq("running")- end-- it "returns nil when the execution is no longer pending" do- execution.update!(status: :running)-expect(described_class.claim_pending(execution)).to be_nilendenddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rbindex 0341ae91826..98d01e73336 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rb@@ -11,13 +11,13 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive dofab!(:admin)fab!(:workflow) dograph =- build_workflow_graph do |g|- g.node "webhook-1",- "trigger:webhook",- configuration: {- "path" => "my-hook",- "http_method" => "POST",- }+ build_workflow_graph do |builder|+ builder.node "webhook-1",+ "trigger:webhook",+ configuration: {+ "path" => "my-hook",+ "http_method" => "POST",+ }endFabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)end@@ -45,34 +45,32 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive doendcontext "when resuming a waiting execution" do- let(:resume_token) { "my-hook" }+ let(:resume_token) { waiting_execution.resume_token }let(:webhook_suffix) { "" }let(:response_mode) { "on_received" }- let(:response_code) { "200" }+ let(:response_code) { Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(:ok).to_s }let(:wait_http_method) { "POST" }let(:waiting_workflow) dograph =- build_workflow_graph do |g|- g.node "trigger-1", "trigger:manual"- g.node "wait-1",- "flow:wait",- configuration: {- "resume" => "webhook",- "http_method" => wait_http_method,- "response_mode" => response_mode,- "response_code" => response_code,- "webhook_suffix" => webhook_suffix,- }- g.chain "trigger-1", "wait-1"+ build_workflow_graph do |builder|+ builder.node "trigger-1", "trigger:manual"+ builder.node "wait-1",+ "flow:wait",+ configuration: {+ "resume" => "webhook",+ "http_method" => wait_http_method,+ "response_mode" => response_mode,+ "response_code" => response_code,+ "webhook_suffix" => webhook_suffix,+ }+ builder.chain "trigger-1", "wait-1"endFabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)endlet(:waiting_execution) do- execution = DiscourseWorkflows::Executor.new(waiting_workflow, "trigger-1", {}).run- execution.update!(resume_token: resume_token)- execution+ DiscourseWorkflows::Executor.new(waiting_workflow, "trigger-1", {}).runendlet(:signature) do@@ -107,10 +105,8 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive doendcontext "when response mode is on_received" do- it { is_expected.to run_successfully }-it "enqueues a ResumeWebhookWaiting job" do- result+ expect(result).to run_successfullyjob = Jobs::DiscourseWorkflows::ResumeWebhookWaiting.jobs.lastexpect(job["args"].first).to include("execution_id" => waiting_execution.id,@@ -151,26 +147,21 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive docontext "when response mode is synchronous" dolet(:response_mode) { "last_node" }- let(:response_code) { "200" }-- fab!(:resumed_execution) { Fabricate(:discourse_workflows_execution, workflow: workflow) }-- before { DiscourseWorkflows::Executor.stubs(:resume).returns(resumed_execution) }- it { is_expected.to run_successfully }-- it "sets sync_result on the context" do- expect(result[:sync_result][:execution]).to eq(resumed_execution)- expect(result[:sync_result][:response_mode]).to eq("last_node")- expect(result[:sync_result][:response_code]).to eq("200")+ it "returns the resumed execution synchronously" do+ expect(result).to run_successfully+ expect(result[:sync_result]).to include(+ execution: waiting_execution,+ response_mode: response_mode,+ response_code: response_code,+ )+ expect(waiting_execution.reload).to be_successend- context "when the execution has already been claimed for resume" do- before do- allow(DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)- end+ it "fails when another request already claimed the execution" do+ DiscourseWorkflows::Execution.stubs(:claim_for_resume).returns(nil)- it { is_expected.to fail_to_find_a_model(:claimed_execution) }+ expect(result).to fail_to_find_a_model(:claimed_execution)endendend@@ -197,10 +188,8 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive doendcontext "when everything is valid" do- it { is_expected.to run_successfully }-it "enqueues an ExecuteWorkflow job" do- result+ expect(result).to run_successfullyjob = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.lastexpect(job["args"].first).to include("trigger_node_id" => "webhook-1",@@ -283,10 +272,8 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive dosuper().merge(headers: { "authorization" => auth }, raw_authorization: auth)end- it { is_expected.to run_successfully }-it "executes the workflow" do- result+ expect(result).to run_successfullyjob = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.lastexpect(job["args"].first["trigger_node_id"]).to eq("webhook-1")end@@ -298,18 +285,16 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive dosuper().merge(headers: { "authorization" => auth }, raw_authorization: auth)end- it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }-it "exposes :denied as the auth failure reason" do+ expect(result).to fail_to_find_a_model(:authenticated_nodes)expect(result[:auth_failure_reason]).to eq(:denied)expect(result[:auth_failure_mode]).to eq("basic_auth")endendcontext "when request has no authorization header" do- it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }-it "exposes :challenge as the auth failure reason" do+ expect(result).to fail_to_find_a_model(:authenticated_nodes)expect(result[:auth_failure_reason]).to eq(:challenge)expect(result[:auth_failure_mode]).to eq("basic_auth")end@@ -318,173 +303,40 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive docontext "when credential record is missing" dobefore { credential.destroy! }- it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }-- it "exposes :misconfigured as the auth failure reason" do- expect(result[:auth_failure_reason]).to eq(:misconfigured)- end- end-- context "when auth mode is unsupported" do- before do- update_workflow_node(workflow, "webhook-1") do |node|- node.merge(- "parameters" => node["parameters"].merge("authentication" => "unknown_mode"),- )- end- publish_workflow!(workflow)- end-- it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }-it "exposes :misconfigured as the auth failure reason" do+ expect(result).to fail_to_find_a_model(:authenticated_nodes)expect(result[:auth_failure_reason]).to eq(:misconfigured)endendend- context "with bearer auth" do- fab!(:credential) do- Fabricate(- :discourse_workflows_credential,- credential_type: "bearer_token",- data: {- "token" => "secret-token",- },- )- end-- before do- update_workflow_node(workflow, "webhook-1") do |node|- node.merge(- DiscourseWorkflows::NodeData.split(- parameters: {- "path" => "my-hook",- "http_method" => "POST",- "authentication" => "bearer_auth",- },- credentials: {- "auth" => {- "id" => credential.id,- "credential_type" => "bearer_token",- },- },- node_type: node["type"],- ),- )- end- publish_workflow!(workflow)- end-- context "when request has valid bearer token" do- let(:params) do- auth = "Bearer secret-token"- super().merge(headers: { "authorization" => auth }, raw_authorization: auth)- end-- it { is_expected.to run_successfully }- end-- context "when bearer token is missing" do- it "exposes :denied as the auth failure reason" do- expect(result[:auth_failure_reason]).to eq(:denied)- end- end- end-- context "with header auth" do- fab!(:credential) do- Fabricate(- :discourse_workflows_credential,- credential_type: "header_auth",- data: {- "name" => "X-Api-Key",- "value" => "secret-value",- },- )- end-- before do- update_workflow_node(workflow, "webhook-1") do |node|- node.merge(- DiscourseWorkflows::NodeData.split(- parameters: {- "path" => "my-hook",- "http_method" => "POST",- "authentication" => "header_auth",- },- credentials: {- "auth" => {- "id" => credential.id,- "credential_type" => "header_auth",- },- },- node_type: node["type"],- ),- )- end- publish_workflow!(workflow)- end-- context "when request has matching header" do- let(:params) { super().merge(headers: { "x-api-key" => "secret-value" }) }-- it { is_expected.to run_successfully }- end-- context "when header is missing" do- it "exposes :denied as the auth failure reason" do- expect(result[:auth_failure_reason]).to eq(:denied)- end- end- end-- context "when another workflow tries to claim the same path" do- fab!(:conflicting_workflow) do- graph =- build_workflow_graph do |g|- g.node "other-webhook-1",- "trigger:webhook",- configuration: {- "path" => "my-hook",- "http_method" => "POST",- "authentication" => "none",- }- end- Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)- end-- it "rejects activation of the second workflow with CollisionError" do- publish_workflow!(workflow)-- expect { publish_workflow!(conflicting_workflow) }.to raise_error(- DiscourseWorkflows::Webhook::Action::ActivateWebhooks::CollisionError,- )- end- end-context "with synchronous response mode" do+ let(:response_code) { Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(:created).to_s }+before doupdate_workflow_node(workflow, "webhook-1") do |node|node.merge("parameters" =>- node["parameters"].merge("response_mode" => "last_node", "response_code" => "201"),+ node["parameters"].merge(+ "response_mode" => "last_node",+ "response_code" => response_code,+ ),)endpublish_workflow!(workflow)end- it { is_expected.to run_successfully }-- it "does not enqueue an async job" do- result+ it "returns a synchronous result without enqueuing a job" do+ expect(result).to run_successfullyexpect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty- end-- it "sets sync_result on the context" do- expect(result[:sync_result][:execution]).to be_a(DiscourseWorkflows::Execution)- expect(result[:sync_result][:response_mode]).to eq("last_node")- expect(result[:sync_result][:response_code]).to eq("201")+ expect(result[:sync_result]).to include(+ response_mode: "last_node",+ response_code: response_code,+ )+ expect(result[:sync_result][:execution]).to have_attributes(+ workflow_id: workflow.id,+ status: "success",+ )endendend@@ -492,6 +344,13 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive docontext "when triggering a test webhook" dolet(:test_listener_id) { nil }let(:params) { super().merge(test_webhook: true, test_listener_id: test_listener_id) }+ let(:listener) do+ DiscourseWorkflows::WebhookTestListener.create!(+ workflow: workflow,+ user: admin,+ trigger_node: workflow.find_node("webhook-1"),+ )+ endbefore { unpublish_workflow!(workflow) }@@ -500,21 +359,13 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive doendcontext "when everything is valid" do- let(:listener) do- DiscourseWorkflows::WebhookTestListener.create!(- workflow: workflow,- user: admin,- trigger_node: workflow.find_node("webhook-1"),- )- endlet(:test_listener_id) { listener.listener_id }- it { is_expected.to run_successfully }-it "runs the draft workflow synchronously" do- expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)+ expect(result).to run_successfully+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty- execution = DiscourseWorkflows::Execution.last+ execution = result[:sync_result][:execution]expect(execution).to have_attributes(workflow_id: workflow.id,trigger_node_id: "webhook-1",@@ -525,22 +376,9 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive do"#{Discourse.base_url}/workflows/webhook-test/#{listener.listener_id}/my-hook",)end-- it "does not enqueue an async job" do- result-- expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty- endendcontext "when request filtering rejects the request" do- let(:listener) do- DiscourseWorkflows::WebhookTestListener.create!(- workflow: workflow,- user: admin,- trigger_node: workflow.find_node("webhook-1"),- )- endlet(:test_listener_id) { listener.listener_id }before do@@ -556,10 +394,8 @@ RSpec.describe DiscourseWorkflows::Webhook::Receive dolet(:params) { super().merge(remote_ip: "192.0.2.10") }- it { is_expected.to fail_to_find_a_model(:request_allowed_nodes) }-it "does not consume the listener" do- result+ expect(result).to fail_to_find_a_model(:request_allowed_nodes)expect(DiscourseWorkflows::WebhookTestListener.find_by_route(method: "POST", path: "my-hook"),diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rbindex 4bc4701024c..56d5027946b 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rb@@ -10,7 +10,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Execute dofab!(:user)fab!(:workflow) do- graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }+ graph = build_workflow_graph { |builder| builder.node "trigger-1", "trigger:manual" }Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)end@@ -50,10 +50,9 @@ RSpec.describe DiscourseWorkflows::Workflow::Execute do)end- it { is_expected.to run_successfully }-it "finds the workflow via dependency index" do- expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)+ expect(result).to run_successfully+ expect(result[:execution]).to have_attributes(workflow_id: workflow.id, status: "success")endend@@ -72,23 +71,14 @@ RSpec.describe DiscourseWorkflows::Workflow::Execute dopublish_workflow!(workflow)end- it { is_expected.to run_successfully }-it "executes the matched version instead of the current active version" do+ expect(result).to run_successfullyexpect(result[:workflow_version]).to eq(matched_version)workflow_data = result[:execution].execution_data.workflow_dataexpect(workflow_data["nodes"]).to contain_exactly(include("id" => "trigger-1"))endend- context "when everything's ok" do- it { is_expected.to run_successfully }-- it "creates an execution record" do- expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)- end- end-context "when no job_id is provided" doit "creates separate executions for repeated calls without a job ID" dofirst_execution = result[:execution]@@ -338,9 +328,8 @@ RSpec.describe DiscourseWorkflows::Workflow::Execute do{ workflow_id: workflow.id, trigger_node_id: "trigger-1", user_id: execution_user.id }end- it { is_expected.to run_successfully }-it "fetches the correct user" do+ expect(result).to run_successfullyexpect(result[:user]).to eq(execution_user)endend