Class: Onlylogs::BatchSender

Inherits:
Object
  • Object
show all
Defined in:
app/models/onlylogs/batch_sender.rb

Instance Method Summary collapse

Constructor Details

#initialize(channel, interval: 0.05) ⇒ BatchSender



5
6
7
8
9
10
11
12
# File 'app/models/onlylogs/batch_sender.rb', line 5

def initialize(channel, interval: 0.05)
  @channel = channel
  @interval = interval
  @buffer = []
  @mutex = Mutex.new
  @running = false
  @sender_thread = nil
end

Instance Method Details

#add_line(line_data) ⇒ Object



48
49
50
51
52
# File 'app/models/onlylogs/batch_sender.rb', line 48

def add_line(line_data)
  @mutex.synchronize do
    @buffer << line_data
  end
end

#startObject



14
15
16
17
18
19
20
21
22
23
24
# File 'app/models/onlylogs/batch_sender.rb', line 14

def start
  return if @running

  @running = true
  @sender_thread = Thread.new do
    while @running
      send_batch
      sleep(@interval)
    end
  end
end

#stop(send_remaining_lines: true) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/models/onlylogs/batch_sender.rb', line 26

def stop(send_remaining_lines: true)
  return unless @running

  @running = false

  # Wait longer for graceful shutdown
  if @sender_thread&.alive?
    @sender_thread.join(0.5)
  end

  # Send any remaining lines
  send_batch
  if send_remaining_lines
    send_batch
  else
    @mutex.synchronize { @buffer.clear }
  end

  # Clear thread reference to allow GC
  @sender_thread = nil
end