Class: NurseAndrea::MetricsShipper

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/nurse_andrea/metrics_shipper.rb

Constant Summary collapse

BATCH_SIZE =
200
FLUSH_INTERVAL =
15

Instance Method Summary collapse

Constructor Details

#initializeMetricsShipper

Returns a new instance of MetricsShipper.



11
12
13
14
15
# File 'lib/nurse_andrea/metrics_shipper.rb', line 11

def initialize
  @queue  = []
  @mutex  = Mutex.new
  @thread = nil
end

Instance Method Details

#enqueue(metric) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/nurse_andrea/metrics_shipper.rb', line 33

def enqueue(metric)
  flush_now = @mutex.synchronize do
    @queue << metric
    @queue.size >= BATCH_SIZE
  end
  flush! if flush_now
end

#flush!Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/nurse_andrea/metrics_shipper.rb', line 41

def flush!
  metrics = @mutex.synchronize do
    return if @queue.empty?
    batch = @queue.dup
    @queue.clear
    batch
  end
  return if metrics.nil? || metrics.empty?

  ship(metrics)
end

#running?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/nurse_andrea/metrics_shipper.rb', line 29

def running?
  @thread&.alive? || false
end

#start!Object



17
18
19
20
21
22
# File 'lib/nurse_andrea/metrics_shipper.rb', line 17

def start!
  return if @thread&.alive?
  @thread = Thread.new { flush_loop }
  @thread.abort_on_exception = false
  @thread.name = "NurseAndrea::MetricsShipper"
end

#stop!Object



24
25
26
27
# File 'lib/nurse_andrea/metrics_shipper.rb', line 24

def stop!
  @thread&.kill
  flush!
end