Module: SafeMemoize::Adapters::OpenTelemetry

Defined in:
lib/safe_memoize/adapters/opentelemetry.rb

Overview

Optional OpenTelemetry adapter.

Wraps each cache-miss computation in an OpenTelemetry span so the time spent computing uncached values is visible in distributed traces.

Configure via Configuration#opentelemetry_tracer:

SafeMemoize.configure do |c| c.opentelemetry_tracer = OpenTelemetry.tracer_provider.tracer("safe_memoize") end

Each span is named SPAN_NAME and carries the attributes +safe_memoize.method+, +safe_memoize.class+, and +safe_memoize.cache_hit+. Falls back to untraced execution when no tracer is configured or the tracer does not respond to +#in_span+.

Constant Summary collapse

SPAN_NAME =

The name given to every span created by this adapter.

"safe_memoize.compute"

Class Method Summary collapse

Class Method Details

.trace(tracer, method_name, class_name) { ... } ⇒ Object

Wraps the block in a span if a tracer is available; otherwise yields directly.

Parameters:

  • tracer (Object, nil)

    an object responding to +#in_span+

  • method_name (Symbol, String)
  • class_name (String, nil)

Yields:

  • the computation block (cache-miss path)

Returns:

  • (Object)

    the result of the block



33
34
35
36
37
38
39
40
41
# File 'lib/safe_memoize/adapters/opentelemetry.rb', line 33

def self.trace(tracer, method_name, class_name)
  return yield unless tracer&.respond_to?(:in_span)

  tracer.in_span(SPAN_NAME, attributes: {
    "safe_memoize.method" => method_name.to_s,
    "safe_memoize.class" => class_name.to_s,
    "safe_memoize.cache_hit" => false
  }) { yield }
end