Implement action mailer delivery metrics observer

This commit is contained in:
Grzegorz Bizon 2018-07-16 13:40:55 +02:00
parent 51b81d7feb
commit dce9599ef5
3 changed files with 73 additions and 2 deletions

View file

@ -3,5 +3,10 @@ unless Gitlab.config.gitlab.email_enabled
ActionMailer::Base.logger = nil
end
ActionMailer::Base.register_interceptor(::Gitlab::Email::Hook::AdditionalHeadersInterceptor)
ActionMailer::Base.register_interceptor(::Gitlab::Email::Hook::EmailTemplateInterceptor)
ActionMailer::Base.register_interceptors(
::Gitlab::Email::Hook::AdditionalHeadersInterceptor,
::Gitlab::Email::Hook::EmailTemplateInterceptor,
::Gitlab::Email::Hook::DeliveryMetricsObserver
)
ActionMailer::Base.register_observer(::Gitlab::Email::Hook::DeliveryMetricsObserver)

View file

@ -0,0 +1,31 @@
module Gitlab
module Email
module Hook
class DeliveryMetricsObserver
extend Gitlab::Utils::StrongMemoize
def self.delivering_email(_message)
delivery_attempts_counter.increment
end
def self.delivered_email(_message)
delivered_emails_counter.increment
end
def self.delivery_attempts_counter
strong_memoize(:delivery_attempts_counter) do
Gitlab::Metrics.counter(:gitlab_emails_delivery_attempts_total,
'Counter of total emails delivery attempts')
end
end
def self.delivered_emails_counter
strong_memoize(:delivered_emails_counter) do
Gitlab::Metrics.counter(:gitlab_emails_delivered_total,
'Counter of total emails delievered')
end
end
end
end
end
end

View file

@ -0,0 +1,35 @@
require 'spec_helper'
describe Gitlab::Email::Hook::DeliveryMetricsObserver do
let(:email) do
ActionMailer::Base.mail(to: 'test@example.com',
from: 'info@example.com',
body: 'hello')
end
context 'when email has been delivered' do
it 'increments both email delivery metrics' do
expect(described_class.delivery_attempts_counter).to receive(:increment)
expect(described_class.delivered_emails_counter).to receive(:increment)
email.deliver_now
end
end
context 'when email has not been delivered due to an error' do
before do
allow(email.delivery_method).to receive(:deliver!)
.and_raise(StandardError, 'Some SMTP error')
end
it 'increments only delivery attempt metric' do
expect(described_class.delivery_attempts_counter)
.to receive(:increment)
expect(described_class.delivered_emails_counter)
.not_to receive(:increment)
expect { email.deliver_now }
.to raise_error(StandardError, 'Some SMTP error')
end
end
end