blob: bf0f1f6f8a14b144ea51be0ee3e6c047d0dbbeb3 [file] [log] [blame]
Joey Armstronge8c091f2023-01-17 16:56:26 -05001// Copyright The OpenTelemetry Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package otel
16
17import (
18 "context"
19
20 "go.opentelemetry.io/otel/internal/baggage"
21 "go.opentelemetry.io/otel/label"
22)
23
24// Baggage returns a copy of the baggage in ctx.
25func Baggage(ctx context.Context) label.Set {
26 // TODO (MrAlias, #1222): The underlying storage, the Map, shares many of
27 // the functional elements of the label.Set. These should be unified so
28 // this conversion is unnecessary and there is no performance hit calling
29 // this.
30 m := baggage.MapFromContext(ctx)
31 values := make([]label.KeyValue, 0, m.Len())
32 m.Foreach(func(kv label.KeyValue) bool {
33 values = append(values, kv)
34 return true
35 })
36 return label.NewSet(values...)
37}
38
39// BaggageValue returns the value related to key in the baggage of ctx. If no
40// value is set, the returned label.Value will be an uninitialized zero-value
41// with type INVALID.
42func BaggageValue(ctx context.Context, key label.Key) label.Value {
43 v, _ := baggage.MapFromContext(ctx).Value(key)
44 return v
45}
46
47// ContextWithBaggageValues returns a copy of parent with pairs updated in the baggage.
48func ContextWithBaggageValues(parent context.Context, pairs ...label.KeyValue) context.Context {
49 m := baggage.MapFromContext(parent).Apply(baggage.MapUpdate{
50 MultiKV: pairs,
51 })
52 return baggage.ContextWithMap(parent, m)
53}
54
55// ContextWithoutBaggageValues returns a copy of parent in which the values related
56// to keys have been removed from the baggage.
57func ContextWithoutBaggageValues(parent context.Context, keys ...label.Key) context.Context {
58 m := baggage.MapFromContext(parent).Apply(baggage.MapUpdate{
59 DropMultiK: keys,
60 })
61 return baggage.ContextWithMap(parent, m)
62}
63
64// ContextWithoutBaggage returns a copy of parent without baggage.
65func ContextWithoutBaggage(parent context.Context) context.Context {
66 return baggage.ContextWithNoCorrelationData(parent)
67}