Module: OpenTrace::TraceContext

Defined in:
lib/opentrace/trace_context.rb

Constant Summary collapse

TRACEPARENT_REGEX =
/\A(\h{2})-(\h{32})-(\h{16})-(\h{2})\z/

Class Method Summary collapse

Class Method Details

.build_traceparent(trace_id:, span_id:, sampled: true) ⇒ Object

Build a W3C traceparent header string.



26
27
28
29
30
# File 'lib/opentrace/trace_context.rb', line 26

def self.build_traceparent(trace_id:, span_id:, sampled: true)
  normalized = normalize_trace_id(trace_id)
  flags = sampled ? "01" : "00"
  "00-#{normalized}-#{span_id}-#{flags}"
end

.generate_span_idObject

Generate a random 16-char span ID (8 bytes hex-encoded).



48
49
50
# File 'lib/opentrace/trace_context.rb', line 48

def self.generate_span_id
  SecureRandom.hex(8)
end

.generate_trace_idObject

Generate a random 32-char trace ID (16 bytes hex-encoded).



53
54
55
# File 'lib/opentrace/trace_context.rb', line 53

def self.generate_trace_id
  SecureRandom.hex(16)
end

.normalize_trace_id(id) ⇒ Object

Normalize any trace ID to 32 lowercase hex characters. Handles UUIDs (strip hyphens), short IDs (pad), and long IDs (truncate).



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/opentrace/trace_context.rb', line 34

def self.normalize_trace_id(id)
  hex = id.to_s.delete("-").downcase.gsub(/[^0-9a-f]/, "")
  return nil if hex.empty?

  if hex.length > 32
    hex[0, 32]
  elsif hex.length < 32
    hex.ljust(32, "0")
  else
    hex
  end
end

.parse_traceparent(header) ⇒ Object

Parse a W3C traceparent header. Returns a Hash with :version, :trace_id, :parent_id, :flags or nil if invalid.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/opentrace/trace_context.rb', line 11

def self.parse_traceparent(header)
  return nil unless header

  match = TRACEPARENT_REGEX.match(header.strip)
  return nil unless match

  {
    version: match[1],
    trace_id: match[2],
    parent_id: match[3],
    flags: match[4]
  }
end