Sha256: f70b3f5798c47ac43cb930574ce028ae258ca2aff43fdbe380a67e84b45ef6ec

Contents?: true

Size: 1.74 KB

Versions: 12

Compression:

Stored size: 1.74 KB

Contents

# frozen_string_literal: true

module Msgr
  # The Dispatcher receives incoming messages,
  # process them through a middleware stack and
  # delegate them to a new and fresh consumer instance.
  #
  class Dispatcher
    include Logging

    attr_reader :config, :pool

    def initialize(config)
      config[:pool_class] ||= 'Msgr::Dispatcher::NullPool'

      log(:debug) do
        "Initialize new dispatcher (#{config[:pool_class]}: #{config})..."
      end

      @config = config
      @pool = config[:pool_class].constantize.new config
    end

    def call(message)
      pool.post(message) do |msg|
        dispatch msg
      end
    end

    # rubocop:disable Metrics/AbcSize
    # rubocop:disable Metrics/MethodLength
    # rubocop:disable Metrics/CyclomaticComplexity
    def dispatch(message)
      consumer_class = Object.const_get message.route.consumer

      log(:debug) { "Dispatch message to #{consumer_class.name}" }

      consumer_class.new.dispatch message

      # Acknowledge message unless it is already acknowledged.
      message.ack unless message.acked?
    rescue => error
      message.nack unless message.acked?

      log(:error) do
        "Dispatcher error: #{error.class.name}: #{error}\n" +
          error.backtrace.join("\n")
      end

      raise error if config[:raise_exceptions]
    ensure
      if defined?(ActiveRecord) &&
         ActiveRecord::Base.connection_pool.active_connection?
        log(:debug) { 'Release used AR connection for dispatcher thread.' }
        ActiveRecord::Base.connection_pool.release_connection
      end
    end

    def shutdown; end

    def to_s
      self.class.name
    end

    class NullPool
      def initialize(*); end

      def post(*args)
        yield(*args)
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
msgr-0.15.2.1.b175 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b169 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b167 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b166 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b165 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b164 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b163 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b162 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b161 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b160 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b159 lib/msgr/dispatcher.rb
msgr-0.15.2.1.b158 lib/msgr/dispatcher.rb