Files

74 lines
2.7 KiB
Go

package natsrpc
import (
"context"
"maps"
"slices"
"github.com/nats-io/nats.go"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
const tracerName = "github.com/samcharles93/archie-core/internal/natsrpc"
// carrier adapts nats.Header to a propagation.TextMapCarrier. nats.Header is
// case-sensitive and propagation.HeaderCarrier canonicalises keys, which would
// miss lowercase senders.
type carrier nats.Header
func (c carrier) Get(k string) string { return nats.Header(c).Get(k) }
func (c carrier) Set(k, v string) { nats.Header(c).Set(k, v) }
func (c carrier) Keys() []string { return slices.Collect(maps.Keys(c)) }
// NewMsg builds a message for subject carrying ctx's trace context.
func NewMsg(ctx context.Context, subject string, data []byte) *nats.Msg {
msg := nats.NewMsg(subject)
msg.Data = data
otel.GetTextMapPropagator().Inject(ctx, carrier(msg.Header))
return msg
}
// Extract returns ctx carrying the trace context found in header.
func Extract(ctx context.Context, header map[string][]string) context.Context {
if header == nil {
return ctx
}
return otel.GetTextMapPropagator().Extract(ctx, carrier(header))
}
func messagingAttrs(subject, op string) trace.SpanStartEventOption {
return trace.WithAttributes(
attribute.String("messaging.system", "nats"),
attribute.String("messaging.destination.name", subject),
attribute.String("messaging.operation.type", op),
)
}
// StartClient starts the CLIENT span of a request/reply call.
func StartClient(ctx context.Context, subject string) (context.Context, trace.Span) {
return otel.Tracer(tracerName).Start(ctx, subject+" request",
trace.WithSpanKind(trace.SpanKindClient), messagingAttrs(subject, "send"))
}
// StartServer starts the SERVER span for a received request, parented to the
// caller's span.
func StartServer(ctx context.Context, msg *nats.Msg) (context.Context, trace.Span) {
ctx = Extract(ctx, msg.Header)
return otel.Tracer(tracerName).Start(ctx, msg.Subject+" process",
trace.WithSpanKind(trace.SpanKindServer), messagingAttrs(msg.Subject, "process"))
}
// StartConsumer starts a CONSUMER span for a delivered stream message. The
// producer is linked rather than made the parent because its span has usually
// ended by delivery time.
func StartConsumer(ctx context.Context, subject string, header map[string][]string) (context.Context, trace.Span) {
producer := trace.SpanContextFromContext(Extract(context.Background(), header))
opts := []trace.SpanStartOption{trace.WithSpanKind(trace.SpanKindConsumer), messagingAttrs(subject, "process")}
if producer.IsValid() {
opts = append(opts, trace.WithLinks(trace.Link{SpanContext: producer}))
}
return otel.Tracer(tracerName).Start(ctx, subject+" process", opts...)
}