diff --git a/lib/mongo/monitoring/event/secure.rb b/lib/mongo/monitoring/event/secure.rb index 7cc8f38e68..01a92605d6 100644 --- a/lib/mongo/monitoring/event/secure.rb +++ b/lib/mongo/monitoring/event/secure.rb @@ -37,6 +37,11 @@ module Secure copydb ].freeze + # The hello / legacy hello command names, hoisted to a constant: the + # sensitivity check runs on every command event and an array literal + # would allocate on each call. + HELLO_COMMANDS = %w[hello ismaster isMaster].freeze + # Check whether the command is sensitive in terms of command monitoring # spec. A command is detected as sensitive if it is in the # list or if it is a hello/legacy hello command, and @@ -53,7 +58,7 @@ def sensitive?(command_name:, document:) # when speculativeAuthenticate is present, their commands AND replies # MUST be redacted from the events. # See https://github.com/mongodb/specifications/blob/master/source/command-logging-and-monitoring/command-logging-and-monitoring.md#security - %w[hello ismaster isMaster].include?(command_name.to_s) && + HELLO_COMMANDS.include?(command_name.to_s) && !!document['speculativeAuthenticate'] end diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 27585839de..9058a8bb75 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -23,12 +23,8 @@ module OpenTelemetry class CommandTracer include Mongo::Monitoring::Event::Secure - # Commands for which a span MUST NOT be created. The OpenTelemetry spec - # requires drivers to skip command spans for sensitive commands listed in - # the Command Logging and Monitoring spec. We additionally skip hello / - # legacy hello in all forms — these are handshake/heartbeat traffic and - # would only add noise to traces. - HELLO_COMMANDS = %w[hello ismaster isMaster].freeze + # Upper bound of the lsid UUID memo cache (see #lsid). + LSID_CACHE_MAX = 128 # Initializes a new CommandTracer. # @@ -41,6 +37,8 @@ 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 # Starts a span for a MongoDB command. @@ -64,55 +62,89 @@ def start_span(message, operation_context, connection); end # @yield the block representing the command to be traced. # # @return [ Object ] the result of the command. - # rubocop:disable Lint/RescueException - def trace_command(message, _operation_context, connection) - return yield if skip_tracing?(message) + def trace_command(message, _operation_context, connection, &block) + # The command document and name are extracted once and threaded + # through: the extraction helpers below allocate on every call. + 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(message, connection) - ::OpenTelemetry::Trace.with_span(span) do |s, c| + span = create_command_span(name, doc, connection) + # An invalid context has no trace identity: it cannot be propagated, + # continued, or correlated with anything downstream, so every + # operation on it, including finishing it, is waste. This is a state + # check on the span we were handed, not detection of whether the SDK + # is available — a custom API-only provider returning real spans + # sees the full path. Must not key on recording?: an + # unsampled-but-valid context still has to be made current for + # propagation. + return yield unless span.context.valid? + + trace_with_span(span, message, name, doc, &block) + end + + private + + # Runs the command with the span made current. 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. + # + # @param span [ OpenTelemetry::Trace::Span ] a span with a valid context. + # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. + # + # @return [ Object ] the result of the command. + # + # rubocop:disable Lint/RescueException + def trace_with_span(span, message, name, doc) + recording = span.recording? + apply_deferred_attributes(span, message, name, doc, cursor_id(name, doc)) if recording + ::OpenTelemetry::Trace.with_span(span) do |s, _c| yield.tap do |result| - process_command_result(result, cursor_id(message), c, s) + process_command_result(result, s) if recording end end rescue Exception => e - handle_command_exception(span, e) + handle_command_exception(span, e) if recording raise e ensure - span&.finish + span.finish end # rubocop:enable Lint/RescueException - private - # Determines whether the command must not be traced. Sensitive auth # commands carry credentials in their payloads (SCRAM proofs, cleartext # passwords, etc.) and the OpenTelemetry spec requires drivers to skip - # command spans for them. Hello / legacy hello are also skipped to keep - # handshake traffic out of traces. + # command spans for them. Hello / legacy hello in all forms + # (Secure::HELLO_COMMANDS) are also skipped to keep handshake traffic + # out of traces. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. + # @param name [ String ] the command name. # # @return [ Boolean ] true when no command span should be created. - def skip_tracing?(message) - name = command_name(message) + def skip_tracing?(doc, name) return true if HELLO_COMMANDS.include?(name) - sensitive?(command_name: name, document: message.documents.first) + sensitive?(command_name: name, document: doc) end # Creates a span for a command. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ OpenTelemetry::Trace::Span ] the created span. - def create_command_span(message, connection) + def create_command_span(name, doc, connection) @otel_tracer.start_span( - command_name(message), - attributes: span_attributes(message, connection), + name, + attributes: span_attributes(doc, name, connection), kind: :client ) end @@ -120,21 +152,17 @@ def create_command_span(message, connection) # Processes the command result and updates span attributes. # # @param result [ Object ] the command result. - # @param cursor_id [ Integer | nil ] the cursor ID. - # @param context [ OpenTelemetry::Context ] the context. # @param span [ OpenTelemetry::Trace::Span ] the current span. - def process_command_result(result, cursor_id, context, span) - process_cursor_context(result, cursor_id, context, span) + def process_command_result(result, span) + process_cursor_context(result, span) maybe_trace_error(result, span) end # Handles exceptions that occur during command execution. # - # @param span [ OpenTelemetry::Trace::Span | nil ] the span. + # @param span [ OpenTelemetry::Trace::Span ] the span. # @param exception [ Exception ] the exception that occurred. def handle_command_exception(span, exception) - return unless span - if exception.is_a?(Mongo::Error::OperationFailure) span.set_attribute('db.response.status_code', exception.code.to_s) end @@ -142,70 +170,85 @@ def handle_command_exception(span, exception) span.status = ::OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{exception.class}") end - # Builds span attributes for the command. + # Builds the attributes passed at span creation: the cheap set the + # OpenTelemetry spec recommends. These are built for every span, + # recorded or not, and are the only ones the sampler sees. The rest + # are deferred to apply_deferred_attributes. Keys whose value is nil + # are omitted rather than compacted afterwards, so the common case + # allocates nothing extra. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. + # @param name [ String ] the command name. # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions. - def span_attributes(message, connection) - base_attributes(message) - .merge(connection_attributes(connection)) - .merge(session_attributes(message)) - .compact - end - - # Returns base database and command attributes. - # - # @param message [ Mongo::Protocol::Message ] the command message. - # - # @return [ Hash ] base span attributes. - def base_attributes(message) - { + def span_attributes(doc, name, connection) + attrs = { 'db.system.name' => 'mongodb', - 'db.namespace' => database(message), - 'db.collection.name' => collection_name(message), - 'db.command.name' => command_name(message), - 'db.query.summary' => query_summary(message), - 'db.query.text' => query_text(message) + 'db.namespace' => database(doc), + 'db.command.name' => name } + if (coll_name = collection_name(name, doc)) + attrs['db.collection.name'] = coll_name + end + attrs.merge(connection_attributes(connection)) end - # Returns connection-related attributes. + # Returns connection-related attributes, computed once per connection + # and frozen. Setting the ivar from here is a benign race: competing + # threads build identical frozen hashes. The value dies with the + # connection, so no cleanup is needed. # # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ Hash ] connection span attributes. def connection_attributes(connection) - { - 'server.port' => connection.address.port, - 'server.address' => connection.address.host, - 'network.transport' => connection.transport.to_s, - 'db.mongodb.server_connection_id' => connection.server.description.server_connection_id, - 'db.mongodb.driver_connection_id' => connection.id - } + attrs = connection.instance_variable_get(:@otel_connection_attributes) + unless attrs + attrs = { + '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 + connection.instance_variable_set(:@otel_connection_attributes, attrs) + end + attrs end - # Returns session and transaction attributes. + # Sets the remaining attributes after span creation. Only called for + # recording spans: on non-recording spans set_attribute discards. + # These attributes are invisible to the sampler, which only sees what + # is passed to start_span; only custom samplers keying on them are + # affected. # + # @param span [ OpenTelemetry::Trace::Span ] the current span. # @param message [ Mongo::Protocol::Message ] the command message. - # - # @return [ Hash ] session span attributes. - def session_attributes(message) - { - 'db.mongodb.cursor_id' => cursor_id(message), - 'db.mongodb.lsid' => lsid(message), - 'db.mongodb.txn_number' => txn_number(message) - } + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. + # @param cursor [ Integer | nil ] the cursor id, extracted once per command. + def apply_deferred_attributes(span, message, name, doc, cursor) + span.set_attribute('db.query.summary', query_summary(name, doc)) + if (text = query_text(message)) + span.set_attribute('db.query.text', text) + end + if (lsid_value = lsid(doc)) + span.set_attribute('db.mongodb.lsid', lsid_value) + end + unless cursor.nil? + span.set_attribute('db.mongodb.cursor_id', cursor) + end + if (txn = txn_number(doc)) + span.set_attribute('db.mongodb.txn_number', txn) + end end # Processes cursor context from the command result. # # @param result [ Object ] the command result. - # @param _cursor_id [ Integer | nil ] the cursor ID (unused). - # @param _context [ OpenTelemetry::Context ] the context (unused). # @param span [ OpenTelemetry::Trace::Span ] the current span. - def process_cursor_context(result, _cursor_id, _context, span) + def process_cursor_context(result, span) cursor_id = normalize_cursor_id(result.cursor_id) return unless cursor_id.positive? @@ -242,51 +285,67 @@ def maybe_trace_error(result, span) # Generates a summary string for the query. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # # @return [ String ] summary in format "command_name db.collection" or "command_name db". - def query_summary(message) - if (coll_name = collection_name(message)) - "#{command_name(message)} #{database(message)}.#{coll_name}" + def query_summary(name, doc) + if (coll_name = collection_name(name, doc)) + "#{name} #{database(doc)}.#{coll_name}" else - "#{command_name(message)} #{database(message)}" + "#{name} #{database(doc)}" end end - # Extracts the collection name from the command message. + # Extracts the collection name from the command document. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # # @return [ String | nil ] the collection name, or nil if not applicable. - def collection_name(message) - case command_name(message) + def collection_name(name, doc) + case name when 'getMore' - message.documents.first['collection'].to_s + doc['collection'].to_s when 'listCollections', 'listDatabases', 'commitTransaction', 'abortTransaction' nil else - value = message.documents.first.values.first + # Iterate instead of using doc.values.first: the block form is + # allocation-free (see #command_name). + value = nil + # rubocop:disable Lint/UnreachableLoop -- intentional: only the first entry is needed + doc.each_value do |v| + value = v + break + end + # rubocop:enable Lint/UnreachableLoop # 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 - # Extracts the command name from the message. + # Extracts the command name from the command document. Iterates + # instead of using doc.keys.first: the block form is allocation-free, + # while keys builds an array of every top-level key per call — and + # this runs on every traced command. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # # @return [ String ] the command name. - def command_name(message) - message.documents.first.keys.first.to_s + def command_name(doc) + # rubocop:disable Lint/UnreachableLoop -- intentional: only the first entry is needed + doc.each_key { |key| return key.to_s } + # rubocop:enable Lint/UnreachableLoop + '' end - # Extracts the database name from the message. + # Extracts the database name from the command document. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # # @return [ String ] the database name. - def database(message) - message.documents.first['$db'].to_s + def database(doc) + doc['$db'].to_s end # Checks if query text capture is enabled. @@ -298,34 +357,48 @@ def query_text? # Extracts the cursor ID from getMore commands. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # # @return [ Integer | nil ] the cursor ID, or nil if not a getMore command. - def cursor_id(message) - return unless command_name(message) == 'getMore' + def cursor_id(name, doc) + return unless name == 'getMore' - message.documents.first['getMore'].value + doc['getMore'].value end - # Extracts the logical session ID from the command. + # Extracts the logical session ID from the command. The UUID string + # is formatted once per session id and memoized in a bounded cache: + # the value is invariant for the life of a session, and formatting it + # per command showed up in the DRIVERS-3620 profile. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # - # @return [ BSON::Binary | nil ] the session ID, or nil if not present. - def lsid(message) - lsid_doc = message.documents.first['lsid'] + # @return [ String | nil ] the session ID as a UUID string, or nil if not present. + def lsid(doc) + lsid_doc = doc['lsid'] return unless lsid_doc - lsid_doc['id'].to_uuid + 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 # Extracts the transaction number from the command. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # # @return [ Integer | nil ] the transaction number, or nil if not present. - def txn_number(message) - txn_num = message.documents.first['txnNumber'] + def txn_number(doc) + txn_num = doc['txnNumber'] return unless txn_num txn_num.value diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index 2800fcd1e6..3f38cfd689 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -37,6 +37,8 @@ class OperationTracer def initialize(otel_tracer, parent_tracer) @otel_tracer = otel_tracer @parent_tracer = parent_tracer + @operation_names = {} + @operation_names_mutex = Mutex.new end # Trace a MongoDB operation. @@ -53,22 +55,52 @@ def initialize(otel_tracer, parent_tracer) # @yield the block representing the operation to be traced. # # @return [ Object ] the result of the operation. - # - # rubocop:disable Lint/RescueException def trace_operation(operation, operation_context, op_name: nil, &block) span = create_operation_span(operation, operation_context, op_name) - execute_with_span(span, operation, &block) + # An invalid context has no trace identity: it cannot be propagated, + # continued, or correlated with anything downstream, so every + # operation on it, including finishing it, is waste. This is a state + # check on the span we were handed, not detection of whether the SDK + # is available — a custom API-only provider returning real spans + # sees the full path. Must not key on recording?: an + # unsampled-but-valid context still has to be made current for + # propagation. Skipping here also leaves the cursor context map + # untouched, consistent with tracing being effectively off. + return yield unless span.context.valid? + + trace_with_span(span, operation, &block) + end + + private + + # Runs the operation with the span made current. A span that is not + # recording is still made current, so that the command spans created + # within it are nested under it, but gets no further attributes and + # no outcome: the SDK would discard them. + # + # @param span [ OpenTelemetry::Trace::Span ] a span with a valid context. + # @param operation [ Mongo::Operation ] the operation. + # + # @return [ Object ] the result of the operation. + # + # rubocop:disable Lint/RescueException + def trace_with_span(span, operation, &block) + recording = span.recording? + if recording && !operation.cursor_id.nil? + span.set_attribute('db.mongodb.cursor_id', operation.cursor_id) + end + execute_with_span(span, operation, recording, &block) rescue Exception => e - handle_span_exception(span, e) + handle_span_exception(span, e) if recording raise e ensure - span&.finish + span.finish end # rubocop:enable Lint/RescueException - private - - # Creates an OpenTelemetry span for the operation. + # Creates an OpenTelemetry span for the operation. The operation name, + # collection name and span name are each computed once and reused + # between the span name and the attributes. # # @param operation [ Mongo::Operation ] the operation. # @param operation_context [ Mongo::Operation::Context ] the operation context. @@ -76,10 +108,13 @@ def trace_operation(operation, operation_context, op_name: nil, &block) # # @return [ OpenTelemetry::Trace::Span ] the created span. def create_operation_span(operation, operation_context, op_name) - parent_context = parent_context_for(operation_context, operation.cursor_id) + parent_context = parent_context_for(operation_context) + name = operation_name(operation, op_name) + coll_name = collection_name(operation) + span_name = operation_span_name(name, operation.db_name, coll_name) @otel_tracer.start_span( - operation_span_name(operation, op_name), - attributes: span_attributes(operation, op_name), + span_name, + attributes: span_attributes(operation, name, span_name, coll_name), with_parent: parent_context, kind: :client ) @@ -89,14 +124,15 @@ def create_operation_span(operation, operation_context, op_name) # # @param span [ OpenTelemetry::Trace::Span ] the span. # @param operation [ Mongo::Operation ] the operation. + # @param recording [ true | false ] whether the span is recording. # # @yield the block to execute. # # @return [ Object ] the result of the block. - def execute_with_span(span, operation) + def execute_with_span(span, operation, recording) ::OpenTelemetry::Trace.with_span(span) do |s, c| yield.tap do |result| - process_cursor_context(result, operation.cursor_id, c, s) + process_cursor_context(result, operation.cursor_id, c, s, recording) end end end @@ -106,8 +142,6 @@ def execute_with_span(span, operation) # @param span [ OpenTelemetry::Trace::Span ] the span. # @param exception [ Exception ] the exception. def handle_span_exception(span, exception) - return unless span - span.record_exception(exception) span.status = ::OpenTelemetry::Trace::Status.error( "Unhandled exception of type: #{exception.class}" @@ -115,30 +149,47 @@ def handle_span_exception(span, exception) end # Returns the operation name from the provided name or operation class. + # The class-derived name is memoized per class: it is invariant and + # deriving it (split + downcase) allocates on every call. The number + # of operation classes is small and fixed, so the cache is unbounded + # by design. Access is synchronized: unsynchronized Hash mutation is + # not safe on all Ruby runtimes (e.g. JRuby). # # @param operation [ Mongo::Operation ] the operation. # @param op_name [ String | nil ] optional operation name. # # @return [ String ] the operation name in lowercase. def operation_name(operation, op_name = nil) - op_name || operation.class.name.split('::').last.downcase + return op_name if op_name + + klass = operation.class + @operation_names_mutex.synchronize do + @operation_names[klass] ||= klass.name.split('::').last.downcase + end end - # Builds span attributes for the operation. + # Builds the attributes passed at span creation: the cheap set. The + # cursor id is deferred to trace_with_span (behind recording?) — on a + # non-recording span set_attribute discards, and the sampler has no + # use for it. db.operation.summary is outside the spec's recommended + # creation set, but here it is the span name, which is built anyway, + # and an attribute passed at creation is cheaper than one set later. # # @param operation [ Mongo::Operation ] the operation. - # @param op_name [ String | nil ] optional operation name. + # @param name [ String ] the operation name. + # @param span_name [ String ] the span name, reused as the summary. + # @param coll_name [ String | nil ] the collection name, computed once. # # @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions. - def span_attributes(operation, op_name) - { + def span_attributes(operation, name, span_name, coll_name) + attrs = { 'db.system.name' => 'mongodb', 'db.namespace' => operation.db_name.to_s, - 'db.collection.name' => collection_name(operation), - 'db.operation.name' => operation_name(operation, op_name), - 'db.operation.summary' => operation_span_name(operation, op_name), - 'db.mongodb.cursor_id' => operation.cursor_id, - }.compact + 'db.operation.name' => name, + 'db.operation.summary' => span_name + } + attrs['db.collection.name'] = coll_name unless coll_name.nil? + attrs end # Processes cursor context after operation execution. @@ -150,7 +201,8 @@ def span_attributes(operation, op_name) # @param cursor_id [ Integer | nil ] the cursor ID before the operation. # @param context [ OpenTelemetry::Context ] the OpenTelemetry context. # @param span [ OpenTelemetry::Trace::Span ] the current span. - def process_cursor_context(result, cursor_id, context, span) + # @param recording [ true | false ] whether the span is recording. + def process_cursor_context(result, cursor_id, context, span, recording) return unless result.is_a?(Cursor) if result.id.zero? @@ -159,7 +211,7 @@ def process_cursor_context(result, cursor_id, context, span) elsif result.id && cursor_id.nil? # New cursor created, store its context. cursor_context_map[result.id] = context - span.set_attribute('db.mongodb.cursor_id', result.id) + span.set_attribute('db.mongodb.cursor_id', result.id) if recording end end @@ -209,16 +261,16 @@ def collection_key_for_operation(operation) # Generates the span name for the operation. # - # @param operation [ Mongo::Operation ] the operation. - # @param op_name [ String | nil ] optional operation name. + # @param name [ String ] the operation name. + # @param db_name [ String ] the database name. + # @param coll_name [ String | nil ] the collection name, if any. # # @return [ String ] span name in format "operation_name db.collection" or "operation_name db". - def operation_span_name(operation, op_name = nil) - coll_name = collection_name(operation) + def operation_span_name(name, db_name, coll_name) if coll_name && !coll_name.empty? - "#{operation_name(operation, op_name)} #{operation.db_name}.#{coll_name}" + "#{name} #{db_name}.#{coll_name}" else - "#{operation_name(operation, op_name)} #{operation.db_name}" + "#{name} #{db_name}" end end end diff --git a/lib/mongo/tracing/open_telemetry/tracer.rb b/lib/mongo/tracing/open_telemetry/tracer.rb index 1def549e52..584df8b2ea 100644 --- a/lib/mongo/tracing/open_telemetry/tracer.rb +++ b/lib/mongo/tracing/open_telemetry/tracer.rb @@ -146,34 +146,20 @@ def cursor_context_map @cursor_context_map ||= {} end - # Generates a unique key for cursor tracking in the context map. - # - # @param session [ Mongo::Session ] the session associated with the cursor. - # @param cursor_id [ Integer ] the cursor ID. - # - # @return [ String | nil ] unique key combining session ID and cursor ID, or nil if either is nil. - def cursor_map_key(session, cursor_id) - return if cursor_id.nil? || session.nil? - - "#{session.session_id['id'].to_uuid}-#{cursor_id}" - end - # Determines the parent OpenTelemetry context for an operation. # - # Returns the transaction context if the operation is part of a transaction, - # otherwise returns nil. Cursor-based context nesting is not currently implemented. + # Returns the transaction context if the operation is part of a + # transaction, otherwise returns nil. Cursor operations deliberately + # have no parent here: a caller-driven getMore must not be nested + # under the span of the operation that created the cursor. # # @param operation_context [ Mongo::Operation::Context ] the operation context. - # @param cursor_id [ Integer ] the cursor ID, if applicable. # # @return [ OpenTelemetry::Context | nil ] parent context or nil. - def parent_context_for(operation_context, cursor_id) - if (key = transaction_map_key(operation_context.session)) - transaction_context_map[key] - elsif (_key = cursor_map_key(operation_context.session, cursor_id)) - # We return nil here unless we decide how to nest cursor operations. - nil - end + def parent_context_for(operation_context) + return unless (key = transaction_map_key(operation_context.session)) + + transaction_context_map[key] end # Returns the transaction context map for tracking active transaction contexts. @@ -200,6 +186,12 @@ def transaction_token_map # Generates a unique key for transaction tracking. # # Returns nil for implicit sessions or sessions not in a transaction. + # The key is invariant for the life of a transaction but is needed on + # every operation span created inside it, and formatting it (a UUID + # plus interpolation) showed the same per-call cost the lsid cache + # removed from the command path. It is memoized on the session, keyed + # by the transaction number, so each transaction formats it once. A + # benign race may format it twice; the results are identical. # # @param session [ Mongo::Session ] the session. # @@ -207,7 +199,13 @@ def transaction_token_map def transaction_map_key(session) return if session.nil? || session.implicit? || !session.in_transaction? - "#{session.session_id['id'].to_uuid}-#{session.txn_num}" + txn_num = session.txn_num + cached = session.instance_variable_get(:@otel_transaction_key) + return cached[1] if cached && cached[0] == txn_num + + key = "#{session.session_id['id'].to_uuid}-#{txn_num}" + session.instance_variable_set(:@otel_transaction_key, [ txn_num, key ].freeze) + key end private diff --git a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb index 28ac8b36fb..7d09d89847 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -18,9 +18,13 @@ id: 123, address: instance_double(Mongo::Address, host: 'localhost', port: 27_017), transport: :tcp, + # The connection's own description carries the id of this + # connection on the server; the server description comes + # from the monitoring connection and must not be used. + description: instance_double(Mongo::Server::Description, server_connection_id: 456), server: instance_double(Mongo::Server, description: instance_double(Mongo::Server::Description, - server_connection_id: 456))) + server_connection_id: 999))) end let(:message) do @@ -65,7 +69,11 @@ end describe '#trace_command' do - let(:span) { instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil) } + let(:span_context) { instance_double(OpenTelemetry::Trace::SpanContext, valid?: true) } + let(:span) do + instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: true, + context: span_context) + end let(:context) { instance_double(Mongo::Operation::Context) } let(:result) { instance_double(Mongo::Operation::Result, cursor_id: 0, successful?: true) } @@ -101,6 +109,137 @@ command_tracer.trace_command(message, operation_context, connection) { result } end + it 'passes only cheap attributes to start_span' do + expect(otel_tracer).to receive(:start_span).with( + 'find', + attributes: hash_excluding('db.query.summary', 'db.query.text', 'db.mongodb.lsid', + 'db.mongodb.cursor_id', 'db.mongodb.txn_number'), + kind: :client + ) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'sets deferred attributes when the span is recording' do + expect(span).to receive(:set_attribute).with('db.query.summary', 'find test_db.users') + expect(span).to receive(:set_attribute).with('db.mongodb.lsid', lsid_value) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + context 'with a non-recording span' do + let(:span) do + instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: false, + context: span_context) + end + + it 'does not build deferred attributes' do + expect(span).not_to receive(:set_attribute) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'still makes the span current, so that its context is propagated' do + expect(OpenTelemetry::Trace).to receive(:with_span).with(span).and_yield(span, context) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'does not record the cursor id from the reply' do + reply = instance_double(Mongo::Operation::Result, cursor_id: 789, successful?: true) + expect(span).not_to receive(:set_attribute) + command_tracer.trace_command(message, operation_context, connection) { reply } + end + + it 'does not record a failed reply' do + error = Mongo::Error::OperationFailure.new('error', nil, code: 42) + reply = instance_double(Mongo::Operation::Result, cursor_id: 0, successful?: false, error: error) + allow(reply).to receive(:validate!).and_raise(error) + expect(span).not_to receive(:set_attribute) + expect(span).not_to receive(:record_exception) + command_tracer.trace_command(message, operation_context, connection) { reply } + end + + it 'does not record a raised exception' do + error = Mongo::Error::OperationFailure.new('error', nil, code: 42) + expect(span).not_to receive(:set_attribute) + expect(span).not_to receive(:record_exception) + expect(span).not_to receive(:status=) + expect do + command_tracer.trace_command(message, operation_context, connection) { raise error } + end.to raise_error(error) + end + + it 'finishes the span' do + expect(span).to receive(:finish) + command_tracer.trace_command(message, operation_context, connection) { result } + end + end + + it 'memoizes connection attributes per connection' do + command_tracer.trace_command(message, operation_context, connection) { result } + command_tracer.trace_command(message, operation_context, connection) { result } + + attrs = connection.instance_variable_get(:@otel_connection_attributes) + expect(attrs).to be_frozen + end + + it 'extracts the command document once per command' do + count = 0 + allow(message).to receive(:documents) do + count += 1 + [ document ] + end + command_tracer.trace_command(message, operation_context, connection) { result } + expect(count).to eq(1) + end + + it 'formats the lsid UUID once across repeated commands' do + count = 0 + allow(document['lsid']['id']).to receive(:to_uuid) do + count += 1 + lsid_value + end + 3.times do + command_tracer.trace_command(message, operation_context, connection) { result } + end + expect(count).to eq(1) + end + + context 'with an invalid span (no SDK installed)' do + let(:invalid_span) { OpenTelemetry::Trace::Span::INVALID } + + before do + allow(otel_tracer).to receive(:start_span).and_return(invalid_span) + end + + it 'does not attach the span to the context' do + expect(OpenTelemetry::Trace).not_to receive(:with_span) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'returns the block result unchanged' do + return_value = command_tracer.trace_command(message, operation_context, connection) { :done } + expect(return_value).to eq(:done) + end + + it 'does not finish the span' do + expect(invalid_span).not_to receive(:finish) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'does not record a raised exception' do + error = StandardError.new('generic error') + expect(invalid_span).not_to receive(:record_exception) + expect do + command_tracer.trace_command(message, operation_context, connection) { raise error } + end.to raise_error(error) + end + + # Guards against an opentelemetry-api upgrade changing no-SDK semantics. + # If this fails, re-evaluate the short-circuit: it degrades to a no-op, + # correctness is unaffected. + it 'pins the API behavior: no-SDK spans have invalid contexts' do + expect(invalid_span.context.valid?).to be false + end + end + context 'when result has cursor_id' do let(:result) do instance_double(Mongo::Operation::Result, cursor_id: 789, successful?: true) @@ -288,7 +427,7 @@ end describe '#span_attributes' do - subject { command_tracer.send(:span_attributes, message, connection) } + subject { command_tracer.send(:span_attributes, document, 'find', connection) } it 'includes db.system.name' do expect(subject['db.system.name']).to eq('mongodb') @@ -306,8 +445,11 @@ expect(subject['db.command.name']).to eq('find') end - it 'includes db.query.summary' do - expect(subject['db.query.summary']).to eq('find test_db.users') + it 'excludes deferred attributes' do + %w[db.query.summary db.query.text db.mongodb.lsid db.mongodb.cursor_id + db.mongodb.txn_number].each do |key| + expect(subject).not_to have_key(key) + end end it 'includes server.port' do @@ -330,14 +472,33 @@ expect(subject['db.mongodb.driver_connection_id']).to eq(123) end - it 'includes db.mongodb.lsid' do - expect(subject['db.mongodb.lsid']).to eq(lsid_value) + context 'with an admin command without a collection' do + let(:document) { { 'serverStatus' => 1, '$db' => 'admin' } } + + it 'omits db.collection.name instead of setting nil' do + expect(subject).not_to have_key('db.collection.name') + end + end + end + + describe '#apply_deferred_attributes' do + let(:deferred_span) { instance_double(OpenTelemetry::Trace::Span, set_attribute: nil) } + + it 'sets the query summary' do + expect(deferred_span).to receive(:set_attribute).with('db.query.summary', 'find test_db.users') + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end - it 'does not include nil values' do - expect(subject).not_to have_key('db.mongodb.cursor_id') - expect(subject).not_to have_key('db.mongodb.txn_number') - expect(subject).not_to have_key('db.query.text') + it 'sets the lsid' do + expect(deferred_span).to receive(:set_attribute).with('db.mongodb.lsid', lsid_value) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) + end + + it 'skips attributes that are absent from the command' do + expect(deferred_span).not_to receive(:set_attribute).with('db.mongodb.cursor_id', anything) + expect(deferred_span).not_to receive(:set_attribute).with('db.mongodb.txn_number', anything) + expect(deferred_span).not_to receive(:set_attribute).with('db.query.text', anything) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end context 'with getMore command' do @@ -349,8 +510,9 @@ } end - it 'includes db.mongodb.cursor_id' do - expect(subject['db.mongodb.cursor_id']).to eq(999) + it 'sets the cursor id' do + expect(deferred_span).to receive(:set_attribute).with('db.mongodb.cursor_id', 999) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'getMore', document, 999) end end @@ -363,25 +525,27 @@ } end - it 'includes db.mongodb.txn_number' do - expect(subject['db.mongodb.txn_number']).to eq(42) + it 'sets the transaction number' do + expect(deferred_span).to receive(:set_attribute).with('db.mongodb.txn_number', 42) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end end context 'with query text enabled' do let(:query_text_max_length) { 1000 } - it 'includes db.query.text' do - expect(subject['db.query.text']).to be_a(String) - expect(subject['db.query.text']).to include('find') + it 'sets the query text' do + expect(deferred_span).to receive(:set_attribute).with('db.query.text', a_string_including('find')) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end end end describe '#collection_name' do - subject { command_tracer.send(:collection_name, message) } + subject { command_tracer.send(:collection_name, name, document) } context 'with find command' do + let(:name) { 'find' } let(:document) { { 'find' => 'users' } } it 'returns the collection name' do @@ -390,6 +554,7 @@ end context 'with getMore command' do + let(:name) { 'getMore' } let(:document) { { 'getMore' => 123, 'collection' => 'users' } } it 'returns the collection name' do @@ -398,6 +563,7 @@ end context 'with listCollections command' do + let(:name) { 'listCollections' } let(:document) { { 'listCollections' => 1 } } it 'returns nil' do @@ -406,6 +572,7 @@ end context 'with listDatabases command' do + let(:name) { 'listDatabases' } let(:document) { { 'listDatabases' => 1 } } it 'returns nil' do @@ -414,6 +581,7 @@ end context 'with commitTransaction command' do + let(:name) { 'commitTransaction' } let(:document) { { 'commitTransaction' => 1 } } it 'returns nil' do @@ -422,6 +590,7 @@ end context 'with abortTransaction command' do + let(:name) { 'abortTransaction' } let(:document) { { 'abortTransaction' => 1 } } it 'returns nil' do @@ -430,6 +599,7 @@ end context 'with admin command with numeric value' do + let(:name) { 'serverStatus' } let(:document) { { 'serverStatus' => 1 } } it 'returns nil' do @@ -439,7 +609,7 @@ end describe '#command_name' do - subject { command_tracer.send(:command_name, message) } + subject { command_tracer.send(:command_name, document) } let(:document) { { 'find' => 'users' } } @@ -449,7 +619,7 @@ end describe '#database' do - subject { command_tracer.send(:database, message) } + subject { command_tracer.send(:database, document) } let(:document) { { 'find' => 'users', '$db' => 'test_db' } } @@ -459,9 +629,9 @@ end describe '#query_summary' do - subject { command_tracer.send(:query_summary, message) } - context 'with collection name' do + subject { command_tracer.send(:query_summary, 'find', document) } + let(:document) { { 'find' => 'users', '$db' => 'test_db' } } it 'includes collection name' do @@ -470,6 +640,8 @@ end context 'without collection name' do + subject { command_tracer.send(:query_summary, 'listCollections', document) } + let(:document) { { 'listCollections' => 1, '$db' => 'test_db' } } it 'does not include collection name' do @@ -479,9 +651,9 @@ end describe '#cursor_id' do - subject { command_tracer.send(:cursor_id, message) } - context 'with getMore command' do + subject { command_tracer.send(:cursor_id, 'getMore', document) } + let(:document) { { 'getMore' => BSON::Int64.new(999) } } it 'returns the cursor ID' do @@ -490,6 +662,8 @@ end context 'with find command' do + subject { command_tracer.send(:cursor_id, 'find', document) } + let(:document) { { 'find' => 'users' } } it 'returns nil' do @@ -499,7 +673,7 @@ end describe '#lsid' do - subject { command_tracer.send(:lsid, message) } + subject { command_tracer.send(:lsid, document) } context 'with lsid present' do let(:document) { { 'find' => 'users', 'lsid' => { 'id' => BSON::Binary.from_uuid(lsid_value) } } } @@ -519,7 +693,7 @@ end describe '#txn_number' do - subject { command_tracer.send(:txn_number, message) } + subject { command_tracer.send(:txn_number, document) } context 'with txnNumber present' do let(:document) { { 'find' => 'users', 'txnNumber' => BSON::Int64.new(42) } } diff --git a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb index 0f7f6f2b00..655686830d 100644 --- a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb @@ -41,6 +41,8 @@ allow(s).to receive(:set_attribute) allow(s).to receive(:record_exception) allow(s).to receive(:status=) + allow(s).to receive(:context).and_return(double('SpanContext', valid?: true)) + allow(s).to receive(:recording?).and_return(true) end end let(:context) { double('OpenTelemetry::Context') } @@ -91,6 +93,102 @@ operation_tracer.trace_operation(operation, operation_context) { result } end + it 'passes only cheap attributes to start_span' do + expect(otel_tracer).to receive(:start_span).with( + anything, + attributes: hash_excluding('db.mongodb.cursor_id'), + with_parent: nil, + kind: :client + ) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'sets the cursor id after span creation when recording' do + operation = instance_double( + Mongo::Operation::GetMore, + db_name: 'test_db', + coll_name: 'test_collection', + cursor_id: 12_345, + class: class_double(Mongo::Operation::GetMore, name: 'Mongo::Operation::GetMore'), + respond_to?: true + ) + expect(span).to receive(:set_attribute).with('db.mongodb.cursor_id', 12_345) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + context 'with a non-recording span' do + before do + allow(span).to receive(:recording?).and_return(false) + end + + it 'does not set attributes' do + expect(span).not_to receive(:set_attribute) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'still makes the span current, so that commands nest under it' do + expect(OpenTelemetry::Trace).to receive(:with_span).with(span).and_yield(span, context) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'does not record the cursor id of a new cursor' do + cursor = instance_double(Mongo::Cursor, id: 12_345) + allow(cursor).to receive(:is_a?).with(Mongo::Cursor).and_return(true) + expect(span).not_to receive(:set_attribute) + operation_tracer.trace_operation(operation, operation_context) { cursor } + end + + it 'does not record a raised exception' do + error = StandardError.new('test error') + expect(span).not_to receive(:record_exception) + expect(span).not_to receive(:status=) + expect do + operation_tracer.trace_operation(operation, operation_context) { raise error } + end.to raise_error(error) + end + + it 'finishes the span' do + expect(span).to receive(:finish) + operation_tracer.trace_operation(operation, operation_context) { result } + end + end + + context 'with an invalid span (no SDK installed)' do + let(:invalid_span) { OpenTelemetry::Trace::Span::INVALID } + + before do + allow(otel_tracer).to receive(:start_span).and_return(invalid_span) + end + + it 'does not attach the span to the context' do + expect(OpenTelemetry::Trace).not_to receive(:with_span) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'returns the block result unchanged' do + return_value = operation_tracer.trace_operation(operation, operation_context) { :done } + expect(return_value).to eq(:done) + end + + it 'leaves the cursor context map untouched' do + operation_tracer.trace_operation(operation, operation_context) { result } + expect(cursor_context_map).to be_empty + end + + it 'does not finish the span' do + expect(invalid_span).not_to receive(:finish) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'does not record a raised exception' do + error = StandardError.new('test error') + expect(invalid_span).not_to receive(:record_exception) + expect do + operation_tracer.trace_operation(operation, operation_context) { raise error } + end.to raise_error(error) + end + end + context 'with custom operation name' do it 'uses the provided op_name' do expect(otel_tracer).to receive(:start_span).with( @@ -176,8 +274,11 @@ expect(cursor_context_map).not_to have_key(cursor_id) end - it 'does not set cursor_id attribute' do - expect(span).not_to receive(:set_attribute).with('db.mongodb.cursor_id', anything) + it 'does not set a new cursor_id attribute' do + # The span carries the operation's own cursor id (set after span + # creation, deferred behind recording?); the closed result must not + # add another. + expect(span).to receive(:set_attribute).with('db.mongodb.cursor_id', 999).once operation_tracer.trace_operation(operation, operation_context) { cursor } end end @@ -218,18 +319,19 @@ end describe '#span_attributes' do - subject(:attributes) { operation_tracer.send(:span_attributes, operation, op_name) } + subject(:attributes) do + operation_tracer.send(:span_attributes, operation, name, span_name, coll_name) + end - let(:op_name) { nil } + let(:name) { 'find' } + let(:span_name) { 'find test_db.users' } + let(:coll_name) { 'users' } let(:operation_class) { class_double(Mongo::Operation::Find, name: 'Mongo::Operation::Find') } let(:operation) do instance_double( Mongo::Operation::Find, db_name: 'test_db', - coll_name: 'users', - cursor_id: nil, - class: operation_class, - respond_to?: true + class: operation_class ) end @@ -253,32 +355,22 @@ expect(attributes['db.operation.summary']).to eq('find test_db.users') end - it 'does not include nil values' do + it 'never includes the cursor id' do expect(attributes).not_to have_key('db.mongodb.cursor_id') end - context 'with cursor_id' do - let(:operation_class) { class_double(Mongo::Operation::GetMore, name: 'Mongo::Operation::GetMore') } - let(:operation) do - instance_double( - Mongo::Operation::GetMore, - db_name: 'test_db', - coll_name: 'users', - cursor_id: 12_345, - class: operation_class, - respond_to?: true - ) - end + context 'without a collection name' do + let(:coll_name) { nil } - it 'includes db.mongodb.cursor_id' do - expect(attributes['db.mongodb.cursor_id']).to eq(12_345) + it 'omits db.collection.name instead of setting nil' do + expect(attributes).not_to have_key('db.collection.name') end end - context 'with custom op_name' do - let(:op_name) { 'custom_operation' } + context 'with custom operation name' do + let(:name) { 'custom_operation' } - it 'uses the custom op_name' do + it 'uses the custom operation name' do expect(attributes['db.operation.name']).to eq('custom_operation') end end @@ -297,6 +389,15 @@ expect(op_name_result).to eq('find') end + it 'memoizes the operation name per operation class' do + operation_tracer.send(:operation_name, operation, nil) + operation_tracer.send(:operation_name, operation, nil) + + cache = operation_tracer.instance_variable_get(:@operation_names) + expect(cache.size).to eq(1) + expect(cache.values.first).to eq('find') + end + context 'with custom op_name' do let(:op_name) { 'CustomOperation' } @@ -496,21 +597,8 @@ end describe '#operation_span_name' do - subject(:span_name) { operation_tracer.send(:operation_span_name, operation, op_name) } - - let(:op_name) { nil } - context 'with collection name' do - let(:operation_class) { class_double(Mongo::Operation::Find, name: 'Mongo::Operation::Find') } - let(:operation) do - instance_double( - Mongo::Operation::Find, - db_name: 'test_db', - coll_name: 'users', - class: operation_class, - respond_to?: true - ) - end + subject(:span_name) { operation_tracer.send(:operation_span_name, 'find', 'test_db', 'users') } it 'includes collection name in format' do expect(span_name).to eq('find test_db.users') @@ -518,22 +606,7 @@ end context 'without collection name' do - let(:operation_class) do - class_double(Mongo::Operation::ListCollections, name: 'Mongo::Operation::ListCollections') - end - let(:operation) do - instance_double( - Mongo::Operation::ListCollections, - db_name: 'test_db', - coll_name: nil, - class: operation_class, - respond_to?: true - ) - end - - before do - allow(operation).to receive(:is_a?).and_return(false) - end + subject(:span_name) { operation_tracer.send(:operation_span_name, 'listcollections', 'test_db', nil) } it 'excludes collection name from format' do expect(span_name).to eq('listcollections test_db') @@ -541,16 +614,7 @@ end context 'with empty collection name' do - let(:operation_class) { class_double(Mongo::Operation::Command, name: 'Mongo::Operation::Command') } - let(:operation) do - instance_double( - Mongo::Operation::Command, - db_name: 'test_db', - coll_name: '', - class: operation_class, - respond_to?: true - ) - end + subject(:span_name) { operation_tracer.send(:operation_span_name, 'command', 'test_db', '') } it 'excludes collection name from format' do expect(span_name).to eq('command test_db') @@ -560,7 +624,7 @@ describe '#process_cursor_context' do subject(:process_result) do - operation_tracer.send(:process_cursor_context, result, cursor_id, context, span) + operation_tracer.send(:process_cursor_context, result, cursor_id, context, span, true) end # rubocop:disable RSpec/VerifiedDoubles diff --git a/spec/mongo/tracing/open_telemetry/tracer_spec.rb b/spec/mongo/tracing/open_telemetry/tracer_spec.rb new file mode 100644 index 0000000000..ddc877ccf6 --- /dev/null +++ b/spec/mongo/tracing/open_telemetry/tracer_spec.rb @@ -0,0 +1,92 @@ +# frozen_string_literal: true + +require 'spec_helper' + +require 'opentelemetry' + +describe Mongo::Tracing::OpenTelemetry::Tracer do + let(:otel_tracer) { double('OpenTelemetry::Trace::Tracer') } + let(:tracer) { described_class.new(enabled: true, otel_tracer: otel_tracer) } + + let(:session_uuid) { 'de124f0e-b9a8-4bfc-8f4e-6d9c8f0a3c1d' } + let(:session_id_binary) { double('BSON::Binary', to_uuid: session_uuid) } + let(:session) do + instance_double( + Mongo::Session, + implicit?: false, + in_transaction?: true, + txn_num: 42, + session_id: { 'id' => session_id_binary } + ) + end + + describe '#transaction_map_key' do + context 'when the session is nil' do + it 'returns nil' do + expect(tracer.transaction_map_key(nil)).to be_nil + end + end + + context 'when the session is implicit' do + let(:session) { instance_double(Mongo::Session, implicit?: true) } + + it 'returns nil' do + expect(tracer.transaction_map_key(session)).to be_nil + end + end + + context 'when the session is not in a transaction' do + let(:session) { instance_double(Mongo::Session, implicit?: false, in_transaction?: false) } + + it 'returns nil' do + expect(tracer.transaction_map_key(session)).to be_nil + end + end + + context 'when the session is in a transaction' do + it 'combines the session UUID and the transaction number' do + expect(tracer.transaction_map_key(session)).to eq("#{session_uuid}-42") + end + + it 'formats the session UUID once across repeated calls' do + expect(session_id_binary).to receive(:to_uuid).once.and_return(session_uuid) + + 3.times { tracer.transaction_map_key(session) } + end + + it 'computes a new key when the transaction number changes' do + expect(tracer.transaction_map_key(session)).to eq("#{session_uuid}-42") + + allow(session).to receive(:txn_num).and_return(43) + expect(tracer.transaction_map_key(session)).to eq("#{session_uuid}-43") + end + end + end + + describe '#parent_context_for' do + let(:operation_context) { instance_double(Mongo::Operation::Context, session: session) } + + context 'when the session is in a transaction' do + it 'returns the transaction context' do + context = double('OpenTelemetry::Context') + tracer.transaction_context_map["#{session_uuid}-42"] = context + + expect(tracer.parent_context_for(operation_context)).to eq(context) + end + + it 'returns nil when the transaction has no stored context' do + expect(tracer.parent_context_for(operation_context)).to be_nil + end + end + + context 'when the session is not in a transaction' do + let(:session) { instance_double(Mongo::Session, implicit?: true) } + + it 'returns nil without formatting a session key' do + expect(session).not_to receive(:session_id) + + expect(tracer.parent_context_for(operation_context)).to be_nil + end + end + end +end diff --git a/spec/support/tracing.rb b/spec/support/tracing.rb index 6eb96801da..36befc8df9 100644 --- a/spec/support/tracing.rb +++ b/spec/support/tracing.rb @@ -22,6 +22,17 @@ def set_attribute(key, value) @attributes[key] = value end + # Mirrors the OpenTelemetry Span API: these spans always record, so the + # driver's deferred-attribute path runs and the assertions see the + # attributes. + def recording? + true + end + + def context + @context ||= Context.new(self) + end + # rubocop:disable Lint/UnusedMethodArgument def record_exception(exception, attributes: nil) set_attribute('exception.type', exception.class.to_s) @@ -53,6 +64,10 @@ class Context def initialize(span) @span = span end + + def valid? + true + end end class Tracer