| | | 1 | | using System.Diagnostics; |
| | | 2 | | using ArturRios.Util.WebApi.Extensions; |
| | | 3 | | |
| | | 4 | | namespace ArturRios.Util.WebApi.Handlers; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Propagates the W3C <c>traceparent</c> (and <c>tracestate</c>, when present) headers on outgoing HttpClient |
| | | 8 | | /// requests. Register it on typed/named HttpClients with |
| | | 9 | | /// <see cref="HttpClientBuilderExtensions.AddTracePropagation"/>. |
| | | 10 | | /// </summary> |
| | | 11 | | public class TracePropagationHandler : DelegatingHandler |
| | | 12 | | { |
| | | 13 | | private const string TraceParentHeader = "traceparent"; |
| | | 14 | | private const string TraceStateHeader = "tracestate"; |
| | | 15 | | |
| | | 16 | | /// <summary>Adds the current <see cref="Activity"/>'s W3C <c>traceparent</c> and <c>tracestate</c> headers to the |
| | | 17 | | /// outgoing request, if they aren't already present, before delegating to the inner handler.</summary> |
| | | 18 | | /// <param name="request">The outgoing HTTP request.</param> |
| | | 19 | | /// <param name="cancellationToken">A token to cancel the send operation.</param> |
| | | 20 | | protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, |
| | | 21 | | CancellationToken cancellationToken) |
| | | 22 | | { |
| | 2 | 23 | | var activity = Activity.Current; |
| | | 24 | | |
| | 2 | 25 | | if (activity is not null && !request.Headers.Contains(TraceParentHeader)) |
| | | 26 | | { |
| | 1 | 27 | | request.Headers.TryAddWithoutValidation(TraceParentHeader, activity.ToTraceParent()); |
| | | 28 | | |
| | 1 | 29 | | if (!string.IsNullOrEmpty(activity.TraceStateString)) |
| | | 30 | | { |
| | 1 | 31 | | request.Headers.TryAddWithoutValidation(TraceStateHeader, activity.TraceStateString); |
| | | 32 | | } |
| | | 33 | | } |
| | | 34 | | |
| | 2 | 35 | | return base.SendAsync(request, cancellationToken); |
| | | 36 | | } |
| | | 37 | | } |