Class: Datadog::DI::Serializer Private

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/di/serializer.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Serializes captured snapshots to primitive types, which are subsequently serialized to JSON and sent to the backend.

Sensitive values are removed from the snapshots.

Serializer normally ought not to invoke user (application) code, to guarantee predictable performance. However, objects like ActiveRecord models cannot be usefully serialized into primitive types without custom logic (for example, the attributes are more than 3 levels down from the top-level object which is the default capture depth, thus they won't be captured at all). To accommodate complex objects, there is an extension mechanism implemented permitting registration of serializer callbacks for arbitrary types. Applications and libraries defining such serializer callbacks should be very careful to have predictable performance and avoid exceptions and infinite loops and other such issues.

All serialization methods take the names of the variables being serialized in order to be able to redact values.

The result of serialization should not reference parameter values when the values are mutable (currently, this only applies to string values). Serializer will duplicate such mutable values, so that if method arguments are captured at entry and then modified during method execution, the serialized values from entry are correctly preserved. Alternatively, we could pass a parameter to the serialization methods which would control whether values are duplicated. This may be more efficient but there would be additional overhead from passing this parameter all the time and the API would get more complex.

Constant Summary collapse

SERIALIZABLE_FATAL_EXCEPTION_CLASSES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Exception classes that must propagate to the caller during serialization: fatal conditions (signals, interrupts, system exit). NoMemoryError is deliberately excluded (unlike DI::FATAL_EXCEPTION_CLASSES): serialization of large or deeply recursive objects can exhaust memory, and the serializer must return a safe stub rather than terminate the process.

[SystemExit, SignalException].freeze
REDACTED_VALUE_FOR_MESSAGE =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Placeholder emitted by #serialize_value_for_message in place of a value whose identifier or type matches the redaction configuration. The message-path counterpart of the notCapturedReason "redactedIdent"/"redactedType" markers that #serialize_value produces on the snapshot path.

"[redacted]"
@@flat_registry =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

Third-party library integration / custom serializers.

Dynamic instrumentation has limited payload sizes, and for efficiency reasons it is not desirable to transmit data to Datadog that will never contain useful information. Additionally, due to depth limits, desired data may not even be included in payloads when serialized with the default, naive serializer. Therefore, custom objects like ActiveRecord model instances may need custom serializers.

CUSTOMER NOTE: The API for defining custom serializers is not yet finalized. Please create an issue at https://github.com/datadog/dd-trace-rb/issues describing the object(s) you wish to serialize so that we can ensure your use case will be supported as the library evolves.

Note that the current implementation does not permit defining a serializer for a particular class, which is the simplest use case. This is because the library itself does not need this functionality yet, and it won't help for ActiveRecord models (that derive from a common base class but are all of different classes) or for Mongoid models (that do not have a common base class at all but include a standard Mongoid module).

Important: these serializers are NOT used in log messages. They are only used for variables that are captured in the snapshots.

Exception handling: If a custom serializer's condition lambda raises an exception (e.g., regex match against invalid UTF-8 strings), the exception will be logged at WARN level, then the serializer will be skipped and the next serializer will be tried. This prevents custom serializers from breaking the entire serialization process.

IMPORTANT: Custom serializers MUST produce data that can be JSON-encoded. Specifically, custom serializers MUST NOT produce strings with binary encoding (ASCII-8BIT) containing non-ASCII code points (bytes >= 0x80) that cannot be automatically transcoded to UTF-8. Such strings will cause JSON encoding to fail, which will result in the probe being disabled and an ERROR status being reported. If your data contains binary content, encode it to a text representation (e.g., Base64, hex string, or UTF-8 with replacement characters) before returning it from the custom serializer.

[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(settings, redactor, logger:, guardrails_telemetry:, telemetry: nil) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initializes the serializer.

Parameters:



128
129
130
131
132
133
134
135
136
137
138
# File 'lib/datadog/di/serializer.rb', line 128

def initialize(settings, redactor, logger:, guardrails_telemetry:, telemetry: nil)
  @settings = settings
  @redactor = redactor
  @logger = logger
  @guardrails_telemetry = guardrails_telemetry
  @telemetry = telemetry
  # Evaluation budget for one expression evaluation, as thread CPU
  # seconds, converted from max_time_to_evaluate_ms here so that
  # deadline resolution per probe firing traverses no settings.
  @evaluation_budget_seconds = settings.dynamic_instrumentation.max_time_to_evaluate_ms / 1000.0
end

Instance Attribute Details

#guardrails_telemetry ⇒ GuardrailsTelemetry (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The guardrails metric emitter.

Returns:



147
148
149
# File 'lib/datadog/di/serializer.rb', line 147

def guardrails_telemetry
  @guardrails_telemetry
end

#logger ⇒ DI::Logger (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The logger.

Returns:



144
145
146
# File 'lib/datadog/di/serializer.rb', line 144

def logger
  @logger
end

#redactor ⇒ Object (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



141
142
143
# File 'lib/datadog/di/serializer.rb', line 141

def redactor
  @redactor
end

#settings ⇒ Object (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



140
141
142
# File 'lib/datadog/di/serializer.rb', line 140

def settings
  @settings
end

#telemetry ⇒ Object (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



148
149
150
# File 'lib/datadog/di/serializer.rb', line 148

def telemetry
  @telemetry
end

Class Method Details

.register(condition:, &block) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Registers a custom serializer. The block serializes each value for which condition returns a truthy value.

Parameters:

  • condition (Proc) —

    receives the value being serialized and returns whether this serializer applies to it

  • block (Proc) —

    serializer for the values condition accepts

Raises:

  • (ArgumentError) —

    if condition is not a Proc or block is absent



107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/datadog/di/serializer.rb', line 107

def self.register(condition:, &block)
  unless condition.is_a?(Proc)
    raise ArgumentError, "Serializer.register condition must be a Proc, got #{condition.class}"
  end

  unless block
    raise ArgumentError, "Serializer.register requires a serializer block"
  end

  @@flat_registry << {condition: condition, proc: block}
  nil
end

Instance Method Details

#combine_args(args, kwargs, target_self) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



160
161
162
163
164
165
166
167
168
169
170
# File 'lib/datadog/di/serializer.rb', line 160

def combine_args(args, kwargs, target_self)
  counter = 0
  combined = args.each_with_object({}) do |value, c|
    counter += 1
    # Conversion to symbol is needed here to put args ahead of
    # kwargs when they are merged below.
    c[:"arg#{counter}"] = value
  end.update(kwargs)
  combined[:self] = target_self
  combined
end

#evaluation_deadline ⇒ Float

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Computes the absolute thread CPU time deadline (in seconds) for an expression evaluation by adding the evaluation budget, converted from max_time_to_evaluate_ms once at construction, to the current thread CPU clock reading.

Returns:

  • (Float) —

    absolute thread CPU clock reading, in seconds, at which the evaluation budget is exhausted



582
583
584
585
# File 'lib/datadog/di/serializer.rb', line 582

def evaluation_deadline
  Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID, :float_second) +
    evaluation_budget_seconds
end

#record_capture_incomplete(reason) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Emits the canonical capture-incomplete metric for a capture limit enforced while serializing a snapshot, with the snapshot event type.

Parameters:

  • reason (String) —

    a GuardrailsTelemetry::Reason constant naming the enforced limit



156
157
158
# File 'lib/datadog/di/serializer.rb', line 156

def record_capture_incomplete(reason)
  guardrails_telemetry.capture_incomplete(reason: reason, event_type: GuardrailsTelemetry::EVENT_TYPE_SNAPSHOT)
end

#serialization_deadline ⇒ Float

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Computes the absolute thread CPU time deadline (in seconds) for a capture point from max_time_to_serialize_ms.

Returns:

  • (Float) —

    absolute thread CPU clock reading, in seconds, at which the capture budget is exhausted



570
571
572
573
# File 'lib/datadog/di/serializer.rb', line 570

def serialization_deadline
  Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID, :float_second) +
    settings.dynamic_instrumentation.max_time_to_serialize_ms / 1000.0
end

#serialize_args(args, kwargs, target_self, deadline:, depth: settings.dynamic_instrumentation.max_capture_depth, attribute_count: settings.dynamic_instrumentation.max_capture_attribute_count, length: nil, collection_size: nil) ⇒ Hash{Symbol => Hash}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Serializes positional and keyword arguments to a method, as obtained by a method probe.

UI supports a single argument list only and does not distinguish between positional and keyword arguments. We convert positional arguments to keyword arguments ("arg1", "arg2", ...) and ensure the positional arguments are listed first.

Parameters:

  • args (Array) —

    positional arguments passed to the probed method

  • kwargs (Hash{Symbol => Object}) —

    keyword arguments passed to the probed method

  • target_self (any) —

    receiver of the probed method invocation

  • deadline (Float) —

    absolute capture deadline in thread CPU clock seconds

Returns:

  • (Hash{Symbol => Hash}) —

    serialized arguments keyed by argument name



185
186
187
188
189
190
191
192
193
194
# File 'lib/datadog/di/serializer.rb', line 185

def serialize_args(args, kwargs, target_self,
  deadline:,
  depth: settings.dynamic_instrumentation.max_capture_depth,
  attribute_count: settings.dynamic_instrumentation.max_capture_attribute_count,
  length: nil,
  collection_size: nil)
  combined = combine_args(args, kwargs, target_self)
  serialize_vars(combined, depth: depth, attribute_count: attribute_count,
    length: length, collection_size: collection_size, deadline: deadline)
end

#serialize_value(value, deadline:, name: nil, depth: settings.dynamic_instrumentation.max_capture_depth, attribute_count: nil, length: nil, collection_size: nil, type: nil) ⇒ Hash{Symbol => Object}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Serializes a single named value.

The name is needed to perform sensitive data redaction.

In some cases, the value being serialized does not have a name (for example, it is the return value of a method). In this case name can be nil.

Returns a data structure comprised of only values of basic types (integers, strings, arrays, hashes).

Respects string length, collection size and traversal depth limits.

Parameters:

  • value (any) —

    value to serialize

  • name (Symbol, String, nil) (defaults to: nil) —

    name the value is bound to, used for redaction

  • deadline (Float) —

    absolute capture deadline in thread CPU clock seconds

Returns:

  • (Hash{Symbol => Object}) —

    serialized value; the notCapturedReason: "timeout" stub when the deadline is exceeded



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/datadog/di/serializer.rb', line 233

def serialize_value(value, deadline:,
  name: nil,
  depth: settings.dynamic_instrumentation.max_capture_depth,
  attribute_count: nil,
  length: nil,
  collection_size: nil,
  type: nil)
  attribute_count ||= settings.dynamic_instrumentation.max_capture_attribute_count
  cls = type || value.class
  begin
    if deadline_exceeded?(deadline)
      telemetry&.inc(DI::TELEMETRY_NAMESPACE, "serialized_values_skipped_by_timeout", 1)
      record_capture_incomplete(GuardrailsTelemetry::Reason::CAPTURE_TIMEOUT)
      return {type: class_name(cls), notCapturedReason: "timeout"}
    end

    if redactor.redact_type?(value)
      return {type: class_name(cls), notCapturedReason: "redactedType"}
    end

    if name && redactor.redact_identifier?(name)
      return {type: class_name(cls), notCapturedReason: "redactedIdent"}
    end

    @@flat_registry.each do |entry|
      condition = entry[:condition]
      if condition
        begin
          condition_result = condition.call(value)
        rescue Exception => e # standard:disable Lint/RescueException
          raise if SERIALIZABLE_FATAL_EXCEPTION_CLASSES.any? { |klass| e.is_a?(klass) }

          # If a custom serializer condition raises an exception (e.g., regex match
          # against invalid UTF-8), skip it and continue with the next serializer.
          # We don't want custom serializer conditions to break the entire serialization.
          #
          # Custom serializers may be defined by customers (in which case we should
          # surface errors so they can fix their serializers) or they may be defined
          # internally by dd-trace-rb (in which case we need to fix them). We use
          # WARN level to surface these errors in either case.
          Datadog.logger.warn("DI: Custom serializer condition failed: #{e.class}: #{e.message}")
          telemetry&.report(e, description: "Custom serializer condition failed")
          next
        end

        if condition_result
          serializer_proc = entry.fetch(:proc)
          return serializer_proc.call(self, value, name: nil, depth: depth, deadline: deadline)
        end
      end
    end

    serialized = {type: class_name(cls)}
    # https://github.com/soutaro/steep/issues/1860
    # @type var serialized: untyped
    case value
    when NilClass
      serialized.update(isNull: true)
    when Integer, Float, TrueClass, FalseClass
      serialized.update(value: value.to_s)
    when Time
      serialized.update(value: value.iso8601)
    when Date
      serialized.update(value: value.to_s)
    when String, Symbol
      need_dup = false
      value = if String === value
        # This is the only place where we duplicate the value, currently.
        # All other values are immutable primitives (e.g. numbers).
        # However, do not duplicate if the string is frozen, or if
        # it is later truncated.
        need_dup = !value.frozen?
        value
      else
        value.to_s
      end

      # Handle binary strings and invalid UTF-8 by escaping to JSON-safe format.
      # For regular strings, the limit is applied to string length in characters.
      length ||= settings.dynamic_instrumentation.max_capture_string_length
      max = length

      if value.encoding == Encoding::BINARY || !value.valid_encoding?
        # Truncate binary data before escaping to avoid cutting mid-escape-sequence
        # For invalid encodings, use bytesize instead of length to avoid encoding errors
        original_size = value.bytesize
        if original_size > max
          serialized.update(truncated: true, size: original_size)
          record_capture_incomplete(GuardrailsTelemetry::Reason::STRING_LENGTH)
          value = value.byteslice(0...max)
        end
        value = escape_binary_string(value) # steep:ignore ArgumentTypeMismatch
      else
        if value.length > max
          serialized.update(truncated: true, size: value.length)
          record_capture_incomplete(GuardrailsTelemetry::Reason::STRING_LENGTH)
          value = value[0...max]
          need_dup = false
        end

        value = value.dup if need_dup
      end

      serialized.update(value: value)
    when Array
      if depth <= 0
        serialized.update(notCapturedReason: "depth")
        record_capture_incomplete(GuardrailsTelemetry::Reason::DEPTH)
      else
        collection_size ||= settings.dynamic_instrumentation.max_capture_collection_size
        max = collection_size
        if max != 0 && value.length > max
          serialized.update(notCapturedReason: "collectionSize", size: value.length)
          record_capture_incomplete(GuardrailsTelemetry::Reason::COLLECTION_SIZE)
          # same steep failure with array slices.
          # https://github.com/soutaro/steep/issues/1219
          value = value[0...max] || []
        end
        entries = []
        value.each do |elt|
          entry = serialize_value(elt, depth: depth - 1, length: length, collection_size: collection_size, attribute_count: attribute_count, deadline: deadline)
          entries << entry
          if entry[:notCapturedReason] == "timeout"
            serialized.update(notCapturedReason: "timeout")
            break
          end
        end
        serialized.update(elements: entries)
      end
    when Hash
      if depth <= 0
        serialized.update(notCapturedReason: "depth")
        record_capture_incomplete(GuardrailsTelemetry::Reason::DEPTH)
      else
        collection_size ||= settings.dynamic_instrumentation.max_capture_collection_size
        max = collection_size
        cur = 0
        entries = []
        value.each do |k, v|
          if max != 0 && cur >= max
            serialized.update(notCapturedReason: "collectionSize", size: value.length)
            record_capture_incomplete(GuardrailsTelemetry::Reason::COLLECTION_SIZE)
            break
          end
          cur += 1
          key_entry = serialize_value(k, depth: depth - 1, length: length, collection_size: collection_size, attribute_count: attribute_count, deadline: deadline)
          if key_entry[:notCapturedReason] == "timeout"
            serialized.update(notCapturedReason: "timeout")
            break
          end
          value_entry = serialize_value(v, name: k, depth: depth - 1, length: length, collection_size: collection_size, attribute_count: attribute_count, deadline: deadline)
          entries << [key_entry, value_entry]
          if value_entry[:notCapturedReason] == "timeout"
            serialized.update(notCapturedReason: "timeout")
            break
          end
        end
        serialized.update(entries: entries)
      end
    else
      if depth <= 0
        serialized.update(notCapturedReason: "depth")
        record_capture_incomplete(GuardrailsTelemetry::Reason::DEPTH)
      else
        fields = {}
        cur = 0

        # MRI and JRuby 9.4.5+ preserve instance variable definition
        # order when calling #instance_variables. Previous JRuby versions
        # did not preserve order and returned the variables in arbitrary
        # order.
        #
        # The arbitrary order is problematic because 1) when there are
        # fewer instance variables than capture limit, the order in which
        # the variables are shown in UI will change from one capture to
        # the next and generally will be arbitrary to the user, and
        # 2) when there are more instance variables than capture limit,
        # *which* variables are captured will also change meaning user
        # looking at the UI may have "new" instance variables appear and
        # existing ones disappear as they are looking at multiple captures.
        #
        # For consistency, we should have some kind of stable order of
        # instance variables on all supported Ruby runtimes, so that the UI
        # stays consistent. Ruby DI does not support JRuby, so JRuby's lack
        # of ordering of #instance_variables is not handled here.
        ivars = value.instance_variables

        ivars.each do |ivar|
          if cur >= attribute_count
            serialized.update(notCapturedReason: "fieldCount", fields: fields)
            record_capture_incomplete(GuardrailsTelemetry::Reason::FIELD_COUNT)
            break
          end
          cur += 1
          entry = serialize_value(value.instance_variable_get(ivar), name: ivar, depth: depth - 1, length: length, collection_size: collection_size, attribute_count: attribute_count, deadline: deadline)
          fields[ivar] = entry
          if entry[:notCapturedReason] == "timeout"
            serialized.update(notCapturedReason: "timeout")
            break
          end
        end
        serialized.update(fields: fields)
      end
    end
    serialized
  rescue Exception => exc # standard:disable Lint/RescueException
    raise if SERIALIZABLE_FATAL_EXCEPTION_CLASSES.any? { |klass| exc.is_a?(klass) }

    # Catch all remaining exceptions: SystemStackError and NoMemoryError can
    # occur during serialization (e.g. a custom serializer recursing
    # infinitely) and produce the safe stub.
    record_capture_incomplete(GuardrailsTelemetry::Reason::RUNTIME_ERROR)
    logger.debug { "di: error serializing value of #{class_name(cls)}: #{exc.class}: #{exc.message}" }
    telemetry&.report(exc, description: "Error serializing")
    {type: class_name(cls), notSerializedReason: exc.to_s}
  end
end

#serialize_value_for_message(value, depth: 1, name: nil) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Serializes a value for interpolation into a log-probe message. Because the output is meant to be human-readable, we cannot use the "normal" serialization format which is meant to be machine-readable. Serialize objects with depth of 1 and include the class name.

Note that this method does not (currently) utilize the custom serializers that the "normal" serialization logic uses.

This serializer differs from the RFC in two ways:

  1. We omit the middle of long strings rather than the end, and also the inner entries in arrays/hashes/objects.
  2. We use Ruby-ish syntax for hashes and objects.

We also use the Ruby-like syntax for symbols, which don't exist in other languages.

name, when given, is the identifier the template expression references at its top level; a redacted identifier yields the redaction placeholder, mirroring #serialize_value on the snapshot path. Message rendering is capped by depth (1) and MAX_MESSAGE_COLLECTION_SIZE / MAX_MESSAGE_ATTRIBUTE_COUNT.



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/datadog/di/serializer.rb', line 472

def serialize_value_for_message(value, depth: 1, name: nil)
  # This method is more verbose than "normal" Ruby code to avoid
  # array allocations.

  return REDACTED_VALUE_FOR_MESSAGE if redactor.redact_type?(value)
  return REDACTED_VALUE_FOR_MESSAGE if name && redactor.redact_identifier?(name)

  case value
  when NilClass
    "nil"
  when Integer, Float, TrueClass, FalseClass, Time, Date
    value.to_s
  when String
    serialize_string_or_symbol_for_message(value)
  when Symbol
    ":" + serialize_string_or_symbol_for_message(value) # steep:ignore ArgumentTypeMismatch
  when Array
    return "..." if depth <= 0

    max = max_capture_collection_size_for_message
    if value.length > max
      value_ = value[0...max - 1] || []
      value_ << "..."
      value_ << value[-1]
      value = value_
    end
    "[" + value.map do |item|
      serialize_value_for_message(item, depth: depth - 1)
    end.join(", ") + "]"
  when Hash
    return "..." if depth <= 0

    max = max_capture_collection_size_for_message
    keys = value.keys
    truncated = false
    if value.length > max
      keys_ = keys[0...max - 1] || []
      keys_ << keys[-1]
      keys = keys_
      truncated = true
    end
    serialized = keys.map do |key|
      serialized_value = if (String === key || Symbol === key) && redactor.redact_identifier?(key)
        REDACTED_VALUE_FOR_MESSAGE
      else
        serialize_value_for_message(value[key], depth: depth - 1)
      end
      "#{serialize_value_for_message(key, depth: depth - 1)} => #{serialized_value}"
    end
    if truncated
      serialized[serialized.length] = serialized[serialized.length - 1]
      serialized[serialized.length - 2] = "..."
    end
    "{#{serialized.join(", ")}}"
  else
    return "..." if depth <= 0

    vars = value.instance_variables
    truncated = false
    max = max_capture_attribute_count_for_message
    if vars.length > max
      vars_ = vars[0...max - 1] || []
      vars_ << vars[-1]
      truncated = true
      vars = vars_
    end
    serialized = vars.map do |var|
      # +var+ here is always the instance variable name which is a
      # symbol, we do not need to run it through our serializer.
      serialized_value = if redactor.redact_identifier?(var)
        REDACTED_VALUE_FOR_MESSAGE
      else
        serialize_value_for_message(value.send(:instance_variable_get, var), depth: depth - 1)
      end
      "#{var}=#{serialized_value}"
    end
    if truncated
      serialized << serialized.last
      serialized[-2] = "..."
    end
    serialized = if serialized.any?
      " " + serialized.join(" ")
    end
    "#<#{class_name(value.class)}#{serialized}>"
  end
rescue Exception => exc # standard:disable Lint/RescueException
  raise if SERIALIZABLE_FATAL_EXCEPTION_CLASSES.any? { |klass| exc.is_a?(klass) }

  telemetry&.report(exc, description: "Error serializing for message")
  # TODO handle class_name raising here as well.
  "#<#{class_name(value.class)}: serialization error>"
end

#serialize_vars(vars, deadline:, depth: settings.dynamic_instrumentation.max_capture_depth, attribute_count: settings.dynamic_instrumentation.max_capture_attribute_count, length: nil, collection_size: nil) ⇒ Hash{Symbol => Hash}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Serializes variables captured by a line probe.

These are normally local variables that exist on a particular line of executed code.

Parameters:

  • vars (Hash{Symbol => Object}) —

    variables to serialize, keyed by variable name

  • deadline (Float) —

    absolute capture deadline in thread CPU clock seconds

Returns:

  • (Hash{Symbol => Hash}) —

    serialized variables keyed by variable name



204
205
206
207
208
209
210
211
212
213
214
# File 'lib/datadog/di/serializer.rb', line 204

def serialize_vars(vars,
  deadline:,
  depth: settings.dynamic_instrumentation.max_capture_depth,
  attribute_count: settings.dynamic_instrumentation.max_capture_attribute_count,
  length: nil,
  collection_size: nil)
  vars.each_with_object({}) do |(k, v), agg|
    agg[k] = serialize_value(v, name: k, depth: depth, attribute_count: attribute_count,
      length: length, collection_size: collection_size, deadline: deadline)
  end
end