Skip to content

Commit

Permalink
[repo/Extensions] Prepare to .NET9 (#2265)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kielek authored Oct 29, 2024
1 parent ae6d420 commit 9b8b4ba
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 45 deletions.
21 changes: 11 additions & 10 deletions src/OpenTelemetry.Extensions.AWS/AWSXRayIdGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -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)
{
Expand All @@ -91,8 +91,8 @@ internal static void UpdateSamplingDecision(Activity activity, Sampler sampler)
/// <returns>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.</returns>
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;
}

Expand All @@ -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());
Expand Down Expand Up @@ -164,6 +164,7 @@ private static ActivitySamplingResult ComputeRootActivitySamplingResult(
{
SamplingDecision.RecordAndSample => ActivitySamplingResult.AllDataAndRecorded,
SamplingDecision.RecordOnly => ActivitySamplingResult.AllData,
SamplingDecision.Drop => ActivitySamplingResult.PropagationData,
_ => ActivitySamplingResult.PropagationData,
};

Expand Down
29 changes: 10 additions & 19 deletions src/OpenTelemetry.Extensions.AWS/Trace/AWSXRayPropagator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,7 @@ public override PropagationContext Extract<T>(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)
{
Expand Down Expand Up @@ -135,10 +130,10 @@ internal static bool TryParseXRayTraceHeader(string rawHeader, out ActivityConte
return false;
}

ReadOnlySpan<char> header = rawHeader.AsSpan();
var header = rawHeader.AsSpan();
while (header.Length > 0)
{
int delimiterIndex = header.IndexOf(TraceHeaderDelimiter);
var delimiterIndex = header.IndexOf(TraceHeaderDelimiter);
ReadOnlySpan<char> part;
if (delimiterIndex >= 0)
{
Expand All @@ -151,14 +146,14 @@ internal static bool TryParseXRayTraceHeader(string rawHeader, out ActivityConte
header = header.Slice(header.Length);
}

ReadOnlySpan<char> trimmedPart = part.Trim();
int equalsIndex = trimmedPart.IndexOf(KeyValueDelimiter);
var trimmedPart = part.Trim();
var equalsIndex = trimmedPart.IndexOf(KeyValueDelimiter);
if (equalsIndex < 0)
{
return false;
}

ReadOnlySpan<char> value = trimmedPart.Slice(equalsIndex + 1);
var value = trimmedPart.Slice(equalsIndex + 1);
if (trimmedPart.StartsWith(RootKey.AsSpan()))
{
if (!TryParseOTFormatTraceId(value, out var otFormatTraceId))
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -252,12 +247,8 @@ internal static bool TryParseOTFormatTraceId(ReadOnlySpan<char> traceId, out Rea

internal static bool IsParentIdValid(ReadOnlySpan<char> 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<char> sampleDecision, out char result)
Expand All @@ -274,7 +265,7 @@ internal static bool TryParseSampleDecision(ReadOnlySpan<char> sampleDecision, o
return false;
}

if (tempChar != SampledValue && tempChar != NotSampledValue)
if (tempChar is not SampledValue and not NotSampledValue)
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public TraceEnrichmentActions(IEnumerable<Action<TraceEnrichmentBag>> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,19 @@ public class AWSXRayPropagatorTests
private const string TraceId = "5759e988bd862e3fe1be46a994272793";
private const string ParentId = "53995c3f42cd8ad8";

private static readonly string[] Empty = Array.Empty<string>();
private static readonly string[] Empty = [];

private static readonly Func<IDictionary<string, string>, string, IEnumerable<string>> 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<IDictionary<string, string>, string, string> Setter = (carrier, name, value) =>
{
carrier[name] = value;
};

private readonly AWSXRayPropagator awsXRayPropagator = new AWSXRayPropagator();
private readonly AWSXRayPropagator awsXRayPropagator = new();

[Fact]
public void TestInjectTraceHeader()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public void ShouldSample_ReturnsRecordAndSample_WhenWithinRateLimit()
case SamplingDecision.Drop:
sampleOut++;
break;
default:
Assert.Fail("Unexpected value");
break;
}

Thread.Sleep(333);
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 9b8b4ba

Please sign in to comment.