From 9b8b4ba250ec26b7db9360dcf054ff3f277ffefc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 29 Oct 2024 21:57:18 +0100 Subject: [PATCH] [repo/Extensions] Prepare to .NET9 (#2265) --- .../AWSXRayIdGenerator.cs | 21 +++++++------- .../Trace/AWSXRayPropagator.cs | 29 +++++++------------ .../Internal/TraceEnrichmentActions.cs | 2 +- .../Trace/AWSXRayPropagatorTests.cs | 11 ++----- .../Trace/BaggageActivityProcessorTests.cs | 9 ++---- .../Trace/RateLimitingSamplerTests.cs | 6 ++++ 6 files changed, 33 insertions(+), 45 deletions(-) diff --git a/src/OpenTelemetry.Extensions.AWS/AWSXRayIdGenerator.cs b/src/OpenTelemetry.Extensions.AWS/AWSXRayIdGenerator.cs index f55193111e..2031bb244d 100644 --- a/src/OpenTelemetry.Extensions.AWS/AWSXRayIdGenerator.cs +++ b/src/OpenTelemetry.Extensions.AWS/AWSXRayIdGenerator.cs @@ -20,10 +20,10 @@ public static class AWSXRayIdGenerator private const long TicksPerMicrosecond = TimeSpan.TicksPerMillisecond / 1000; private const long MicrosecondPerSecond = TimeSpan.TicksPerSecond / TicksPerMicrosecond; - private static readonly DateTime EpochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly DateTime EpochStart = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private static readonly long UnixEpochMicroseconds = EpochStart.Ticks / TicksPerMicrosecond; - private static readonly Random Global = new Random(); - private static object randLock = new object(); + private static readonly Random Global = new(); + private static readonly object RandLock = new(); internal static void ReplaceTraceId(Sampler? sampler = null) { @@ -67,15 +67,15 @@ internal static ActivityTraceId GenerateAWSXRayCompatibleTraceId() internal static void UpdateSamplingDecision(Activity activity, Sampler sampler) { - if (!(sampler is AlwaysOnSampler) && !(sampler is AlwaysOffSampler)) + if (sampler is not AlwaysOnSampler and not AlwaysOffSampler) { - ActivitySamplingResult result = !Sdk.SuppressInstrumentation ? ComputeRootActivitySamplingResult(activity, sampler) : ActivitySamplingResult.None; + var result = !Sdk.SuppressInstrumentation ? ComputeRootActivitySamplingResult(activity, sampler) : ActivitySamplingResult.None; activity.ActivityTraceFlags = ActivityTraceFlags.None; // Following the same behavior when .NET runtime sets the trace flag for a newly created root activity. // See: https://github.com/dotnet/runtime/blob/master/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs#L1022-L1027 - activity.IsAllDataRequested = result == ActivitySamplingResult.AllData || result == ActivitySamplingResult.AllDataAndRecorded; + activity.IsAllDataRequested = result is ActivitySamplingResult.AllData or ActivitySamplingResult.AllDataAndRecorded; if (result == ActivitySamplingResult.AllDataAndRecorded) { @@ -91,8 +91,8 @@ internal static void UpdateSamplingDecision(Activity activity, Sampler sampler) /// The number of seconds elapsed since 1970-01-01 00:00:00 UTC. The value is expressed in whole and fractional seconds with resolution of microsecond. private static decimal ToUnixTimeSeconds(this DateTime date) { - long microseconds = date.Ticks / TicksPerMicrosecond; - long microsecondsSinceEpoch = microseconds - UnixEpochMicroseconds; + var microseconds = date.Ticks / TicksPerMicrosecond; + var microsecondsSinceEpoch = microseconds - UnixEpochMicroseconds; return (decimal)microsecondsSinceEpoch / MicrosecondPerSecond; } @@ -105,11 +105,11 @@ private static string GenerateHexNumber(int digits) { Guard.ThrowIfOutOfRange(digits, min: 0); - byte[] bytes = new byte[digits / 2]; + var bytes = new byte[digits / 2]; string hexNumber; - lock (randLock) + lock (RandLock) { NextBytes(bytes); hexNumber = string.Concat(bytes.Select(x => x.ToString("x2", CultureInfo.InvariantCulture)).ToArray()); @@ -164,6 +164,7 @@ private static ActivitySamplingResult ComputeRootActivitySamplingResult( { SamplingDecision.RecordAndSample => ActivitySamplingResult.AllDataAndRecorded, SamplingDecision.RecordOnly => ActivitySamplingResult.AllData, + SamplingDecision.Drop => ActivitySamplingResult.PropagationData, _ => ActivitySamplingResult.PropagationData, }; diff --git a/src/OpenTelemetry.Extensions.AWS/Trace/AWSXRayPropagator.cs b/src/OpenTelemetry.Extensions.AWS/Trace/AWSXRayPropagator.cs index 569bae5391..8927b136f7 100644 --- a/src/OpenTelemetry.Extensions.AWS/Trace/AWSXRayPropagator.cs +++ b/src/OpenTelemetry.Extensions.AWS/Trace/AWSXRayPropagator.cs @@ -68,12 +68,7 @@ public override PropagationContext Extract(PropagationContext context, T carr var parentHeader = parentTraceHeader.First(); - if (!TryParseXRayTraceHeader(parentHeader, out var newActivityContext)) - { - return context; - } - - return new PropagationContext(newActivityContext, context.Baggage); + return !TryParseXRayTraceHeader(parentHeader, out var newActivityContext) ? context : new PropagationContext(newActivityContext, context.Baggage); } catch (Exception ex) { @@ -135,10 +130,10 @@ internal static bool TryParseXRayTraceHeader(string rawHeader, out ActivityConte return false; } - ReadOnlySpan header = rawHeader.AsSpan(); + var header = rawHeader.AsSpan(); while (header.Length > 0) { - int delimiterIndex = header.IndexOf(TraceHeaderDelimiter); + var delimiterIndex = header.IndexOf(TraceHeaderDelimiter); ReadOnlySpan part; if (delimiterIndex >= 0) { @@ -151,14 +146,14 @@ internal static bool TryParseXRayTraceHeader(string rawHeader, out ActivityConte header = header.Slice(header.Length); } - ReadOnlySpan trimmedPart = part.Trim(); - int equalsIndex = trimmedPart.IndexOf(KeyValueDelimiter); + var trimmedPart = part.Trim(); + var equalsIndex = trimmedPart.IndexOf(KeyValueDelimiter); if (equalsIndex < 0) { return false; } - ReadOnlySpan value = trimmedPart.Slice(equalsIndex + 1); + var value = trimmedPart.Slice(equalsIndex + 1); if (trimmedPart.StartsWith(RootKey.AsSpan())) { if (!TryParseOTFormatTraceId(value, out var otFormatTraceId)) @@ -188,7 +183,7 @@ internal static bool TryParseXRayTraceHeader(string rawHeader, out ActivityConte } } - if (traceId == default || parentId == default || traceOptions == default) + if (traceId.IsEmpty || parentId.IsEmpty || traceOptions == default) { return false; } @@ -252,12 +247,8 @@ internal static bool TryParseOTFormatTraceId(ReadOnlySpan traceId, out Rea internal static bool IsParentIdValid(ReadOnlySpan parentId) { - if (parentId.IsEmpty || parentId.IsWhiteSpace()) - { - return false; - } - - return parentId.Length == ParentIdHexDigits && long.TryParse(parentId.ToString(), NumberStyles.HexNumber, null, out _); + return !parentId.IsEmpty && !parentId.IsWhiteSpace() && parentId.Length == ParentIdHexDigits && + long.TryParse(parentId.ToString(), NumberStyles.HexNumber, null, out _); } internal static bool TryParseSampleDecision(ReadOnlySpan sampleDecision, out char result) @@ -274,7 +265,7 @@ internal static bool TryParseSampleDecision(ReadOnlySpan sampleDecision, o return false; } - if (tempChar != SampledValue && tempChar != NotSampledValue) + if (tempChar is not SampledValue and not NotSampledValue) { return false; } diff --git a/src/OpenTelemetry.Extensions.Enrichment/Internal/TraceEnrichmentActions.cs b/src/OpenTelemetry.Extensions.Enrichment/Internal/TraceEnrichmentActions.cs index 1417e5edb3..aa745bfed3 100644 --- a/src/OpenTelemetry.Extensions.Enrichment/Internal/TraceEnrichmentActions.cs +++ b/src/OpenTelemetry.Extensions.Enrichment/Internal/TraceEnrichmentActions.cs @@ -16,7 +16,7 @@ public TraceEnrichmentActions(IEnumerable> actions) public override void Enrich(in TraceEnrichmentBag bag) { - for (int i = 0; i < this.actions.Length; i++) + for (var i = 0; i < this.actions.Length; i++) { this.actions[i].Invoke(bag); } diff --git a/test/OpenTelemetry.Extensions.AWS.Tests/Trace/AWSXRayPropagatorTests.cs b/test/OpenTelemetry.Extensions.AWS.Tests/Trace/AWSXRayPropagatorTests.cs index c654ec2b9e..3502808f42 100644 --- a/test/OpenTelemetry.Extensions.AWS.Tests/Trace/AWSXRayPropagatorTests.cs +++ b/test/OpenTelemetry.Extensions.AWS.Tests/Trace/AWSXRayPropagatorTests.cs @@ -14,16 +14,11 @@ public class AWSXRayPropagatorTests private const string TraceId = "5759e988bd862e3fe1be46a994272793"; private const string ParentId = "53995c3f42cd8ad8"; - private static readonly string[] Empty = Array.Empty(); + private static readonly string[] Empty = []; private static readonly Func, string, IEnumerable> Getter = (headers, name) => { - if (headers.TryGetValue(name, out var value)) - { - return new[] { value }; - } - - return Empty; + return headers.TryGetValue(name, out var value) ? [value] : Empty; }; private static readonly Action, string, string> Setter = (carrier, name, value) => @@ -31,7 +26,7 @@ public class AWSXRayPropagatorTests carrier[name] = value; }; - private readonly AWSXRayPropagator awsXRayPropagator = new AWSXRayPropagator(); + private readonly AWSXRayPropagator awsXRayPropagator = new(); [Fact] public void TestInjectTraceHeader() diff --git a/test/OpenTelemetry.Extensions.Tests/Trace/BaggageActivityProcessorTests.cs b/test/OpenTelemetry.Extensions.Tests/Trace/BaggageActivityProcessorTests.cs index 1f96b7c72d..0f43e32d8f 100644 --- a/test/OpenTelemetry.Extensions.Tests/Trace/BaggageActivityProcessorTests.cs +++ b/test/OpenTelemetry.Extensions.Tests/Trace/BaggageActivityProcessorTests.cs @@ -62,7 +62,7 @@ public void BaggageActivityProcessor_CanUseRegex() var regex = new Regex("^mykey", RegexOptions.Compiled); using var provider = Sdk.CreateTracerProviderBuilder() - .AddBaggageActivityProcessor((baggageKey) => regex.IsMatch(baggageKey)) + .AddBaggageActivityProcessor(regex.IsMatch) .AddSource(sourceName) .Build(); @@ -107,12 +107,7 @@ public void BaggageActivityProcessor_PredicateThrows_OnlyDropsEntriesThatThrow() using var provider = Sdk.CreateTracerProviderBuilder() .AddBaggageActivityProcessor(key => { - if (key == "key") - { - throw new Exception("Predicate throws an exception."); - } - - return true; + return key == "key" ? throw new Exception("Predicate throws an exception.") : true; }) .AddSource(sourceName) .Build(); diff --git a/test/OpenTelemetry.Extensions.Tests/Trace/RateLimitingSamplerTests.cs b/test/OpenTelemetry.Extensions.Tests/Trace/RateLimitingSamplerTests.cs index 2acc236783..df56e6430d 100644 --- a/test/OpenTelemetry.Extensions.Tests/Trace/RateLimitingSamplerTests.cs +++ b/test/OpenTelemetry.Extensions.Tests/Trace/RateLimitingSamplerTests.cs @@ -40,6 +40,9 @@ public void ShouldSample_ReturnsRecordAndSample_WhenWithinRateLimit() case SamplingDecision.Drop: sampleOut++; break; + default: + Assert.Fail("Unexpected value"); + break; } Thread.Sleep(333); @@ -82,6 +85,9 @@ public async Task ShouldFilter_WhenAboveRateLimit() case SamplingDecision.Drop: sampleOut++; break; + default: + Assert.Fail("Unexpected value"); + break; } // Task.Delay is limited by the OS Scheduler, so we can't guarantee the exact time