debian-mirror-gitlab/app/services/incident_management/pager_duty/process_webhook_service.rb

78 lines
2.1 KiB
Ruby
Raw Normal View History

2020-07-28 23:09:34 +05:30
# frozen_string_literal: true
module IncidentManagement
module PagerDuty
2021-03-08 18:12:59 +05:30
class ProcessWebhookService
2020-07-28 23:09:34 +05:30
include Gitlab::Utils::StrongMemoize
include IncidentManagement::Settings
# https://developer.pagerduty.com/docs/webhooks/webhook-behavior/#size-limit
PAGER_DUTY_PAYLOAD_SIZE_LIMIT = 55.kilobytes
# https://developer.pagerduty.com/docs/webhooks/v2-overview/#webhook-types
PAGER_DUTY_PROCESSABLE_EVENT_TYPES = %w(incident.trigger).freeze
2021-03-08 18:12:59 +05:30
def initialize(project, payload)
@project = project
@payload = payload
end
2020-07-28 23:09:34 +05:30
def execute(token)
return forbidden unless webhook_setting_active?
return unauthorized unless valid_token?(token)
return bad_request unless valid_payload_size?
process_incidents
accepted
end
private
2021-03-08 18:12:59 +05:30
attr_reader :project, :payload
2020-07-28 23:09:34 +05:30
def process_incidents
pager_duty_processable_events.each do |event|
::IncidentManagement::PagerDuty::ProcessIncidentWorker.perform_async(project.id, event['incident'])
end
end
def pager_duty_processable_events
strong_memoize(:pager_duty_processable_events) do
::PagerDuty::WebhookPayloadParser
2021-03-08 18:12:59 +05:30
.call(payload.to_h)
2021-01-03 14:25:43 +05:30
.filter { |msg| msg['event'].to_s.in?(PAGER_DUTY_PROCESSABLE_EVENT_TYPES) }
2020-07-28 23:09:34 +05:30
end
end
def webhook_setting_active?
2020-10-24 23:57:45 +05:30
incident_management_setting.pagerduty_active?
2020-07-28 23:09:34 +05:30
end
def valid_token?(token)
token && incident_management_setting.pagerduty_token == token
end
def valid_payload_size?
2021-03-08 18:12:59 +05:30
Gitlab::Utils::DeepSize.new(payload, max_size: PAGER_DUTY_PAYLOAD_SIZE_LIMIT).valid?
2020-07-28 23:09:34 +05:30
end
def accepted
ServiceResponse.success(http_status: :accepted)
end
def forbidden
ServiceResponse.error(message: 'Forbidden', http_status: :forbidden)
end
def unauthorized
ServiceResponse.error(message: 'Unauthorized', http_status: :unauthorized)
end
def bad_request
ServiceResponse.error(message: 'Bad Request', http_status: :bad_request)
end
end
end
end