mongo 2.26.0 → 2.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/lib/mongo/address/validator.rb +14 -9
  3. data/lib/mongo/auth.rb +8 -3
  4. data/lib/mongo/client.rb +40 -9
  5. data/lib/mongo/client_encryption.rb +47 -1
  6. data/lib/mongo/cluster/topology.rb +3 -3
  7. data/lib/mongo/collection/view/aggregation.rb +9 -9
  8. data/lib/mongo/collection/view/change_stream.rb +1 -5
  9. data/lib/mongo/collection/view/iterable.rb +2 -9
  10. data/lib/mongo/collection/view/map_reduce.rb +5 -4
  11. data/lib/mongo/collection/view/readable.rb +3 -3
  12. data/lib/mongo/crypt/auto_encrypter.rb +15 -1
  13. data/lib/mongo/crypt/context.rb +30 -4
  14. data/lib/mongo/crypt/encryption_io.rb +103 -17
  15. data/lib/mongo/crypt/explicit_encrypter.rb +6 -2
  16. data/lib/mongo/csot_timeout_holder.rb +5 -2
  17. data/lib/mongo/cursor.rb +13 -0
  18. data/lib/mongo/database/view.rb +7 -6
  19. data/lib/mongo/database.rb +7 -10
  20. data/lib/mongo/error/invalid_read_option.rb +9 -2
  21. data/lib/mongo/error/invalid_uri.rb +14 -6
  22. data/lib/mongo/index/view.rb +3 -2
  23. data/lib/mongo/monitoring/event/secure.rb +6 -1
  24. data/lib/mongo/operation/map_reduce/result.rb +6 -2
  25. data/lib/mongo/operation/shared/result/aggregatable.rb +3 -3
  26. data/lib/mongo/options/redacted.rb +230 -30
  27. data/lib/mongo/protocol/serializers.rb +1 -9
  28. data/lib/mongo/server/app_metadata.rb +1 -2
  29. data/lib/mongo/server/connection.rb +7 -0
  30. data/lib/mongo/server/connection_pool.rb +60 -9
  31. data/lib/mongo/session.rb +7 -0
  32. data/lib/mongo/socket/ssl.rb +32 -6
  33. data/lib/mongo/srv/resolver.rb +38 -6
  34. data/lib/mongo/srv/result.rb +8 -6
  35. data/lib/mongo/tracing/open_telemetry/command_tracer.rb +142 -103
  36. data/lib/mongo/tracing/open_telemetry/operation_tracer.rb +56 -32
  37. data/lib/mongo/tracing/open_telemetry/tracer.rb +16 -30
  38. data/lib/mongo/uri/options_mapper.rb +44 -22
  39. data/lib/mongo/uri/srv_protocol.rb +18 -11
  40. data/lib/mongo/uri.rb +174 -41
  41. data/lib/mongo/version.rb +1 -1
  42. metadata +545 -537
@@ -23,12 +23,8 @@ module Mongo
23
23
  class CommandTracer
24
24
  include Mongo::Monitoring::Event::Secure
25
25
 
26
- # Commands for which a span MUST NOT be created. The OpenTelemetry spec
27
- # requires drivers to skip command spans for sensitive commands listed in
28
- # the Command Logging and Monitoring spec. We additionally skip hello /
29
- # legacy hello in all forms — these are handshake/heartbeat traffic and
30
- # would only add noise to traces.
31
- HELLO_COMMANDS = %w[hello ismaster isMaster].freeze
26
+ # Upper bound of the lsid string cache (see #lsid).
27
+ LSID_CACHE_MAX = 128
32
28
 
33
29
  # Initializes a new CommandTracer.
34
30
  #
@@ -41,6 +37,8 @@ module Mongo
41
37
  @otel_tracer = otel_tracer
42
38
  @parent_tracer = parent_tracer
43
39
  @query_text_max_length = query_text_max_length
40
+ @lsid_cache = {}
41
+ @lsid_cache_mutex = Mutex.new
44
42
  end
45
43
 
46
44
  # Starts a span for a MongoDB command.
@@ -64,55 +62,84 @@ module Mongo
64
62
  # @yield the block representing the command to be traced.
65
63
  #
66
64
  # @return [ Object ] the result of the command.
67
- # rubocop:disable Lint/RescueException
68
- def trace_command(message, _operation_context, connection)
69
- return yield if skip_tracing?(message)
65
+ def trace_command(message, _operation_context, connection, &block)
66
+ # Read the command document and name once and pass them on: every
67
+ # read of message.documents allocates.
68
+ doc = message.documents.first
69
+ name = command_name(doc)
70
+ return yield if skip_tracing?(doc, name)
70
71
 
71
72
  # Commands should always be nested under their operation span, not directly under
72
73
  # the transaction span. Don't pass with_parent to use automatic parent resolution
73
74
  # from the currently active span (the operation span).
74
- span = create_command_span(message, connection)
75
- ::OpenTelemetry::Trace.with_span(span) do |s, c|
75
+ span = create_command_span(name, doc, connection)
76
+ # With no SDK and no valid parent, the API returns a span with an
77
+ # invalid context. It cannot be made current, recorded or
78
+ # propagated, so it gets no work at all, not even finishing it.
79
+ return yield unless span.context.valid?
80
+
81
+ trace_with_span(span, message, name, doc, &block)
82
+ end
83
+
84
+ private
85
+
86
+ # Runs the command with the span made current, and finishes the span.
87
+ # A span that is not recording is still made current, so that its
88
+ # context is propagated, but gets no further attributes and no
89
+ # outcome: the SDK would discard them.
90
+ #
91
+ # @param span [ OpenTelemetry::Trace::Span ] a span with a valid context.
92
+ # @param message [ Mongo::Protocol::Message ] the command message.
93
+ # @param name [ String ] the command name.
94
+ # @param doc [ Hash ] the command document.
95
+ #
96
+ # @return [ Object ] the result of the command.
97
+ #
98
+ # rubocop:disable Lint/RescueException
99
+ def trace_with_span(span, message, name, doc)
100
+ recording = span.recording?
101
+ apply_deferred_attributes(span, message, name, doc) if recording
102
+ ::OpenTelemetry::Trace.with_span(span) do |s, _c|
76
103
  yield.tap do |result|
77
- process_command_result(result, cursor_id(message), c, s)
104
+ process_command_result(result, s) if recording
78
105
  end
79
106
  end
80
107
  rescue Exception => e
81
- handle_command_exception(span, e)
108
+ handle_command_exception(span, e) if recording
82
109
  raise e
83
110
  ensure
84
- span&.finish
111
+ span.finish
85
112
  end
86
113
  # rubocop:enable Lint/RescueException
87
114
 
88
- private
89
-
90
115
  # Determines whether the command must not be traced. Sensitive auth
91
116
  # commands carry credentials in their payloads (SCRAM proofs, cleartext
92
117
  # passwords, etc.) and the OpenTelemetry spec requires drivers to skip
93
- # command spans for them. Hello / legacy hello are also skipped to keep
94
- # handshake traffic out of traces.
118
+ # command spans for them. Hello / legacy hello in all forms
119
+ # (Secure::HELLO_COMMANDS) are also skipped: they are handshake and
120
+ # heartbeat traffic and would only add noise to traces.
95
121
  #
96
- # @param message [ Mongo::Protocol::Message ] the command message.
122
+ # @param doc [ Hash ] the command document.
123
+ # @param name [ String ] the command name.
97
124
  #
98
125
  # @return [ Boolean ] true when no command span should be created.
99
- def skip_tracing?(message)
100
- name = command_name(message)
126
+ def skip_tracing?(doc, name)
101
127
  return true if HELLO_COMMANDS.include?(name)
102
128
 
103
- sensitive?(command_name: name, document: message.documents.first)
129
+ sensitive?(command_name: name, document: doc)
104
130
  end
105
131
 
106
132
  # Creates a span for a command.
107
133
  #
108
- # @param message [ Mongo::Protocol::Message ] the command message.
134
+ # @param name [ String ] the command name.
135
+ # @param doc [ Hash ] the command document.
109
136
  # @param connection [ Mongo::Server::Connection ] the connection.
110
137
  #
111
138
  # @return [ OpenTelemetry::Trace::Span ] the created span.
112
- def create_command_span(message, connection)
139
+ def create_command_span(name, doc, connection)
113
140
  @otel_tracer.start_span(
114
- command_name(message),
115
- attributes: span_attributes(message, connection),
141
+ name,
142
+ attributes: span_attributes(doc, name, connection),
116
143
  kind: :client
117
144
  )
118
145
  end
@@ -120,21 +147,17 @@ module Mongo
120
147
  # Processes the command result and updates span attributes.
121
148
  #
122
149
  # @param result [ Object ] the command result.
123
- # @param cursor_id [ Integer | nil ] the cursor ID.
124
- # @param context [ OpenTelemetry::Context ] the context.
125
150
  # @param span [ OpenTelemetry::Trace::Span ] the current span.
126
- def process_command_result(result, cursor_id, context, span)
127
- process_cursor_context(result, cursor_id, context, span)
151
+ def process_command_result(result, span)
152
+ process_cursor_context(result, span)
128
153
  maybe_trace_error(result, span)
129
154
  end
130
155
 
131
156
  # Handles exceptions that occur during command execution.
132
157
  #
133
- # @param span [ OpenTelemetry::Trace::Span | nil ] the span.
158
+ # @param span [ OpenTelemetry::Trace::Span ] the span.
134
159
  # @param exception [ Exception ] the exception that occurred.
135
160
  def handle_command_exception(span, exception)
136
- return unless span
137
-
138
161
  if exception.is_a?(Mongo::Error::OperationFailure)
139
162
  span.set_attribute('db.response.status_code', exception.code.to_s)
140
163
  end
@@ -142,70 +165,68 @@ module Mongo
142
165
  span.status = ::OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{exception.class}")
143
166
  end
144
167
 
145
- # Builds span attributes for the command.
168
+ # Builds the attributes passed at span creation: the cheap set the
169
+ # OpenTelemetry spec recommends. They are built for every span,
170
+ # recorded or not, and are the only ones the sampler sees. The rest
171
+ # are set by apply_deferred_attributes once the span is known to
172
+ # record.
146
173
  #
147
- # @param message [ Mongo::Protocol::Message ] the command message.
174
+ # @param doc [ Hash ] the command document.
175
+ # @param name [ String ] the command name.
148
176
  # @param connection [ Mongo::Server::Connection ] the connection.
149
177
  #
150
178
  # @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions.
151
- def span_attributes(message, connection)
152
- base_attributes(message)
153
- .merge(connection_attributes(connection))
154
- .merge(session_attributes(message))
155
- .compact
179
+ def span_attributes(doc, name, connection)
180
+ {
181
+ 'db.system.name' => 'mongodb',
182
+ 'db.namespace' => database(doc),
183
+ 'db.collection.name' => collection_name(name, doc),
184
+ 'db.command.name' => name
185
+ }.compact.merge(connection_attributes(connection))
156
186
  end
157
187
 
158
- # Returns base database and command attributes.
188
+ # Sets the remaining attributes on a span that is recording. They are
189
+ # not visible to the sampler; only custom samplers keying on them are
190
+ # affected.
159
191
  #
192
+ # @param span [ OpenTelemetry::Trace::Span ] the span.
160
193
  # @param message [ Mongo::Protocol::Message ] the command message.
161
- #
162
- # @return [ Hash ] base span attributes.
163
- def base_attributes(message)
194
+ # @param name [ String ] the command name.
195
+ # @param doc [ Hash ] the command document.
196
+ def apply_deferred_attributes(span, message, name, doc)
164
197
  {
165
- 'db.system.name' => 'mongodb',
166
- 'db.namespace' => database(message),
167
- 'db.collection.name' => collection_name(message),
168
- 'db.command.name' => command_name(message),
169
- 'db.query.summary' => query_summary(message),
170
- 'db.query.text' => query_text(message)
171
- }
198
+ 'db.query.summary' => query_summary(name, doc),
199
+ 'db.query.text' => query_text(message),
200
+ 'db.mongodb.cursor_id' => cursor_id(name, doc),
201
+ 'db.mongodb.lsid' => lsid(doc),
202
+ 'db.mongodb.txn_number' => txn_number(doc)
203
+ }.each do |key, value|
204
+ span.set_attribute(key, value) unless value.nil?
205
+ end
172
206
  end
173
207
 
174
- # Returns connection-related attributes.
208
+ # Returns connection-related attributes, built once per connection,
209
+ # frozen and kept on the connection. Two threads may build them at
210
+ # the same time; they build the same hash, so either result is fine.
175
211
  #
176
212
  # @param connection [ Mongo::Server::Connection ] the connection.
177
213
  #
178
214
  # @return [ Hash ] connection span attributes.
179
215
  def connection_attributes(connection)
180
- {
216
+ connection.tracing_attributes ||= {
181
217
  'server.port' => connection.address.port,
182
218
  'server.address' => connection.address.host,
183
219
  'network.transport' => connection.transport.to_s,
184
- 'db.mongodb.server_connection_id' => connection.server.description.server_connection_id,
220
+ 'db.mongodb.server_connection_id' => connection.description.server_connection_id,
185
221
  'db.mongodb.driver_connection_id' => connection.id
186
- }
187
- end
188
-
189
- # Returns session and transaction attributes.
190
- #
191
- # @param message [ Mongo::Protocol::Message ] the command message.
192
- #
193
- # @return [ Hash ] session span attributes.
194
- def session_attributes(message)
195
- {
196
- 'db.mongodb.cursor_id' => cursor_id(message),
197
- 'db.mongodb.lsid' => lsid(message),
198
- 'db.mongodb.txn_number' => txn_number(message)
199
- }
222
+ }.freeze
200
223
  end
201
224
 
202
225
  # Processes cursor context from the command result.
203
226
  #
204
227
  # @param result [ Object ] the command result.
205
- # @param _cursor_id [ Integer | nil ] the cursor ID (unused).
206
- # @param _context [ OpenTelemetry::Context ] the context (unused).
207
228
  # @param span [ OpenTelemetry::Trace::Span ] the current span.
208
- def process_cursor_context(result, _cursor_id, _context, span)
229
+ def process_cursor_context(result, span)
209
230
  cursor_id = normalize_cursor_id(result.cursor_id)
210
231
  return unless cursor_id.positive?
211
232
 
@@ -242,51 +263,56 @@ module Mongo
242
263
 
243
264
  # Generates a summary string for the query.
244
265
  #
245
- # @param message [ Mongo::Protocol::Message ] the command message.
266
+ # @param name [ String ] the command name.
267
+ # @param doc [ Hash ] the command document.
246
268
  #
247
269
  # @return [ String ] summary in format "command_name db.collection" or "command_name db".
248
- def query_summary(message)
249
- if (coll_name = collection_name(message))
250
- "#{command_name(message)} #{database(message)}.#{coll_name}"
270
+ def query_summary(name, doc)
271
+ if (coll_name = collection_name(name, doc))
272
+ "#{name} #{database(doc)}.#{coll_name}"
251
273
  else
252
- "#{command_name(message)} #{database(message)}"
274
+ "#{name} #{database(doc)}"
253
275
  end
254
276
  end
255
277
 
256
- # Extracts the collection name from the command message.
278
+ # Extracts the collection name from the command document.
257
279
  #
258
- # @param message [ Mongo::Protocol::Message ] the command message.
280
+ # @param name [ String ] the command name.
281
+ # @param doc [ Hash ] the command document.
259
282
  #
260
283
  # @return [ String | nil ] the collection name, or nil if not applicable.
261
- def collection_name(message)
262
- case command_name(message)
284
+ def collection_name(name, doc)
285
+ case name
263
286
  when 'getMore'
264
- message.documents.first['collection'].to_s
287
+ doc['collection'].to_s
265
288
  when 'listCollections', 'listDatabases', 'commitTransaction', 'abortTransaction'
266
289
  nil
267
290
  else
268
- value = message.documents.first.values.first
291
+ # The first value, read without building an array of all of them.
292
+ value = doc.each_value { |v| break v } # rubocop:disable Lint/UnreachableLoop -- first value only
269
293
  # Return nil if the value is not a string (e.g., for admin commands that have numeric values)
270
294
  value.is_a?(String) ? value : nil
271
295
  end
272
296
  end
273
297
 
274
- # Extracts the command name from the message.
298
+ # Extracts the command name, the first key of the command document,
299
+ # without building an array of all keys.
275
300
  #
276
- # @param message [ Mongo::Protocol::Message ] the command message.
301
+ # @param doc [ Hash ] the command document.
277
302
  #
278
303
  # @return [ String ] the command name.
279
- def command_name(message)
280
- message.documents.first.keys.first.to_s
304
+ def command_name(doc)
305
+ doc.each_key { |key| return key.to_s } # rubocop:disable Lint/UnreachableLoop -- first key only
306
+ ''
281
307
  end
282
308
 
283
- # Extracts the database name from the message.
309
+ # Extracts the database name from the command document.
284
310
  #
285
- # @param message [ Mongo::Protocol::Message ] the command message.
311
+ # @param doc [ Hash ] the command document.
286
312
  #
287
313
  # @return [ String ] the database name.
288
- def database(message)
289
- message.documents.first['$db'].to_s
314
+ def database(doc)
315
+ doc['$db'].to_s
290
316
  end
291
317
 
292
318
  # Checks if query text capture is enabled.
@@ -298,34 +324,47 @@ module Mongo
298
324
 
299
325
  # Extracts the cursor ID from getMore commands.
300
326
  #
301
- # @param message [ Mongo::Protocol::Message ] the command message.
327
+ # @param name [ String ] the command name.
328
+ # @param doc [ Hash ] the command document.
302
329
  #
303
330
  # @return [ Integer | nil ] the cursor ID, or nil if not a getMore command.
304
- def cursor_id(message)
305
- return unless command_name(message) == 'getMore'
331
+ def cursor_id(name, doc)
332
+ return unless name == 'getMore'
306
333
 
307
- message.documents.first['getMore'].value
334
+ doc['getMore'].value
308
335
  end
309
336
 
310
- # Extracts the logical session ID from the command.
337
+ # Extracts the logical session ID from the command, as a UUID string.
338
+ # The string is formatted once per session id and kept in a small
339
+ # cache, cleared when it reaches LSID_CACHE_MAX entries.
311
340
  #
312
- # @param message [ Mongo::Protocol::Message ] the command message.
341
+ # @param doc [ Hash ] the command document.
313
342
  #
314
- # @return [ BSON::Binary | nil ] the session ID, or nil if not present.
315
- def lsid(message)
316
- lsid_doc = message.documents.first['lsid']
343
+ # @return [ String | nil ] the session ID, or nil if not present.
344
+ def lsid(doc)
345
+ lsid_doc = doc['lsid']
317
346
  return unless lsid_doc
318
347
 
319
- lsid_doc['id'].to_uuid
348
+ binary = lsid_doc['id']
349
+ key = binary.data
350
+ cached = @lsid_cache_mutex.synchronize { @lsid_cache[key] }
351
+ return cached if cached
352
+
353
+ uuid = binary.to_uuid
354
+ @lsid_cache_mutex.synchronize do
355
+ @lsid_cache.clear if @lsid_cache.size >= LSID_CACHE_MAX
356
+ @lsid_cache[key] = uuid
357
+ end
358
+ uuid
320
359
  end
321
360
 
322
361
  # Extracts the transaction number from the command.
323
362
  #
324
- # @param message [ Mongo::Protocol::Message ] the command message.
363
+ # @param doc [ Hash ] the command document.
325
364
  #
326
365
  # @return [ Integer | nil ] the transaction number, or nil if not present.
327
- def txn_number(message)
328
- txn_num = message.documents.first['txnNumber']
366
+ def txn_number(doc)
367
+ txn_num = doc['txnNumber']
329
368
  return unless txn_num
330
369
 
331
370
  txn_num.value
@@ -24,7 +24,6 @@ module Mongo
24
24
  extend Forwardable
25
25
 
26
26
  def_delegators :@parent_tracer,
27
- :cursor_context_map,
28
27
  :parent_context_for,
29
28
  :transaction_context_map,
30
29
  :transaction_map_key
@@ -37,6 +36,8 @@ module Mongo
37
36
  def initialize(otel_tracer, parent_tracer)
38
37
  @otel_tracer = otel_tracer
39
38
  @parent_tracer = parent_tracer
39
+ @operation_names = {}
40
+ @operation_names_mutex = Mutex.new
40
41
  end
41
42
 
42
43
  # Trace a MongoDB operation.
@@ -53,21 +54,43 @@ module Mongo
53
54
  # @yield the block representing the operation to be traced.
54
55
  #
55
56
  # @return [ Object ] the result of the operation.
56
- #
57
- # rubocop:disable Lint/RescueException
58
57
  def trace_operation(operation, operation_context, op_name: nil, &block)
59
58
  span = create_operation_span(operation, operation_context, op_name)
60
- execute_with_span(span, operation, &block)
59
+ # With no SDK and no valid parent, the API returns a span with an
60
+ # invalid context. It cannot be made current, recorded or
61
+ # propagated, so it gets no work at all, not even finishing it.
62
+ return yield unless span.context.valid?
63
+
64
+ trace_with_span(span, operation, &block)
65
+ end
66
+
67
+ private
68
+
69
+ # Runs the operation with the span made current, and finishes the span.
70
+ # A span that is not recording is still made current, so that the
71
+ # command spans created within it nest under it, but gets no further
72
+ # attributes and no outcome: the SDK would discard them.
73
+ #
74
+ # @param span [ OpenTelemetry::Trace::Span ] a span with a valid context.
75
+ # @param operation [ Mongo::Operation ] the operation.
76
+ #
77
+ # @return [ Object ] the result of the operation.
78
+ #
79
+ # rubocop:disable Lint/RescueException
80
+ def trace_with_span(span, operation, &block)
81
+ recording = span.recording?
82
+ if recording && !operation.cursor_id.nil?
83
+ span.set_attribute('db.mongodb.cursor_id', operation.cursor_id)
84
+ end
85
+ execute_with_span(span, operation, recording, &block)
61
86
  rescue Exception => e
62
- handle_span_exception(span, e)
87
+ handle_span_exception(span, e) if recording
63
88
  raise e
64
89
  ensure
65
- span&.finish
90
+ span.finish
66
91
  end
67
92
  # rubocop:enable Lint/RescueException
68
93
 
69
- private
70
-
71
94
  # Creates an OpenTelemetry span for the operation.
72
95
  #
73
96
  # @param operation [ Mongo::Operation ] the operation.
@@ -76,7 +99,7 @@ module Mongo
76
99
  #
77
100
  # @return [ OpenTelemetry::Trace::Span ] the created span.
78
101
  def create_operation_span(operation, operation_context, op_name)
79
- parent_context = parent_context_for(operation_context, operation.cursor_id)
102
+ parent_context = parent_context_for(operation_context)
80
103
  @otel_tracer.start_span(
81
104
  operation_span_name(operation, op_name),
82
105
  attributes: span_attributes(operation, op_name),
@@ -89,14 +112,15 @@ module Mongo
89
112
  #
90
113
  # @param span [ OpenTelemetry::Trace::Span ] the span.
91
114
  # @param operation [ Mongo::Operation ] the operation.
115
+ # @param recording [ true | false ] whether the span is recording.
92
116
  #
93
117
  # @yield the block to execute.
94
118
  #
95
119
  # @return [ Object ] the result of the block.
96
- def execute_with_span(span, operation)
97
- ::OpenTelemetry::Trace.with_span(span) do |s, c|
120
+ def execute_with_span(span, operation, recording)
121
+ ::OpenTelemetry::Trace.with_span(span) do |s, _context|
98
122
  yield.tap do |result|
99
- process_cursor_context(result, operation.cursor_id, c, s)
123
+ record_cursor_id(result, operation.cursor_id, s, recording)
100
124
  end
101
125
  end
102
126
  end
@@ -106,8 +130,6 @@ module Mongo
106
130
  # @param span [ OpenTelemetry::Trace::Span ] the span.
107
131
  # @param exception [ Exception ] the exception.
108
132
  def handle_span_exception(span, exception)
109
- return unless span
110
-
111
133
  span.record_exception(exception)
112
134
  span.status = ::OpenTelemetry::Trace::Status.error(
113
135
  "Unhandled exception of type: #{exception.class}"
@@ -115,16 +137,28 @@ module Mongo
115
137
  end
116
138
 
117
139
  # Returns the operation name from the provided name or operation class.
140
+ # The name derived from the class is cached per class. There are few
141
+ # operation classes, so the cache needs no bound. It is guarded by a
142
+ # mutex because not every Ruby runtime makes Hash writes thread-safe.
118
143
  #
119
144
  # @param operation [ Mongo::Operation ] the operation.
120
145
  # @param op_name [ String | nil ] optional operation name.
121
146
  #
122
147
  # @return [ String ] the operation name in lowercase.
123
148
  def operation_name(operation, op_name = nil)
124
- op_name || operation.class.name.split('::').last.downcase
149
+ return op_name if op_name
150
+
151
+ klass = operation.class
152
+ @operation_names_mutex.synchronize do
153
+ @operation_names[klass] ||= klass.name.split('::').last.downcase
154
+ end
125
155
  end
126
156
 
127
- # Builds span attributes for the operation.
157
+ # Builds the attributes passed at span creation. The cursor id is set
158
+ # by trace_with_span once the span is known to record.
159
+ # db.operation.summary is outside the spec's recommended creation set,
160
+ # but it is the span name, which is built anyway, and an attribute
161
+ # passed at creation is cheaper than one set later.
128
162
  #
129
163
  # @param operation [ Mongo::Operation ] the operation.
130
164
  # @param op_name [ String | nil ] optional operation name.
@@ -136,31 +170,21 @@ module Mongo
136
170
  'db.namespace' => operation.db_name.to_s,
137
171
  'db.collection.name' => collection_name(operation),
138
172
  'db.operation.name' => operation_name(operation, op_name),
139
- 'db.operation.summary' => operation_span_name(operation, op_name),
140
- 'db.mongodb.cursor_id' => operation.cursor_id,
173
+ 'db.operation.summary' => operation_span_name(operation, op_name)
141
174
  }.compact
142
175
  end
143
176
 
144
- # Processes cursor context after operation execution.
145
- #
146
- # Updates the cursor context map based on the result. Removes closed cursors
147
- # and stores context for newly created cursors.
177
+ # Records the id of a cursor the operation opened.
148
178
  #
149
179
  # @param result [ Object ] the operation result.
150
180
  # @param cursor_id [ Integer | nil ] the cursor ID before the operation.
151
- # @param context [ OpenTelemetry::Context ] the OpenTelemetry context.
152
181
  # @param span [ OpenTelemetry::Trace::Span ] the current span.
153
- def process_cursor_context(result, cursor_id, context, span)
182
+ # @param recording [ true | false ] whether the span is recording.
183
+ def record_cursor_id(result, cursor_id, span, recording)
154
184
  return unless result.is_a?(Cursor)
185
+ return if cursor_id || result.id.nil? || result.id.zero? || !recording
155
186
 
156
- if result.id.zero?
157
- # If the cursor is closed, remove it from the context map.
158
- cursor_context_map.delete(cursor_id)
159
- elsif result.id && cursor_id.nil?
160
- # New cursor created, store its context.
161
- cursor_context_map[result.id] = context
162
- span.set_attribute('db.mongodb.cursor_id', result.id)
163
- end
187
+ span.set_attribute('db.mongodb.cursor_id', result.id)
164
188
  end
165
189
 
166
190
  # Extracts the collection name from the operation.
@@ -139,41 +139,18 @@ module Mongo
139
139
  end
140
140
  end
141
141
 
142
- # Returns the cursor context map for tracking cursor-related OpenTelemetry contexts.
143
- #
144
- # @return [ Hash ] map of cursor IDs to OpenTelemetry contexts.
145
- def cursor_context_map
146
- @cursor_context_map ||= {}
147
- end
148
-
149
- # Generates a unique key for cursor tracking in the context map.
150
- #
151
- # @param session [ Mongo::Session ] the session associated with the cursor.
152
- # @param cursor_id [ Integer ] the cursor ID.
153
- #
154
- # @return [ String | nil ] unique key combining session ID and cursor ID, or nil if either is nil.
155
- def cursor_map_key(session, cursor_id)
156
- return if cursor_id.nil? || session.nil?
157
-
158
- "#{session.session_id['id'].to_uuid}-#{cursor_id}"
159
- end
160
-
161
142
  # Determines the parent OpenTelemetry context for an operation.
162
143
  #
163
- # Returns the transaction context if the operation is part of a transaction,
164
- # otherwise returns nil. Cursor-based context nesting is not currently implemented.
144
+ # Returns the transaction context if the operation is part of a
145
+ # transaction, otherwise nil. Cursor-based context nesting is not
146
+ # implemented.
165
147
  #
166
148
  # @param operation_context [ Mongo::Operation::Context ] the operation context.
167
- # @param cursor_id [ Integer ] the cursor ID, if applicable.
168
149
  #
169
150
  # @return [ OpenTelemetry::Context | nil ] parent context or nil.
170
- def parent_context_for(operation_context, cursor_id)
171
- if (key = transaction_map_key(operation_context.session))
172
- transaction_context_map[key]
173
- elsif (_key = cursor_map_key(operation_context.session, cursor_id))
174
- # We return nil here unless we decide how to nest cursor operations.
175
- nil
176
- end
151
+ def parent_context_for(operation_context)
152
+ key = transaction_map_key(operation_context.session)
153
+ transaction_context_map[key] if key
177
154
  end
178
155
 
179
156
  # Returns the transaction context map for tracking active transaction contexts.
@@ -200,6 +177,9 @@ module Mongo
200
177
  # Generates a unique key for transaction tracking.
201
178
  #
202
179
  # Returns nil for implicit sessions or sessions not in a transaction.
180
+ # Every operation in a transaction needs the key, so it is cached on
181
+ # the session together with the transaction number it was built for.
182
+ # Two threads may build it at the same time; they build the same key.
203
183
  #
204
184
  # @param session [ Mongo::Session ] the session.
205
185
  #
@@ -207,7 +187,13 @@ module Mongo
207
187
  def transaction_map_key(session)
208
188
  return if session.nil? || session.implicit? || !session.in_transaction?
209
189
 
210
- "#{session.session_id['id'].to_uuid}-#{session.txn_num}"
190
+ txn_num = session.txn_num
191
+ cached = session.tracing_transaction_key
192
+ return cached[1] if cached && cached[0] == txn_num
193
+
194
+ key = "#{session.session_id['id'].to_uuid}-#{txn_num}"
195
+ session.tracing_transaction_key = [ txn_num, key ].freeze
196
+ key
211
197
  end
212
198
 
213
199
  private