Class: Brow::MessageBatch

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/brow/message_batch.rb

Overview

Internal: A batch of messages to be sent to the API.

Defined Under Namespace

Classes: JSONGenerationError

Constant Summary collapse

MAX_BYTES_PER_MESSAGE =

Private: Maximum bytes for an individual message.

32_768
MAX_BYTES =

Private: Maximum total bytes for a batch.

512_000
MAX_SIZE =

Private: Maximum number of messages in a batch.

100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ MessageBatch

Returns a new instance of MessageBatch.



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/brow/message_batch.rb', line 30

def initialize(options = {})
  clear
  @max_size = options.fetch(:max_size) {
    ENV.fetch("BROW_BATCH_SIZE", MAX_SIZE).to_i
  }

  unless @max_size > 0
    raise ArgumentError, ":max_size must be > 0 but was #{@max_size.inspect}"
  end

  @logger = options.fetch(:logger) { Brow.logger }
end

Instance Attribute Details

#json_sizeObject (readonly)

Returns the value of attribute json_size.



28
29
30
# File 'lib/brow/message_batch.rb', line 28

def json_size
  @json_size
end

#max_sizeObject (readonly)

Returns the value of attribute max_size.



28
29
30
# File 'lib/brow/message_batch.rb', line 28

def max_size
  @max_size
end

#uuidObject (readonly)

Returns the value of attribute uuid.



28
29
30
# File 'lib/brow/message_batch.rb', line 28

def uuid
  @uuid
end

Instance Method Details

#<<(message) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/brow/message_batch.rb', line 43

def <<(message)
  begin
    message_json = message.to_json
  rescue StandardError => error
    raise JSONGenerationError, "Serialization error: #{error}"
  end

  message_json_size = message_json.bytesize

  if message_too_big?(message_json_size)
    @logger.error { "#{LOG_PREFIX} a message exceeded the maximum allowed size" }
  else
    @messages << message
    @json_size += message_json_size + 1 # One byte for the comma
  end
end

#as_jsonObject



70
71
72
73
74
75
# File 'lib/brow/message_batch.rb', line 70

def as_json
  {
    uuid: @uuid,
    messages: @messages,
  }
end

#clearObject



64
65
66
67
68
# File 'lib/brow/message_batch.rb', line 64

def clear
  @messages = []
  @json_size = 0
  @uuid = SecureRandom.uuid
end

#full?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/brow/message_batch.rb', line 60

def full?
  item_count_exhausted? || size_exhausted?
end

#to_jsonObject



77
78
79
# File 'lib/brow/message_batch.rb', line 77

def to_json
  JSON.generate(as_json)
end