diff --git a/examples/MicroserviceExample/Utils/Messaging/MessageSender.cs b/examples/MicroserviceExample/Utils/Messaging/MessageSender.cs index d8c93e706..20dd5b054 100644 --- a/examples/MicroserviceExample/Utils/Messaging/MessageSender.cs +++ b/examples/MicroserviceExample/Utils/Messaging/MessageSender.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; +using OpenTelemetry; using OpenTelemetry.Context.Propagation; using RabbitMQ.Client; @@ -61,7 +62,7 @@ namespace Utils.Messaging if (activity != null) { // Inject the ActivityContext into the message headers to propagate trace context to the receiving service. - TextFormat.Inject(new PropagationContext(activity.Context, activity.Baggage), props, this.InjectTraceContextIntoBasicProperties); + TextFormat.Inject(new PropagationContext(activity.Context, Baggage.Current), props, this.InjectTraceContextIntoBasicProperties); // The OpenTelemetry messaging specification defines a number of attributes. These attributes are added here. RabbitMqHelper.AddMessagingTags(activity); diff --git a/src/OpenTelemetry.Api/Baggage.cs b/src/OpenTelemetry.Api/Baggage.cs new file mode 100644 index 000000000..9e5abd91c --- /dev/null +++ b/src/OpenTelemetry.Api/Baggage.cs @@ -0,0 +1,305 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using OpenTelemetry.Context; + +namespace OpenTelemetry +{ + /// + /// Baggage implementation. + /// + /// + /// Spec reference: Baggage API. + /// + public readonly struct Baggage : IEquatable + { + private static readonly RuntimeContextSlot RuntimeContextSlot = RuntimeContext.RegisterSlot("otel.baggage"); + private static readonly Dictionary EmptyBaggage = new Dictionary(); + + private readonly Dictionary baggage; + + /// + /// Initializes a new instance of the struct. + /// + /// Baggage key/value pairs. + internal Baggage(Dictionary baggage) + { + this.baggage = baggage; + } + + /// + /// Gets or sets the current . + /// + public static Baggage Current + { + get => RuntimeContextSlot.Get(); + set => RuntimeContextSlot.Set(value); + } + + /// + /// Gets the number of key/value pairs in the baggage. + /// + public int Count => this.baggage?.Count ?? 0; + + /// + /// Compare two entries of for equality. + /// + /// First Entry to compare. + /// Second Entry to compare. + public static bool operator ==(Baggage left, Baggage right) => left.Equals(right); + + /// + /// Compare two entries of for not equality. + /// + /// First Entry to compare. + /// Second Entry to compare. + public static bool operator !=(Baggage left, Baggage right) => !(left == right); + + /// + /// Create a instance from dictionary of baggage key/value pairs. + /// + /// Baggage key/value pairs. + /// . + public static Baggage Create(Dictionary baggageItems = null) + { + if (baggageItems == null) + { + return default; + } + + Dictionary baggageCopy = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (KeyValuePair baggageItem in baggageItems) + { + if (string.IsNullOrEmpty(baggageItem.Value)) + { + baggageCopy.Remove(baggageItem.Key); + continue; + } + + baggageCopy[baggageItem.Key] = baggageItem.Value; + } + + return new Baggage(baggageCopy); + } + + /// + /// Returns the name/value pairs in the . + /// + /// Optional . is used if not specified. + /// Baggage key/value pairs. + public static IReadOnlyDictionary GetBaggage(Baggage baggage = default) + => baggage == default ? Current.GetBaggage() : baggage.GetBaggage(); + + /// + /// Returns an enumerator that iterates through the . + /// + /// Optional . is used if not specified. + /// . + public static Dictionary.Enumerator GetEnumerator(Baggage baggage = default) + => baggage == default ? Current.GetEnumerator() : baggage.GetEnumerator(); + + /// + /// Returns the value associated with the given name, or if the given name is not present. + /// + /// Baggage item name. + /// Optional . is used if not specified. + /// Baggage item or if nothing was found. + public static string GetBaggage(string name, Baggage baggage = default) + => baggage == default ? Current.GetBaggage(name) : baggage.GetBaggage(name); + + /// + /// Returns a new which contains the new key/value pair. + /// + /// Baggage item name. + /// Baggage item value. + /// Optional . is used if not specified. + /// New containing the key/value pair. + public static Baggage SetBaggage(string name, string value, Baggage baggage = default) + => baggage == default ? Current.SetBaggage(name, value) : baggage.SetBaggage(name, value); + + /// + /// Returns a new which contains the new key/value pair. + /// + /// Baggage key/value pairs. + /// Optional . is used if not specified. + /// New containing the key/value pair. + public static Baggage SetBaggage(IEnumerable> baggageItems, Baggage baggage = default) + => baggage == default ? Current.SetBaggage(baggageItems) : baggage.SetBaggage(baggageItems); + + /// + /// Returns a new with the key/value pair removed. + /// + /// Baggage item name. + /// Optional . is used if not specified. + /// New containing the key/value pair. + public static Baggage RemoveBaggage(string name, Baggage baggage = default) + => baggage == default ? Current.RemoveBaggage(name) : baggage.RemoveBaggage(name); + + /// + /// Returns a new with all the key/value pairs removed. + /// + /// Optional . is used if not specified. + /// New containing the key/value pair. + public static Baggage ClearBaggage(Baggage baggage = default) + => baggage == default ? Current.ClearBaggage() : baggage.ClearBaggage(); + + /// + /// Returns the name/value pairs in the . + /// + /// Baggage key/value pairs. + public IReadOnlyDictionary GetBaggage() + => this.baggage ?? EmptyBaggage; + + /// + /// Returns the value associated with the given name, or if the given name is not present. + /// + /// Baggage item name. + /// Baggage item or if nothing was found. + public string GetBaggage(string name) + { + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentNullException(nameof(name)); + } + + return this.baggage != null && this.baggage.TryGetValue(name, out string value) + ? value + : null; + } + + /// + /// Returns a new which contains the new key/value pair. + /// + /// Baggage item name. + /// Baggage item value. + /// New containing the key/value pair. + public Baggage SetBaggage(string name, string value) + { + if (string.IsNullOrEmpty(value)) + { + return this.RemoveBaggage(name); + } + + return Current = new Baggage( + new Dictionary(this.baggage ?? EmptyBaggage, StringComparer.OrdinalIgnoreCase) + { + [name] = value, + }); + } + + /// + /// Returns a new which contains the new key/value pair. + /// + /// Baggage key/value pairs. + /// New containing the key/value pair. + public Baggage SetBaggage(params KeyValuePair[] baggageItems) + => this.SetBaggage((IEnumerable>)baggageItems); + + /// + /// Returns a new which contains the new key/value pair. + /// + /// Baggage key/value pairs. + /// New containing the key/value pair. + public Baggage SetBaggage(IEnumerable> baggageItems) + { + if ((baggageItems?.Count() ?? 0) <= 0) + { + return this; + } + + var newBaggage = new Dictionary(this.baggage ?? EmptyBaggage, StringComparer.OrdinalIgnoreCase); + + foreach (var item in baggageItems) + { + if (string.IsNullOrEmpty(item.Value)) + { + newBaggage.Remove(item.Key); + } + else + { + newBaggage[item.Key] = item.Value; + } + } + + return Current = new Baggage(newBaggage); + } + + /// + /// Returns a new with the key/value pair removed. + /// + /// Baggage item name. + /// New containing the key/value pair. + public Baggage RemoveBaggage(string name) + { + var baggage = new Dictionary(this.baggage ?? EmptyBaggage, StringComparer.OrdinalIgnoreCase); + baggage.Remove(name); + + return Current = new Baggage(baggage); + } + + /// + /// Returns a new with all the key/value pairs removed. + /// + /// New containing the key/value pair. + public Baggage ClearBaggage() + => Current = default; + + /// + /// Returns an enumerator that iterates through the . + /// + /// . + public Dictionary.Enumerator GetEnumerator() + => (this.baggage ?? EmptyBaggage).GetEnumerator(); + + /// + public bool Equals(Baggage other) + { + bool baggageIsNullOrEmpty = this.baggage == null || this.baggage.Count <= 0; + + if (baggageIsNullOrEmpty != (other.baggage == null || other.baggage.Count <= 0)) + { + return false; + } + + return baggageIsNullOrEmpty || this.baggage.SequenceEqual(other.baggage); + } + + /// + public override bool Equals(object obj) + => (obj is Baggage baggage) && this.Equals(baggage); + + /// + public override int GetHashCode() + { + var baggage = this.baggage ?? EmptyBaggage; + + unchecked + { + int res = 17; + foreach (var item in baggage) + { + res = (res * 23) + baggage.Comparer.GetHashCode(item.Key); + res = (res * 23) + item.Value.GetHashCode(); + } + + return res; + } + } + } +} diff --git a/src/OpenTelemetry.Api/CHANGELOG.md b/src/OpenTelemetry.Api/CHANGELOG.md index d6829bfd2..f65501d68 100644 --- a/src/OpenTelemetry.Api/CHANGELOG.md +++ b/src/OpenTelemetry.Api/CHANGELOG.md @@ -44,6 +44,11 @@ * Changed `StartSpan` to not set the created span as Active to match the spec ([#994](https://github.com/open-telemetry/opentelemetry-dotnet/pull/994)) * Updated System.Diagnostics.DiagnosticSource to version 5.0.0-preview.8.20407.11. +* Removed `CorrelationContext` and added `Baggage`, an implementation of the + [`Baggage + API`](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/baggage/api.md) + spec + ([#1106](https://github.com/open-telemetry/opentelemetry-dotnet/pull/1106)) ## 0.4.0-beta.2 diff --git a/src/OpenTelemetry.Api/Context/CorrelationContext.cs b/src/OpenTelemetry.Api/Context/CorrelationContext.cs deleted file mode 100644 index 955fde1fd..000000000 --- a/src/OpenTelemetry.Api/Context/CorrelationContext.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; - -namespace OpenTelemetry.Context -{ - /// - /// Correlation context. - /// - public readonly struct CorrelationContext : IEquatable - { - internal static readonly CorrelationContext Empty = new CorrelationContext(null); -#if NET452 - internal static readonly IEnumerable> EmptyBaggage = new KeyValuePair[0]; -#else - internal static readonly IEnumerable> EmptyBaggage = Array.Empty>(); -#endif - private readonly Activity activity; - - internal CorrelationContext(in Activity activity) - { - this.activity = activity; - } - - /// - /// Gets the current . - /// - public static CorrelationContext Current - { - get - { - Activity activity = Activity.Current; - return activity == null - ? Empty - : new CorrelationContext(activity); - } - } - - /// - /// Gets the correlation values. - /// - public IEnumerable> Correlations => this.activity?.Baggage ?? EmptyBaggage; - - /// - /// Compare two entries of for equality. - /// - /// First Entry to compare. - /// Second Entry to compare. - public static bool operator ==(CorrelationContext left, CorrelationContext right) => left.Equals(right); - - /// - /// Compare two entries of for equality. - /// - /// First Entry to compare. - /// Second Entry to compare. - public static bool operator !=(CorrelationContext left, CorrelationContext right) => !(left == right); - - /// - /// Retrieves a correlation item. - /// - /// Correlation item key. - /// Retrieved correlation value or if no match was found. - public string GetCorrelation(string key) - => this.activity?.GetBaggageItem(key); - - /// - /// Adds a correlation item. - /// - /// Correlation item key. - /// Correlation item value. - /// The instance for chaining. - public CorrelationContext AddCorrelation(string key, string value) - { - this.activity?.AddBaggage(key, value); - - return this; - } - - /// - /// Adds correlation items. - /// - /// Correlation items. - /// The instance for chaining. - public CorrelationContext AddCorrelation(IEnumerable> correlations) - { - if (correlations != null) - { - foreach (KeyValuePair correlation in correlations) - { - this.activity?.AddBaggage(correlation.Key, correlation.Value); - } - } - - return this; - } - - /// - public bool Equals(CorrelationContext other) - { - var thisCorrelations = this.Correlations; - var otherCorrelations = other.Correlations; - - if (thisCorrelations.Count() != otherCorrelations.Count()) - { - return false; - } - - var thisEnumerator = thisCorrelations.GetEnumerator(); - var otherEnumerator = otherCorrelations.GetEnumerator(); - - while (thisEnumerator.MoveNext() && otherEnumerator.MoveNext()) - { - if (thisEnumerator.Current.Key != otherEnumerator.Current.Key - || thisEnumerator.Current.Value != otherEnumerator.Current.Value) - { - return false; - } - } - - return true; - } - - /// - public override bool Equals(object obj) - { - return obj is CorrelationContext context && this.Equals(context); - } - - /// - public override int GetHashCode() - { - return this.Correlations.GetHashCode(); - } - } -} diff --git a/src/OpenTelemetry.Api/Context/Propagation/B3Format.cs b/src/OpenTelemetry.Api/Context/Propagation/B3Format.cs index d168ddad3..c633c24e9 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/B3Format.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/B3Format.cs @@ -188,7 +188,7 @@ namespace OpenTelemetry.Context.Propagation return new PropagationContext( new ActivityContext(traceId, spanId, traceOptions, isRemote: true), - context.ActivityBaggage); + context.Baggage); } catch (Exception e) { @@ -248,7 +248,7 @@ namespace OpenTelemetry.Context.Propagation return new PropagationContext( new ActivityContext(traceId, spanId, traceOptions, isRemote: true), - context.ActivityBaggage); + context.Baggage); } catch (Exception e) { diff --git a/src/OpenTelemetry.Api/Context/Propagation/BaggageFormat.cs b/src/OpenTelemetry.Api/Context/Propagation/BaggageFormat.cs index 7fa8afd45..3c970bbbf 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/BaggageFormat.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/BaggageFormat.cs @@ -39,7 +39,7 @@ namespace OpenTelemetry.Context.Propagation /// public PropagationContext Extract(PropagationContext context, T carrier, Func> getter) { - if (context.ActivityBaggage != null) + if (context.Baggage != default) { // If baggage has already been extracted, perform a noop. return context; @@ -59,7 +59,7 @@ namespace OpenTelemetry.Context.Propagation try { - IEnumerable> baggage = null; + Dictionary baggage = null; var baggageCollection = getter(carrier, BaggageHeaderName); if (baggageCollection?.Any() ?? false) { @@ -68,7 +68,7 @@ namespace OpenTelemetry.Context.Propagation return new PropagationContext( context.ActivityContext, - baggage ?? context.ActivityBaggage); + baggage == null ? context.Baggage : new Baggage(baggage)); } catch (Exception ex) { @@ -93,24 +93,29 @@ namespace OpenTelemetry.Context.Propagation return; } - using IEnumerator> e = context.ActivityBaggage?.GetEnumerator(); + using var e = context.Baggage.GetEnumerator(); - if (e?.MoveNext() == true) + if (e.MoveNext() == true) { - int itemCount = 1; + int itemCount = 0; StringBuilder baggage = new StringBuilder(); do { KeyValuePair item = e.Current; + if (string.IsNullOrEmpty(item.Value)) + { + continue; + } + baggage.Append(WebUtility.UrlEncode(item.Key)).Append('=').Append(WebUtility.UrlEncode(item.Value)).Append(','); } - while (e.MoveNext() && itemCount++ < MaxBaggageItems && baggage.Length < MaxBaggageLength); + while (e.MoveNext() && ++itemCount < MaxBaggageItems && baggage.Length < MaxBaggageLength); baggage.Remove(baggage.Length - 1, 1); setter(carrier, BaggageHeaderName, baggage.ToString()); } } - internal static bool TryExtractBaggage(string[] baggageCollection, out IEnumerable> baggage) + internal static bool TryExtractBaggage(string[] baggageCollection, out Dictionary baggage) { int baggageLength = -1; bool done = false; @@ -140,6 +145,11 @@ namespace OpenTelemetry.Context.Propagation if (NameValueHeaderValue.TryParse(pair, out NameValueHeaderValue baggageItem)) { + if (string.IsNullOrEmpty(baggageItem.Name) || string.IsNullOrEmpty(baggageItem.Value)) + { + continue; + } + if (baggageDictionary == null) { baggageDictionary = new Dictionary(); diff --git a/src/OpenTelemetry.Api/Context/Propagation/PropagationContext.cs b/src/OpenTelemetry.Api/Context/Propagation/PropagationContext.cs index ecaeea64b..f633b3cce 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/PropagationContext.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/PropagationContext.cs @@ -15,9 +15,7 @@ // using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; namespace OpenTelemetry.Context.Propagation { @@ -29,23 +27,23 @@ namespace OpenTelemetry.Context.Propagation /// /// Initializes a new instance of the struct. /// - /// Entries for activity context. - /// Entries for activity baggage. - public PropagationContext(ActivityContext activityContext, IEnumerable> activityBaggage) + /// . + /// . + public PropagationContext(ActivityContext activityContext, Baggage baggage) { this.ActivityContext = activityContext; - this.ActivityBaggage = activityBaggage; + this.Baggage = baggage; } /// - /// Gets . + /// Gets . /// public ActivityContext ActivityContext { get; } /// - /// Gets ActivityBaggage. + /// Gets . /// - public IEnumerable> ActivityBaggage { get; } + public Baggage Baggage { get; } /// /// Compare two entries of for equality. @@ -64,35 +62,8 @@ namespace OpenTelemetry.Context.Propagation /// public bool Equals(PropagationContext value) { - if (this.ActivityContext != value.ActivityContext - || this.ActivityBaggage is null != value.ActivityBaggage is null) - { - return false; - } - - if (this.ActivityBaggage is null) - { - return true; - } - - if (this.ActivityBaggage.Count() != value.ActivityBaggage.Count()) - { - return false; - } - - var thisEnumerator = this.ActivityBaggage.GetEnumerator(); - var valueEnumerator = value.ActivityBaggage.GetEnumerator(); - - while (thisEnumerator.MoveNext() && valueEnumerator.MoveNext()) - { - if (thisEnumerator.Current.Key != valueEnumerator.Current.Key - || thisEnumerator.Current.Value != valueEnumerator.Current.Value) - { - return false; - } - } - - return true; + return this.ActivityContext == value.ActivityContext + && this.Baggage == value.Baggage; } /// @@ -103,7 +74,7 @@ namespace OpenTelemetry.Context.Propagation { var hashCode = 323591981; hashCode = (hashCode * -1521134295) + this.ActivityContext.GetHashCode(); - hashCode = (hashCode * -1521134295) + EqualityComparer>>.Default.GetHashCode(this.ActivityBaggage); + hashCode = (hashCode * -1521134295) + this.Baggage.GetHashCode(); return hashCode; } } diff --git a/src/OpenTelemetry.Api/Context/Propagation/TraceContextFormat.cs b/src/OpenTelemetry.Api/Context/Propagation/TraceContextFormat.cs index 971b4bb4d..0dd4bf363 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/TraceContextFormat.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/TraceContextFormat.cs @@ -90,7 +90,7 @@ namespace OpenTelemetry.Context.Propagation return new PropagationContext( new ActivityContext(traceId, spanId, traceoptions, tracestate, isRemote: true), - context.ActivityBaggage); + context.Baggage); } catch (Exception ex) { diff --git a/src/OpenTelemetry.Api/Metrics/BoundCounterMetric.cs b/src/OpenTelemetry.Api/Metrics/BoundCounterMetric.cs index 5e04dffe0..fced2d786 100644 --- a/src/OpenTelemetry.Api/Metrics/BoundCounterMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/BoundCounterMetric.cs @@ -29,15 +29,15 @@ namespace OpenTelemetry.Metrics /// /// Adds the given value to the bound counter metric. /// - /// the associated span context. + /// the associated . /// value by which the bound counter metric should be added. public abstract void Add(in SpanContext context, T value); /// /// Adds the given value to the bound counter metric. /// - /// the associated distributed context. + /// the associated . /// value by which the bound counter metric should be added. - public abstract void Add(in CorrelationContext context, T value); + public abstract void Add(in Baggage context, T value); } } diff --git a/src/OpenTelemetry.Api/Metrics/BoundMeasureMetric.cs b/src/OpenTelemetry.Api/Metrics/BoundMeasureMetric.cs index d5126e2e0..f86965844 100644 --- a/src/OpenTelemetry.Api/Metrics/BoundMeasureMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/BoundMeasureMetric.cs @@ -29,15 +29,15 @@ namespace OpenTelemetry.Metrics /// /// Record the given value to the bound measure metric. /// - /// the associated span context. + /// the associated . /// the measurement to be recorded. public abstract void Record(in SpanContext context, T value); /// /// Record the given value to the bound measure metric. /// - /// the associated distributed context. + /// the associated . /// the measurement to be recorded. - public abstract void Record(in CorrelationContext context, T value); + public abstract void Record(in Baggage context, T value); } } diff --git a/src/OpenTelemetry.Api/Metrics/CounterMetric.cs b/src/OpenTelemetry.Api/Metrics/CounterMetric.cs index 9da617fca..9f1e03e73 100644 --- a/src/OpenTelemetry.Api/Metrics/CounterMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/CounterMetric.cs @@ -30,7 +30,7 @@ namespace OpenTelemetry.Metrics /// /// Adds or Increments the counter. /// - /// the associated span context. + /// the associated . /// value by which the counter should be incremented. /// The labelset associated with this value. public abstract void Add(in SpanContext context, T value, LabelSet labelset); @@ -38,7 +38,7 @@ namespace OpenTelemetry.Metrics /// /// Adds or Increments the counter. /// - /// the associated span context. + /// the associated . /// value by which the counter should be incremented. /// The labels or dimensions associated with this value. public abstract void Add(in SpanContext context, T value, IEnumerable> labels); @@ -46,18 +46,18 @@ namespace OpenTelemetry.Metrics /// /// Adds or Increments the counter. /// - /// the associated distributed context. + /// the associated . /// value by which the counter should be incremented. /// The labelset associated with this value. - public abstract void Add(in CorrelationContext context, T value, LabelSet labelset); + public abstract void Add(in Baggage context, T value, LabelSet labelset); /// /// Adds or Increments the counter. /// - /// the associated distributed context. + /// the associated . /// value by which the counter should be incremented. /// The labels or dimensions associated with this value. - public abstract void Add(in CorrelationContext context, T value, IEnumerable> labels); + public abstract void Add(in Baggage context, T value, IEnumerable> labels); /// /// Gets the bound counter metric with given labelset. diff --git a/src/OpenTelemetry.Api/Metrics/MeasureMetric.cs b/src/OpenTelemetry.Api/Metrics/MeasureMetric.cs index 153b2497d..5dfea1ecb 100644 --- a/src/OpenTelemetry.Api/Metrics/MeasureMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/MeasureMetric.cs @@ -30,7 +30,7 @@ namespace OpenTelemetry.Metrics /// /// Records a measure. /// - /// the associated span context. + /// the associated . /// value to record. /// The labelset associated with this value. public void Record(in SpanContext context, T value, LabelSet labelset) => this.Bind(labelset).Record(context, value); @@ -38,7 +38,7 @@ namespace OpenTelemetry.Metrics /// /// Records a measure. /// - /// the associated span context. + /// the associated . /// value to record. /// The labels or dimensions associated with this value. public void Record(in SpanContext context, T value, IEnumerable> labels) => this.Bind(labels).Record(context, value); @@ -46,18 +46,18 @@ namespace OpenTelemetry.Metrics /// /// Records a measure. /// - /// the associated distributed context. + /// the associated . /// value to record. /// The labelset associated with this value. - public void Record(in CorrelationContext context, T value, LabelSet labelset) => this.Bind(labelset).Record(context, value); + public void Record(in Baggage context, T value, LabelSet labelset) => this.Bind(labelset).Record(context, value); /// /// Records a measure. /// - /// the associated distributed context. + /// the associated . /// value to record. /// The labels or dimensions associated with this value. - public void Record(in CorrelationContext context, T value, IEnumerable> labels) => this.Bind(labels).Record(context, value); + public void Record(in Baggage context, T value, IEnumerable> labels) => this.Bind(labels).Record(context, value); /// /// Gets the bound measure metric with given labelset. diff --git a/src/OpenTelemetry.Api/Metrics/NoopBoundCounterMetric.cs b/src/OpenTelemetry.Api/Metrics/NoopBoundCounterMetric.cs index 6acfce58d..c357aaf54 100644 --- a/src/OpenTelemetry.Api/Metrics/NoopBoundCounterMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/NoopBoundCounterMetric.cs @@ -37,7 +37,7 @@ namespace OpenTelemetry.Metrics } /// - public override void Add(in CorrelationContext context, T value) + public override void Add(in Baggage context, T value) { } } diff --git a/src/OpenTelemetry.Api/Metrics/NoopBoundMeasureMetric.cs b/src/OpenTelemetry.Api/Metrics/NoopBoundMeasureMetric.cs index 66aef213e..165a748a5 100644 --- a/src/OpenTelemetry.Api/Metrics/NoopBoundMeasureMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/NoopBoundMeasureMetric.cs @@ -37,7 +37,7 @@ namespace OpenTelemetry.Metrics } /// - public override void Record(in CorrelationContext context, T value) + public override void Record(in Baggage context, T value) { } } diff --git a/src/OpenTelemetry.Api/Metrics/NoopCounterMetric.cs b/src/OpenTelemetry.Api/Metrics/NoopCounterMetric.cs index de95886dd..2aee061d3 100644 --- a/src/OpenTelemetry.Api/Metrics/NoopCounterMetric.cs +++ b/src/OpenTelemetry.Api/Metrics/NoopCounterMetric.cs @@ -43,12 +43,12 @@ namespace OpenTelemetry.Metrics } /// - public override void Add(in CorrelationContext context, T value, LabelSet labelset) + public override void Add(in Baggage context, T value, LabelSet labelset) { } /// - public override void Add(in CorrelationContext context, T value, IEnumerable> labels) + public override void Add(in Baggage context, T value, IEnumerable> labels) { } diff --git a/src/OpenTelemetry.Api/Trace/TelemetrySpan.cs b/src/OpenTelemetry.Api/Trace/TelemetrySpan.cs index 9ec013835..524983bcf 100644 --- a/src/OpenTelemetry.Api/Trace/TelemetrySpan.cs +++ b/src/OpenTelemetry.Api/Trace/TelemetrySpan.cs @@ -31,11 +31,6 @@ namespace OpenTelemetry.Trace { internal static readonly TelemetrySpan NoopInstance = new TelemetrySpan(null); internal readonly Activity Activity; -#if NET452 - private static readonly IEnumerable> EmptyBaggage = new KeyValuePair[0]; -#else - private static readonly IEnumerable> EmptyBaggage = Array.Empty>(); -#endif internal TelemetrySpan(Activity activity) { @@ -71,11 +66,6 @@ namespace OpenTelemetry.Trace } } - /// - /// Gets the span baggage. - /// - public IEnumerable> Baggage => this.Activity?.Baggage ?? EmptyBaggage; - /// /// Sets the status of the span execution. /// @@ -281,30 +271,6 @@ namespace OpenTelemetry.Trace this.Activity?.Stop(); } - /// - /// Retrieves a baggage item. - /// - /// Baggage item key. - /// Retrieved baggage value or if no match was found. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public string GetBaggageItem(string key) - { - return this.Activity?.GetBaggageItem(key); - } - - /// - /// Adds a baggage item to the . - /// - /// Baggage item key. - /// Baggage item value. - /// The instance for chaining. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public TelemetrySpan AddBaggage(string key, string value) - { - this.Activity?.AddBaggage(key, value); - return this; - } - /// /// Record Exception. /// diff --git a/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs index 201ff7ec4..060fa4665 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Web; using System.Web.Routing; +using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; @@ -86,12 +87,9 @@ namespace OpenTelemetry.Instrumentation.AspNet.Implementation activity = newOne; } - if (ctx.ActivityBaggage != null) + if (ctx.Baggage != default) { - foreach (var baggageItem in ctx.ActivityBaggage) - { - activity.AddBaggage(baggageItem.Key, baggageItem.Value); - } + Baggage.Current = ctx.Baggage; } } @@ -134,7 +132,7 @@ namespace OpenTelemetry.Instrumentation.AspNet.Implementation // this instrumentation created in Start. // This is because Asp.Net, under certain circumstances, restores Activity.Current // to its own activity. - if (activity.OperationName.Equals("Microsoft.AspNet.HttpReqIn.Start", StringComparison.Ordinal)) + if (activity.OperationName.Equals("Microsoft.AspNet.HttpReqIn.Start")) { // This block is hit if Asp.Net did restore Current to its own activity, // and we need to retrieve the one created by HttpInListener, @@ -194,7 +192,7 @@ namespace OpenTelemetry.Instrumentation.AspNet.Implementation if (!(this.options.TextFormat is TraceContextFormat)) { - if (activity.OperationName.Equals(ActivityNameByHttpInListener, StringComparison.Ordinal)) + if (activity.OperationName.Equals(ActivityNameByHttpInListener)) { // If instrumentation started a new Activity, it must // be stopped here. diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs index 6a75517be..e073aacc1 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs @@ -17,11 +17,11 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; using System.Linq; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Instrumentation.GrpcNetClient; using OpenTelemetry.Trace; @@ -87,12 +87,9 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation activity = newOne; } - if (ctx.ActivityBaggage != null) + if (ctx.Baggage != default) { - foreach (var baggageItem in ctx.ActivityBaggage) - { - activity.AddBaggage(baggageItem.Key, baggageItem.Value); - } + Baggage.Current = ctx.Baggage; } } @@ -155,7 +152,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation } } - if (activity.OperationName.Equals(ActivityNameByHttpInListener, StringComparison.Ordinal)) + if (activity.OperationName.Equals(ActivityNameByHttpInListener)) { // If instrumentation started a new Activity, it must // be stopped here. @@ -261,7 +258,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation } activity.AddTag(SemanticConventions.AttributeNetPeerIp, context.Connection.RemoteIpAddress.ToString()); - activity.AddTag(SemanticConventions.AttributeNetPeerPort, context.Connection.RemotePort.ToString(CultureInfo.InvariantCulture)); + activity.AddTag(SemanticConventions.AttributeNetPeerPort, context.Connection.RemotePort.ToString()); activity.SetStatus(GrpcTagHelper.GetGrpcStatusCodeFromActivity(activity)); } } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index 71c7a28af..d0200800a 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -16,13 +16,13 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; using System.Net.Http; using System.Net.Sockets; using System.Reflection; using System.Runtime.Versioning; using System.Text.RegularExpressions; using System.Threading.Tasks; +using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; @@ -71,7 +71,7 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation { var match = CoreAppMajorVersionCheckRegex.Match(framework); - this.httpClientSupportsW3C = match.Success && int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture) >= 3; + this.httpClientSupportsW3C = match.Success && int.Parse(match.Groups[1].Value) >= 3; } this.options = options; @@ -113,7 +113,7 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation if (!(this.httpClientSupportsW3C && this.options.TextFormat is TraceContextFormat)) { - this.options.TextFormat.Inject(new PropagationContext(activity.Context, activity.Baggage), request, HttpRequestMessageHeaderValueSetter); + this.options.TextFormat.Inject(new PropagationContext(activity.Context, Baggage.Current), request, HttpRequestMessageHeaderValueSetter); } } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index b5b8dc158..4d31674cb 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -23,6 +23,7 @@ using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text; +using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; @@ -189,7 +190,7 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InstrumentRequest(HttpWebRequest request, Activity activity) - => Options.TextFormat.Inject(new PropagationContext(activity.Context, activity.Baggage), request, HttpWebRequestHeaderValuesSetter); + => Options.TextFormat.Inject(new PropagationContext(activity.Context, Baggage.Current), request, HttpWebRequestHeaderValuesSetter); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsRequestInstrumented(HttpWebRequest request) diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs index 8cf0baa17..6b0bf6e9a 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs @@ -17,22 +17,20 @@ using System; using System.Collections.Generic; using global::OpenTracing; +using OpenTelemetry.Context; namespace OpenTelemetry.Shims.OpenTracing { public sealed class SpanContextShim : ISpanContext { - private readonly IEnumerable> baggage; - - public SpanContextShim(in Trace.SpanContext spanContext, IEnumerable> baggage = null) + public SpanContextShim(in Trace.SpanContext spanContext) { if (!spanContext.IsValid) { - throw new ArgumentException($"{nameof(spanContext)} must be valid."); + throw new ArgumentException(nameof(spanContext)); } this.SpanContext = spanContext; - this.baggage = baggage; } public Trace.SpanContext SpanContext { get; private set; } @@ -43,8 +41,7 @@ namespace OpenTelemetry.Shims.OpenTracing /// public string SpanId => this.SpanContext.SpanId.ToString(); - /// public IEnumerable> GetBaggageItems() - => this.baggage; + => Baggage.GetBaggage(); } } diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs index e751ecd42..e4a1fb861 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; using System.Linq; using global::OpenTracing; +using OpenTelemetry.Context; using OpenTelemetry.Trace; namespace OpenTelemetry.Shims.OpenTracing @@ -52,7 +53,7 @@ namespace OpenTelemetry.Shims.OpenTracing throw new ArgumentException(nameof(this.Span.Context)); } - this.spanContextShim = new SpanContextShim(this.Span.Context, this.Span.Baggage); + this.spanContextShim = new SpanContextShim(this.Span.Context); } public ISpanContext Context => this.spanContextShim; @@ -73,14 +74,7 @@ namespace OpenTelemetry.Shims.OpenTracing /// public string GetBaggageItem(string key) - { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - - return this.Context.GetBaggageItems().FirstOrDefault(kvp => kvp.Key.Equals(key, StringComparison.Ordinal)).Value; - } + => Baggage.GetBaggage(key); /// public global::OpenTracing.ISpan Log(DateTimeOffset timestamp, IEnumerable> fields) @@ -173,13 +167,8 @@ namespace OpenTelemetry.Shims.OpenTracing /// public global::OpenTracing.ISpan SetBaggageItem(string key, string value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - - // TODO Revisit once CorrelationContext is finalized - throw new NotImplementedException(); + Baggage.SetBaggage(key, value); + return this; } /// diff --git a/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs b/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs index 0b2e14f82..aa07208f8 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using global::OpenTracing.Propagation; +using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; namespace OpenTelemetry.Shims.OpenTracing @@ -83,7 +84,12 @@ namespace OpenTelemetry.Shims.OpenTracing propagationContext = this.textFormat.Extract(propagationContext, carrierMap, GetCarrierKeyValue); } - return !propagationContext.ActivityContext.IsValid() ? null : new SpanContextShim(new Trace.SpanContext(propagationContext.ActivityContext), propagationContext.ActivityBaggage); + // TODO: + // Not sure what to do here. Really, Baggage should be returned and not set until this ISpanContext is turned into a live Span. + // But that code doesn't seem to exist. + // Baggage.Current = propagationContext.Baggage; + + return !propagationContext.ActivityContext.IsValid() ? null : new SpanContextShim(new Trace.SpanContext(propagationContext.ActivityContext)); } /// @@ -115,7 +121,7 @@ namespace OpenTelemetry.Shims.OpenTracing if ((format == BuiltinFormats.TextMap || format == BuiltinFormats.HttpHeaders) && carrier is ITextMap textMapCarrier) { this.textFormat.Inject( - new PropagationContext(shim.SpanContext, shim.GetBaggageItems()), + new PropagationContext(shim.SpanContext, Baggage.Current), textMapCarrier, (instrumentation, key, value) => instrumentation.Set(key, value)); } diff --git a/src/OpenTelemetry/Metrics/DoubleBoundCounterMetricSdk.cs b/src/OpenTelemetry/Metrics/DoubleBoundCounterMetricSdk.cs index 57bf8dbb8..f5c652c2a 100644 --- a/src/OpenTelemetry/Metrics/DoubleBoundCounterMetricSdk.cs +++ b/src/OpenTelemetry/Metrics/DoubleBoundCounterMetricSdk.cs @@ -34,7 +34,7 @@ namespace OpenTelemetry.Metrics this.sumAggregator.Update(value); } - public override void Add(in CorrelationContext context, double value) + public override void Add(in Baggage context, double value) { this.sumAggregator.Update(value); } diff --git a/src/OpenTelemetry/Metrics/DoubleBoundMeasureMetricSdk.cs b/src/OpenTelemetry/Metrics/DoubleBoundMeasureMetricSdk.cs index 1c457f0ad..1542c3950 100644 --- a/src/OpenTelemetry/Metrics/DoubleBoundMeasureMetricSdk.cs +++ b/src/OpenTelemetry/Metrics/DoubleBoundMeasureMetricSdk.cs @@ -29,7 +29,7 @@ namespace OpenTelemetry.Metrics this.measureAggregator.Update(value); } - public override void Record(in CorrelationContext context, double value) + public override void Record(in Baggage context, double value) { this.measureAggregator.Update(value); } diff --git a/src/OpenTelemetry/Metrics/DoubleCounterMetricSdk.cs b/src/OpenTelemetry/Metrics/DoubleCounterMetricSdk.cs index 9832b8748..9fdae904c 100644 --- a/src/OpenTelemetry/Metrics/DoubleCounterMetricSdk.cs +++ b/src/OpenTelemetry/Metrics/DoubleCounterMetricSdk.cs @@ -39,13 +39,13 @@ namespace OpenTelemetry.Metrics this.Bind(new LabelSetSdk(labels), isShortLived: true).Add(context, value); } - public override void Add(in CorrelationContext context, double value, LabelSet labelset) + public override void Add(in Baggage context, double value, LabelSet labelset) { // user not using bound instrument. Hence create a short-lived bound instrument. this.Bind(labelset, isShortLived: true).Add(context, value); } - public override void Add(in CorrelationContext context, double value, IEnumerable> labels) + public override void Add(in Baggage context, double value, IEnumerable> labels) { // user not using bound instrument. Hence create a short-lived bound instrument. this.Bind(new LabelSetSdk(labels), isShortLived: true).Add(context, value); diff --git a/src/OpenTelemetry/Metrics/Int64BoundCounterMetricSdk.cs b/src/OpenTelemetry/Metrics/Int64BoundCounterMetricSdk.cs index 86b2d7242..46d2cd9c3 100644 --- a/src/OpenTelemetry/Metrics/Int64BoundCounterMetricSdk.cs +++ b/src/OpenTelemetry/Metrics/Int64BoundCounterMetricSdk.cs @@ -34,7 +34,7 @@ namespace OpenTelemetry.Metrics this.sumAggregator.Update(value); } - public override void Add(in CorrelationContext context, long value) + public override void Add(in Baggage context, long value) { this.sumAggregator.Update(value); } diff --git a/src/OpenTelemetry/Metrics/Int64BoundMeasureMetricSdk.cs b/src/OpenTelemetry/Metrics/Int64BoundMeasureMetricSdk.cs index 77c6c16f5..d20a80a36 100644 --- a/src/OpenTelemetry/Metrics/Int64BoundMeasureMetricSdk.cs +++ b/src/OpenTelemetry/Metrics/Int64BoundMeasureMetricSdk.cs @@ -29,7 +29,7 @@ namespace OpenTelemetry.Metrics this.measureAggregator.Update(value); } - public override void Record(in CorrelationContext context, long value) + public override void Record(in Baggage context, long value) { this.measureAggregator.Update(value); } diff --git a/src/OpenTelemetry/Metrics/Int64CounterMetricSdk.cs b/src/OpenTelemetry/Metrics/Int64CounterMetricSdk.cs index ea8e2dd67..d2d03adee 100644 --- a/src/OpenTelemetry/Metrics/Int64CounterMetricSdk.cs +++ b/src/OpenTelemetry/Metrics/Int64CounterMetricSdk.cs @@ -39,13 +39,13 @@ namespace OpenTelemetry.Metrics this.Bind(new LabelSetSdk(labels), isShortLived: true).Add(context, value); } - public override void Add(in CorrelationContext context, long value, LabelSet labelset) + public override void Add(in Baggage context, long value, LabelSet labelset) { // user not using bound instrument. Hence create a short-lived bound instrument. this.Bind(labelset, isShortLived: true).Add(context, value); } - public override void Add(in CorrelationContext context, long value, IEnumerable> labels) + public override void Add(in Baggage context, long value, IEnumerable> labels) { // user not using bound instrument. Hence create a short-lived bound instrument. this.Bind(new LabelSetSdk(labels), isShortLived: true).Add(context, value); diff --git a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs index a3e45e400..e63c05f1d 100644 --- a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs @@ -133,7 +133,7 @@ namespace OpenTelemetry.Instrumentation.AspNet.Tests expectedTraceId, expectedSpanId, ActivityTraceFlags.Recorded), - null)); + default)); var activity = new Activity(ActivityNameAspNet).AddBaggage("Stuff", "123"); activity.SetParentId(expectedTraceId, expectedSpanId, ActivityTraceFlags.Recorded); diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs index 3b5db7b8c..8250daca8 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs @@ -143,11 +143,13 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Tests var expectedSpanId = ActivitySpanId.CreateRandom(); var textFormat = new Mock(); - textFormat.Setup(m => m.Extract(It.IsAny(), It.IsAny(), It.IsAny>>())).Returns(new PropagationContext( - new ActivityContext( - expectedTraceId, - expectedSpanId, - ActivityTraceFlags.Recorded), null)); + textFormat.Setup(m => m.Extract(It.IsAny(), It.IsAny(), It.IsAny>>())).Returns( + new PropagationContext( + new ActivityContext( + expectedTraceId, + expectedSpanId, + ActivityTraceFlags.Recorded), + default)); // Arrange using (var testFactory = this.factory diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.netcore31.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.netcore31.cs index 3283576ca..758c67664 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.netcore31.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.netcore31.cs @@ -21,6 +21,7 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Moq; +using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Instrumentation.Http.Implementation; using OpenTelemetry.Tests; @@ -250,6 +251,43 @@ namespace OpenTelemetry.Instrumentation.Http.Tests Assert.Equal(2, processor.Invocations.Count); // OnShutdown/Dispose called. } + [Fact] + public async Task HttpClientInstrumentationCorrelationAndBaggage() + { + var activityProcessor = new Mock(); + + using var parent = new Activity("w3c activity"); + parent.SetIdFormat(ActivityIdFormat.W3C); + parent.AddBaggage("k1", "v1"); + parent.ActivityTraceFlags = ActivityTraceFlags.Recorded; + parent.Start(); + + Baggage.SetBaggage("k2", "v2"); + + using (Sdk.CreateTracerProviderBuilder() + .AddHttpClientInstrumentation() + .AddProcessor(activityProcessor.Object) + .Build()) + { + using var c = new HttpClient(); + using var r = await c.GetAsync("https://opentelemetry.io/").ConfigureAwait(false); + } + + Assert.Equal(4, activityProcessor.Invocations.Count); + + var activity = (Activity)activityProcessor.Invocations[1].Arguments[0]; + + HttpRequestMessage thisRequest = (HttpRequestMessage)activity.GetCustomProperty(HttpHandlerDiagnosticListener.RequestCustomPropertyName); + + string[] correlationContext = thisRequest.Headers.GetValues("Correlation-Context").First().Split(','); + Assert.Single(correlationContext); + Assert.Contains("k1=v1", correlationContext); + + string[] baggage = thisRequest.Headers.GetValues("Baggage").First().Split(','); + Assert.Single(baggage); + Assert.Contains("k2=v2", baggage); + } + public void Dispose() { this.serverLifeTime?.Dispose(); diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index cc8b15a0c..1ab063d4d 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -24,6 +24,7 @@ using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using OpenTelemetry.Context; using OpenTelemetry.Instrumentation.Http.Implementation; using OpenTelemetry.Tests; using OpenTelemetry.Trace; @@ -375,7 +376,7 @@ namespace OpenTelemetry.Instrumentation.Http.Tests } [Fact] - public async Task TestTraceStateAndCorrelationContext() + public async Task TestTraceStateAndBaggage() { try { @@ -384,9 +385,10 @@ namespace OpenTelemetry.Instrumentation.Http.Tests var parent = new Activity("w3c activity"); parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom()); parent.TraceStateString = "some=state"; - parent.AddBaggage("k", "v"); parent.Start(); + Baggage.SetBaggage("k", "v"); + // Send a random Http request to generate some events using (var client = new HttpClient()) { @@ -402,10 +404,10 @@ namespace OpenTelemetry.Instrumentation.Http.Tests var traceparent = startRequest.Headers["traceparent"]; var tracestate = startRequest.Headers["tracestate"]; - var correlationContext = startRequest.Headers["baggage"]; + var baggage = startRequest.Headers["baggage"]; Assert.NotNull(traceparent); Assert.Equal("some=state", tracestate); - Assert.Equal("k=v", correlationContext); + Assert.Equal("k=v", baggage); Assert.StartsWith($"00-{parent.TraceId.ToHexString()}-", traceparent); Assert.Matches("^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$", traceparent); } @@ -692,32 +694,29 @@ namespace OpenTelemetry.Instrumentation.Http.Tests [Fact] public async Task TestInvalidBaggage() { - var parentActivity = new Activity("parent") - .AddBaggage("key", "value") - .AddBaggage("bad/key", "value") - .AddBaggage("goodkey", "bad/value") - .Start(); - using (var eventRecords = new ActivitySourceRecorder()) + Baggage + .SetBaggage("key", "value") + .SetBaggage("bad/key", "value") + .SetBaggage("goodkey", "bad/value"); + + using var eventRecords = new ActivitySourceRecorder(); + + using (var client = new HttpClient()) { - using (var client = new HttpClient()) - { - (await client.GetAsync(this.BuildRequestUrl())).Dispose(); - } - - Assert.Equal(2, eventRecords.Records.Count()); - Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); - Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - - WebRequest thisRequest = (WebRequest)eventRecords.Records.First().Value.GetCustomProperty(HttpWebRequestActivitySource.RequestCustomPropertyName); - string[] correlationContext = thisRequest.Headers["baggage"].Split(','); - - Assert.Equal(3, correlationContext.Length); - Assert.Contains("key=value", correlationContext); - Assert.Contains("bad%2Fkey=value", correlationContext); - Assert.Contains("goodkey=bad%2Fvalue", correlationContext); + (await client.GetAsync(this.BuildRequestUrl())).Dispose(); } - parentActivity.Stop(); + Assert.Equal(2, eventRecords.Records.Count()); + Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); + Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); + + WebRequest thisRequest = (WebRequest)eventRecords.Records.First().Value.GetCustomProperty(HttpWebRequestActivitySource.RequestCustomPropertyName); + string[] baggage = thisRequest.Headers["Baggage"].Split(','); + + Assert.Equal(3, baggage.Length); + Assert.Contains("key=value", baggage); + Assert.Contains("bad%2Fkey=value", baggage); + Assert.Contains("goodkey=bad%2Fvalue", baggage); } /// diff --git a/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanContextShimTests.cs b/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanContextShimTests.cs index 352b2c122..b870dc1df 100644 --- a/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanContextShimTests.cs +++ b/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanContextShimTests.cs @@ -51,7 +51,7 @@ namespace OpenTelemetry.Shims.OpenTracing.Tests { var shim = GetSpanContextShim(); var baggage = shim.GetBaggageItems(); - Assert.Null(baggage); + Assert.Empty(baggage); } internal static SpanContextShim GetSpanContextShim() diff --git a/test/OpenTelemetry.Tests/BaggageTests.cs b/test/OpenTelemetry.Tests/BaggageTests.cs new file mode 100644 index 000000000..2a7ada747 --- /dev/null +++ b/test/OpenTelemetry.Tests/BaggageTests.cs @@ -0,0 +1,273 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Collections.Generic; +using Xunit; + +namespace OpenTelemetry.Tests +{ + public class BaggageTests + { + private const string K1 = "Key1"; + private const string K2 = "Key2"; + private const string K3 = "Key3"; + + private const string V1 = "Value1"; + private const string V2 = "Value2"; + private const string V3 = "Value3"; + + [Fact] + public void EmptyTest() + { + Assert.Empty(Baggage.GetBaggage()); + Assert.Empty(Baggage.Current.GetBaggage()); + } + + [Fact] + public void SetAndGetTest() + { + var list = new List>(2) + { + new KeyValuePair(K1, V1), + new KeyValuePair(K2, V2), + }; + + Baggage.SetBaggage(K1, V1); + Baggage.Current.SetBaggage(K2, V2); + + Assert.NotEmpty(Baggage.GetBaggage()); + Assert.Equal(list, Baggage.GetBaggage(Baggage.Current)); + + Assert.Equal(V1, Baggage.GetBaggage(K1)); + Assert.Equal(V1, Baggage.GetBaggage(K1.ToLower())); + Assert.Equal(V1, Baggage.GetBaggage(K1.ToUpper())); + Assert.Null(Baggage.GetBaggage("NO_KEY")); + Assert.Equal(V2, Baggage.Current.GetBaggage(K2)); + + Assert.Throws(() => Baggage.GetBaggage(null)); + } + + [Fact] + public void SetExistingKeyTest() + { + var list = new List>(2) + { + new KeyValuePair(K1, V1), + }; + + Baggage.Current.SetBaggage(new KeyValuePair(K1, V1)); + var baggage = Baggage.SetBaggage(K1, V1); + Baggage.SetBaggage(new Dictionary { [K1] = V1 }, baggage); + + Assert.Equal(list, Baggage.GetBaggage()); + } + + [Fact] + public void SetNullValueTest() + { + var baggage = Baggage.Current; + baggage = Baggage.SetBaggage(K1, V1, baggage); + + Assert.Equal(1, Baggage.Current.Count); + Assert.Equal(1, baggage.Count); + + Baggage.Current.SetBaggage(K2, null); + + Assert.Equal(1, Baggage.Current.Count); + + Assert.Empty(Baggage.SetBaggage(K1, null).GetBaggage()); + + Baggage.SetBaggage(K1, V1); + Baggage.SetBaggage(new Dictionary + { + [K1] = null, + [K2] = V2, + }); + Assert.Equal(1, Baggage.Current.Count); + Assert.Contains(Baggage.GetBaggage(), kvp => kvp.Key == K2); + } + + [Fact] + public void RemoveTest() + { + var empty = Baggage.Current; + var empty2 = Baggage.RemoveBaggage(K1); + Assert.True(empty == empty2); + + var baggage = Baggage.SetBaggage(new Dictionary + { + [K1] = V1, + [K2] = V2, + [K3] = V3, + }); + + var baggage2 = Baggage.RemoveBaggage(K1, baggage); + + Assert.Equal(3, baggage.Count); + Assert.Equal(2, baggage2.Count); + + Assert.DoesNotContain(new KeyValuePair(K1, V1), baggage2.GetBaggage()); + } + + [Fact] + public void ClearTest() + { + var baggage = Baggage.SetBaggage(new Dictionary + { + [K1] = V1, + [K2] = V2, + [K3] = V3, + }); + + Assert.Equal(3, baggage.Count); + + Baggage.ClearBaggage(); + + Assert.Equal(0, Baggage.Current.Count); + } + + [Fact] + public void ContextFlowTest() + { + var baggage = Baggage.SetBaggage(K1, V1); + var baggage2 = Baggage.Current.SetBaggage(K2, V2); + var baggage3 = Baggage.SetBaggage(K3, V3); + + Assert.Equal(1, baggage.Count); + Assert.Equal(2, baggage2.Count); + Assert.Equal(3, baggage3.Count); + + Baggage.Current = baggage; + + var baggage4 = Baggage.SetBaggage(K3, V3); + + Assert.Equal(2, baggage4.Count); + Assert.DoesNotContain(new KeyValuePair(K2, V2), baggage4.GetBaggage()); + } + + [Fact] + public void EnumeratorTest() + { + var list = new List>(2) + { + new KeyValuePair(K1, V1), + new KeyValuePair(K2, V2), + }; + + var baggage = Baggage.SetBaggage(K1, V1); + baggage = Baggage.SetBaggage(K2, V2, baggage); + + var enumerator = Baggage.GetEnumerator(baggage); + + Assert.True(enumerator.MoveNext()); + var tag1 = enumerator.Current; + Assert.True(enumerator.MoveNext()); + var tag2 = enumerator.Current; + Assert.False(enumerator.MoveNext()); + + Assert.Equal(list, new List> { tag1, tag2 }); + + Baggage.ClearBaggage(); + + enumerator = Baggage.GetEnumerator(); + + Assert.False(enumerator.MoveNext()); + } + + [Fact] + public void EqualsTest() + { + var bc1 = new Baggage(new Dictionary() { [K1] = V1, [K2] = V2 }); + var bc2 = new Baggage(new Dictionary() { [K1] = V1, [K2] = V2 }); + var bc3 = new Baggage(new Dictionary() { [K2] = V2, [K1] = V1 }); + var bc4 = new Baggage(new Dictionary() { [K1] = V1, [K2] = V1 }); + var bc5 = new Baggage(new Dictionary() { [K1] = V2, [K2] = V1 }); + + Assert.True(bc1.Equals(bc2)); + + Assert.False(bc1.Equals(bc3)); + Assert.False(bc1.Equals(bc4)); + Assert.False(bc2.Equals(bc4)); + Assert.False(bc3.Equals(bc4)); + Assert.False(bc5.Equals(bc4)); + Assert.False(bc4.Equals(bc5)); + } + + [Fact] + public void CreateBaggageTest() + { + var baggage = Baggage.Create(null); + + Assert.Equal(default, baggage); + + baggage = Baggage.Create(new Dictionary + { + [K1] = V1, + ["key2"] = "value2", + ["KEY2"] = "VALUE2", + ["KEY3"] = "VALUE3", + ["Key3"] = null, + }); + + Assert.Equal(2, baggage.Count); + Assert.Contains(baggage.GetBaggage(), kvp => kvp.Key == K1); + Assert.Equal("VALUE2", Baggage.GetBaggage("key2", baggage)); + } + + [Fact] + public void EqualityTests() + { + var emptyBaggage = Baggage.Create(null); + + var baggage = Baggage.SetBaggage(K1, V1); + + Assert.NotEqual(emptyBaggage, baggage); + + Assert.True(emptyBaggage != baggage); + + baggage = Baggage.ClearBaggage(baggage); + + Assert.Equal(emptyBaggage, baggage); + + baggage = Baggage.SetBaggage(K1, V1); + + var baggage2 = Baggage.SetBaggage(null); + + Assert.Equal(baggage, baggage2); + + Assert.False(baggage.Equals(this)); + Assert.True(baggage.Equals((object)baggage2)); + } + + [Fact] + public void GetHashCodeTests() + { + var baggage = Baggage.Current; + var emptyBaggage = Baggage.Create(null); + + Assert.Equal(emptyBaggage.GetHashCode(), baggage.GetHashCode()); + + baggage = Baggage.SetBaggage(K1, V1, baggage); + + Assert.NotEqual(emptyBaggage.GetHashCode(), baggage.GetHashCode()); + + var expectedBaggage = Baggage.Create(new Dictionary { [K1] = V1 }); + + Assert.Equal(expectedBaggage.GetHashCode(), baggage.GetHashCode()); + } + } +} diff --git a/test/OpenTelemetry.Tests/Context/CorrelationContextTest.cs b/test/OpenTelemetry.Tests/Context/CorrelationContextTest.cs deleted file mode 100644 index 56bcc4430..000000000 --- a/test/OpenTelemetry.Tests/Context/CorrelationContextTest.cs +++ /dev/null @@ -1,148 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -using System.Collections.Generic; -using System.Diagnostics; -using Xunit; - -namespace OpenTelemetry.Context.Tests -{ - public class CorrelationContextTest - { - private const string K1 = "Key1"; - private const string K2 = "Key2"; - - private const string V1 = "Value1"; - private const string V2 = "Value2"; - - [Fact] - public void EmptyContext() - { - var cc = CorrelationContext.Current; - Assert.Empty(cc.Correlations); - Assert.Equal(CorrelationContext.Empty, cc); - - cc.AddCorrelation(K1, V1); - Assert.Empty(cc.Correlations); - - Assert.Null(cc.GetCorrelation(K1)); - } - - [Fact] - public void NonEmptyContext() - { - using Activity activity = new Activity("TestActivity"); - activity.Start(); - - var list = new List>(2) - { - new KeyValuePair(K1, V1), - new KeyValuePair(K2, V2), - }; - - var cc = CorrelationContext.Current; - - cc.AddCorrelation(K1, V1); - cc.AddCorrelation(K2, V2); - - Assert.NotEqual(CorrelationContext.Empty, cc); - Assert.Equal(list, cc.Correlations); - - Assert.Equal(V1, cc.GetCorrelation(K1)); - Assert.Null(cc.GetCorrelation(K1.ToLower())); - Assert.Null(cc.GetCorrelation(K1.ToUpper())); - Assert.Null(cc.GetCorrelation("NO_KEY")); - } - - [Fact] - public void AddExistingKey() - { - using Activity activity = new Activity("TestActivity"); - activity.Start(); - - var list = new List>(2) - { - new KeyValuePair(K1, V1), - new KeyValuePair(K1, V1), - }; - - var cc = CorrelationContext.Current; - - cc.AddCorrelation(K1, V1); - cc.AddCorrelation(K1, V1); - - Assert.Equal(list, cc.Correlations); - } - - [Fact] - public void TestIterator() - { - using Activity activity = new Activity("TestActivity"); - activity.Start(); - - var list = new List>(2) - { - new KeyValuePair(K1, V1), - new KeyValuePair(K2, V2), - }; - - var cc = CorrelationContext.Current; - - cc.AddCorrelation(K1, V1); - cc.AddCorrelation(K2, V2); - - var i = cc.Correlations.GetEnumerator(); - - Assert.True(i.MoveNext()); - var tag1 = i.Current; - Assert.True(i.MoveNext()); - var tag2 = i.Current; - Assert.False(i.MoveNext()); - - Assert.Equal(list, new List> { tag1, tag2 }); - } - - [Fact] - public void TestEquals() - { - var cc1 = CreateCorrelationContext(new KeyValuePair(K1, V1), new KeyValuePair(K2, V2)); - var cc2 = CreateCorrelationContext(new KeyValuePair(K1, V1), new KeyValuePair(K2, V2)); - var cc3 = CreateCorrelationContext(new KeyValuePair(K2, V2), new KeyValuePair(K1, V1)); - var cc4 = CreateCorrelationContext(new KeyValuePair(K1, V1), new KeyValuePair(K2, V1)); - var cc5 = CreateCorrelationContext(new KeyValuePair(K1, V2), new KeyValuePair(K2, V1)); - - Assert.True(cc1.Equals(cc2)); - - Assert.False(cc1.Equals(cc3)); - Assert.False(cc1.Equals(cc4)); - Assert.False(cc2.Equals(cc4)); - Assert.False(cc3.Equals(cc4)); - Assert.False(cc5.Equals(cc4)); - Assert.False(cc4.Equals(cc5)); - } - - private static CorrelationContext CreateCorrelationContext(params KeyValuePair[] correlations) - { - using Activity activity = new Activity("TestActivity"); - activity.Start(); - - var cc = CorrelationContext.Current; - - cc.AddCorrelation(correlations); - - return cc; - } - } -} diff --git a/test/OpenTelemetry.Tests/Trace/Propagation/B3FormatTest.cs b/test/OpenTelemetry.Tests/Trace/Propagation/B3FormatTest.cs index 2c6c381cb..2d5c096da 100644 --- a/test/OpenTelemetry.Tests/Trace/Propagation/B3FormatTest.cs +++ b/test/OpenTelemetry.Tests/Trace/Propagation/B3FormatTest.cs @@ -56,7 +56,7 @@ namespace OpenTelemetry.Context.Propagation.Tests public void Serialize_SampledContext() { var carrier = new Dictionary(); - this.b3Format.Inject(new PropagationContext(new ActivityContext(TraceId, SpanId, TraceOptions), null), carrier, Setter); + this.b3Format.Inject(new PropagationContext(new ActivityContext(TraceId, SpanId, TraceOptions), default), carrier, Setter); this.ContainsExactly(carrier, new Dictionary { { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, { B3Format.XB3Sampled, "1" } }); } @@ -66,7 +66,7 @@ namespace OpenTelemetry.Context.Propagation.Tests var carrier = new Dictionary(); var context = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); this.output.WriteLine(context.ToString()); - this.b3Format.Inject(new PropagationContext(context, null), carrier, Setter); + this.b3Format.Inject(new PropagationContext(context, default), carrier, Setter); this.ContainsExactly(carrier, new Dictionary { { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 } }); } @@ -78,7 +78,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, }; var spanContext = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(spanContext, null), this.b3Format.Extract(default, headersNotSampled, Getter)); + Assert.Equal(new PropagationContext(spanContext, default), this.b3Format.Extract(default, headersNotSampled, Getter)); } [Fact] @@ -89,7 +89,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, { B3Format.XB3Sampled, "1" }, }; var activityContext = new ActivityContext(TraceId, SpanId, TraceOptions); - Assert.Equal(new PropagationContext(activityContext, null), this.b3Format.Extract(default, headersSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3Format.Extract(default, headersSampled, Getter)); } [Fact] @@ -100,7 +100,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, { B3Format.XB3Sampled, "0" }, }; var activityContext = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(activityContext, null), this.b3Format.Extract(default, headersNotSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3Format.Extract(default, headersNotSampled, Getter)); } [Fact] @@ -111,7 +111,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, { B3Format.XB3Flags, "1" }, }; var activityContext = new ActivityContext(TraceId, SpanId, TraceOptions); - Assert.Equal(new PropagationContext(activityContext, null), this.b3Format.Extract(default, headersFlagSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3Format.Extract(default, headersFlagSampled, Getter)); } [Fact] @@ -122,7 +122,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, { B3Format.XB3Flags, "0" }, }; var activityContext = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(activityContext, null), this.b3Format.Extract(default, headersFlagNotSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3Format.Extract(default, headersFlagNotSampled, Getter)); } [Fact] @@ -135,7 +135,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3Sampled, "1" }, }; var activityContext = new ActivityContext(TraceIdEightBytes, SpanId, TraceOptions); - Assert.Equal(new PropagationContext(activityContext, null), this.b3Format.Extract(default, headersEightBytes, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3Format.Extract(default, headersEightBytes, Getter)); } [Fact] @@ -146,7 +146,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3TraceId, TraceIdBase16EightBytes }, { B3Format.XB3SpanId, SpanIdBase16 }, }; var activityContext = new ActivityContext(TraceIdEightBytes, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(activityContext, null), this.b3Format.Extract(default, headersEightBytes, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3Format.Extract(default, headersEightBytes, Getter)); } [Fact] @@ -209,7 +209,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { var carrier = new Dictionary(); var activityContext = new ActivityContext(TraceId, SpanId, TraceOptions); - this.b3FormatSingleHeader.Inject(new PropagationContext(activityContext, null), carrier, Setter); + this.b3FormatSingleHeader.Inject(new PropagationContext(activityContext, default), carrier, Setter); this.ContainsExactly(carrier, new Dictionary { { B3Format.XB3Combined, $"{TraceIdBase16}-{SpanIdBase16}-1" } }); } @@ -219,7 +219,7 @@ namespace OpenTelemetry.Context.Propagation.Tests var carrier = new Dictionary(); var activityContext = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); this.output.WriteLine(activityContext.ToString()); - this.b3FormatSingleHeader.Inject(new PropagationContext(activityContext, null), carrier, Setter); + this.b3FormatSingleHeader.Inject(new PropagationContext(activityContext, default), carrier, Setter); this.ContainsExactly(carrier, new Dictionary { { B3Format.XB3Combined, $"{TraceIdBase16}-{SpanIdBase16}" } }); } @@ -231,7 +231,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3Combined, $"{TraceIdBase16}-{SpanIdBase16}" }, }; var activityContext = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(activityContext, null), this.b3FormatSingleHeader.Extract(default, headersNotSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3FormatSingleHeader.Extract(default, headersNotSampled, Getter)); } [Fact] @@ -243,7 +243,7 @@ namespace OpenTelemetry.Context.Propagation.Tests }; Assert.Equal( - new PropagationContext(new ActivityContext(TraceId, SpanId, TraceOptions), null), + new PropagationContext(new ActivityContext(TraceId, SpanId, TraceOptions), default), this.b3FormatSingleHeader.Extract(default, headersSampled, Getter)); } @@ -256,7 +256,7 @@ namespace OpenTelemetry.Context.Propagation.Tests }; Assert.Equal( - new PropagationContext(new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None), null), + new PropagationContext(new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None), default), this.b3FormatSingleHeader.Extract(default, headersNotSampled, Getter)); } @@ -268,7 +268,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3Combined, $"{TraceIdBase16}-{SpanIdBase16}-1" }, }; var activityContext = new ActivityContext(TraceId, SpanId, TraceOptions); - Assert.Equal(new PropagationContext(activityContext, null), this.b3FormatSingleHeader.Extract(default, headersFlagSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3FormatSingleHeader.Extract(default, headersFlagSampled, Getter)); } [Fact] @@ -279,7 +279,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3Combined, $"{TraceIdBase16}-{SpanIdBase16}-0" }, }; var activityContext = new ActivityContext(TraceId, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(activityContext, null), this.b3FormatSingleHeader.Extract(default, headersFlagNotSampled, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3FormatSingleHeader.Extract(default, headersFlagNotSampled, Getter)); } [Fact] @@ -290,7 +290,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3Combined, $"{TraceIdBase16EightBytes}-{SpanIdBase16}-1" }, }; var activityContext = new ActivityContext(TraceIdEightBytes, SpanId, TraceOptions); - Assert.Equal(new PropagationContext(activityContext, null), this.b3FormatSingleHeader.Extract(default, headersEightBytes, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3FormatSingleHeader.Extract(default, headersEightBytes, Getter)); } [Fact] @@ -301,7 +301,7 @@ namespace OpenTelemetry.Context.Propagation.Tests { B3Format.XB3Combined, $"{TraceIdBase16EightBytes}-{SpanIdBase16}" }, }; var activityContext = new ActivityContext(TraceIdEightBytes, SpanId, ActivityTraceFlags.None); - Assert.Equal(new PropagationContext(activityContext, null), this.b3FormatSingleHeader.Extract(default, headersEightBytes, Getter)); + Assert.Equal(new PropagationContext(activityContext, default), this.b3FormatSingleHeader.Extract(default, headersEightBytes, Getter)); } [Fact] diff --git a/test/OpenTelemetry.Tests/Trace/Propagation/BaggageFormatTest.cs b/test/OpenTelemetry.Tests/Trace/Propagation/BaggageFormatTest.cs index 455445e4b..6b37bc1e6 100644 --- a/test/OpenTelemetry.Tests/Trace/Propagation/BaggageFormatTest.cs +++ b/test/OpenTelemetry.Tests/Trace/Propagation/BaggageFormatTest.cs @@ -81,12 +81,12 @@ namespace OpenTelemetry.Context.Propagation.Tests }; var propagationContext = this.baggage.Extract(default, carrier, Getter); Assert.False(propagationContext == default); - Assert.Single(propagationContext.ActivityBaggage); + Assert.Single(propagationContext.Baggage.GetBaggage()); - var array = propagationContext.ActivityBaggage.ToArray(); + var baggage = propagationContext.Baggage.GetBaggage().FirstOrDefault(); - Assert.Equal("name", array[0].Key); - Assert.Equal("test", array[0].Value); + Assert.Equal("name", baggage.Key); + Assert.Equal("test", baggage.Value); } [Fact] @@ -104,9 +104,9 @@ namespace OpenTelemetry.Context.Propagation.Tests Assert.False(propagationContext == default); Assert.True(propagationContext.ActivityContext == default); - Assert.Equal(2, propagationContext.ActivityBaggage.Count()); + Assert.Equal(2, propagationContext.Baggage.Count); - var array = propagationContext.ActivityBaggage.ToArray(); + var array = propagationContext.Baggage.GetBaggage().ToArray(); Assert.Equal("name1", array[0].Key); Assert.Equal("test1", array[0].Value); @@ -124,9 +124,9 @@ namespace OpenTelemetry.Context.Propagation.Tests }; var propagationContext = this.baggage.Extract(default, carrier, Getter); Assert.False(propagationContext == default); - Assert.Single(propagationContext.ActivityBaggage); + Assert.Single(propagationContext.Baggage.GetBaggage()); - var array = propagationContext.ActivityBaggage.ToArray(); + var array = propagationContext.Baggage.GetBaggage().ToArray(); Assert.Equal("name", array[0].Key); Assert.Equal(new string('x', 8186), array[0].Value); @@ -145,11 +145,13 @@ namespace OpenTelemetry.Context.Propagation.Tests public void ValidateBaggageInjection() { var carrier = new Dictionary(); - var propagationContext = new PropagationContext(default, new Dictionary - { - { "key1", "value1" }, - { "key2", "value2" }, - }); + var propagationContext = new PropagationContext( + default, + new Baggage(new Dictionary + { + { "key1", "value1" }, + { "key2", "value2" }, + })); this.baggage.Inject(propagationContext, carrier, Setter); diff --git a/test/OpenTelemetry.Tests/Trace/Propagation/CompositePropagatorTest.cs b/test/OpenTelemetry.Tests/Trace/Propagation/CompositePropagatorTest.cs index 251a79b65..1a2c1d39c 100644 --- a/test/OpenTelemetry.Tests/Trace/Propagation/CompositePropagatorTest.cs +++ b/test/OpenTelemetry.Tests/Trace/Propagation/CompositePropagatorTest.cs @@ -62,7 +62,7 @@ namespace OpenTelemetry.Context.Propagation.Tests }); var activityContext = new ActivityContext(this.traceId, this.spanId, ActivityTraceFlags.Recorded, traceState: null); - PropagationContext propagationContext = new PropagationContext(activityContext, null); + PropagationContext propagationContext = new PropagationContext(activityContext, default); var carrier = new Dictionary(); var activity = new Activity("test"); @@ -84,7 +84,7 @@ namespace OpenTelemetry.Context.Propagation.Tests }); var activityContext = new ActivityContext(this.traceId, this.spanId, ActivityTraceFlags.Recorded, traceState: null); - PropagationContext propagationContext = new PropagationContext(activityContext, null); + PropagationContext propagationContext = new PropagationContext(activityContext, default); var carrier = new Dictionary(); @@ -115,9 +115,9 @@ namespace OpenTelemetry.Context.Propagation.Tests var activityContext = new ActivityContext(this.traceId, this.spanId, ActivityTraceFlags.Recorded, traceState: null, isRemote: true); var baggage = new Dictionary { ["key1"] = "value1" }; - PropagationContext propagationContextActivityOnly = new PropagationContext(activityContext, null); - PropagationContext propagationContextBaggageOnly = new PropagationContext(default, baggage); - PropagationContext propagationContextBoth = new PropagationContext(activityContext, baggage); + PropagationContext propagationContextActivityOnly = new PropagationContext(activityContext, default); + PropagationContext propagationContextBaggageOnly = new PropagationContext(default, new Baggage(baggage)); + PropagationContext propagationContextBoth = new PropagationContext(activityContext, new Baggage(baggage)); var carrier = new Dictionary(); compositePropagator.Inject(propagationContextActivityOnly, carrier, Setter); diff --git a/test/OpenTelemetry.Tests/Trace/Propagation/TestPropagator.cs b/test/OpenTelemetry.Tests/Trace/Propagation/TestPropagator.cs index a52ffbea1..770b189b2 100644 --- a/test/OpenTelemetry.Tests/Trace/Propagation/TestPropagator.cs +++ b/test/OpenTelemetry.Tests/Trace/Propagation/TestPropagator.cs @@ -64,7 +64,7 @@ namespace OpenTelemetry.Context.Propagation.Tests return new PropagationContext( new ActivityContext(traceId, spanId, traceoptions, tracestate), - context.ActivityBaggage); + context.Baggage); } public void Inject(PropagationContext context, T carrier, Action setter) diff --git a/test/OpenTelemetry.Tests/Trace/Propagation/TraceContextTest.cs b/test/OpenTelemetry.Tests/Trace/Propagation/TraceContextTest.cs index 0b9f1e522..63bdd97cc 100644 --- a/test/OpenTelemetry.Tests/Trace/Propagation/TraceContextTest.cs +++ b/test/OpenTelemetry.Tests/Trace/Propagation/TraceContextTest.cs @@ -149,7 +149,7 @@ namespace OpenTelemetry.Context.Propagation.Tests }; var activityContext = new ActivityContext(traceId, spanId, ActivityTraceFlags.Recorded, traceState: null); - PropagationContext propagationContext = new PropagationContext(activityContext, null); + PropagationContext propagationContext = new PropagationContext(activityContext, default); var carrier = new Dictionary(); var f = new TraceContextFormat(); f.Inject(propagationContext, carrier, Setter); @@ -169,7 +169,7 @@ namespace OpenTelemetry.Context.Propagation.Tests }; var activityContext = new ActivityContext(traceId, spanId, ActivityTraceFlags.Recorded, expectedHeaders[TraceState]); - PropagationContext propagationContext = new PropagationContext(activityContext, null); + PropagationContext propagationContext = new PropagationContext(activityContext, default); var carrier = new Dictionary(); var f = new TraceContextFormat(); f.Inject(propagationContext, carrier, Setter);