|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'securerandom' |
| 4 | +require_relative '../internal/payload_input' |
| 5 | +require_relative '../primitives/callable' |
| 6 | +require_relative 'delivery' |
| 7 | +require_relative 'schema_catalog' |
| 8 | +require_relative 'webhook_signer' |
| 9 | + |
| 10 | +# Copyright Codevedas Inc. 2025-present |
| 11 | +# |
| 12 | +# This source code is licensed under the MIT license found in the |
| 13 | +# LICENSE file in the root directory of this source tree. |
| 14 | + |
| 15 | +module Karya |
| 16 | + module OutboundEvents |
| 17 | + # Builds canonical outbound deliveries from runtime instrumentation events. |
| 18 | + class Dispatcher |
| 19 | + def initialize(delivery_handler:, signer: nil, clock: -> { Time.now.utc }, event_id_generator: -> { SecureRandom.uuid }) |
| 20 | + @delivery_handler = Primitives::Callable.new(:delivery_handler, delivery_handler, error_class: InvalidOutboundEventError).normalize |
| 21 | + @signer = normalize_signer(signer) |
| 22 | + @clock = Primitives::Callable.new(:clock, clock, error_class: InvalidOutboundEventError).normalize |
| 23 | + @event_id_generator = Primitives::Callable.new( |
| 24 | + :event_id_generator, |
| 25 | + event_id_generator, |
| 26 | + error_class: InvalidOutboundEventError |
| 27 | + ).normalize |
| 28 | + end |
| 29 | + |
| 30 | + def call(event_name, payload = Internal::PayloadInput::ABSENT, **payload_keywords) |
| 31 | + return nil unless SchemaCatalog.supported?(event_name) |
| 32 | + |
| 33 | + occurred_at = clock.call |
| 34 | + raise InvalidOutboundEventError, 'clock must return a Time' unless occurred_at.is_a?(Time) |
| 35 | + |
| 36 | + payload_given = !payload.equal?(Internal::PayloadInput::ABSENT) |
| 37 | + |
| 38 | + event = SchemaCatalog.build_event( |
| 39 | + event_name:, |
| 40 | + payload: Internal::PayloadInput.new( |
| 41 | + payload_given ? payload : nil, |
| 42 | + payload_keywords, |
| 43 | + payload_given:, |
| 44 | + error_class: InvalidOutboundEventError, |
| 45 | + mixed_payload_message: 'payload must be a Hash when keyword payload is also given' |
| 46 | + ).to_h, |
| 47 | + occurred_at:, |
| 48 | + event_id: event_id_generator.call |
| 49 | + ) |
| 50 | + body = event.to_json.freeze |
| 51 | + signature = signer&.sign(body:, now: occurred_at) |
| 52 | + delivery = Delivery.new(event:, signature:, body:) |
| 53 | + delivery_handler.call(delivery) |
| 54 | + delivery |
| 55 | + end |
| 56 | + |
| 57 | + private |
| 58 | + |
| 59 | + attr_reader :clock, :delivery_handler, :event_id_generator, :signer |
| 60 | + |
| 61 | + def normalize_signer(value) |
| 62 | + return nil if [nil].include?(value) |
| 63 | + return value if value.is_a?(WebhookSigner) |
| 64 | + |
| 65 | + raise InvalidOutboundEventError, 'signer must be Karya::OutboundEvents::WebhookSigner' |
| 66 | + end |
| 67 | + end |
| 68 | + end |
| 69 | +end |
0 commit comments