Module: Datadog::Utils

Extended by:
Forking
Defined in:
lib/ddtrace/utils.rb,
lib/ddtrace/utils/time.rb,
lib/ddtrace/utils/forking.rb,
lib/ddtrace/utils/database.rb,
lib/ddtrace/utils/sequence.rb,
lib/ddtrace/utils/only_once.rb,
lib/ddtrace/utils/object_set.rb,
lib/ddtrace/utils/compression.rb,
lib/ddtrace/utils/string_table.rb

Overview

Utils contains low-level utilities, typically to provide pseudo-random trace IDs.

Defined Under Namespace

Modules: Compression, Database, Forking, Time Classes: ObjectSet, OnlyOnce, Sequence, StringTable

Constant Summary collapse

EMPTY_STRING =
''.encode(::Encoding::UTF_8).freeze

Class Method Summary collapse

Methods included from Forking

after_fork!, extended, fork_pid, forked?, included, update_fork_pid!

Class Method Details

.next_idObject

Return a randomly generated integer, valid as a Span ID or Trace ID. This method is thread-safe and fork-safe.



17
18
19
20
# File 'lib/ddtrace/utils.rb', line 17

def self.next_id
  after_fork! { reset! }
  id_rng.rand(Datadog::Span::RUBY_MAX_ID) # TODO: This should never return zero
end

.truncate(value, size, omission = '...'.freeze) ⇒ Object

Stringifies ‘value` and ensures the outcome is string is no longer than `size`. `omission` replaces the end of the output if `value.to_s` does not fit in `size`, to signify truncation.

If ‘omission.size` is larger than `size`, the output will still be `omission.size` in length.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ddtrace/utils.rb', line 40

def self.truncate(value, size, omission = '...'.freeze)
  string = value.to_s

  return string if string.size <= size

  string = string.slice(0, size - 1)

  if size < omission.size
    string[0, size] = omission
  else
    string[size - omission.size, size] = omission
  end

  string
end

.utf8_encode(str, options = {}) ⇒ Object

Ensure ‘str` is a valid UTF-8, ready to be sent through the tracer transport.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ddtrace/utils.rb', line 58

def self.utf8_encode(str, options = {})
  str = str.to_s

  if options[:binary]
    # This option is useful for "gracefully" displaying binary data that
    # often contains text such as marshalled objects
    str.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
  elsif str.encoding == ::Encoding::UTF_8
    str
  elsif str.empty?
    # DEV Optimization as `nil.to_s` is a very common source for an empty string,
    # DEV but it comes encoded as US_ASCII.
    EMPTY_STRING
  else
    str.encode(::Encoding::UTF_8)
  end
rescue => e
  Datadog.logger.debug("Error encoding string in UTF-8: #{e}")

  options.fetch(:placeholder, EMPTY_STRING)
end