123456789_123456789_123456789_123456789_123456789_

Class: Mongo::Tracing::OpenTelemetry::CommandTracer Private

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Inherits: Object
Defined in: lib/mongo/tracing/open_telemetry/command_tracer.rb

Overview

CommandTracer is responsible for tracing MongoDB server commands using ::Mongo::Tracing::OpenTelemetry.

Constant Summary

::Mongo::Monitoring::Event::Secure - Included

HELLO_COMMANDS, REDACTED_COMMANDS

Class Method Summary

Instance Attribute Summary

Instance Method Summary

::Mongo::Monitoring::Event::Secure - Included

#compression_allowed?

Is compression allowed for a given command message.

#redacted

Redact secure information from the document if:

#sensitive?

Check whether the command is sensitive in terms of command monitoring spec.

Constructor Details

.new(otel_tracer, parent_tracer, query_text_max_length: 0) ⇒ CommandTracer

Initializes a new CommandTracer.

Parameters:

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 36

def initialize(otel_tracer, parent_tracer, query_text_max_length: 0)
  @otel_tracer = otel_tracer
  @parent_tracer = parent_tracer
  @query_text_max_length = query_text_max_length
  @lsid_cache = {}
  @lsid_cache_mutex = Mutex.new
end

Instance Attribute Details

#query_text? ⇒ Boolean (readonly, private)

Checks if query text capture is enabled.

Returns:

  • (Boolean) —

    true if query text should be captured.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 321

def query_text?
  @query_text_max_length.positive?
end

Instance Method Details

#apply_deferred_attributes(span, message, name, doc) (private)

Sets the remaining attributes on a span that is recording. They are not visible to the sampler; only custom samplers keying on them are affected.

Parameters:

  • span (OpenTelemetry::Trace::Span) —

    the span.

  • message (Mongo::Protocol::Message) —

    the command message.

  • name (String) —

    the command name.

  • doc (Hash) —

    the command document.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 196

def apply_deferred_attributes(span, message, name, doc)
  {
    'db.query.summary' => query_summary(name, doc),
    'db.query.text' => query_text(message),
    'db.mongodb.cursor_id' => cursor_id(name, doc),
    'db.mongodb.lsid' => lsid(doc),
    'db.mongodb.txn_number' => txn_number(doc)
  }.each do |key, value|
    span.set_attribute(key, value) unless value.nil?
  end
end

#collection_name(name, doc) ⇒ String | nil (private)

Extracts the collection name from the command document.

Parameters:

  • name (String) —

    the command name.

  • doc (Hash) —

    the command document.

Returns:

  • (String | nil) —

    the collection name, or nil if not applicable.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 284

def collection_name(name, doc)
  case name
  when 'getMore'
    doc['collection'].to_s
  when 'listCollections', 'listDatabases', 'commitTransaction', 'abortTransaction'
    nil
  else
    # The first value, read without building an array of all of them.
    value = doc.each_value { |v| break v } # rubocop:disable Lint/UnreachableLoop -- first value only
    # Return nil if the value is not a string (e.g., for admin commands that have numeric values)
    value.is_a?(String) ? value : nil
  end
end

#command_name(doc) ⇒ String (private)

Extracts the command name, the first key of the command document, without building an array of all keys.

Parameters:

  • doc (Hash) —

    the command document.

Returns:

  • (String) —

    the command name.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 304

def command_name(doc)
  doc.each_key { |key| return key.to_s } # rubocop:disable Lint/UnreachableLoop -- first key only
  ''
end

#connection_attributes(connection) ⇒ Hash (private)

Returns connection-related attributes, built once per connection, frozen and kept on the connection. Two threads may build them at the same time; they build the same hash, so either result is fine.

Parameters:

Returns:

  • (Hash) —

    connection span attributes.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 215

def connection_attributes(connection)
  connection.tracing_attributes ||= {
    'server.port' => connection.address.port,
    'server.address' => connection.address.host,
    'network.transport' => connection.transport.to_s,
    'db.mongodb.server_connection_id' => connection.description.server_connection_id,
    'db.mongodb.driver_connection_id' => connection.id
  }.freeze
end

#create_command_span(name, doc, connection) ⇒ OpenTelemetry::Trace::Span (private)

Creates a span for a command.

Parameters:

  • name (String) —

    the command name.

  • doc (Hash) —

    the command document.

  • connection (Mongo::Server::Connection) —

    the connection.

Returns:

  • (OpenTelemetry::Trace::Span) —

    the created span.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 139

def create_command_span(name, doc, connection)
  @otel_tracer.start_span(
    name,
    attributes: span_attributes(doc, name, connection),
    kind: :client
  )
end

#cursor_id(name, doc) ⇒ Integer | nil (private)

Extracts the cursor ID from getMore commands.

Parameters:

  • name (String) —

    the command name.

  • doc (Hash) —

    the command document.

Returns:

  • (Integer | nil) —

    the cursor ID, or nil if not a getMore command.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 331

def cursor_id(name, doc)
  return unless name == 'getMore'

  doc['getMore'].value
end

#database(doc) ⇒ String (private)

Extracts the database name from the command document.

Parameters:

  • doc (Hash) —

    the command document.

Returns:

  • (String) —

    the database name.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 314

def database(doc)
  doc['$db'].to_s
end

#handle_command_exception(span, exception) (private)

Handles exceptions that occur during command execution.

Parameters:

  • span (OpenTelemetry::Trace::Span) —

    the span.

  • exception (Exception) —

    the exception that occurred.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 160

def handle_command_exception(span, exception)
  if exception.is_a?(Mongo::Error::OperationFailure)
    span.set_attribute('db.response.status_code', exception.code.to_s)
  end
  span.record_exception(exception)
  span.status = ::OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{exception.class}")
end

#lsid(doc) ⇒ String | nil (private)

Extracts the logical session ID from the command, as a UUID string. The string is formatted once per session id and kept in a small cache, cleared when it reaches LSID_CACHE_MAX entries.

Parameters:

  • doc (Hash) —

    the command document.

Returns:

  • (String | nil) —

    the session ID, or nil if not present.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 344

def lsid(doc)
  lsid_doc = doc['lsid']
  return unless lsid_doc

  binary = lsid_doc['id']
  key = binary.data
  cached = @lsid_cache_mutex.synchronize { @lsid_cache[key] }
  return cached if cached

  uuid = binary.to_uuid
  @lsid_cache_mutex.synchronize do
    @lsid_cache.clear if @lsid_cache.size >= LSID_CACHE_MAX
    @lsid_cache[key] = uuid
  end
  uuid
end

#maybe_trace_error(result, span) (private)

Records error status code if the command failed.

Parameters:

  • result (Object) —

    the command result.

  • span (OpenTelemetry::Trace::Span) —

    the current span.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 253

def maybe_trace_error(result, span)
  return if result.successful?

  span.set_attribute('db.response.status_code', result.error.code.to_s)
  begin
    result.validate!
  rescue Mongo::Error::OperationFailure => e
    span.record_exception(e)
  end
end

#normalize_cursor_id(cursor_id) ⇒ Integer (private)

Normalizes a cursor id to a plain Integer.

OP_MSG replies deserialized in :bson mode expose the cursor id as a BSON::Int64, which does not implement Numeric#positive? and is not a valid ::Mongo::Tracing::OpenTelemetry attribute type.

Parameters:

  • cursor_id (Integer | BSON::Int64) —

    the raw cursor id.

Returns:

  • (Integer) —

    the cursor id as an Integer.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 245

def normalize_cursor_id(cursor_id)
  cursor_id.is_a?(BSON::Int64) ? cursor_id.value : cursor_id
end

#process_command_result(result, span) (private)

Processes the command result and updates span attributes.

Parameters:

  • result (Object) —

    the command result.

  • span (OpenTelemetry::Trace::Span) —

    the current span.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 151

def process_command_result(result, span)
  process_cursor_context(result, span)
  maybe_trace_error(result, span)
end

#process_cursor_context(result, span) (private)

Processes cursor context from the command result.

Parameters:

  • result (Object) —

    the command result.

  • span (OpenTelemetry::Trace::Span) —

    the current span.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 229

def process_cursor_context(result, span)
  cursor_id = normalize_cursor_id(result.cursor_id)
  return unless cursor_id.positive?

  span.set_attribute('db.mongodb.cursor_id', cursor_id)
end

#query_summary(name, doc) ⇒ String (private)

Generates a summary string for the query.

Parameters:

  • name (String) —

    the command name.

  • doc (Hash) —

    the command document.

Returns:

  • (String) —

    summary in format "command_name db.collection" or "command_name db".

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 270

def query_summary(name, doc)
  if (coll_name = collection_name(name, doc))
    "#{name} #{database(doc)}.#{coll_name}"
  else
    "#{name} #{database(doc)}"
  end
end

#query_text(message) ⇒ String | nil (readonly, private)

Extracts and formats the query text from the command.

Parameters:

Returns:

  • (String | nil) —

    JSON representation of the command, truncated if necessary, or nil if disabled.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 384

def query_text(message)
  return unless query_text?

  text = message
         .payload['command']
         .reject { |key, _| EXCLUDED_KEYS.include?(key) }
         .to_json
  if text.length > @query_text_max_length
    "#{text[0...@query_text_max_length]}#{ELLIPSIS}"
  else
    text
  end
end

#skip_tracing?(doc, name) ⇒ Boolean (private)

Determines whether the command must not be traced. Sensitive auth commands carry credentials in their payloads (SCRAM proofs, cleartext passwords, etc.) and the ::Mongo::Tracing::OpenTelemetry spec requires drivers to skip command spans for them. Hello / legacy hello in all forms (Secure::HELLO_COMMANDS) are also skipped: they are handshake and heartbeat traffic and would only add noise to traces.

Parameters:

  • doc (Hash) —

    the command document.

  • name (String) —

    the command name.

Returns:

  • (Boolean) —

    true when no command span should be created.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 126

def skip_tracing?(doc, name)
  return true if HELLO_COMMANDS.include?(name)

  sensitive?(command_name: name, document: doc)
end

#span_attributes(doc, name, connection) ⇒ Hash (private)

Builds the attributes passed at span creation: the cheap set the ::Mongo::Tracing::OpenTelemetry spec recommends. They are built for every span, recorded or not, and are the only ones the sampler sees. The rest are set by apply_deferred_attributes once the span is known to record.

Parameters:

  • doc (Hash) —

    the command document.

  • name (String) —

    the command name.

  • connection (Mongo::Server::Connection) —

    the connection.

Returns:

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 179

def span_attributes(doc, name, connection)
  {
    'db.system.name' => 'mongodb',
    'db.namespace' => database(doc),
    'db.collection.name' => collection_name(name, doc),
    'db.command.name' => name
  }.compact.merge(connection_attributes(connection))
end

#start_span(message, operation_context, connection)

Starts a span for a MongoDB command.

Parameters:

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 49

def start_span(message, operation_context, connection); end

#trace_command(message, _operation_context, connection) { ... } ⇒ Object

Trace a MongoDB command.

Creates an ::Mongo::Tracing::OpenTelemetry span for the command, capturing attributes such as command name, database name, collection name, server address, connection IDs, and optionally query text. The span is automatically nested under the current operation span and is finished when the command completes or fails.

Parameters:

Yields:

  • the block representing the command to be traced.

Returns:

  • (Object) —

    the result of the command.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 65

def trace_command(message, _operation_context, connection, &block)
  # Read the command document and name once and pass them on: every
  # read of message.documents allocates.
  doc = message.documents.first
  name = command_name(doc)
  return yield if skip_tracing?(doc, name)

  # Commands should always be nested under their operation span, not directly under
  # the transaction span. Don't pass with_parent to use automatic parent resolution
  # from the currently active span (the operation span).
  span = create_command_span(name, doc, connection)
  # With no SDK and no valid parent, the API returns a span with an
  # invalid context. It cannot be made current, recorded or
  # propagated, so it gets no work at all, not even finishing it.
  return yield unless span.context.valid?

  trace_with_span(span, message, name, doc, &block)
end

#trace_with_span(span, message, name, doc) ⇒ Object (private)

Runs the command with the span made current, and finishes the span. A span that is not recording is still made current, so that its context is propagated, but gets no further attributes and no outcome: the SDK would discard them.

Parameters:

  • span (OpenTelemetry::Trace::Span) —

    a span with a valid context.

  • message (Mongo::Protocol::Message) —

    the command message.

  • name (String) —

    the command name.

  • doc (Hash) —

    the command document.

Returns:

  • (Object) —

    the result of the command.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 99

def trace_with_span(span, message, name, doc)
  recording = span.recording?
  apply_deferred_attributes(span, message, name, doc) if recording
  ::OpenTelemetry::Trace.with_span(span) do |s, _c|
    yield.tap do |result|
      process_command_result(result, s) if recording
    end
  end
rescue Exception => e
  handle_command_exception(span, e) if recording
  raise e
ensure
  span.finish
end

#txn_number(doc) ⇒ Integer | nil (private)

Extracts the transaction number from the command.

Parameters:

  • doc (Hash) —

    the command document.

Returns:

  • (Integer | nil) —

    the transaction number, or nil if not present.

[ GitHub ]

  
# File 'lib/mongo/tracing/open_telemetry/command_tracer.rb', line 366

def txn_number(doc)
  txn_num = doc['txnNumber']
  return unless txn_num

  txn_num.value
end