2020-02-14 19:08:48 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module Utils
|
|
|
|
module LogLimitedArray
|
|
|
|
MAXIMUM_ARRAY_LENGTH = 10.kilobytes
|
|
|
|
|
|
|
|
# Prepare an array for logging by limiting its JSON representation
|
2020-02-19 10:09:09 -05:00
|
|
|
# to around 10 kilobytes. Once we hit the limit, add the sentinel
|
|
|
|
# value as the last item in the returned array.
|
|
|
|
def self.log_limited_array(array, sentinel: '...')
|
2020-06-12 08:08:56 -04:00
|
|
|
return [] unless array.is_a?(Array) || array.is_a?(Enumerator::Lazy)
|
2020-02-14 19:08:48 -05:00
|
|
|
|
|
|
|
total_length = 0
|
|
|
|
limited_array = array.take_while do |arg|
|
2020-03-04 07:07:52 -05:00
|
|
|
total_length += JsonSizeEstimator.estimate(arg)
|
2020-02-14 19:08:48 -05:00
|
|
|
|
|
|
|
total_length <= MAXIMUM_ARRAY_LENGTH
|
2020-06-12 08:08:56 -04:00
|
|
|
end.to_a
|
2020-02-14 19:08:48 -05:00
|
|
|
|
2020-02-19 10:09:09 -05:00
|
|
|
limited_array.push(sentinel) if total_length > MAXIMUM_ARRAY_LENGTH
|
2020-02-14 19:08:48 -05:00
|
|
|
|
|
|
|
limited_array
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|