Class: Msgr::Dispatcher

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/msgr/dispatcher.rb

Overview

The Dispatcher receives incoming messages, process them through a middleware stack and delegate them to a new and fresh consumer instance.

Defined Under Namespace

Classes: NullPool

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#log, #log_name

Constructor Details

#initialize(config) ⇒ Dispatcher

Returns a new instance of Dispatcher.



12
13
14
15
16
17
# File 'lib/msgr/dispatcher.rb', line 12

def initialize(config)
  config[:pool_class] ||= 'Msgr::Dispatcher::NullPool'
  log(:info) { "Initialize new dispatcher (#{config[:pool_class]}: #{config})..." }

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

Instance Attribute Details

#poolObject (readonly)

Returns the value of attribute pool.



10
11
12
# File 'lib/msgr/dispatcher.rb', line 10

def pool
  @pool
end

Instance Method Details

#call(message) ⇒ Object



19
20
21
22
23
# File 'lib/msgr/dispatcher.rb', line 19

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

#dispatch(message) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/msgr/dispatcher.rb', line 25

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
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

#shutdownObject



48
49
# File 'lib/msgr/dispatcher.rb', line 48

def shutdown
end

#to_sObject



51
52
53
# File 'lib/msgr/dispatcher.rb', line 51

def to_s
  self.class.name
end