Class: Kafka::AsyncProducer::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/kafka/async_producer.rb

Instance Method Summary collapse

Constructor Details

#initialize(queue:, producer:, delivery_threshold:, max_retries: -1,, retry_backoff: 0, instrumenter:, logger:) ⇒ Worker

Returns a new instance of Worker.



189
190
191
192
193
194
195
196
197
# File 'lib/kafka/async_producer.rb', line 189

def initialize(queue:, producer:, delivery_threshold:, max_retries: -1, retry_backoff: 0, instrumenter:, logger:)
  @queue = queue
  @producer = producer
  @delivery_threshold = delivery_threshold
  @max_retries = max_retries
  @retry_backoff = retry_backoff
  @instrumenter = instrumenter
  @logger = TaggedLogger.new(logger)
end

Instance Method Details

#runObject



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
233
234
235
236
237
238
239
240
241
242
# File 'lib/kafka/async_producer.rb', line 199

def run
  @logger.push_tags(@producer.to_s)
  @logger.info "Starting async producer in the background..."

  loop do
    operation, payload = @queue.pop

    case operation
    when :produce
      produce(*payload)
      deliver_messages if threshold_reached?
    when :deliver_messages
      deliver_messages
    when :shutdown
      begin
        # Deliver any pending messages first.
        @producer.deliver_messages
      rescue Error => e
        @logger.error("Failed to deliver messages during shutdown: #{e.message}")

        @instrumenter.instrument("drop_messages.async_producer", {
          message_count: @producer.buffer_size + @queue.size,
        })
      end

      # Stop the run loop.
      break
    else
      raise "Unknown operation #{operation.inspect}"
    end
  end
rescue Kafka::Error => e
  @logger.error "Unexpected Kafka error #{e.class}: #{e.message}\n#{e.backtrace.join("\n")}"
  @logger.info "Restarting in 10 seconds..."

  sleep 10
  retry
rescue Exception => e
  @logger.error "Unexpected Kafka error #{e.class}: #{e.message}\n#{e.backtrace.join("\n")}"
  @logger.error "Async producer crashed!"
ensure
  @producer.shutdown
  @logger.pop_tags
end