Class: Datadog::Statsd::MessageBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/statsd/message_buffer.rb

Constant Summary collapse

PAYLOAD_SIZE_TOLERANCE =
0.05

Instance Method Summary collapse

Constructor Details

#initialize(connection, max_payload_size: nil, max_pool_size: DEFAULT_BUFFER_POOL_SIZE, overflowing_stategy: :drop) ⇒ MessageBuffer

Returns a new instance of MessageBuffer.

Raises:

  • (ArgumentError)

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/datadog/statsd/message_buffer.rb', line 8

def initialize(connection,
  max_payload_size: nil,
  max_pool_size: DEFAULT_BUFFER_POOL_SIZE,
  overflowing_stategy: :drop
)
  raise ArgumentError, 'max_payload_size keyword argument must be provided' unless max_payload_size
  raise ArgumentError, 'max_pool_size keyword argument must be provided' unless max_pool_size

  @connection = connection
  @max_payload_size = max_payload_size
  @max_pool_size = max_pool_size
  @overflowing_stategy = overflowing_stategy

  @buffer = String.new
  @message_count = 0
end

Instance Method Details

#add(message) ⇒ Object


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/datadog/statsd/message_buffer.rb', line 25

def add(message)
  message_size = message.bytesize

  return nil unless message_size > 0 # to avoid adding empty messages to the buffer
  return nil unless ensure_sendable!(message_size)

  flush if should_flush?(message_size)

  buffer << "\n" unless buffer.empty?
  buffer << message

  @message_count += 1

  # flush when we're pretty sure that we won't be able
  # to add another message to the buffer
  flush if preemptive_flush?

  true
end

#flushObject


45
46
47
48
49
50
51
52
# File 'lib/datadog/statsd/message_buffer.rb', line 45

def flush
  return if buffer.empty?

  connection.write(buffer)

  buffer.clear
  @message_count = 0
end