diff --git a/lib/mongo/server/connection.rb b/lib/mongo/server/connection.rb index bfb822a903..11d579bd62 100644 --- a/lib/mongo/server/connection.rb +++ b/lib/mongo/server/connection.rb @@ -124,6 +124,13 @@ def initialize(server, options = {}) # across all connections. attr_reader :global_id + # @return [ Hash | nil ] OpenTelemetry span attributes describing this + # connection. Built once by the tracer and reused for every command + # on the connection. + # + # @api private + attr_accessor :tracing_attributes + def_delegators :server, :tracer # The connection pool from which this connection was created. diff --git a/lib/mongo/session.rb b/lib/mongo/session.rb index 1ed626e7fe..14957c933e 100644 --- a/lib/mongo/session.rb +++ b/lib/mongo/session.rb @@ -297,6 +297,13 @@ def session_id # @api private attr_accessor :recovery_token + # @return [ Array | nil ] The transaction number and the + # OpenTelemetry tracer's key for that transaction. Built once by the + # tracer and reused for every operation in the transaction. + # + # @api private + attr_accessor :tracing_transaction_key + # Error message indicating that the session was retrieved from a client with a different cluster than that of the # client through which it is currently being used. # diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 9e32573f0e..bead889f10 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -30,6 +30,9 @@ class CommandTracer # would only add noise to traces. HELLO_COMMANDS = %w[hello ismaster isMaster].freeze + # Upper bound of the lsid string cache (see #lsid). + LSID_CACHE_MAX = 128 + # Initializes a new CommandTracer. # # @param otel_tracer [ OpenTelemetry::Trace::Tracer ] the OpenTelemetry tracer. @@ -41,6 +44,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. @@ -196,19 +201,21 @@ def apply_deferred_attributes(span, message) end end - # Returns connection-related attributes. + # 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. # # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ Hash ] connection span attributes. 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.server.description.server_connection_id, 'db.mongodb.driver_connection_id' => connection.id - } + }.freeze end # Processes cursor context from the command result. @@ -317,16 +324,28 @@ def cursor_id(message) message.documents.first['getMore'].value end - # Extracts the logical session ID from the command. + # 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. # # @param message [ Mongo::Protocol::Message ] the command message. # - # @return [ BSON::Binary | nil ] the session ID, or nil if not present. + # @return [ String | nil ] the session ID, or nil if not present. def lsid(message) lsid_doc = message.documents.first['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. diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index 7eef6c2209..3179f66f60 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. @@ -136,13 +138,21 @@ def handle_span_exception(span, exception) end # Returns the operation name from the provided name or operation class. + # The name derived from the class is cached per class. There are few + # operation classes, so the cache needs no bound. It is guarded by a + # mutex because not every Ruby runtime makes Hash writes thread-safe. # # @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 the attributes passed at span creation. The cursor id is set diff --git a/lib/mongo/tracing/open_telemetry/tracer.rb b/lib/mongo/tracing/open_telemetry/tracer.rb index 1def549e52..57dbb966f4 100644 --- a/lib/mongo/tracing/open_telemetry/tracer.rb +++ b/lib/mongo/tracing/open_telemetry/tracer.rb @@ -200,6 +200,9 @@ def transaction_token_map # Generates a unique key for transaction tracking. # # Returns nil for implicit sessions or sessions not in a transaction. + # Every operation in a transaction needs the key, so it is cached on + # the session together with the transaction number it was built for. + # Two threads may build it at the same time; they build the same key. # # @param session [ Mongo::Session ] the session. # @@ -207,7 +210,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.tracing_transaction_key + return cached[1] if cached && cached[0] == txn_num + + key = "#{session.session_id['id'].to_uuid}-#{txn_num}" + session.tracing_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 45580e662c..e24b01d9af 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -18,9 +18,15 @@ id: 123, address: instance_double(Mongo::Address, host: 'localhost', port: 27_017), transport: :tcp, + tracing_attributes: nil, server: instance_double(Mongo::Server, description: instance_double(Mongo::Server::Description, - server_connection_id: 456))) + server_connection_id: 456))).tap do |conn| + # Behaves like the real accessor: what the tracer stores, it reads back. + allow(conn).to receive(:tracing_attributes=) do |attrs| + allow(conn).to receive(:tracing_attributes).and_return(attrs) + end + end end let(:message) do @@ -94,6 +100,33 @@ command_tracer.trace_command(message, operation_context, connection) { result } end + it 'builds the connection attributes once per connection' do + address = instance_double(Mongo::Address, host: 'localhost', port: 27_017) + expect(connection).to receive(:address).twice.and_return(address) + 3.times do + command_tracer.trace_command(message, operation_context, connection) { result } + end + end + + it 'stores the connection attributes on the connection, frozen' do + command_tracer.trace_command(message, operation_context, connection) { result } + + expect(connection.tracing_attributes).to be_frozen + expect(connection.tracing_attributes['db.mongodb.driver_connection_id']).to eq(123) + end + + it 'formats the lsid 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 + # A span the sampler dropped is still made current, so that its context # is propagated and nested spans stay nested, but gets nothing else. context 'with a span that is not recording' do diff --git a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb index 8b9392ca57..6bb1a62ee0 100644 --- a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb @@ -390,6 +390,11 @@ expect(op_name_result).to eq('find') end + it 'derives the name once per operation class' do + expect(operation_class).to receive(:name).once.and_return('Mongo::Operation::Find') + 3.times { operation_tracer.send(:operation_name, operation, nil) } + end + context 'with custom op_name' do let(:op_name) { 'CustomOperation' } 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..0dddc2d9df --- /dev/null +++ b/spec/mongo/tracing/open_telemetry/tracer_spec.rb @@ -0,0 +1,71 @@ +# 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 }, + tracing_transaction_key: nil + ).tap do |s| + # Behaves like the real accessor: what the tracer stores, it reads back. + allow(s).to receive(:tracing_transaction_key=) do |value| + allow(s).to receive(:tracing_transaction_key).and_return(value) + end + end + 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 +end