Trace propagation inside plugin HTTP requests

Hi, everyone!

I want to set tracing headers inside requests I make from a plugin.
I was able to create a W3C traceparent header by using the following logic:

local kong = kong
local tracer = kong.tracing
local resty_string = require "resty.string"

function get_w3c_traceparent_header()
    local active_span = tracer.active_span()
    if active_span == nil then
        return ""
    end

    -- gets binary trace_id and convert it to hex string
    local trace_id = resty_string.to_hex(active_span.trace_id)
    -- gets binary span_id and convert it to hex string
    local span_id = resty_string.to_hex(active_span.span_id)

    -- gets integer flags value and convert it to hex string
    local intflags = active_span.tracer.sampler(active_span.trace_id)
    local flags = (tostring(intflags):gsub(".", function(char) return string.format("%2x", char:byte()) end))

    -- returns a traceparent header according with the W3C spec
    return string.format("00-%s-%s-%s", trace_id, span_id, flags)
end

I pass the generated header along my plugin HTTP requests and it works as expected… Problem is that I have other plugins where I have this same need, too.

My first instinct is to create a plugin to do so, but I want to confirm some things before:

  • Is that above the best (or even the correct) way to parse the trace id/span id/flags values?
  • Is there a native way of doing it? (e.g. a HTTP client with inherited tracing or something like that)