Class: EventTracer::Buffer

Inherits:
Object
  • Object
show all
Defined in:
lib/event_tracer/buffer.rb

Overview

This is an implementation of buffer storage. We use Concurrent::Array underneath to ensure thread-safe behavior. Data is stored until certain size / interval before flushing.

Caveats: We should only store non-important data like logs in this buffer because if a process is killed, the data in this buffer is lost.

Constant Summary collapse

DEFAULT_BUFFER_SIZE =

Buffer can store maximum 10 items. Bigger size requires more memory to store, so choose a reasonable number

10
DEFAULT_FLUSH_INTERVAL =

An item can live in buffer for at least 10s between each ‘Buffer#add` if the buffer is not full If there are larger interval between the calls, it can live longer.

10

Instance Method Summary collapse

Constructor Details

#initialize(buffer_size: DEFAULT_BUFFER_SIZE, flush_interval: DEFAULT_FLUSH_INTERVAL) ⇒ Buffer

Returns a new instance of Buffer.



18
19
20
21
22
23
24
25
# File 'lib/event_tracer/buffer.rb', line 18

def initialize(
  buffer_size: DEFAULT_BUFFER_SIZE,
  flush_interval: DEFAULT_FLUSH_INTERVAL
)
  @buffer_size = buffer_size
  @flush_interval = flush_interval
  @buffer = Concurrent::Array.new
end

Instance Method Details

#add(item) ⇒ Object

Add an item to buffer

Parameters:

  • item:

    data to be added to buffer

Returns:

  • true if the item can be added, otherwise false



31
32
33
34
35
36
37
38
# File 'lib/event_tracer/buffer.rb', line 31

def add(item)
  if add_item?
    buffer.push({ item: item, created_at: Time.now })
    true
  else
    false
  end
end

#flushObject

Remove all existing items from buffer

Returns:

  • all items in buffer



43
44
45
46
47
48
49
50
51
52
# File 'lib/event_tracer/buffer.rb', line 43

def flush
  data = []

  # NOTE: We need to use this to avoid race-condition
  buffer.cycle do
    data << buffer.shift[:item]
  end

  data
end

#sizeObject

This method is only used to facilitate testing



55
56
57
# File 'lib/event_tracer/buffer.rb', line 55

def size
  buffer.size
end