diff --git a/src/OpenTelemetry.Sampler.AWS/AWSXRayRemoteSampler.cs b/src/OpenTelemetry.Sampler.AWS/AWSXRayRemoteSampler.cs index 802f72351a..cc1836fc0e 100644 --- a/src/OpenTelemetry.Sampler.AWS/AWSXRayRemoteSampler.cs +++ b/src/OpenTelemetry.Sampler.AWS/AWSXRayRemoteSampler.cs @@ -14,7 +14,7 @@ public sealed class AWSXRayRemoteSampler : Trace.Sampler, IDisposable { internal static readonly TimeSpan DefaultTargetInterval = TimeSpan.FromSeconds(10); - private static readonly Random Random = new Random(); + private static readonly Random Random = new(); private bool isFallBackEventToWriteSwitch = true; [SuppressMessage("Performance", "CA5394: Do not use insecure randomness", Justification = "Secure random is not required for jitters.")] @@ -111,9 +111,9 @@ public void Dispose() Justification = "using insecure random is fine here since clientId doesn't need to be secure.")] private static string GenerateClientId() { - char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - char[] clientIdChars = new char[24]; - for (int i = 0; i < clientIdChars.Length; i++) + char[] hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; + var clientIdChars = new char[24]; + for (var i = 0; i < clientIdChars.Length; i++) { clientIdChars[i] = hex[Random.Next(hex.Length)]; } @@ -133,7 +133,7 @@ private void Dispose(bool disposing) private async void GetAndUpdateRules(object? state) { - List rules = await this.Client.GetSamplingRules().ConfigureAwait(false); + var rules = await this.Client.GetSamplingRules().ConfigureAwait(false); this.RulesCache.UpdateRules(rules); @@ -143,14 +143,14 @@ private async void GetAndUpdateRules(object? state) private async void GetAndUpdateTargets(object? state) { - List statistics = this.RulesCache.Snapshot(this.Clock.Now()); + var statistics = this.RulesCache.Snapshot(this.Clock.Now()); - GetSamplingTargetsRequest request = new GetSamplingTargetsRequest(statistics); - GetSamplingTargetsResponse? response = await this.Client.GetSamplingTargets(request).ConfigureAwait(false); + var request = new GetSamplingTargetsRequest(statistics); + var response = await this.Client.GetSamplingTargets(request).ConfigureAwait(false); if (response != null) { - Dictionary targets = new Dictionary(); - foreach (SamplingTargetDocument target in response.SamplingTargetDocuments) + Dictionary targets = []; + foreach (var target in response.SamplingTargetDocuments) { if (target.RuleName != null) { @@ -174,7 +174,7 @@ private async void GetAndUpdateTargets(object? state) // schedule next target poll var nextTargetFetchTime = this.RulesCache.NextTargetFetchTime(); - TimeSpan nextTargetFetchInterval = nextTargetFetchTime.Subtract(this.Clock.Now()); + var nextTargetFetchInterval = nextTargetFetchTime.Subtract(this.Clock.Now()); if (nextTargetFetchInterval < TimeSpan.Zero) { nextTargetFetchInterval = DefaultTargetInterval; diff --git a/src/OpenTelemetry.Sampler.AWS/AWSXRaySamplerClient.cs b/src/OpenTelemetry.Sampler.AWS/AWSXRaySamplerClient.cs index 758a0817fd..a99b090261 100644 --- a/src/OpenTelemetry.Sampler.AWS/AWSXRaySamplerClient.cs +++ b/src/OpenTelemetry.Sampler.AWS/AWSXRaySamplerClient.cs @@ -26,7 +26,7 @@ public AWSXRaySamplerClient(string host) public async Task> GetSamplingRules() { - List samplingRules = new List(); + List samplingRules = []; using (var request = new HttpRequestMessage(HttpMethod.Post, this.getSamplingRulesEndpoint) { @@ -37,7 +37,7 @@ public async Task> GetSamplingRules() try { - GetSamplingRulesResponse? getSamplingRulesResponse = JsonSerializer + var getSamplingRulesResponse = JsonSerializer #if NET .Deserialize(responseJson, SourceGenerationContext.Default.GetSamplingRulesResponse); #else @@ -89,7 +89,7 @@ public async Task> GetSamplingRules() try { - GetSamplingTargetsResponse? getSamplingTargetsResponse = JsonSerializer + var getSamplingTargetsResponse = JsonSerializer #if NET .Deserialize(responseJson, SourceGenerationContext.Default.GetSamplingTargetsResponse); #else diff --git a/src/OpenTelemetry.Sampler.AWS/FallbackSampler.cs b/src/OpenTelemetry.Sampler.AWS/FallbackSampler.cs index bf92a8ec97..356ecf4570 100644 --- a/src/OpenTelemetry.Sampler.AWS/FallbackSampler.cs +++ b/src/OpenTelemetry.Sampler.AWS/FallbackSampler.cs @@ -9,23 +9,16 @@ internal class FallbackSampler : Trace.Sampler { private readonly Trace.Sampler reservoirSampler; private readonly Trace.Sampler fixedRateSampler; - private readonly Clock clock; public FallbackSampler(Clock clock) { - this.clock = clock; this.reservoirSampler = new ParentBasedSampler(new RateLimitingSampler(1, clock)); this.fixedRateSampler = new ParentBasedSampler(new TraceIdRatioBasedSampler(0.05)); } public override SamplingResult ShouldSample(in SamplingParameters samplingParameters) { - SamplingResult result = this.reservoirSampler.ShouldSample(in samplingParameters); - if (result.Decision != SamplingDecision.Drop) - { - return result; - } - - return this.fixedRateSampler.ShouldSample(in samplingParameters); + var result = this.reservoirSampler.ShouldSample(in samplingParameters); + return result.Decision != SamplingDecision.Drop ? result : this.fixedRateSampler.ShouldSample(in samplingParameters); } } diff --git a/src/OpenTelemetry.Sampler.AWS/Matcher.cs b/src/OpenTelemetry.Sampler.AWS/Matcher.cs index 3c51cf16d0..a08f3a67b7 100644 --- a/src/OpenTelemetry.Sampler.AWS/Matcher.cs +++ b/src/OpenTelemetry.Sampler.AWS/Matcher.cs @@ -36,9 +36,9 @@ public static bool WildcardMatch(string? text, string? globPattern) // it is faster to check if we need a regex comparison than // doing always regex comparison, even where we may not need it. - foreach (char c in globPattern) + foreach (var c in globPattern) { - if (c == '*' || c == '?') + if (c is '*' or '?') { return Regex.IsMatch(text, ToRegexPattern(globPattern)); } @@ -59,7 +59,7 @@ public static bool AttributeMatch(IEnumerable>? ta return false; } - int matchedCount = 0; + var matchedCount = 0; foreach (var tag in tags) { @@ -77,23 +77,18 @@ public static bool AttributeMatch(IEnumerable>? ta } } - if (matchedCount == ruleAttributes.Count) - { - return true; - } - - return false; + return matchedCount == ruleAttributes.Count; } private static string ToRegexPattern(string globPattern) { - int tokenStart = -1; - StringBuilder patternBuilder = new StringBuilder(); + var tokenStart = -1; + var patternBuilder = new StringBuilder(); - for (int i = 0; i < globPattern.Length; i++) + for (var i = 0; i < globPattern.Length; i++) { - char c = globPattern[i]; - if (c == '*' || c == '?') + var c = globPattern[i]; + if (c is '*' or '?') { if (tokenStart != -1) { diff --git a/src/OpenTelemetry.Sampler.AWS/RateLimiter.cs b/src/OpenTelemetry.Sampler.AWS/RateLimiter.cs index 6dfc5b5099..5745d669fb 100644 --- a/src/OpenTelemetry.Sampler.AWS/RateLimiter.cs +++ b/src/OpenTelemetry.Sampler.AWS/RateLimiter.cs @@ -20,7 +20,7 @@ internal RateLimiter(double creditsPerSecond, double maxBalance, Clock clock) public bool TrySpend(double itemCost) { - long cost = (long)(itemCost / this.creditsPerMillisecond); + var cost = (long)(itemCost / this.creditsPerMillisecond); long currentMillis; long currentBalanceMillis; long availableBalanceAfterWithdrawal; @@ -29,7 +29,7 @@ public bool TrySpend(double itemCost) { currentBalanceMillis = Interlocked.Read(ref this.currentBalance); currentMillis = this.clock.NowInMilliSeconds(); - long currentAvailableBalance = currentMillis - currentBalanceMillis; + var currentAvailableBalance = currentMillis - currentBalanceMillis; if (currentAvailableBalance > this.maxBalance) { currentAvailableBalance = this.maxBalance; diff --git a/src/OpenTelemetry.Sampler.AWS/RulesCache.cs b/src/OpenTelemetry.Sampler.AWS/RulesCache.cs index 33c4cfbb39..deb00da679 100644 --- a/src/OpenTelemetry.Sampler.AWS/RulesCache.cs +++ b/src/OpenTelemetry.Sampler.AWS/RulesCache.cs @@ -20,7 +20,7 @@ public RulesCache(Clock clock, string clientId, Resource resource, Trace.Sampler this.ClientId = clientId; this.Resource = resource; this.FallbackSampler = fallbackSampler; - this.RuleAppliers = new List(); + this.RuleAppliers = []; this.UpdatedAt = this.Clock.Now(); } @@ -54,7 +54,7 @@ public void UpdateRules(List newRules) // sort the new rules newRules.Sort((x, y) => x.CompareTo(y)); - List newRuleAppliers = new List(); + List newRuleAppliers = []; foreach (var rule in newRules) { // If the ruleApplier already exists in the current list of appliers, then we reuse it. @@ -104,7 +104,7 @@ public SamplingResult ShouldSample(in SamplingParameters samplingParameters) public List Snapshot(DateTimeOffset now) { - List snapshots = new List(); + List snapshots = []; foreach (var ruleApplier in this.RuleAppliers) { snapshots.Add(ruleApplier.Snapshot(now)); @@ -115,10 +115,10 @@ public List Snapshot(DateTimeOffset now) public void UpdateTargets(Dictionary targets) { - List newRuleAppliers = new List(); + List newRuleAppliers = []; foreach (var ruleApplier in this.RuleAppliers) { - targets.TryGetValue(ruleApplier.RuleName, out SamplingTargetDocument? target); + targets.TryGetValue(ruleApplier.RuleName, out var target); if (target != null) { newRuleAppliers.Add(ruleApplier.WithTarget(target, this.Clock.Now())); @@ -154,12 +154,7 @@ public DateTimeOffset NextTargetFetchTime() .Select(r => r.NextSnapshotTime) .Min(); - if (minPollingTime < this.Clock.Now()) - { - return defaultPollingTime; - } - - return minPollingTime; + return minPollingTime < this.Clock.Now() ? defaultPollingTime : minPollingTime; } public void Dispose() diff --git a/src/OpenTelemetry.Sampler.AWS/SamplingRule.cs b/src/OpenTelemetry.Sampler.AWS/SamplingRule.cs index bba8f75088..fa14605f90 100644 --- a/src/OpenTelemetry.Sampler.AWS/SamplingRule.cs +++ b/src/OpenTelemetry.Sampler.AWS/SamplingRule.cs @@ -73,7 +73,7 @@ public SamplingRule( public int CompareTo(SamplingRule? other) { - int result = this.Priority.CompareTo(other?.Priority); + var result = this.Priority.CompareTo(other?.Priority); if (result == 0) { result = string.Compare(this.RuleName, other?.RuleName, StringComparison.Ordinal); diff --git a/src/OpenTelemetry.Sampler.AWS/SamplingRuleApplier.cs b/src/OpenTelemetry.Sampler.AWS/SamplingRuleApplier.cs index b5910499c5..73a59c17bf 100644 --- a/src/OpenTelemetry.Sampler.AWS/SamplingRuleApplier.cs +++ b/src/OpenTelemetry.Sampler.AWS/SamplingRuleApplier.cs @@ -116,25 +116,18 @@ public bool Matches(SamplingParameters samplingParameters, Resource resource) // URL path may be in either http.target or http.url if (httpTarget == null && httpUrl != null) { - int schemeEndIndex = httpUrl.IndexOf("://", StringComparison.Ordinal); + var schemeEndIndex = httpUrl.IndexOf("://", StringComparison.Ordinal); // Per spec, http.url is always populated with scheme://host/target. If scheme doesn't // match, assume it's bad instrumentation and ignore. if (schemeEndIndex > 0) { - int pathIndex = httpUrl.IndexOf('/', schemeEndIndex + "://".Length); - if (pathIndex < 0) - { - httpTarget = "/"; - } - else - { - httpTarget = httpUrl.Substring(pathIndex); - } + var pathIndex = httpUrl.IndexOf('/', schemeEndIndex + "://".Length); + httpTarget = pathIndex < 0 ? "/" : httpUrl.Substring(pathIndex); } } - string serviceName = (string)resource.Attributes.FirstOrDefault(kvp => + var serviceName = (string)resource.Attributes.FirstOrDefault(kvp => kvp.Key.Equals("service.name", StringComparison.Ordinal)).Value; return Matcher.AttributeMatch(samplingParameters.Tags, this.Rule.Attributes) && @@ -149,8 +142,8 @@ public bool Matches(SamplingParameters samplingParameters, Resource resource) public SamplingResult ShouldSample(in SamplingParameters samplingParameters) { Interlocked.Increment(ref this.Statistics.RequestCount); - bool reservoirExpired = this.Clock.Now() >= this.ReservoirEndTime; - SamplingResult result = !reservoirExpired + var reservoirExpired = this.Clock.Now() >= this.ReservoirEndTime; + var result = !reservoirExpired ? this.ReservoirSampler.ShouldSample(in samplingParameters) : new SamplingResult(SamplingDecision.Drop); @@ -178,13 +171,13 @@ public SamplingResult ShouldSample(in SamplingParameters samplingParameters) // take the snapshot and reset the statistics. public SamplingStatisticsDocument Snapshot(DateTimeOffset now) { - double timestamp = this.Clock.ToDouble(now); + var timestamp = this.Clock.ToDouble(now); - long matchedRequests = Interlocked.Exchange(ref this.Statistics.RequestCount, 0L); - long sampledRequests = Interlocked.Exchange(ref this.Statistics.SampleCount, 0L); - long borrowedRequests = Interlocked.Exchange(ref this.Statistics.BorrowCount, 0L); + var matchedRequests = Interlocked.Exchange(ref this.Statistics.RequestCount, 0L); + var sampledRequests = Interlocked.Exchange(ref this.Statistics.SampleCount, 0L); + var borrowedRequests = Interlocked.Exchange(ref this.Statistics.BorrowCount, 0L); - SamplingStatisticsDocument statiscticsDocument = new SamplingStatisticsDocument( + var statiscticsDocument = new SamplingStatisticsDocument( this.ClientId, this.RuleName, matchedRequests, @@ -197,27 +190,22 @@ public SamplingStatisticsDocument Snapshot(DateTimeOffset now) public SamplingRuleApplier WithTarget(SamplingTargetDocument target, DateTimeOffset now) { - Trace.Sampler newFixedRateSampler = target.FixedRate != null + var newFixedRateSampler = target.FixedRate != null ? new ParentBasedSampler(new TraceIdRatioBasedSampler(target.FixedRate.Value)) : this.FixedRateSampler; Trace.Sampler newReservoirSampler = new AlwaysOffSampler(); - DateTimeOffset newReservoirEndTime = DateTimeOffset.MaxValue; + var newReservoirEndTime = DateTimeOffset.MaxValue; if (target.ReservoirQuota != null && target.ReservoirQuotaTTL != null) { - if (target.ReservoirQuota > 0) - { - newReservoirSampler = new ParentBasedSampler(new RateLimitingSampler(target.ReservoirQuota.Value, this.Clock)); - } - else - { - newReservoirSampler = new AlwaysOffSampler(); - } + newReservoirSampler = target.ReservoirQuota > 0 + ? new ParentBasedSampler(new RateLimitingSampler(target.ReservoirQuota.Value, this.Clock)) + : new AlwaysOffSampler(); newReservoirEndTime = this.Clock.ToDateTime(target.ReservoirQuotaTTL.Value); } - DateTimeOffset newNextSnapshotTime = target.Interval != null + var newNextSnapshotTime = target.Interval != null ? now.AddSeconds(target.Interval.Value) : now.Add(AWSXRayRemoteSampler.DefaultTargetInterval); @@ -235,21 +223,17 @@ public SamplingRuleApplier WithTarget(SamplingTargetDocument target, DateTimeOff private static string GetServiceType(Resource resource) { - string cloudPlatform = (string)resource.Attributes.FirstOrDefault(kvp => + var cloudPlatform = (string)resource.Attributes.FirstOrDefault(kvp => kvp.Key.Equals("cloud.platform", StringComparison.Ordinal)).Value; - if (cloudPlatform == null) - { - return string.Empty; - } - - return Matcher.XRayCloudPlatform.TryGetValue(cloudPlatform, out string? value) ? value : string.Empty; + return cloudPlatform == null ? string.Empty : + Matcher.XRayCloudPlatform.TryGetValue(cloudPlatform, out var value) ? value : string.Empty; } private static string GetArn(in SamplingParameters samplingParameters, Resource resource) { // currently the aws resource detectors only capture ARNs for ECS and Lambda environments. - string? arn = (string?)resource.Attributes.FirstOrDefault(kvp => + var arn = (string?)resource.Attributes.FirstOrDefault(kvp => kvp.Key.Equals("aws.ecs.container.arn", StringComparison.Ordinal)).Value; if (arn != null) diff --git a/src/OpenTelemetry.Sampler.AWS/SystemClock.cs b/src/OpenTelemetry.Sampler.AWS/SystemClock.cs index c079d58527..8c960542c7 100644 --- a/src/OpenTelemetry.Sampler.AWS/SystemClock.cs +++ b/src/OpenTelemetry.Sampler.AWS/SystemClock.cs @@ -6,7 +6,7 @@ namespace OpenTelemetry.Sampler.AWS; // A clock based on System time. internal class SystemClock : Clock { - private static readonly SystemClock Instance = new SystemClock(); + private static readonly SystemClock Instance = new(); private static readonly DateTimeOffset EpochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); @@ -37,7 +37,7 @@ public override DateTimeOffset ToDateTime(double seconds) public override double ToDouble(DateTimeOffset dateTime) { var current = new TimeSpan(dateTime.ToUniversalTime().Ticks - EpochStart.Ticks); - double timestamp = Math.Round(current.TotalMilliseconds, 0) / 1000.0; + var timestamp = Math.Round(current.TotalMilliseconds, 0) / 1000.0; return timestamp; } } diff --git a/src/Shared/Guard.cs b/src/Shared/Guard.cs index 2e21736b00..a00cfafb09 100644 --- a/src/Shared/Guard.cs +++ b/src/Shared/Guard.cs @@ -174,12 +174,9 @@ public static void ThrowIfOutOfRange(double value, [CallerArgumentExpression(nam [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T ThrowIfNotOfType([NotNull] object? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) { - if (value is not T result) - { - throw new InvalidCastException($"Cannot cast '{paramName}' from '{value?.GetType().ToString() ?? "null"}' to '{typeof(T)}'"); - } - - return result; + return value is not T result + ? throw new InvalidCastException($"Cannot cast '{paramName}' from '{value?.GetType().ToString() ?? "null"}' to '{typeof(T)}'") + : result; } [DebuggerHidden] diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRayRemoteSampler.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRayRemoteSampler.cs index 3c629e79c6..e61cb76d31 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRayRemoteSampler.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRayRemoteSampler.cs @@ -16,10 +16,10 @@ public class TestAWSXRayRemoteSampler [Fact] public void TestSamplerWithConfiguration() { - TimeSpan pollingInterval = TimeSpan.FromSeconds(5); - string endpoint = "http://localhost:3000"; + var pollingInterval = TimeSpan.FromSeconds(5); + var endpoint = "http://localhost:3000"; - AWSXRayRemoteSampler sampler = AWSXRayRemoteSampler.Builder(ResourceBuilder.CreateEmpty().Build()) + var sampler = AWSXRayRemoteSampler.Builder(ResourceBuilder.CreateEmpty().Build()) .SetPollingInterval(pollingInterval) .SetEndpoint(endpoint) .Build(); @@ -33,7 +33,7 @@ public void TestSamplerWithConfiguration() [Fact] public void TestSamplerWithDefaults() { - AWSXRayRemoteSampler sampler = AWSXRayRemoteSampler.Builder(ResourceBuilder.CreateEmpty().Build()).Build(); + var sampler = AWSXRayRemoteSampler.Builder(ResourceBuilder.CreateEmpty().Build()).Build(); Assert.Equal(TimeSpan.FromMinutes(5), sampler.PollingInterval); Assert.Equal("http://localhost:2000", sampler.Endpoint); @@ -45,11 +45,11 @@ public void TestSamplerWithDefaults() public void TestSamplerUpdateAndSample() { // setup mock server - TestClock clock = new TestClock(); - WireMockServer mockServer = WireMockServer.Start(); + var clock = new TestClock(); + var mockServer = WireMockServer.Start(); // create sampler - AWSXRayRemoteSampler sampler = AWSXRayRemoteSampler.Builder(ResourceBuilder.CreateEmpty().Build()) + var sampler = AWSXRayRemoteSampler.Builder(ResourceBuilder.CreateEmpty().Build()) .SetPollingInterval(TimeSpan.FromMilliseconds(10)) .SetEndpoint(mockServer.Url!) .SetClock(clock) @@ -100,10 +100,7 @@ private SamplingDecision DoSample(Trace.Sampler sampler, string serviceName) ActivityTraceId.CreateRandom(), "myActivityName", ActivityKind.Server, - new List> - { - new("test", serviceName), - }, + [new("test", serviceName)], null); return sampler.ShouldSample(samplingParams).Decision; diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs index 401a48a026..42f99c5e6c 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestAWSXRaySamplerClient.cs @@ -82,7 +82,7 @@ public async Task TestGetSamplingRulesMalformed() .RespondWith( Response.Create().WithStatusCode(200).WithHeader("Content-Type", "application/json").WithBody("notJson")); - List rules = await this.client.GetSamplingRules(); + var rules = await this.client.GetSamplingRules(); Assert.Empty(rules); } @@ -90,12 +90,12 @@ public async Task TestGetSamplingRulesMalformed() [Fact] public async Task TestGetSamplingTargets() { - TestClock clock = new TestClock(); + var clock = new TestClock(); this.CreateResponse("/SamplingTargets", "Data/GetSamplingTargetsResponse.json"); - var request = new GetSamplingTargetsRequest(new List - { + var request = new GetSamplingTargetsRequest( + [ new( "clientId", "rule1", @@ -117,7 +117,7 @@ public async Task TestGetSamplingTargets() 10, 2, clock.ToDouble(clock.Now())), - }); + ]); var targetsResponse = await this.client.GetSamplingTargets(request); Assert.NotNull(targetsResponse); @@ -145,14 +145,14 @@ public async Task TestGetSamplingTargets() [Fact] public async Task TestGetSamplingTargetsWithMalformed() { - TestClock clock = new TestClock(); + var clock = new TestClock(); this.mockServer .Given(Request.Create().WithPath("/SamplingTargets").UsingPost()) .RespondWith( Response.Create().WithStatusCode(200).WithHeader("Content-Type", "application/json").WithBody("notJson")); - var request = new GetSamplingTargetsRequest(new List - { + var request = new GetSamplingTargetsRequest( + [ new( "clientId", "rule1", @@ -160,7 +160,7 @@ public async Task TestGetSamplingTargetsWithMalformed() 50, 10, clock.ToDouble(clock.Now())), - }); + ]); var targetsResponse = await this.client.GetSamplingTargets(request); @@ -169,7 +169,7 @@ public async Task TestGetSamplingTargetsWithMalformed() private void CreateResponse(string endpoint, string filePath) { - string mockResponse = File.ReadAllText(filePath); + var mockResponse = File.ReadAllText(filePath); this.mockServer .Given(Request.Create().WithPath(endpoint).UsingPost()) .RespondWith( diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestClock.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestClock.cs index 7ddcb72daf..0cfe5c25cb 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestClock.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestClock.cs @@ -35,8 +35,8 @@ public override DateTimeOffset ToDateTime(double seconds) public override double ToDouble(DateTimeOffset dateTime) { - TimeSpan current = new TimeSpan(dateTime.ToUniversalTime().Ticks - EpochStart.Ticks); - double timestamp = Math.Round(current.TotalMilliseconds, 0) / 1000.0; + var current = new TimeSpan(dateTime.ToUniversalTime().Ticks - EpochStart.Ticks); + var timestamp = Math.Round(current.TotalMilliseconds, 0) / 1000.0; return timestamp; } diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs index d0224d6c9b..e586079a61 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestMatcher.cs @@ -74,7 +74,7 @@ public void TestAttributeMatchingWithoutSpanTags() { "cow", "mooo" }, }; - Assert.False(Matcher.AttributeMatch(new List>(), ruleAttributes)); + Assert.False(Matcher.AttributeMatch([], ruleAttributes)); Assert.False(Matcher.AttributeMatch(null, ruleAttributes)); } } diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimiter.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimiter.cs index acb46916c0..c404f26163 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimiter.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimiter.cs @@ -16,7 +16,7 @@ public class TestRateLimiter public void TestRateLimiterWholeNumber() { var testClock = new TestClock(); - RateLimiter limiter = new RateLimiter(2.0, 2.0, testClock); + var limiter = new RateLimiter(2.0, 2.0, testClock); Assert.True(limiter.TrySpend(1.0)); Assert.True(limiter.TrySpend(1.0)); @@ -44,8 +44,8 @@ public void TestRateLimiterWholeNumber() [Fact] public void TestRateLimiterLessThanOne() { - TestClock clock = new TestClock(); - RateLimiter limiter = new RateLimiter(0.5, 0.5, clock); + var clock = new TestClock(); + var limiter = new RateLimiter(0.5, 0.5, clock); Assert.True(limiter.TrySpend(0.25)); Assert.True(limiter.TrySpend(0.25)); @@ -72,8 +72,8 @@ public void TestRateLimiterLessThanOne() [Fact] public void TestRateLimiterMaxBalance() { - TestClock clock = new TestClock(); - RateLimiter limiter = new RateLimiter(0.1, 1.0, clock); + var clock = new TestClock(); + var limiter = new RateLimiter(0.1, 1.0, clock); clock.Advance(TimeSpan.FromMilliseconds(0.1)); Assert.True(limiter.TrySpend(1.0)); @@ -90,8 +90,8 @@ public void TestRateLimiterMaxBalance() [Fact] public void TestRateLimiterInitial() { - TestClock clock = new TestClock(); - RateLimiter limiter = new RateLimiter(1000, 100, clock); + var clock = new TestClock(); + var limiter = new RateLimiter(1000, 100, clock); Assert.True(limiter.TrySpend(100)); // consume initial (max) balance Assert.False(limiter.TrySpend(1)); @@ -115,18 +115,18 @@ public void TestRateLimiterInitial() [Fact] public async Task TestRateLimiterConcurrencyAsync() { - int numWorkers = 8; - int creditsPerWorker = 1000; - TestClock clock = new TestClock(); - RateLimiter limiter = new RateLimiter(1, numWorkers * creditsPerWorker, clock); - int count = 0; + var numWorkers = 8; + var creditsPerWorker = 1000; + var clock = new TestClock(); + var limiter = new RateLimiter(1, numWorkers * creditsPerWorker, clock); + var count = 0; List tasks = new(numWorkers); - for (int w = 0; w < numWorkers; ++w) + for (var w = 0; w < numWorkers; ++w) { - Task task = Task.Run(() => + var task = Task.Run(() => { - for (int i = 0; i < creditsPerWorker * 2; ++i) + for (var i = 0; i < creditsPerWorker * 2; ++i) { if (limiter.TrySpend(1)) { diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimitingSampler.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimitingSampler.cs index 090cf882b5..2eb3e1710a 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimitingSampler.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestRateLimitingSampler.cs @@ -11,7 +11,7 @@ public class TestRateLimitingSampler [Fact] public void TestLimitsRate() { - TestClock clock = new TestClock(); + var clock = new TestClock(); Trace.Sampler sampler = new RateLimitingSampler(1, clock); Assert.Equal(SamplingDecision.RecordAndSample, sampler.ShouldSample(Utils.CreateSamplingParameters()).Decision); diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestRulesCache.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestRulesCache.cs index f0e6831989..d24d2457bf 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestRulesCache.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestRulesCache.cs @@ -44,7 +44,7 @@ public void TestUpdateRules() // update the default rule var newDefaultRule = this.CreateDefaultRule(10, 0.20); - cache.UpdateRules(new List { newDefaultRule }); + cache.UpdateRules([newDefaultRule]); // asserts Assert.Single(cache.RuleAppliers); @@ -74,7 +74,7 @@ public void TestUpdateRulesRemovesOlderRule() // the update contains only the default rule var newDefaultRule = this.CreateDefaultRule(10, 0.20); - rulesCache.UpdateRules(new List { newDefaultRule }); + rulesCache.UpdateRules([newDefaultRule]); // assert that Rule1 doesn't exist in rules cache Assert.Single(rulesCache.RuleAppliers); @@ -116,7 +116,7 @@ public void TestFallbackSamplerMatchesWhenNoRules() var clock = new TestClock(); var rulesCache = new RulesCache(clock, "clientId", ResourceBuilder.CreateEmpty().Build(), new AlwaysOffSampler()) { - RuleAppliers = new List(), + RuleAppliers = [], }; // the fallback sampler will not sample @@ -233,6 +233,6 @@ private SamplingRule CreateRule(string name, int reservoirSize, double fixedRate serviceType: "*", urlPath: "*", version: 1, - attributes: new Dictionary()); + attributes: []); } } diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/TestSamplingRuleApplier.cs b/test/OpenTelemetry.Sampler.AWS.Tests/TestSamplingRuleApplier.cs index 283528e90f..f93bd7804e 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/TestSamplingRuleApplier.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/TestSamplingRuleApplier.cs @@ -23,7 +23,7 @@ public void TestRuleMatchesWithAllAttributes() serviceType: "AWS::Lambda::Function", urlPath: "/helloworld", version: 1, - attributes: new Dictionary()); + attributes: []); var activityTags = new Dictionary { @@ -52,7 +52,7 @@ public void TestRuleMatchesWithWildcardAttributes() serviceType: "*", urlPath: "/helloworld", version: 1, - attributes: new Dictionary()); + attributes: []); var activityTags = new Dictionary { @@ -80,7 +80,7 @@ public void TestRuleMatchesWithNoActivityAttributes() serviceType: "*", urlPath: "/helloworld", version: 1, - attributes: new Dictionary()); + attributes: []); var activityTags = new Dictionary(); @@ -103,7 +103,7 @@ public void TestRuleMatchesWithNoActivityAttributesAndWildcardRules() serviceType: "*", urlPath: "*", version: 1, - attributes: new Dictionary()); + attributes: []); var activityTags = new Dictionary(); @@ -126,7 +126,7 @@ public void TestRuleMatchesWithHttpTarget() serviceType: "*", urlPath: "/hello*", version: 1, - attributes: new Dictionary()); + attributes: []); var activityTags = new Dictionary { @@ -208,8 +208,8 @@ public void TestAttributeMatchingWithLessActivityTags() [Fact] public void TestFixedRateAlwaysSample() { - TestClock clock = new TestClock(); - SamplingRule rule = new SamplingRule( + var clock = new TestClock(); + var rule = new SamplingRule( "rule1", 1, 1.0, // fixed rate @@ -221,7 +221,7 @@ public void TestFixedRateAlwaysSample() "*", "*", 1, - new Dictionary()); + []); var applier = new SamplingRuleApplier("clientId", clock, rule, new Statistics()); @@ -247,8 +247,8 @@ public void TestFixedRateAlwaysSample() [Fact] public void TestFixedRateNeverSample() { - TestClock clock = new TestClock(); - SamplingRule rule = new SamplingRule( + var clock = new TestClock(); + var rule = new SamplingRule( "rule1", 1, 0.0, // fixed rate @@ -260,7 +260,7 @@ public void TestFixedRateNeverSample() "*", "*", 1, - new Dictionary()); + []); var applier = new SamplingRuleApplier("clientId", clock, rule, new Statistics()); @@ -279,8 +279,8 @@ public void TestFixedRateNeverSample() [Fact] public void TestBorrowFromReservoir() { - TestClock clock = new TestClock(); - SamplingRule rule = new SamplingRule( + var clock = new TestClock(); + var rule = new SamplingRule( "rule1", 1, 0.0, // fixed rate @@ -292,7 +292,7 @@ public void TestBorrowFromReservoir() "*", "*", 1, - new Dictionary()); + []); var applier = new SamplingRuleApplier("clientId", clock, rule, new Statistics()); @@ -315,8 +315,8 @@ public void TestBorrowFromReservoir() [Fact] public void TestWithTarget() { - TestClock clock = new TestClock(); - SamplingRule rule = new SamplingRule( + var clock = new TestClock(); + var rule = new SamplingRule( "rule1", 1, 0.0, // fixed rate @@ -328,7 +328,7 @@ public void TestWithTarget() "*", "*", 1, - new Dictionary()); + []); var applier = new SamplingRuleApplier("clientId", clock, rule, new Statistics()); @@ -340,7 +340,7 @@ public void TestWithTarget() Assert.Equal(SamplingDecision.Drop, applier.ShouldSample(default).Decision); // get the target - SamplingTargetDocument target = new SamplingTargetDocument + var target = new SamplingTargetDocument { FixedRate = 0.0, Interval = 10, @@ -360,8 +360,8 @@ public void TestWithTarget() [Fact] public void TestWithTargetWithoutQuota() { - TestClock clock = new TestClock(); - SamplingRule rule = new SamplingRule( + var clock = new TestClock(); + var rule = new SamplingRule( "rule1", 1, 0.0, // fixed rate @@ -373,7 +373,7 @@ public void TestWithTargetWithoutQuota() "*", "*", 1, - new Dictionary()); + []); var applier = new SamplingRuleApplier("clientId", clock, rule, new Statistics()); @@ -390,7 +390,7 @@ public void TestWithTargetWithoutQuota() Assert.Equal(2, statistics.BorrowCount); // get the target - SamplingTargetDocument target = new SamplingTargetDocument + var target = new SamplingTargetDocument { FixedRate = 1.0, Interval = 10, diff --git a/test/OpenTelemetry.Sampler.AWS.Tests/Utils.cs b/test/OpenTelemetry.Sampler.AWS.Tests/Utils.cs index 7b53882827..3d5f45aef6 100644 --- a/test/OpenTelemetry.Sampler.AWS.Tests/Utils.cs +++ b/test/OpenTelemetry.Sampler.AWS.Tests/Utils.cs @@ -11,14 +11,14 @@ internal static class Utils { internal static SamplingParameters CreateSamplingParameters() { - return CreateSamplingParametersWithTags(new Dictionary()); + return CreateSamplingParametersWithTags([]); } internal static SamplingParameters CreateSamplingParametersWithTags(Dictionary tags) { - ActivityTraceId traceId = ActivityTraceId.CreateRandom(); - ActivitySpanId parentSpanId = ActivitySpanId.CreateRandom(); - ActivityTraceFlags traceFlags = ActivityTraceFlags.None; + var traceId = ActivityTraceId.CreateRandom(); + var parentSpanId = ActivitySpanId.CreateRandom(); + var traceFlags = ActivityTraceFlags.None; var parentContext = new ActivityContext(traceId, parentSpanId, traceFlags);