Skip to content

Commit caa826c

Browse files
radhushongalex
andauthored
feat(pubsub): allow trace extraction from protobuf message (#10827)
Export the function NewMessageCarrierFromPB which, given a protobuf PubsubMessage, returns a TextMapCarrier which can be used to extract trace contexts. This allows it to be used in e.g. HTTP push endpoints. Co-authored-by: Alex Hong <9397363+hongalex@users.noreply.github.com>
1 parent 48addbf commit caa826c

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

pubsub/trace.go

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"log"
2121
"sync"
2222

23+
pb "cloud.google.com/go/pubsub/apiv1/pubsubpb"
2324
"cloud.google.com/go/pubsub/internal"
2425
"go.opencensus.io/stats"
2526
"go.opencensus.io/stats/view"
@@ -273,33 +274,42 @@ func tracer() trace.Tracer {
273274

274275
var _ propagation.TextMapCarrier = (*messageCarrier)(nil)
275276

276-
// messageCarrier injects and extracts traces from a pubsub.Message.
277+
// messageCarrier injects and extracts traces from pubsub.Message attributes.
277278
type messageCarrier struct {
278-
msg *Message
279+
attributes map[string]string
279280
}
280281

281282
const googclientPrefix string = "googclient_"
282283

283284
// newMessageCarrier creates a new PubsubMessageCarrier.
284285
func newMessageCarrier(msg *Message) messageCarrier {
285-
return messageCarrier{msg: msg}
286+
return messageCarrier{attributes: msg.Attributes}
287+
}
288+
289+
// NewMessageCarrierFromPB creates a propagation.TextMapCarrier that can be used to extract the trace
290+
// context from a protobuf PubsubMessage.
291+
//
292+
// Example:
293+
// ctx = propagation.TraceContext{}.Extract(ctx, pubsub.NewMessageCarrierFromPB(msg))
294+
func NewMessageCarrierFromPB(msg *pb.PubsubMessage) propagation.TextMapCarrier {
295+
return messageCarrier{attributes: msg.Attributes}
286296
}
287297

288298
// Get retrieves a single value for a given key.
289299
func (c messageCarrier) Get(key string) string {
290-
return c.msg.Attributes[googclientPrefix+key]
300+
return c.attributes[googclientPrefix+key]
291301
}
292302

293303
// Set sets an attribute.
294304
func (c messageCarrier) Set(key, val string) {
295-
c.msg.Attributes[googclientPrefix+key] = val
305+
c.attributes[googclientPrefix+key] = val
296306
}
297307

298308
// Keys returns a slice of all keys in the carrier.
299309
func (c messageCarrier) Keys() []string {
300310
i := 0
301-
out := make([]string, len(c.msg.Attributes))
302-
for k := range c.msg.Attributes {
311+
out := make([]string, len(c.attributes))
312+
for k := range c.attributes {
303313
out[i] = k
304314
i++
305315
}

0 commit comments

Comments
 (0)