Class: EventQ::RabbitMq::QueueWorkerV2

Inherits:
Object
  • Object
show all
Includes:
WorkerId
Defined in:
lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeQueueWorkerV2

Returns a new instance of QueueWorkerV2.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 8

def initialize
  @threads = []
  @forks = []
  @is_running = false

  @retry_exceeded_block = nil
  @on_retry_block = nil
  @on_error_block = nil
  @hash_helper = HashKit::Helper.new
  @serialization_provider_manager = EventQ::SerializationProviders::Manager.new
  @signature_provider_manager = EventQ::SignatureProviders::Manager.new
  @last_gc_flush = Time.now
  @gc_flush_interval = 10
end

Instance Attribute Details

#is_runningObject

Returns the value of attribute is_running.



6
7
8
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 6

def is_running
  @is_running
end

Instance Method Details

#call_on_error_block(error:, message: nil) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 110

def call_on_error_block(error:, message: nil)
  if @on_error_block
    EventQ.logger.debug { "[#{self.class}] - Executing on_error block." }
    begin
      @on_error_block.call(error, message)
    rescue => e
      EventQ.logger.error("[#{self.class}] - An error occurred executing the on_error block. Error: #{e}")
    end
  else
    EventQ.logger.debug { "[#{self.class}] - No on_error block specified to execute." }
  end
end

#call_on_retry_block(message) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 179

def call_on_retry_block(message)
  if @on_retry_block
    EventQ.logger.debug { "[#{self.class}] - Executing on_retry block." }
    begin
      @on_retry_block.call(message, abort)
    rescue => e
      EventQ.logger.error("[#{self.class}] - An error occurred executing the on_retry block. Error: #{e}")
    end
  else
    EventQ.logger.debug { "[#{self.class}] - No on_retry block specified." }
  end
end

#call_on_retry_exceeded_block(message) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 166

def call_on_retry_exceeded_block(message)
  if @retry_exceeded_block != nil
    EventQ.logger.debug { "[#{self.class}] - Executing on_retry_exceeded block." }
    begin
      @retry_exceeded_block.call(message)
    rescue => e
      EventQ.logger.error("[#{self.class}] - An error occurred executing the on_retry_exceeded block. Error: #{e}")
    end
  else
    EventQ.logger.debug { "[#{self.class}] - No on_retry_exceeded block specified." }
  end
end

#configure(queue, options = {}) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 234

def configure(queue, options = {})
  @queue = queue

  # default thread count
  @thread_count = 1
  if options.key?(:thread_count)
    @thread_count = options[:thread_count]
  end

  @fork_count = 1
  if options.key?(:fork_count)
    @fork_count = options[:fork_count]
  end

  EventQ.logger.info(
    "[#{self.class}] - Configuring. Process Count: #{@fork_count} | Thread Count: #{@thread_count} | "\
"Interval Sleep: #{@sleep}."
  )

  return true
end

#deserialize_message(payload) ⇒ Object



156
157
158
159
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 156

def deserialize_message(payload)
  provider = @serialization_provider_manager.get_provider(EventQ::Configuration.serialization_provider)
  return provider.deserialize(payload)
end

#on_error(&block) ⇒ Object



147
148
149
150
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 147

def on_error(&block)
  @on_error_block = block
  return nil
end

#on_retry(&block) ⇒ Object



142
143
144
145
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 142

def on_retry(&block)
  @on_retry_block = block
  return nil
end

#on_retry_exceeded(&block) ⇒ Object



137
138
139
140
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 137

def on_retry_exceeded(&block)
  @retry_exceeded_block = block
  return nil
end

#reject_message(channel, message, delivery_tag, retry_exchange, queue, abort) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 192

def reject_message(channel, message, delivery_tag, retry_exchange, queue, abort)
  EventQ.logger.info("[#{self.class}] - Message rejected removing from queue.")
  # reject the message to remove from queue
  channel.reject(delivery_tag, false)

  # check if the message retry limit has been exceeded
  if message.retry_attempts >= queue.max_retry_attempts

    EventQ.logger.info("[#{self.class}] - Message retry attempt limit exceeded. Msg: #{serialize_message(message)}")

    call_on_retry_exceeded_block(message)

  # check if the message is allowed to be retried
  elsif queue.allow_retry
    EventQ.logger.debug { "[#{self.class}] - Incrementing retry attempts count." }
    message.retry_attempts += 1

    if queue.allow_retry_back_off == true
      EventQ.logger.debug do
        "[#{self.class}] - Calculating message back off retry delay. "\
"Attempts: #{message.retry_attempts} * Retry Delay: #{queue.retry_delay}"
      end
      message_ttl = message.retry_attempts * queue.retry_delay
      if (message.retry_attempts * queue.retry_delay) > queue.max_retry_delay
        EventQ.logger.debug { "[#{self.class}] - Max message back off retry delay reached." }
        message_ttl = queue.max_retry_delay
      end
    else
      EventQ.logger.debug { "[#{self.class}] - Setting fixed retry delay for message." }
      message_ttl = queue.retry_delay
    end

    EventQ.logger.debug { "[#{self.class}] - Sending message for retry. Message TTL: #{message_ttl}" }
    retry_exchange.publish(serialize_message(message), :expiration => message_ttl)
    EventQ.logger.debug { "[#{self.class}] - Published message to retry exchange." }

    call_on_retry_block(message)
  end

  return true
end

#running?Boolean

Returns:

  • (Boolean)


152
153
154
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 152

def running?
  return @is_running
end

#serialize_message(msg) ⇒ Object



161
162
163
164
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 161

def serialize_message(msg)
  provider = @serialization_provider_manager.get_provider(EventQ::Configuration.serialization_provider)
  return provider.serialize(msg)
end

#start(queue, options = {}, &block) ⇒ Object



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
51
52
53
54
55
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 23

def start(queue, options = {}, &block)

  EventQ.logger.info("[#{self.class}] - Preparing to start listening for messages.")

  configure(queue, options)

  raise "[#{self.class}] - Worker is already running." if running?

  if options[:client] == nil
    raise "[#{self.class}] - :client (QueueClient) must be specified."
  end

  EventQ.logger.info("[#{self.class}] - Listening for messages.")
  EventQ.logger.debug do
    "[#{self.class} #start] - Listening for messages on queue: #{EventQ.create_queue_name(queue.name)}"
  end

  @forks = []

  if @fork_count > 1
    Thread.new do
      @fork_count.times do
        pid = fork do
          start_process(options, queue, block)
        end
        @forks.push(pid)
      end
      @forks.each { |pid| Process.wait(pid) }
    end
  else
    start_process(options, queue, block)
  end
end

#start_process(options, queue, block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 57

def start_process(options, queue, block)
  @is_running = true

  %w'INT TERM'.each do |sig|
    Signal.trap(sig) {
      stop
      exit
    }
  end

  if !options.key?(:durable)
    options[:durable] = true
  end

  client = options[:client]
  manager = EventQ::RabbitMq::QueueManager.new
  manager.durable = options[:durable]
  @connection = client.get_connection

  @threads = []

  # loop through each thread count
  @thread_count.times do
    channel = @connection.create_channel

    q = manager.get_queue(channel, queue)
    retry_exchange = manager.get_retry_exchange(channel, queue)

    q.subscribe(:manual_ack => true, :consumer_tag => SecureRandom.uuid) do |delivery_info, properties, payload|
      begin
        tag_processing_thread
        process_message(payload, queue, channel, retry_exchange, delivery_info.delivery_tag, block)
      rescue => e
        EventQ.logger.error(
          "[#{self.class}] - An error occurred attempting to process a message. Error: #{e} | "\
"Backtrace: #{e.backtrace}"
        )
        call_on_error_block(error: e)
      ensure
        untag_processing_thread
      end
    end
  end

  if (options.key?(:wait) && options[:wait] == true) || (options.key?(:fork_count) && options[:fork_count] > 1)
    while running? do
      sleep 5
    end
  end

  return true
end

#stopObject



123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker_v2.rb', line 123

def stop
  EventQ.logger.info { "[#{self.class}] - Stopping..." }
  @is_running = false

  if @connection != nil
    begin
      @connection.close if @connection.open?
    rescue Timeout::Error
      EventQ.logger.error { 'Timeout occurred closing connection.' }
    end
  end
  return true
end