class Segment::Analytics::MessageBatch
A batch of ‘Message`s to be sent to the API
Public Class Methods
new(max_message_count)
click to toggle source
# File lib/segment/analytics/message_batch.rb, line 16 def initialize(max_message_count) @messages = [] @max_message_count = max_message_count @json_size = 0 end
Public Instance Methods
<<(message)
click to toggle source
# File lib/segment/analytics/message_batch.rb, line 22 def <<(message) begin message_json = message.to_json rescue StandardError => e raise JSONGenerationError, "Serialization error: #{e}" end message_json_size = message_json.bytesize if message_too_big?(message_json_size) logger.error('a message exceeded the maximum allowed size') raise JSONGenerationError, 'Message Exceeded Maximum Allowed Size' else @messages << message @json_size += message_json_size + 1 # One byte for the comma end end
clear()
click to toggle source
# File lib/segment/analytics/message_batch.rb, line 43 def clear @messages.clear @json_size = 0 end
full?()
click to toggle source
# File lib/segment/analytics/message_batch.rb, line 39 def full? item_count_exhausted? || size_exhausted? end
Private Instance Methods
item_count_exhausted?()
click to toggle source
# File lib/segment/analytics/message_batch.rb, line 54 def item_count_exhausted? @messages.length >= @max_message_count end
message_too_big?(message_json_size)
click to toggle source
# File lib/segment/analytics/message_batch.rb, line 58 def message_too_big?(message_json_size) message_json_size > Defaults::Message::MAX_BYTES end
size_exhausted?()
click to toggle source
We consider the max size here as just enough to leave room for one more message of the largest size possible. This is a shortcut that allows us to use a native Ruby ‘Queue` that doesn’t allow peeking. The tradeoff here is that we might fit in less messages than possible into a batch.
The alternative is to use our own ‘Queue` implementation that allows peeking, and to consider the next message size when calculating whether the message can be accomodated in this batch.
# File lib/segment/analytics/message_batch.rb, line 70 def size_exhausted? @json_size >= (MAX_BYTES - Defaults::Message::MAX_BYTES) end