Module: Coolhand::WebhookInterceptor

Defined in:
lib/coolhand/webhook_interceptor.rb

Instance Method Summary collapse

Instance Method Details

#intercept_batch_requestObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/coolhand/webhook_interceptor.rb', line 8

def intercept_batch_request
  Rails.logger.info("[Interceptor] #{controller_name}##{action_name}")

  @validator = Coolhand::OpenAi::WebhookValidator.new(request, webhook_secret)

  unless @validator.valid?
    Rails.logger.info("[Interceptor] Webhook validated failed: #{@validator.error_message}")
    head :unauthorized
    return false
  end

  payload = JSON.parse(@validator.payload)
  raise TypeError, "webhook payload must be a JSON object, got #{payload.class}" unless payload.is_a?(Hash)

  process_event(payload)
rescue StandardError => e
  # Fail closed: any error here (malformed payload, a bug in
  # process_event/BatchResultProcessor, etc.) must still halt the
  # before_action chain. Falling through without calling `head` would
  # let the controller action run for a request whose webhook
  # signature was never confirmed valid.
  Rails.logger.error("[Interceptor] Failed to intercept batch request: #{e.message}")
  head :unauthorized
  false
end

#process_event(payload) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/coolhand/webhook_interceptor.rb', line 38

def process_event(payload)
  event_type = payload["type"]
  event_data = payload["data"]

  case event_type
  when "batch.completed", "batch.failed", "batch.expired", "batch.cancelled"
    Coolhand::OpenAi::BatchResultProcessor.new(event_data: event_data).call
  else
    Rails.logger.info("[Interceptor] Unhandled OpenAI webhook event type: #{event_type}")
  end
end

#webhook_secretObject

Raises:

  • (NotImplementedError)


34
35
36
# File 'lib/coolhand/webhook_interceptor.rb', line 34

def webhook_secret
  raise NotImplementedError, "#{self.class} must implement #webhook_secret"
end