Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Separate request logic into two classes.
Sebastian Palmaa3d3f850b50e
diff --git a/api/app/jobs/spree/webhooks/endpoints/make_request_job.rb b/api/app/jobs/spree/webhooks/endpoints/make_request_job.rbindex f94f183291..d9e5936a35 100644--- a/api/app/jobs/spree/webhooks/endpoints/make_request_job.rb+++ b/api/app/jobs/spree/webhooks/endpoints/make_request_job.rb@@ -5,7 +5,7 @@ module Spreequeue_as :spree_webhooksdef perform(body, event, url)- Spree::Webhooks::Endpoints::MakeRequest.new(body: body, event: event, url: url).call+ Spree::Webhooks::Endpoints::HandleRequest.new(body: body, event: event, url: url).callendendenddiff --git a/api/app/services/spree/webhooks/endpoints/handle_request.rb b/api/app/services/spree/webhooks/endpoints/handle_request.rbnew file mode 100644index 0000000000..086e0be73e--- /dev/null+++ b/api/app/services/spree/webhooks/endpoints/handle_request.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++module Spree+ module Webhooks+ module Endpoints+ class HandleRequest+ def initialize(body:, event:, url:)+ @body = body+ @event = event+ @url = url+ end++ def call+ return if body == ''++ Rails.logger.debug(webhooks_log("sending to '#{url}'"))+ Rails.logger.debug(webhooks_log("body: #{body}"))++ if request.unprocessable_uri?+ Rails.logger.warn(webhooks_log("can not make a request to '#{url}'"))+ return+ end++ if request.failed_request?+ Rails.logger.warn(webhooks_log("failed for '#{url}'"))+ return+ end++ Rails.logger.debug(webhooks_log("success for URL '#{url}'"))+ end++ private++ attr_reader :body, :event, :url++ def request+ @request ||= Spree::Webhooks::Endpoints::MakeRequest.new(body: body, url: url)+ end++ def webhooks_log(msg)+ "[SPREE WEBHOOKS] '#{event}' #{msg}"+ end+ end+ end+ end+enddiff --git a/api/app/services/spree/webhooks/endpoints/make_request.rb b/api/app/services/spree/webhooks/endpoints/make_request.rbindex 4601920453..8fdb185c57 100644--- a/api/app/services/spree/webhooks/endpoints/make_request.rb+++ b/api/app/services/spree/webhooks/endpoints/make_request.rb@@ -4,48 +4,29 @@ module Spreemodule Webhooksmodule Endpointsclass MakeRequest- def initialize(body:, event:, url:)+ def initialize(body:, url:)@body = body- @event = event@url = url+ @webhooks_timeout = ENV['SPREE_WEBHOOKS_TIMEOUT']end- def call- return if body == ''-- Rails.logger.debug(webhooks_log("sending to '#{url}'"))- Rails.logger.debug(webhooks_log("body: #{body}"))-- if unprocessable_uri?- Rails.logger.warn(webhooks_log("can not make a request to '#{url}'"))- return- end-- if failed_request?- Rails.logger.warn(webhooks_log("failed for '#{url}'"))- return- end+ def failed_request?+ (200...300).exclude?(request_status_code)+ end- Rails.logger.debug(webhooks_log("success for URL '#{url}'"))+ def unprocessable_uri?+ uri_path == '' && uri_host.nil? && uri_port.nil?endprivate- attr_reader :body, :event, :url+ attr_reader :body, :url, :webhooks_timeoutHEADERS = { 'Content-Type' => 'application/json' }.freezeprivate_constant :HEADERSdelegate :host, :path, :port, to: :uri, prefix: true- def unprocessable_uri?- uri_path == '' && uri_host.nil? && uri_port.nil?- end-- def failed_request?- (200...300).exclude?(request_status_code)- end-def request_status_codehttp.request(request).code.to_irescue SocketError, Net::ReadTimeout@@ -54,12 +35,8 @@ module Spreedef httphttp = Net::HTTP.new(uri_host, uri_port)- if (webhooks_timeout = ENV['SPREE_WEBHOOKS_TIMEOUT'])- http.read_timeout = webhooks_timeout.to_i- end- unless Rails.env.development? || Rails.env.test?- http.use_ssl = true- end+ http.read_timeout = webhooks_timeout.to_i if custom_read_timeout?+ http.use_ssl = true if use_ssl?httpend@@ -69,12 +46,16 @@ module Spreereqend- def uri- URI(url)+ def custom_read_timeout?+ webhooks_timeout.present?+ end++ def use_ssl?+ !(Rails.env.development? || Rails.env.test?)end- def webhooks_log(msg)- "[SPREE WEBHOOKS] '#{event}' #{msg}"+ def uri+ URI(url)endendenddiff --git a/api/db/migrate/20210902162826_create_spree_webhooks_tables.rb b/api/db/migrate/20210902162826_create_spree_webhooks_tables.rbindex 5a0a6bf5d8..bc65024a2f 100644--- a/api/db/migrate/20210902162826_create_spree_webhooks_tables.rb+++ b/api/db/migrate/20210902162826_create_spree_webhooks_tables.rb@@ -4,20 +4,13 @@ class CreateSpreeWebhooksTables < ActiveRecord::Migration[5.2]t.string :url, null: falset.boolean :enabled, default: false, index: true- create_subscriptions_column!(t)+ if t.respond_to? :jsonb+ t.jsonb :subscriptions+ else+ t.json :subscriptions+ endt.timestampsendend-- private-- def create_subscriptions_column!(table)- case ActiveRecord::Base.connection.adapter_name- when 'Mysql2'- table.json :subscriptions- when 'PostgreSQL'- table.jsonb :subscriptions- end- endenddiff --git a/api/spec/jobs/spree/webhooks/endpoints/make_request_job_spec.rb b/api/spec/jobs/spree/webhooks/endpoints/make_request_job_spec.rbindex 85190bf671..986cabf533 100644--- a/api/spec/jobs/spree/webhooks/endpoints/make_request_job_spec.rb+++ b/api/spec/jobs/spree/webhooks/endpoints/make_request_job_spec.rb@@ -6,7 +6,7 @@ describe Spree::Webhooks::Endpoints::MakeRequestJob dolet(:queue) { 'spree_webhooks' }let(:url) { 'http://url.com/' }- it 'enqueues a HTTP request using Spree::Webhooks::Endpoints::MakeRequest', :job do+ it 'enqueues a HTTP request using Spree::Webhooks::Endpoints::HandleRequest', :job doexpect { described_class.perform_later(body, event, url) }.to have_enqueued_job.on_queue(queue)endenddiff --git a/api/spec/services/spree/webhooks/endpoints/handle_request_spec.rb b/api/spec/services/spree/webhooks/endpoints/handle_request_spec.rbnew file mode 100644index 0000000000..1486e9012c--- /dev/null+++ b/api/spec/services/spree/webhooks/endpoints/handle_request_spec.rb@@ -0,0 +1,86 @@+require 'spec_helper'++describe Spree::Webhooks::Endpoints::HandleRequest do+ describe '#call' do+ subject { described_class.new(body: body, event: event, url: url) }++ let(:body) { { foo: :bar }.to_json }+ let(:event) { 'order.cancel' }+ let(:headers) { { 'Content-Type' => 'application/json' } }+ let(:request_double) { instance_double(Spree::Webhooks::Endpoints::MakeRequest) }+ let(:url) { 'http://google.com/' }++ context 'with an unexpected body' do+ let(:body) { '' }++ it 'does not instantiate a new request' do+ expect(Spree::Webhooks::Endpoints::MakeRequest).not_to receive(:new)+ subject.call+ end++ it { expect(subject.call).to eq(nil) }+ end++ context 'with an unprocessable uri' do+ let(:url) { '' }++ before do+ allow(subject).to receive(:request).and_return(request_double)+ allow(request_double).to receive(:unprocessable_uri?).and_return(true)+ end++ it 'debug logs before the request' do+ allow(Rails.logger).to receive(:warn)+ subject.call+ message = "[SPREE WEBHOOKS] 'order.cancel' can not make a request to ''"+ expect(Rails.logger).to have_received(:warn).with(message)+ end++ it { expect(subject.call).to eq(nil) }+ end++ context 'with a processable uri' do+ before { stub_request(:post, url) }++ it 'debug logs before the request' do+ allow(Rails.logger).to receive(:debug)+ subject.call+ message_fst = "[SPREE WEBHOOKS] 'order.cancel' sending to 'http://google.com/'"+ message_snd = "[SPREE WEBHOOKS] 'order.cancel' body: #{body}"+ expect(Rails.logger).to have_received(:debug).with(message_fst)+ expect(Rails.logger).to have_received(:debug).with(message_snd)+ end++ context 'with a failed request' do+ before do+ allow(subject).to receive(:request).and_return(request_double)+ allow(request_double).to receive(:unprocessable_uri?).and_return(false)+ allow(request_double).to receive(:failed_request?).and_return(true)+ end++ it 'warn logs after the request' do+ allow(Rails.logger).to receive(:warn)+ subject.call+ message = "[SPREE WEBHOOKS] 'order.cancel' failed for 'http://google.com/'"+ expect(Rails.logger).to have_received(:warn).with(message)+ end++ it { expect(subject.call).to eq(nil) }+ end++ context 'without a failed request' do+ let(:message) { "[SPREE WEBHOOKS] 'order.cancel' success for URL 'http://google.com/'" }++ it 'debug logs after the request' do+ allow(Rails.logger).to receive(:debug)+ subject.call+ expect(Rails.logger).to have_received(:debug).with(message)+ end++ it 'returns the debug logger' do+ expect(subject.call).to eq(Rails.logger.debug(message))+ end+ end+ end+ end+enddiff --git a/api/spec/services/spree/webhooks/endpoints/make_request_spec.rb b/api/spec/services/spree/webhooks/endpoints/make_request_spec.rbindex df58e1f005..dbcededc47 100644--- a/api/spec/services/spree/webhooks/endpoints/make_request_spec.rb+++ b/api/spec/services/spree/webhooks/endpoints/make_request_spec.rb@@ -1,187 +1,163 @@require 'spec_helper'describe Spree::Webhooks::Endpoints::MakeRequest do- describe '#call' do- subject { described_class.new(body: body, event: event, url: url).call }+ let(:body) { { data: [{}] }.to_json }+ let(:url) { 'google.com' }- let(:event) { 'order.cancel' }- let(:url) { 'http://google.com/' }- let(:body) { { foo: :bar }.to_json }- let(:uri) { URI(url) }+ describe '#failed_request?' do+ subject { described_class.new(body: body, url: url).failed_request? }++ before { stub_request(:post, url) }++ let(:headers) { { 'Content-Type' => 'application/json' } }let(:http) { Net::HTTP.new(uri.host, uri.port) }+ let(:http_double) { instance_double(Net::HTTP) }+ let(:uri) { URI(url) }+ let(:url) { 'http://google.com/' }++ describe 'ssl usage' do+ shared_examples 'makes the request without setting use_ssl' do+ it 'does not set use_ssl' do+ allow(Net::HTTP).to receive(:new).with(uri.host, uri.port).and_return(http)+ expect(http).not_to receive(:use_ssl=)+ subject+ end- shared_examples 'returns nil without making a request' do- it 'does not instantiate Net::HTTP::Post to make a request' do- expect(Net::HTTP::Post).not_to receive(:new)- subject+ it 'makes a post HTTP request to the given url and body' do+ subject+ expect(WebMock).to have_requested(:post, url).with(body: body, headers: headers).once+ endend- it { expect(subject).to eq(nil) }- end+ context 'with development environment' do+ before { allow(Rails).to receive_message_chain(:env, :development?).and_return(true) }- context 'with an unexpected body' do- let(:body) { '' }+ include_examples 'makes the request without setting use_ssl'+ end- include_examples 'returns nil without making a request'- end+ context 'with test environment' do+ include_examples 'makes the request without setting use_ssl'+ end++ context 'without test and/or development environment' do+ before do+ allow(Rails).to receive_message_chain(:env, :development?).and_return(false)+ allow(Rails).to receive_message_chain(:env, :test?).and_return(false)+ end- context 'with an expected body' do- context 'without a valid URL' do- let(:url) { '' }+ let(:url) { 'http://google.com/' }- it 'debug logs before the request' do- allow(Rails.logger).to receive(:warn)+ it 'sets use_ssl' do+ allow(Net::HTTP).to receive(:new).and_return(http)+ expect(http).to receive(:use_ssl=).with(true)subject- message = "[SPREE WEBHOOKS] 'order.cancel' can not make a request to ''"- expect(Rails.logger).to have_received(:warn).with(message)end- include_examples 'returns nil without making a request'+ it 'makes a post HTTP request to the given url and body' do+ allow(Net::HTTP).to receive(:new).and_return(http)+ allow(http).to receive(:use_ssl=).with(true)+ subject+ expect(WebMock).to have_requested(:post, url).with(body: body, headers: headers).once+ endend+ end- context 'with a valid URL' do- let(:headers) { { 'Content-Type' => 'application/json' } }-- before { stub_request(:post, url) }+ describe 'setting read_timeout with SPREE_WEBHOOKS_TIMEOUT' do+ context 'without SPREE_WEBHOOKS_TIMEOUT' do+ before { ENV['SPREE_WEBHOOKS_TIMEOUT'] = nil }- it 'debug logs before the request' do- allow(Rails.logger).to receive(:debug)+ it 'does not set Net::HTTP#read_timeout=' do+ expect(http).not_to receive(:read_timeout=)subject- message_fst = "[SPREE WEBHOOKS] 'order.cancel' sending to 'http://google.com/'"- message_snd = "[SPREE WEBHOOKS] 'order.cancel' body: #{body}"- expect(Rails.logger).to have_received(:debug).with(message_fst)- expect(Rails.logger).to have_received(:debug).with(message_snd)end+ end- describe 'ssl usage' do- shared_examples 'makes the request without setting use_ssl' do- it 'does not set use_ssl' do- allow(Net::HTTP).to receive(:new).with(uri.host, uri.port).and_return(http)- expect(http).not_to receive(:use_ssl=)- subject- end-- it 'makes a post HTTP request to the given url and body' do- subject- expect(WebMock).to have_requested(:post, url).with(body: body, headers: headers).once- end- end-- context 'with development environment' do- before { allow(Rails).to receive_message_chain(:env, :development?).and_return(true) }-- include_examples 'makes the request without setting use_ssl'- end-- context 'with test environment' do- include_examples 'makes the request without setting use_ssl'- end-- context 'without test and/or development environment' do- before do- allow(Rails).to receive_message_chain(:env, :development?).and_return(false)- allow(Rails).to receive_message_chain(:env, :test?).and_return(false)- end-- let(:url) { 'http://google.com/' }-- it 'sets use_ssl' do- allow(Net::HTTP).to receive(:new).and_return(http)- expect(http).to receive(:use_ssl=).with(true)- subject- end-- it 'makes a post HTTP request to the given url and body' do- allow(Net::HTTP).to receive(:new).and_return(http)- allow(http).to receive(:use_ssl=).with(true)- subject- expect(WebMock).to have_requested(:post, url).with(body: body, headers: headers).once- end- end+ context 'with SPREE_WEBHOOKS_TIMEOUT' do+ before do+ ENV['SPREE_WEBHOOKS_TIMEOUT'] = spree_webhooks_timeout.to_s+ allow(Net::HTTP).to receive(:new).with(uri.host, uri.port).and_return(http)end- describe 'setting the read_timeout through the SPREE_WEBHOOKS_TIMEOUT env var' do- context 'without a SPREE_WEBHOOKS_TIMEOUT env var' do- before { ENV['SPREE_WEBHOOKS_TIMEOUT'] = nil }+ after { ENV['SPREE_WEBHOOKS_TIMEOUT'] = nil }- it 'does not set Net::HTTP#read_timeout=' do- expect(http).not_to receive(:read_timeout=)- subject- end- end+ let(:spree_webhooks_timeout) { 15 } # time in seconds- context 'with a SPREE_WEBHOOKS_TIMEOUT env var' do- before do- ENV['SPREE_WEBHOOKS_TIMEOUT'] = spree_webhooks_timeout.to_s- allow(Net::HTTP).to receive(:new).with(uri.host, uri.port).and_return(http)- end+ it 'sets Net::HTTP#read_timeout= to the integer value of SPREE_WEBHOOKS_TIMEOUT' do+ expect(http).to receive(:read_timeout=).with(spree_webhooks_timeout)+ subject+ end+ end+ end- after { ENV['SPREE_WEBHOOKS_TIMEOUT'] = nil }+ context 'when the request raises a SocketError exception' do+ before do+ allow(Net::HTTP).to receive(:new).and_return(http_double)+ allow(http_double).to receive(:request) { raise SocketError }+ end- let(:spree_webhooks_timeout) { 15 } # time in seconds+ it { expect(subject).to eq(true) }+ end- it 'sets Net::HTTP#read_timeout= to the integer value of SPREE_WEBHOOKS_TIMEOUT' do- expect(http).to receive(:read_timeout=).with(spree_webhooks_timeout)- subject- end- end- end+ context 'when the request raises a Net::ReadTimeout exception' do+ before do+ allow(Net::HTTP).to receive(:new).and_return(http_double)+ allow(http_double).to receive(:request) { raise Net::ReadTimeout }+ end- describe 'handling the request response status code' do- let(:http_double) { instance_double(Net::HTTP) }-- context 'when the request status code is not 2xx' do- before do- allow(Net::HTTP).to receive(:new).and_return(http_double)- allow(http_double).to(- receive(:request).and_return(- double(:request).tap do |request|- allow(request).to receive(:code).and_return('304')- end- )- )- end-- it 'warn logs after the request' do- allow(Rails.logger).to receive(:warn)- subject- message = "[SPREE WEBHOOKS] 'order.cancel' failed for 'http://google.com/'"- expect(Rails.logger).to have_received(:warn).with(message)- end-- it { expect(subject).to eq(nil) }- end-- context 'when the request raises a SocketError exception' do- before do- allow(Net::HTTP).to receive(:new).and_return(http_double)- allow(http_double).to receive(:request) do- raise SocketError- end- end-- it { expect(subject).to eq(nil) }- end-- context 'when the request raises a Net::ReadTimeout exception' do- before do- allow(Net::HTTP).to receive(:new).and_return(http_double)- allow(http_double).to receive(:request) do- raise Net::ReadTimeout- end- end-- it { expect(subject).to eq(nil) }- end-- context 'when request status code is 2xx' do- it 'debug logs after the request and returns its value' do- message = "[SPREE WEBHOOKS] 'order.cancel' success for URL 'http://google.com/'"- expect(subject).to eq(Rails.logger.debug(message))- end- end- end+ it { expect(subject).to eq(true) }+ end++ context 'when the request status code is not 2xx' do+ before do+ allow(Net::HTTP).to receive(:new).and_return(http_double)+ allow(http_double).to receive(:request).and_return(request_double)+ allow(request_double).to receive(:code).and_return('304')end++ let(:request_double) { double }++ it { expect(subject).to eq(true) }+ end++ context 'when request status code is 2xx' do+ it { expect(subject).to eq(false) }+ end+ end++ describe '#unprocessable_uri?' do+ subject { described_class.new(body: body, url: url) }++ before { allow(subject).to receive(:URI).with(url).and_return(uri) }++ shared_examples 'detects an unprocessable uri' do+ it { expect(subject.unprocessable_uri?).to eq(true) }+ end++ let(:uri) { URI(url) }++ context 'uri with path ""' do+ before { uri.path = '' }++ include_examples 'detects an unprocessable uri'+ end++ context 'uri with path "" and without host' do+ before do+ uri.path = ''+ uri.host = nil+ end++ include_examples 'detects an unprocessable uri'+ end++ context 'uri with path "", without host and without port' do+ before do+ uri.path = ''+ uri.host = nil+ uri.port = nil+ end++ include_examples 'detects an unprocessable uri'endendend