Class: WebHookEmitter

Inherits:
Object
  • Object
show all
Defined in:
app/services/web_hook_emitter.rb

Constant Summary collapse

REQUEST_TIMEOUT =
20

Instance Method Summary collapse

Constructor Details

#initialize(webhook, webhook_event) ⇒ WebHookEmitter

Returns a new instance of WebHookEmitter.



6
7
8
9
# File 'app/services/web_hook_emitter.rb', line 6

def initialize(webhook, webhook_event)
  @webhook = webhook
  @webhook_event = webhook_event
end

Instance Method Details

#emit!(headers:, body:) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/services/web_hook_emitter.rb', line 11

def emit!(headers:, body:)
  uri = URI(@webhook.payload_url.strip)

  connection_opts = {
    request: {
      write_timeout: REQUEST_TIMEOUT,
      read_timeout: REQUEST_TIMEOUT,
      open_timeout: REQUEST_TIMEOUT,
    },
  }

  connection_opts[:ssl] = { verify: false } if !@webhook.verify_certificate

  conn = Faraday.new(nil, connection_opts) { |f| f.adapter FinalDestination::FaradayAdapter }

  start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
  error = nil
  response = nil
  begin
    response = conn.post(uri.to_s, body, headers)
  rescue => e
    error = e
  end
  duration = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) - start
  event_update_args = { headers: MultiJson.dump(headers), duration: duration }
  if response
    event_update_args[:response_headers] = MultiJson.dump(response.headers)
    event_update_args[:response_body] = response.body
    event_update_args[:status] = response.status
  else
    event_update_args[:status] = -1
    if error.is_a?(Faraday::Error) &&
         error.wrapped_exception.is_a?(FinalDestination::SSRFDetector::DisallowedIpError)
      error = I18n.t("webhooks.payload_url.blocked_or_internal")
    end
    event_update_args[:response_headers] = MultiJson.dump(error: error)
  end
  @webhook_event.update!(**event_update_args)
  response
end