Class: Polyn::Tracing

Inherits:
Object
  • Object
show all
Defined in:
lib/polyn/tracing.rb

Overview

Methods to enable distributed tracing across services Attempts to follow OpenTelemetry conventions opentelemetry.io/docs/reference/specification/trace/semantic_conventions/messaging/

Class Method Summary collapse

Class Method Details

.connect_span_with_received_message(msg, &block) ⇒ Object

Uses the message header to extract trace information from the published message so the subscription handler can use it as the parent span. This will allow us to create a distributed trace between publications and subscriptions. It’s expecting a ‘traceparent` header to be set on the message www.w3.org/TR/trace-context/#traceparent-header



36
37
38
39
# File 'lib/polyn/tracing.rb', line 36

def self.connect_span_with_received_message(msg, &block)
  context = OpenTelemetry.propagation.extract(msg.header)
  ::OpenTelemetry::Context.with_current(context, &block)
end

.processing_span(type, &block) ⇒ Object

Start a span to handle processing of batch messages



65
66
67
# File 'lib/polyn/tracing.rb', line 65

def self.processing_span(type, &block)
  tracer.in_span("#{type} process", kind: "CONSUMER", &block)
end

.publish_span(type, &block) ⇒ Object

Start a span for publishing an event



51
52
53
# File 'lib/polyn/tracing.rb', line 51

def self.publish_span(type, &block)
  tracer.in_span("#{type} send", kind: "PRODUCER", &block)
end

.span_attributes(span, nats:, type:, event:, payload:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/polyn/tracing.rb', line 18

def self.span_attributes(span, nats:, type:, event:, payload:)
  span.add_attributes({
    "messaging.system"                     => "NATS",
    "messaging.destination"                => type,
    "messaging.protocol"                   => "Polyn",
    "messaging.url"                        => nats.uri.to_s,
    "messaging.message_id"                 => event.id,
    "messaging.message_payload_size_bytes" => payload.bytesize,
  })
end

.subscribe_span(type, msg, links: nil, &block) ⇒ Object

Start a span for handling a received event



57
58
59
60
61
# File 'lib/polyn/tracing.rb', line 57

def self.subscribe_span(type, msg, links: nil, &block)
  connect_span_with_received_message(msg) do
    tracer.in_span("#{type} receive", kind: "CONSUMER", links: convert_links(links), &block)
  end
end

.trace_header(headers = {}) ⇒ Object

Add a ‘traceparent` header to the headers for a message so that the subscribers can be connected with it www.w3.org/TR/trace-context/#traceparent-header



45
46
47
# File 'lib/polyn/tracing.rb', line 45

def self.trace_header(headers = {})
  ::OpenTelemetry.propagation.inject(headers)
end

.tracerObject

Tracer object to use to start a trace



11
12
13
# File 'lib/polyn/tracing.rb', line 11

def self.tracer
  ::OpenTelemetry.tracer_provider.tracer("polyn", Polyn::VERSION)
end