Class: Boatload::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/boatload/worker.rb

Overview

A worker that will run in the background, batching up and processing messages.

Instance Method Summary collapse

Constructor Details

#initialize(queue:, max_backlog_size: 0, logger:, context: nil, &block) ⇒ Worker

Returns a new instance of Worker.



6
7
8
9
10
11
12
13
# File 'lib/boatload/worker.rb', line 6

def initialize(queue:, max_backlog_size: 0, logger:, context: nil, &block)
  @backlog = []
  @context = context
  @incoming_queue = queue
  @logger = logger
  @max_backlog_size = max_backlog_size
  @process_proc = block
end

Instance Method Details

#runObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/boatload/worker.rb', line 15

def run
  @logger.info 'Starting Worker in the background...'

  loop do
    operation, payload = @incoming_queue.pop

    case operation
    when :item
      @backlog.push payload
      process if threshold_reached?
    when :process
      process
    when :shutdown
      begin
        process
      rescue StandardError => e
        @logger.error "Failed to process backlog during shutdown: #{e.full_message}"
      end

      break
    else
      raise "Unknown operation: #{operation.inspect}"
    end
  end
rescue StandardError => e
  @logger.error "Worker thread encountered an unexpected error:\n#{e.full_message}"
end