Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds a keys method to the NATS message header #1573

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

autodidaddict
Copy link

On the surface this is just a convenience function, however, by adding the Keys method with this signature, we make the msg.Header field a suitable target for injection of open telemetry span context. In other words, after this change, the Header field will satisfy the TextMapCarrier interface:

type TextMapCarrier interface {

	// Get returns the value associated with the passed key.
	Get(key) string
	// Set stores the key-value pair.
	Set(key string, value string)
	// Keys lists the keys stored in this carrier.
	Keys() []string
}

This means we'll be able to use NATS message headers to automatically convey OpenTelemetry span context via the TraceContext's Inject and Extract functions:

tctx.Inject(ctx, msg.Header)
...
rehydratedContext := tctx.Extract(ctx, msg.Header)

Signed-off-by: Kevin Hoffman <[email protected]>
Copy link
Collaborator

@piotrpio piotrpio left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@wallyqs
Copy link
Member

wallyqs commented Feb 28, 2024

I think you can do this instead?

tctx.Inject(ctx, otel.HeaderCarrier(msg.Header))
rehydratedContext := tctx.Extract(ctx, otel.HeaderCarrier(msg.Header))

@wallyqs
Copy link
Member

wallyqs commented Feb 28, 2024

This is a small example of how to adapt msg.Header to the otel interface:

package main

import (
	"fmt"
	"net/http"
	"github.com/nats-io/nats.go"
	otel "go.opentelemetry.io/otel/propagation"
)

func main() {
	hdr := http.Header{}
	hdr.Set("foo", "1")
	hdr.Set("bar", "2")
	hdr.Set("quux", "3")
	msg := &nats.Msg{}
	msg.Header = nats.Header(hdr)
	nhdr := otel.HeaderCarrier(msg.Header)
	fmt.Println(nhdr.Keys())
	// => [Foo Bar Quux]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants