From abe224371883209d4db1bc8e099750a5b7d8ebb5 Mon Sep 17 00:00:00 2001 From: Bhautik Pipaliya <56270044+bhautikpip@users.noreply.github.com> Date: Thu, 22 Jul 2021 11:39:27 -0700 Subject: [PATCH] API: create new linked span from current context (#2115) * API: create new linked span from current context * ran make precommit * Update trace/trace.go * Updated CHANGELOG Co-authored-by: Tyler Yahn --- CHANGELOG.md | 1 + trace/trace.go | 8 ++++++++ trace/trace_test.go | 18 ++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00cc68b561f..6ebf2fcb081 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Added `WithOSDescription` resource configuration option to set OS (Operating System) description resource attribute (`os.description`). (#1840) - Added `WithOS` resource configuration option to set all OS (Operating System) resource attributes at once. (#1840) +- Added API `LinkFromContext` to return Link which encapsulates SpanContext from provided context and also encapsulates attributes. (#2115) ### Changed diff --git a/trace/trace.go b/trace/trace.go index 15eb4673b41..8564cb9dfe6 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -408,6 +408,14 @@ type Link struct { DroppedAttributeCount int } +// LinkFromContext returns a link encapsulating the SpanContext in the provided ctx. +func LinkFromContext(ctx context.Context, attrs ...attribute.KeyValue) Link { + return Link{ + SpanContext: SpanContextFromContext(ctx), + Attributes: attrs, + } +} + // SpanKind is the role a Span plays in a Trace. type SpanKind int diff --git a/trace/trace_test.go b/trace/trace_test.go index 2a32270b27b..d6115f286b9 100644 --- a/trace/trace_test.go +++ b/trace/trace_test.go @@ -16,8 +16,13 @@ package trace import ( "bytes" + "context" "testing" + "github.com/stretchr/testify/assert" + + "go.opentelemetry.io/otel/attribute" + "github.com/google/go-cmp/cmp" ) @@ -643,3 +648,16 @@ func TestSpanContextDerivation(t *testing.T) { t.Fatalf("WithTraceState: Unexpected context created: %s", cmp.Diff(modified, to)) } } + +func TestLinkFromContext(t *testing.T) { + k1v1 := attribute.String("key1", "value1") + spanCtx := SpanContext{traceID: TraceID([16]byte{1}), remote: true} + + receiverCtx := ContextWithRemoteSpanContext(context.Background(), spanCtx) + link := LinkFromContext(receiverCtx, k1v1) + + if !assertSpanContextEqual(link.SpanContext, spanCtx) { + t.Fatalf("LinkFromContext: Unexpected context created: %s", cmp.Diff(link.SpanContext, spanCtx)) + } + assert.Equal(t, link.Attributes[0], k1v1) +}