Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: #251 send webhook notification if event creation failed #252

Merged
merged 4 commits into from
Jun 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/jobs/send_webhook_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ def perform(webhook_type, object)
Webhooks::InvoicesService.new(object).call
when :add_on
Webhooks::AddOnService.new(object).call
when :event
Webhooks::EventService.new(object).call
else
raise NotImplementedError
end
Expand Down
12 changes: 12 additions & 0 deletions app/serializers/error_serializer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

class ErrorSerializer < ModelSerializer
def serialize
{
status: 422,
error: 'Unprocessable entity',
message: model.error,
input_params: model.input_params
}
end
end
36 changes: 35 additions & 1 deletion app/services/events_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,19 @@ def create(organization:, params:, timestamp:, metadata:)
end

unless current_customer(organization.id, params[:customer_id])
return result.fail!('missing_argument', 'customer does not exists')
result.fail!('missing_argument', 'customer does not exist')

send_webhook_notice(organization, params)

return result
end

unless valid_code?(params[:code], organization)
result.fail!('missing_argument', 'code does not exist')

send_webhook_notice(organization, params)

return result
end

event = organization.events.new
Expand All @@ -38,6 +50,10 @@ def create(organization:, params:, timestamp:, metadata:)
result
rescue ActiveRecord::RecordInvalid => e
result.fail_with_validations!(e.record)

send_webhook_notice(organization, params)

result
end

private
Expand All @@ -48,4 +64,22 @@ def current_customer(organization_id = nil, customer_id = nil)
organization_id: organization_id,
)
end

def valid_code?(code, organization)
valid_codes = organization.billable_metrics.pluck(:code)

valid_codes.include? code
end

def send_webhook_notice(organization, params)
return unless organization.webhook_url?

object = {
input_params: params,
error: result.error,
organization_id: organization.id
}

SendWebhookJob.perform_later(:event, object)
end
end
26 changes: 26 additions & 0 deletions app/services/webhooks/event_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# frozen_string_literal: true

module Webhooks
class EventService < Webhooks::BaseService
private

def current_organization
@current_organization ||= Organization.find(object[:organization_id])
end

def object_serializer
::ErrorSerializer.new(
OpenStruct.new(object),
root_name: 'event_error',
)
end

def webhook_type
'event.error'
end

def object_type
'event_error'
end
end
end
29 changes: 29 additions & 0 deletions spec/jobs/send_webhook_job_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
RSpec.describe SendWebhookJob, type: :job do
let(:webhook_invoice_service) { instance_double(Webhooks::InvoicesService) }
let(:webhook_add_on_service) { instance_double(Webhooks::AddOnService) }
let(:webhook_event_service) { instance_double(Webhooks::EventService) }
let(:organization) { create(:organization, webhook_url: 'http://foo.bar') }
let(:invoice) { create(:invoice) }

Expand Down Expand Up @@ -40,6 +41,34 @@
end
end

context 'when webhook_type is event' do
let(:object) do
{
input_params: {
customer_id: 'customer',
transaction_id: SecureRandom.uuid,
code: 'code'
},
error: 'Code does not exist',
organization_id: organization.id
}
end

before do
allow(Webhooks::EventService).to receive(:new)
.with(object)
.and_return(webhook_event_service)
allow(webhook_event_service).to receive(:call)
end

it 'calls the webhook event service' do
described_class.perform_now(:event, object)

expect(Webhooks::EventService).to have_received(:new)
expect(webhook_event_service).to have_received(:call)
end
end

context 'with not implemented webhook type' do
it 'raises a NotImplementedError' do
expect { described_class.perform_now(:subscription, invoice) }
Expand Down
40 changes: 40 additions & 0 deletions spec/serializers/error_serializer_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe ErrorSerializer do
let(:transaction_id) { SecureRandom.uuid }
let(:object) do
{
input_params: {
customer_id: 'customer',
transaction_id: transaction_id,
code: 'code'
},
error: 'Code does not exist',
organization_id: 'testtest'
}
end
let(:json_response_hash) do
{
'event_error' => {
'status' => 422,
'error' => 'Unprocessable entity',
'message' => 'Code does not exist',
'input_params' => {
'customer_id' => 'customer',
'transaction_id' => transaction_id,
'code' => 'code'
}
}
}
end
let(:serializer) do
described_class.new(OpenStruct.new(object), root_name: 'event_error')
end
let(:result) { JSON.parse(serializer.to_json) }

it 'serializes object' do
expect(result).to eq json_response_hash
end
end
57 changes: 52 additions & 5 deletions spec/services/events_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
subject(:event_service) { described_class.new }

let(:organization) { create(:organization) }
let(:billable_metric) { create(:billable_metric, organization: organization) }
let(:customer) { create(:customer, organization: organization) }

describe '.validate_params' do
Expand Down Expand Up @@ -49,7 +50,7 @@
let(:create_args) do
{
customer_id: customer.customer_id,
code: 'event_code',
code: billable_metric.code,
transaction_id: SecureRandom.uuid,
properties: { foo: 'bar' },
timestamp: Time.zone.now.to_i,
Expand All @@ -72,7 +73,7 @@
aggregate_failures do
expect(event.customer_id).to eq(customer.id)
expect(event.organization_id).to eq(organization.id)
expect(event.code).to eq('event_code')
expect(event.code).to eq(billable_metric.code)
expect(event.timestamp).to be_a(Time)
end
end
Expand Down Expand Up @@ -100,6 +101,41 @@
let(:create_args) do
{
customer_id: SecureRandom.uuid,
code: billable_metric.code,
transaction_id: SecureRandom.uuid,
properties: { foo: 'bar' },
timestamp: Time.zone.now.to_i,
}
end

it 'fails' do
result = event_service.create(
organization: organization,
params: create_args,
timestamp: timestamp,
metadata: {},
)

expect(result).not_to be_success
expect(result.error).to eq('customer does not exist')
end

it 'enqueues a SendWebhookJob' do
expect do
event_service.create(
organization: organization,
params: create_args,
timestamp: timestamp,
metadata: {},
)
end.to have_enqueued_job(SendWebhookJob)
end
end

context 'when code does not exist' do
let(:create_args) do
{
customer_id: customer.customer_id,
code: 'event_code',
transaction_id: SecureRandom.uuid,
properties: { foo: 'bar' },
Expand All @@ -116,15 +152,26 @@
)

expect(result).not_to be_success
expect(result.error).to eq('customer does not exists')
expect(result.error).to eq('code does not exist')
end

it 'enqueues a SendWebhookJob' do
expect do
event_service.create(
organization: organization,
params: create_args,
timestamp: timestamp,
metadata: {},
)
end.to have_enqueued_job(SendWebhookJob)
end
end

context 'when properties are empty' do
let(:create_args) do
{
customer_id: customer.customer_id,
code: 'event_code',
code: billable_metric.code,
transaction_id: SecureRandom.uuid,
timestamp: Time.zone.now.to_i,
}
Expand All @@ -145,7 +192,7 @@
aggregate_failures do
expect(event.customer_id).to eq(customer.id)
expect(event.organization_id).to eq(organization.id)
expect(event.code).to eq('event_code')
expect(event.code).to eq(billable_metric.code)
expect(event.timestamp).to be_a(Time)
expect(event.properties).to eq({})
end
Expand Down
94 changes: 94 additions & 0 deletions spec/services/webhooks/event_service_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe Webhooks::EventService do
subject(:webhook_event_service) { described_class.new(object) }

let(:organization) { create(:organization, webhook_url: webhook_url) }
let(:webhook_url) { 'http://foo.bar' }
let(:object) do
{
input_params: {
customer_id: 'customer',
transaction_id: SecureRandom.uuid,
code: 'code'
},
error: 'Code does not exist',
organization_id: organization.id
}
end

describe '.call' do
let(:lago_client) { instance_double(LagoHttpClient::Client) }

before do
allow(LagoHttpClient::Client).to receive(:new)
.with(organization.webhook_url)
.and_return(lago_client)
allow(lago_client).to receive(:post)
end

it 'calls the organization webhook url' do
webhook_event_service.call

expect(LagoHttpClient::Client).to have_received(:new)
.with(organization.webhook_url)
expect(lago_client).to have_received(:post)
end

it 'builds payload with event.error webhook type' do
webhook_event_service.call

expect(LagoHttpClient::Client).to have_received(:new)
.with(organization.webhook_url)
expect(lago_client).to have_received(:post) do |payload|
expect(payload[:webhook_type]).to eq('event.error')
expect(payload[:object_type]).to eq('event_error')
end
end

context 'without webhook_url' do
let(:webhook_url) { nil }

it 'does not call the organization webhook url' do
webhook_event_service.call

expect(LagoHttpClient::Client).not_to have_received(:new)
expect(lago_client).not_to have_received(:post)
end
end
end

describe '.generate_headers' do
let(:payload) do
::ErrorSerializer.new(
OpenStruct.new(object),
root_name: 'error_event',
).serialize.merge(webhook_type: 'event.error')
end

it 'generates the query headers' do
headers = webhook_event_service.__send__(:generate_headers, payload)

expect(headers).to include(have_key('X-Lago-Signature'))
end

it 'generates a correct signature' do
signature = webhook_event_service.__send__(:generate_signature, payload)

decoded_signature = JWT.decode(
signature,
RsaPublicKey,
true,
{
algorithm: 'RS256',
iss: ENV['LAGO_API_URL'],
verify_iss: true,
},
).first

expect(decoded_signature['data']).to eq(payload.to_json)
end
end
end