From b022779f24efb7c3fb5a8ab212b05612f419b304 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:36:11 +0100 Subject: [PATCH 01/12] Fix IDE0300/IDE0028 --- .../HttpClientInstrumentation.cs | 16 +++++------ .../HttpClientMetrics.cs | 8 +++--- .../HttpWebRequestActivitySource.netfx.cs | 27 +++++++++---------- 3 files changed, 25 insertions(+), 26 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs index 40daae9660..1da373d2e4 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs @@ -10,18 +10,18 @@ namespace OpenTelemetry.Instrumentation.Http; /// internal sealed class HttpClientInstrumentation : IDisposable { - private static readonly HashSet ExcludedDiagnosticSourceEventsNet7OrGreater = new() - { + private static readonly HashSet ExcludedDiagnosticSourceEventsNet7OrGreater = + [ "System.Net.Http.Request", "System.Net.Http.Response", - "System.Net.Http.HttpRequestOut", - }; + "System.Net.Http.HttpRequestOut" + ]; - private static readonly HashSet ExcludedDiagnosticSourceEvents = new() - { + private static readonly HashSet ExcludedDiagnosticSourceEvents = + [ "System.Net.Http.Request", - "System.Net.Http.Response", - }; + "System.Net.Http.Response" + ]; private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber; diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs index e03cd6a46a..8913f8daf7 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs @@ -10,11 +10,11 @@ namespace OpenTelemetry.Instrumentation.Http; /// internal sealed class HttpClientMetrics : IDisposable { - private static readonly HashSet ExcludedDiagnosticSourceEvents = new() - { + private static readonly HashSet ExcludedDiagnosticSourceEvents = + [ "System.Net.Http.Request", - "System.Net.Http.Response", - }; + "System.Net.Http.Response" + ]; private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber; diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index c99639639d..247050f661 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -359,12 +359,11 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC // Disposed HttpWebResponse throws when accessing properties, so let's make a copy of the data to ensure that doesn't happen. HttpWebResponse responseCopy = httpWebResponseCtor( - new object[] - { - uriAccessor(response), verbAccessor(response), coreResponseDataAccessor(response), mediaTypeAccessor(response), + [ + uriAccessor(response), verbAccessor(response), coreResponseDataAccessor(response), mediaTypeAccessor(response), usesProxySemanticsAccessor(response), DecompressionMethods.None, - isWebSocketResponseAccessor(response), connectionGroupNameAccessor(response), - }); + isWebSocketResponseAccessor(response), connectionGroupNameAccessor(response) + ]); if (activity != null) { @@ -567,7 +566,7 @@ private static void PerformInjection() ?? throw new InvalidOperationException("Unable to access the ServicePointTable field"); Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable; - ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? new Hashtable()); + ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? []); foreach (DictionaryEntry existingServicePoint in originalTable) { @@ -587,7 +586,7 @@ private static void HookServicePoint(object value) // which allows us to intercept each new ConnectionGroup object added under // this ServicePoint. Hashtable originalTable = connectionGroupListField.GetValue(servicePoint) as Hashtable; - ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? new Hashtable()); + ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? []); foreach (DictionaryEntry existingConnectionGroup in originalTable) { @@ -606,7 +605,7 @@ private static void HookConnectionGroup(object value) // which allows us to intercept each new Connection object added under // this ConnectionGroup. ArrayList originalArrayList = connectionListField.GetValue(value) as ArrayList; - ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? new ArrayList()); + ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? []); foreach (object connection in originalArrayList) { @@ -625,7 +624,7 @@ private static void HookConnection(object value) // which allows us to intercept each new HttpWebRequest object added under // this Connection. ArrayList originalArrayList = writeListField.GetValue(value) as ArrayList; - HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? new ArrayList()); + HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? []); writeListField.SetValue(value, newArrayList); } @@ -638,7 +637,7 @@ private static Func CreateFieldGetter(string fie if (field != null) { string methodName = field.ReflectedType.FullName + ".get_" + field.Name; - DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(TClass) }, true); + DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(TClass)], true); ILGenerator generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); @@ -659,7 +658,7 @@ private static Func CreateFieldGetter(Type classType, st if (field != null) { string methodName = classType.FullName + ".get_" + field.Name; - DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(object) }, true); + DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(object)], true); ILGenerator generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); @@ -682,7 +681,7 @@ private static Action CreateFieldSetter(Type classType, if (field != null) { string methodName = classType.FullName + ".set_" + field.Name; - DynamicMethod setterMethod = new DynamicMethod(methodName, null, new[] { typeof(object), typeof(TField) }, true); + DynamicMethod setterMethod = new DynamicMethod(methodName, null, [typeof(object), typeof(TField)], true); ILGenerator generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); @@ -702,7 +701,7 @@ private static Action CreateFieldSetter(Type classType, private static Func CreateTypeChecker(Type classType) { string methodName = classType.FullName + ".typeCheck"; - DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(bool), new[] { typeof(object) }, true); + DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(bool), [typeof(object)], true); ILGenerator generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Isinst, classType); @@ -720,7 +719,7 @@ private static Func CreateTypeInstance(ConstructorInfo construct { Type classType = typeof(T); string methodName = classType.FullName + ".ctor"; - DynamicMethod setterMethod = new DynamicMethod(methodName, classType, new Type[] { typeof(object[]) }, true); + DynamicMethod setterMethod = new DynamicMethod(methodName, classType, [typeof(object[])], true); ILGenerator generator = setterMethod.GetILGenerator(); ParameterInfo[] ctorParams = constructorInfo.GetParameters(); From eeefda42018315f0c5334841fb3dce2ffbba2068 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:36:44 +0100 Subject: [PATCH 02/12] Fix IDE0010 --- .../Implementation/HttpHandlerDiagnosticListener.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index 14e2ebbec7..969451783f 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -65,6 +65,8 @@ public override void OnEventWritten(string name, object? payload) this.OnException(activity, payload); } + break; + default: break; } } From 093c6486813f76d37de3a2dd85ced7e850ca2272 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:37:02 +0100 Subject: [PATCH 03/12] Fix IDE0027 --- .../Implementation/HttpWebRequestActivitySource.netfx.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index 247050f661..d96200cd71 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -89,10 +89,7 @@ static HttpWebRequestActivitySource() internal static HttpClientTraceInstrumentationOptions TracingOptions { get => tracingOptions; - set - { - tracingOptions = value; - } + set => tracingOptions = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] From 50d991aed78faeb0e23ca60d90fcb38ebbf5f170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:37:43 +0100 Subject: [PATCH 04/12] Fix IDE0061 --- .../HttpHandlerMetricsDiagnosticListener.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs index 7a841bf654..6ac516d19a 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs @@ -98,16 +98,20 @@ public static void OnStopEventWritten(Activity activity, object? payload) #if NET [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The System.Net.Http library guarantees that top-level properties are preserved")] #endif - static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) => - StopRequestFetcher.TryFetch(payload, out request) && request != null; + static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) + { + return StopRequestFetcher.TryFetch(payload, out request) && request != null; + } // The AOT-annotation DynamicallyAccessedMembers in System.Net.Http library ensures that top-level properties on the payload object are always preserved. // see https://github.com/dotnet/runtime/blob/f9246538e3d49b90b0e9128d7b1defef57cd6911/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs#L325 #if NET [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The System.Net.Http library guarantees that top-level properties are preserved")] #endif - static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpResponseMessage? response) => - StopResponseFetcher.TryFetch(payload, out response) && response != null; + static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpResponseMessage? response) + { + return StopResponseFetcher.TryFetch(payload, out response) && response != null; + } } public static void OnExceptionEventWritten(Activity activity, object? payload) From a73ee98b895f743c4e4448ee9ce839afea8089d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:38:51 +0100 Subject: [PATCH 05/12] Fix IDE0120 --- .../HttpClientTests.Basic.cs | 8 ++++---- .../HttpWebRequestActivitySourceTests.netfx.cs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs index 05bc602e81..612969801d 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs @@ -189,8 +189,8 @@ public async Task InjectsHeadersAsync(bool shouldEnrich) #if NETFRAMEWORK if (shouldEnrich) { - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpWebRequest").FirstOrDefault().Value); - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpWebResponse").FirstOrDefault().Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpWebRequest").Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpWebResponse").Value); } else { @@ -206,8 +206,8 @@ public async Task InjectsHeadersAsync(bool shouldEnrich) if (shouldEnrich) { - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpRequestMessage").FirstOrDefault().Value); - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpResponseMessage").FirstOrDefault().Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpRequestMessage").Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpResponseMessage").Value); } else { diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index ebcb77d0b0..6284572960 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -54,7 +54,7 @@ public HttpWebRequestActivitySourceTests() Activity.ForceDefaultIdFormat = false; this.testServer = TestHttpServer.RunServer( - ctx => ProcessServerRequest(ctx), + ProcessServerRequest, out this.testServerHost, out this.testServerPort); From 3e2e13b0246cee169e0315216a0565841785e7c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:39:27 +0100 Subject: [PATCH 06/12] Fix IDe0100 --- .../Implementation/HttpHandlerDiagnosticListener.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index 969451783f..478b37905e 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -111,7 +111,7 @@ public void OnStartActivity(Activity activity, object? payload) { try { - if (this.options.EventFilterHttpRequestMessage(activity.OperationName, request) == false) + if (!this.options.EventFilterHttpRequestMessage(activity.OperationName, request)) { HttpInstrumentationEventSource.Log.RequestIsFilteredOut(activity.OperationName); activity.IsAllDataRequested = false; From afb84b48a8f482d15649fcd1ff9a83b80d336116 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:40:54 +0100 Subject: [PATCH 07/12] Fix IDE0078 --- .../HttpClientInstrumentation.cs | 9 +------- .../HttpHandlerDiagnosticListener.cs | 21 +++---------------- .../HttpHandlerMetricsDiagnosticListener.cs | 14 ++----------- .../HttpWebRequestActivitySource.netfx.cs | 2 +- .../Implementation/TelemetryHelper.cs | 14 ++----------- .../HttpClientTests.Basic.cs | 6 +----- .../HttpClientTests.cs | 8 +------ ...HttpWebRequestActivitySourceTests.netfx.cs | 14 +++---------- 8 files changed, 14 insertions(+), 74 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs index 1da373d2e4..ff4b6bead0 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs @@ -43,14 +43,7 @@ public HttpClientInstrumentation(HttpClientTraceInstrumentationOptions options) // the framework will fall back to creating activity anyways due to active diagnostic source listener // To prevent this, isEnabled is implemented which will return false always // so that the sampler's decision is respected. - if (HttpHandlerDiagnosticListener.IsNet7OrGreater) - { - this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabledNet7OrGreater, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); - } - else - { - this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabled, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); - } + this.diagnosticSourceSubscriber = HttpHandlerDiagnosticListener.IsNet7OrGreater ? new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabledNet7OrGreater, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent) : new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabled, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); this.diagnosticSourceSubscriber.Subscribe(); } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index 478b37905e..ca4c7d8ad3 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -163,12 +163,7 @@ public void OnStartActivity(Activity activity, object? payload) #endif static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) { - if (!StartRequestFetcher.TryFetch(payload, out request) || request == null) - { - return false; - } - - return true; + return StartRequestFetcher.TryFetch(payload, out request) && request != null; } } @@ -248,12 +243,7 @@ static TaskStatus GetRequestStatus(object? payload) #endif static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpResponseMessage? response) { - if (StopResponseFetcher.TryFetch(payload, out response) && response != null) - { - return true; - } - - return false; + return StopResponseFetcher.TryFetch(payload, out response) && response != null; } } @@ -301,12 +291,7 @@ public void OnException(Activity activity, object? payload) #endif static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) { - if (!StopExceptionFetcher.TryFetch(payload, out exc) || exc == null) - { - return false; - } - - return true; + return StopExceptionFetcher.TryFetch(payload, out exc) && exc != null; } } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs index 6ac516d19a..20acc1f0af 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs @@ -135,12 +135,7 @@ public static void OnExceptionEventWritten(Activity activity, object? payload) #endif static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) { - if (!StopExceptionFetcher.TryFetch(payload, out exc) || exc == null) - { - return false; - } - - return true; + return StopExceptionFetcher.TryFetch(payload, out exc) && exc != null; } // The AOT-annotation DynamicallyAccessedMembers in System.Net.Http library ensures that top-level properties on the payload object are always preserved. @@ -150,12 +145,7 @@ static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception #endif static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) { - if (!RequestFetcher.TryFetch(payload, out request) || request == null) - { - return false; - } - - return true; + return RequestFetcher.TryFetch(payload, out request) && request != null; } } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index d96200cd71..c19492ebbf 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -1180,7 +1180,7 @@ public AsyncCallbackWrapper(HttpWebRequest request, Activity activity, AsyncCall public void AsyncCallback(IAsyncResult asyncResult) { object result = resultAccessor(asyncResult); - if (result is Exception || result is HttpWebResponse) + if (result is Exception or HttpWebResponse) { ProcessResult( asyncResult, diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs index 49bd111f4e..76426ab255 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs @@ -13,23 +13,13 @@ internal static class TelemetryHelper public static object GetBoxedStatusCode(HttpStatusCode statusCode) { int intStatusCode = (int)statusCode; - if (intStatusCode >= 100 && intStatusCode < 600) - { - return BoxedStatusCodes[intStatusCode - 100].Item1; - } - - return statusCode; + return intStatusCode is >= 100 and < 600 ? BoxedStatusCodes[intStatusCode - 100].Item1 : statusCode; } public static string GetStatusCodeString(HttpStatusCode statusCode) { int intStatusCode = (int)statusCode; - if (intStatusCode >= 100 && intStatusCode < 600) - { - return BoxedStatusCodes[intStatusCode - 100].Item2; - } - - return statusCode.ToString(); + return intStatusCode is >= 100 and < 600 ? BoxedStatusCodes[intStatusCode - 100].Item2 : statusCode.ToString(); } private static (object, string)[] InitializeBoxedStatusCodes() diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs index 612969801d..0ee5a4b4c7 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs @@ -38,11 +38,7 @@ public HttpClientTests(ITestOutputHelper output) var custom_traceparent = ctx.Request.Headers["custom_traceparent"]; var contextRequired = ctx.Request.Headers["contextRequired"]; var responseCode = ctx.Request.Headers["responseCode"]; - if ((contextRequired == null - || bool.Parse(contextRequired)) - && - (string.IsNullOrWhiteSpace(traceparent) - && string.IsNullOrWhiteSpace(custom_traceparent))) + if ((contextRequired == null || bool.Parse(contextRequired)) && string.IsNullOrWhiteSpace(traceparent) && string.IsNullOrWhiteSpace(custom_traceparent)) { ctx.Response.StatusCode = 500; ctx.Response.StatusDescription = "Missing trace context"; diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs index 83e594179b..76bbdbc19f 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs @@ -151,13 +151,7 @@ public async Task ValidateNet8MetricsAsync(HttpOutTestCase tc) } var requestMetrics = metrics - .Where(metric => - metric.Name == "http.client.request.duration" || - metric.Name == "http.client.active_requests" || - metric.Name == "http.client.request.time_in_queue" || - metric.Name == "http.client.connection.duration" || - metric.Name == "http.client.open_connections" || - metric.Name == "dns.lookup.duration") + .Where(metric => metric.Name is "http.client.request.duration" or "http.client.active_requests" or "http.client.request.time_in_queue" or "http.client.connection.duration" or "http.client.open_connections" or "dns.lookup.duration") .ToArray(); if (tc.ResponseExpected) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index 6284572960..360e2eb332 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -84,14 +84,7 @@ void ProcessServerRequest(HttpListenerContext context) } string responseCode = context.Request.QueryString["responseCode"]; - if (!string.IsNullOrWhiteSpace(responseCode)) - { - context.Response.StatusCode = int.Parse(responseCode); - } - else - { - context.Response.StatusCode = 200; - } + context.Response.StatusCode = !string.IsNullOrWhiteSpace(responseCode) ? int.Parse(responseCode) : 200; if (context.Response.StatusCode != 204) { @@ -565,7 +558,7 @@ public async Task TestCanceledRequest(string method) ? client.GetAsync(new Uri(url), cts.Token) : client.PostAsync(new Uri(url), new StringContent("hello world"), cts.Token); }); - Assert.True(ex is TaskCanceledException || ex is WebException); + Assert.True(ex is TaskCanceledException or WebException); } // We should have one Start event and one Stop event with an exception. @@ -739,8 +732,7 @@ await Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(async _ => Activity activity = pair.Value; Assert.True( - pair.Key == "Start" || - pair.Key == "Stop", + pair.Key is "Start" or "Stop", "An unexpected event of name " + pair.Key + "was received"); } } From f9302a8817ee88c95d7f8a184552aabcc44b46a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:44:12 +0100 Subject: [PATCH 08/12] ue auto property --- .../HttpWebRequestActivitySource.netfx.cs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index c19492ebbf..359b67c22d 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -40,8 +40,6 @@ internal static class HttpWebRequestActivitySource private static readonly Meter WebRequestMeter = new(MeterName, Version); private static readonly Histogram HttpClientRequestDuration = WebRequestMeter.CreateHistogram("http.client.request.duration", "s", "Duration of HTTP client requests."); - private static HttpClientTraceInstrumentationOptions tracingOptions; - // Fields for reflection private static FieldInfo connectionGroupListField; private static Type connectionGroupType; @@ -86,11 +84,7 @@ static HttpWebRequestActivitySource() } } - internal static HttpClientTraceInstrumentationOptions TracingOptions - { - get => tracingOptions; - set => tracingOptions = value; - } + internal static HttpClientTraceInstrumentationOptions TracingOptions { get; set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AddRequestTagsAndInstrumentRequest(HttpWebRequest request, Activity activity) @@ -105,7 +99,7 @@ private static void AddRequestTagsAndInstrumentRequest(HttpWebRequest request, A activity.SetTag(SemanticConventions.AttributeServerAddress, request.RequestUri.Host); activity.SetTag(SemanticConventions.AttributeServerPort, request.RequestUri.Port); - activity.SetTag(SemanticConventions.AttributeUrlFull, HttpTagHelper.GetUriTagValueFromRequestUri(request.RequestUri, tracingOptions.DisableUrlQueryRedaction)); + activity.SetTag(SemanticConventions.AttributeUrlFull, HttpTagHelper.GetUriTagValueFromRequestUri(request.RequestUri, TracingOptions.DisableUrlQueryRedaction)); try { From be06daa8c7aa1c6dbf1f6d4a835f955f970165ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:44:40 +0100 Subject: [PATCH 09/12] Fix IDE0028 --- .../HttpWebRequestActivitySourceTests.netfx.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index 360e2eb332..8020526bde 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -690,7 +690,7 @@ public async Task TestMultipleConcurrentRequests() using var parentActivity = new Activity("parent").Start(); using var eventRecords = new ActivitySourceRecorder(); - Dictionary> requestData = new Dictionary>(); + Dictionary> requestData = []; for (int i = 0; i < 10; i++) { Uri uriWithRedirect = new Uri(this.BuildRequestUrl(queryString: $"q={i}&redirects=3")); @@ -700,7 +700,7 @@ public async Task TestMultipleConcurrentRequests() // Issue all requests simultaneously using var httpClient = new HttpClient(); - Dictionary> tasks = new Dictionary>(); + Dictionary> tasks = []; CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); foreach (var url in requestData.Keys) From be948477182062541568198f4f941f8a4d626d8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 07:46:07 +0100 Subject: [PATCH 10/12] Fix IDE0007 --- .../HttpClientTraceInstrumentationOptions.cs | 2 +- .../HttpHandlerDiagnosticListener.cs | 8 +- .../HttpHandlerMetricsDiagnosticListener.cs | 6 +- .../HttpWebRequestActivitySource.netfx.cs | 112 +++++++++--------- .../Implementation/TelemetryHelper.cs | 4 +- .../HttpClientTests.cs | 20 ++-- ...HttpWebRequestActivitySourceTests.netfx.cs | 92 +++++++------- .../HttpWebRequestTests.Basic.cs | 14 +-- .../HttpWebRequestTests.cs | 14 +-- .../RepeatHandler.cs | 2 +- 10 files changed, 137 insertions(+), 137 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs index e63f77bae3..cba754cc9f 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs @@ -165,7 +165,7 @@ internal bool EventFilterHttpRequestMessage(string activityName, object arg1) { return this.FilterHttpRequestMessage == null || - !TryParseHttpRequestMessage(activityName, arg1, out HttpRequestMessage? requestMessage) || + !TryParseHttpRequestMessage(activityName, arg1, out var requestMessage) || this.FilterHttpRequestMessage(requestMessage); } catch (Exception ex) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index ca4c7d8ad3..5b65c673d0 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -83,7 +83,7 @@ public void OnStartActivity(Activity activity, object? payload) // By this time, samplers have already run and // activity.IsAllDataRequested populated accordingly. - if (!TryFetchRequest(payload, out HttpRequestMessage? request)) + if (!TryFetchRequest(payload, out var request)) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnStartActivity)); return; @@ -173,7 +173,7 @@ public void OnStopActivity(Activity activity, object? payload) { var requestTaskStatus = GetRequestStatus(payload); - ActivityStatusCode currentStatusCode = activity.Status; + var currentStatusCode = activity.Status; if (requestTaskStatus != TaskStatus.RanToCompletion) { if (requestTaskStatus == TaskStatus.Canceled) @@ -197,7 +197,7 @@ public void OnStopActivity(Activity activity, object? payload) } } - if (TryFetchResponse(payload, out HttpResponseMessage? response)) + if (TryFetchResponse(payload, out var response)) { if (currentStatusCode == ActivityStatusCode.Unset) { @@ -251,7 +251,7 @@ public void OnException(Activity activity, object? payload) { if (activity.IsAllDataRequested) { - if (!TryFetchException(payload, out Exception? exc)) + if (!TryFetchException(payload, out var exc)) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnException)); return; diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs index 20acc1f0af..dd3dc6970c 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs @@ -39,7 +39,7 @@ public HttpHandlerMetricsDiagnosticListener(string name) public static void OnStopEventWritten(Activity activity, object? payload) { - if (TryFetchRequest(payload, out HttpRequestMessage? request)) + if (TryFetchRequest(payload, out var request)) { // see the spec https://github.com/open-telemetry/semantic-conventions/blob/v1.23.0/docs/http/http-metrics.md TagList tags = default; @@ -58,7 +58,7 @@ public static void OnStopEventWritten(Activity activity, object? payload) } } - if (TryFetchResponse(payload, out HttpResponseMessage? response)) + if (TryFetchResponse(payload, out var response)) { tags.Add(new KeyValuePair(SemanticConventions.AttributeNetworkProtocolVersion, RequestDataHelper.GetHttpProtocolVersion(response.Version))); tags.Add(new KeyValuePair(SemanticConventions.AttributeHttpResponseStatusCode, TelemetryHelper.GetBoxedStatusCode(response.StatusCode))); @@ -116,7 +116,7 @@ static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpRespon public static void OnExceptionEventWritten(Activity activity, object? payload) { - if (!TryFetchException(payload, out Exception? exc) || !TryFetchRequest(payload, out HttpRequestMessage? request)) + if (!TryFetchException(payload, out var exc) || !TryFetchRequest(payload, out var request)) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerMetricsDiagnosticListener), nameof(OnExceptionEventWritten)); return; diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index 359b67c22d..7f8ba01066 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -223,7 +223,7 @@ private static void ProcessRequest(HttpWebRequest request) return; } - Activity activity = enableTracing + var activity = enableTracing ? WebRequestActivitySource.StartActivity(ActivityName, ActivityKind.Client) : null; @@ -234,12 +234,12 @@ private static void ProcessRequest(HttpWebRequest request) // Eg: Parent could be the Asp.Net activity. InstrumentRequest(request, activityContext); - IAsyncResult asyncContext = writeAResultAccessor(request); + var asyncContext = writeAResultAccessor(request); if (asyncContext != null) { // Flow here is for [Begin]GetRequestStream[Async]. - AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); + var callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); asyncCallbackModifier(asyncContext, callback.AsyncCallback); } else @@ -247,7 +247,7 @@ private static void ProcessRequest(HttpWebRequest request) // Flow here is for [Begin]GetResponse[Async] without a prior call to [Begin]GetRequestStream[Async]. asyncContext = readAResultAccessor(request); - AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); + var callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); asyncCallbackModifier(asyncContext, callback.AsyncCallback); } @@ -259,7 +259,7 @@ private static void ProcessRequest(HttpWebRequest request) private static void HookOrProcessResult(HttpWebRequest request) { - IAsyncResult writeAsyncContext = writeAResultAccessor(request); + var writeAsyncContext = writeAResultAccessor(request); if (writeAsyncContext == null || asyncCallbackAccessor(writeAsyncContext)?.Target is not AsyncCallbackWrapper writeAsyncContextCallback) { // If we already hooked into the read result during ProcessRequest or we hooked up after the fact already we don't need to do anything here. @@ -268,7 +268,7 @@ private static void HookOrProcessResult(HttpWebRequest request) // If we got here it means the user called [Begin]GetRequestStream[Async] and we have to hook the read result after the fact. - IAsyncResult readAsyncContext = readAResultAccessor(request); + var readAsyncContext = readAResultAccessor(request); if (readAsyncContext == null) { // We're still trying to establish the connection (no read has started). @@ -286,7 +286,7 @@ private static void HookOrProcessResult(HttpWebRequest request) } // Hook into the result callback if it hasn't already fired. - AsyncCallbackWrapper callback = new AsyncCallbackWrapper(writeAsyncContextCallback.Request, writeAsyncContextCallback.Activity, asyncCallbackAccessor(readAsyncContext), Stopwatch.GetTimestamp()); + var callback = new AsyncCallbackWrapper(writeAsyncContextCallback.Request, writeAsyncContextCallback.Activity, asyncCallbackAccessor(readAsyncContext), Stopwatch.GetTimestamp()); asyncCallbackModifier(readAsyncContext, callback.AsyncCallback); } @@ -295,7 +295,7 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC HttpStatusCode? httpStatusCode = null; string errorType = null; Version protocolVersion = null; - ActivityStatusCode activityStatus = ActivityStatusCode.Unset; + var activityStatus = ActivityStatusCode.Unset; // Activity may be null if we are not tracing in these cases: // 1. No listeners @@ -340,7 +340,7 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC } else { - HttpWebResponse response = (HttpWebResponse)result; + var response = (HttpWebResponse)result; if (forceResponseCopy || (asyncCallback == null && isContextAwareResultChecker(asyncResult))) { @@ -349,7 +349,7 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC // in which case they could dispose the HttpWebResponse before our listeners have a chance to work with it. // Disposed HttpWebResponse throws when accessing properties, so let's make a copy of the data to ensure that doesn't happen. - HttpWebResponse responseCopy = httpWebResponseCtor( + var responseCopy = httpWebResponseCtor( [ uriAccessor(response), verbAccessor(response), coreResponseDataAccessor(response), mediaTypeAccessor(response), usesProxySemanticsAccessor(response), DecompressionMethods.None, @@ -448,8 +448,8 @@ private static void PrepareReflectionObjects() { // At any point, if the operation failed, it should just throw. The caller should catch all exceptions and swallow. - Type servicePointType = typeof(ServicePoint); - Assembly systemNetHttpAssembly = servicePointType.Assembly; + var servicePointType = typeof(ServicePoint); + var systemNetHttpAssembly = servicePointType.Assembly; connectionGroupListField = servicePointType.GetField("m_ConnectionGroupList", BindingFlags.Instance | BindingFlags.NonPublic); connectionGroupType = systemNetHttpAssembly?.GetType("System.Net.ConnectionGroup"); connectionListField = connectionGroupType?.GetField("m_ConnectionList", BindingFlags.Instance | BindingFlags.NonPublic); @@ -479,7 +479,7 @@ private static void PrepareReflectionObjects() private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAssembly) { - Type lazyAsyncResultType = systemNetHttpAssembly?.GetType("System.Net.LazyAsyncResult"); + var lazyAsyncResultType = systemNetHttpAssembly?.GetType("System.Net.LazyAsyncResult"); if (lazyAsyncResultType != null) { asyncCallbackAccessor = CreateFieldGetter(lazyAsyncResultType, "m_AsyncCallback", BindingFlags.NonPublic | BindingFlags.Instance); @@ -490,7 +490,7 @@ private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAs resultAccessor = CreateFieldGetter(lazyAsyncResultType, "m_Result", BindingFlags.NonPublic | BindingFlags.Instance); } - Type contextAwareResultType = systemNetHttpAssembly?.GetType("System.Net.ContextAwareResult"); + var contextAwareResultType = systemNetHttpAssembly?.GetType("System.Net.ContextAwareResult"); if (contextAwareResultType != null) { isContextAwareResultChecker = CreateTypeChecker(contextAwareResultType); @@ -507,8 +507,8 @@ private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAs private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHttpAssembly) { - Type knownHttpVerbType = systemNetHttpAssembly?.GetType("System.Net.KnownHttpVerb"); - Type coreResponseData = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData"); + var knownHttpVerbType = systemNetHttpAssembly?.GetType("System.Net.KnownHttpVerb"); + var coreResponseData = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData"); if (knownHttpVerbType != null && coreResponseData != null) { @@ -519,7 +519,7 @@ private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHt typeof(bool), typeof(string), }; - ConstructorInfo ctor = typeof(HttpWebResponse).GetConstructor( + var ctor = typeof(HttpWebResponse).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, constructorParameterTypes, @@ -553,11 +553,11 @@ private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHt private static void PerformInjection() { - FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic) - ?? throw new InvalidOperationException("Unable to access the ServicePointTable field"); + var servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("Unable to access the ServicePointTable field"); - Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable; - ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? []); + var originalTable = servicePointTableField.GetValue(null) as Hashtable; + var newTable = new ServicePointHashtable(originalTable ?? []); foreach (DictionaryEntry existingServicePoint in originalTable) { @@ -576,8 +576,8 @@ private static void HookServicePoint(object value) // Replace the ConnectionGroup hashtable inside this ServicePoint object, // which allows us to intercept each new ConnectionGroup object added under // this ServicePoint. - Hashtable originalTable = connectionGroupListField.GetValue(servicePoint) as Hashtable; - ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? []); + var originalTable = connectionGroupListField.GetValue(servicePoint) as Hashtable; + var newTable = new ConnectionGroupHashtable(originalTable ?? []); foreach (DictionaryEntry existingConnectionGroup in originalTable) { @@ -595,10 +595,10 @@ private static void HookConnectionGroup(object value) // Replace the Connection arraylist inside this ConnectionGroup object, // which allows us to intercept each new Connection object added under // this ConnectionGroup. - ArrayList originalArrayList = connectionListField.GetValue(value) as ArrayList; - ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? []); + var originalArrayList = connectionListField.GetValue(value) as ArrayList; + var newArrayList = new ConnectionArrayList(originalArrayList ?? []); - foreach (object connection in originalArrayList) + foreach (var connection in originalArrayList) { HookConnection(connection); } @@ -614,8 +614,8 @@ private static void HookConnection(object value) // Replace the HttpWebRequest arraylist inside this Connection object, // which allows us to intercept each new HttpWebRequest object added under // this Connection. - ArrayList originalArrayList = writeListField.GetValue(value) as ArrayList; - HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? []); + var originalArrayList = writeListField.GetValue(value) as ArrayList; + var newArrayList = new HttpWebRequestArrayList(originalArrayList ?? []); writeListField.SetValue(value, newArrayList); } @@ -624,12 +624,12 @@ private static void HookConnection(object value) private static Func CreateFieldGetter(string fieldName, BindingFlags flags) where TClass : class { - FieldInfo field = typeof(TClass).GetField(fieldName, flags); + var field = typeof(TClass).GetField(fieldName, flags); if (field != null) { - string methodName = field.ReflectedType.FullName + ".get_" + field.Name; - DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(TClass)], true); - ILGenerator generator = getterMethod.GetILGenerator(); + var methodName = field.ReflectedType.FullName + ".get_" + field.Name; + var getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(TClass)], true); + var generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ret); @@ -645,12 +645,12 @@ private static Func CreateFieldGetter(string fie /// private static Func CreateFieldGetter(Type classType, string fieldName, BindingFlags flags) { - FieldInfo field = classType.GetField(fieldName, flags); + var field = classType.GetField(fieldName, flags); if (field != null) { - string methodName = classType.FullName + ".get_" + field.Name; - DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(object)], true); - ILGenerator generator = getterMethod.GetILGenerator(); + var methodName = classType.FullName + ".get_" + field.Name; + var getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(object)], true); + var generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); generator.Emit(OpCodes.Ldfld, field); @@ -668,12 +668,12 @@ private static Func CreateFieldGetter(Type classType, st /// private static Action CreateFieldSetter(Type classType, string fieldName, BindingFlags flags) { - FieldInfo field = classType.GetField(fieldName, flags); + var field = classType.GetField(fieldName, flags); if (field != null) { - string methodName = classType.FullName + ".set_" + field.Name; - DynamicMethod setterMethod = new DynamicMethod(methodName, null, [typeof(object), typeof(TField)], true); - ILGenerator generator = setterMethod.GetILGenerator(); + var methodName = classType.FullName + ".set_" + field.Name; + var setterMethod = new DynamicMethod(methodName, null, [typeof(object), typeof(TField)], true); + var generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); generator.Emit(OpCodes.Ldarg_1); @@ -691,9 +691,9 @@ private static Action CreateFieldSetter(Type classType, /// private static Func CreateTypeChecker(Type classType) { - string methodName = classType.FullName + ".typeCheck"; - DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(bool), [typeof(object)], true); - ILGenerator generator = setterMethod.GetILGenerator(); + var methodName = classType.FullName + ".typeCheck"; + var setterMethod = new DynamicMethod(methodName, typeof(bool), [typeof(object)], true); + var generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Isinst, classType); generator.Emit(OpCodes.Ldnull); @@ -708,13 +708,13 @@ private static Func CreateTypeChecker(Type classType) /// private static Func CreateTypeInstance(ConstructorInfo constructorInfo) { - Type classType = typeof(T); - string methodName = classType.FullName + ".ctor"; - DynamicMethod setterMethod = new DynamicMethod(methodName, classType, [typeof(object[])], true); - ILGenerator generator = setterMethod.GetILGenerator(); + var classType = typeof(T); + var methodName = classType.FullName + ".ctor"; + var setterMethod = new DynamicMethod(methodName, classType, [typeof(object[])], true); + var generator = setterMethod.GetILGenerator(); - ParameterInfo[] ctorParams = constructorInfo.GetParameters(); - for (int i = 0; i < ctorParams.Length; i++) + var ctorParams = constructorInfo.GetParameters(); + for (var i = 0; i < ctorParams.Length; i++) { generator.Emit(OpCodes.Ldarg_0); switch (i) @@ -732,7 +732,7 @@ private static Func CreateTypeInstance(ConstructorInfo construct } generator.Emit(OpCodes.Ldelem_Ref); - Type paramType = ctorParams[i].ParameterType; + var paramType = ctorParams[i].ParameterType; generator.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } @@ -1073,7 +1073,7 @@ public override void TrimToSize() public ArrayList Swap() { - ArrayList old = this.list; + var old = this.list; this.list = new ArrayList(old.Capacity); return old; } @@ -1115,7 +1115,7 @@ public HttpWebRequestArrayList(ArrayList list) public override int Add(object value) { // Add before firing events so if some user code cancels/aborts the request it will be found in the outstanding list. - int index = base.Add(value); + var index = base.Add(value); if (value is HttpWebRequest request) { @@ -1127,7 +1127,7 @@ public override int Add(object value) public override void RemoveAt(int index) { - object request = this[index]; + var request = this[index]; base.RemoveAt(index); @@ -1139,8 +1139,8 @@ public override void RemoveAt(int index) public override void Clear() { - ArrayList oldList = this.Swap(); - for (int i = 0; i < oldList.Count; i++) + var oldList = this.Swap(); + for (var i = 0; i < oldList.Count; i++) { if (oldList[i] is HttpWebRequest request) { @@ -1173,7 +1173,7 @@ public AsyncCallbackWrapper(HttpWebRequest request, Activity activity, AsyncCall public void AsyncCallback(IAsyncResult asyncResult) { - object result = resultAccessor(asyncResult); + var result = resultAccessor(asyncResult); if (result is Exception or HttpWebResponse) { ProcessResult( diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs index 76426ab255..4a5a4e84f4 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs @@ -12,13 +12,13 @@ internal static class TelemetryHelper public static object GetBoxedStatusCode(HttpStatusCode statusCode) { - int intStatusCode = (int)statusCode; + var intStatusCode = (int)statusCode; return intStatusCode is >= 100 and < 600 ? BoxedStatusCodes[intStatusCode - 100].Item1 : statusCode; } public static string GetStatusCodeString(HttpStatusCode statusCode) { - int intStatusCode = (int)statusCode; + var intStatusCode = (int)statusCode; return intStatusCode is >= 100 and < 600 ? BoxedStatusCodes[intStatusCode - 100].Item2 : statusCode.ToString(); } diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs index 76bbdbc19f..fd01551bf3 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs @@ -215,11 +215,11 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( bool enableTracing, bool enableMetrics) { - bool enrichWithHttpWebRequestCalled = false; - bool enrichWithHttpWebResponseCalled = false; - bool enrichWithHttpRequestMessageCalled = false; - bool enrichWithHttpResponseMessageCalled = false; - bool enrichWithExceptionCalled = false; + var enrichWithHttpWebRequestCalled = false; + var enrichWithHttpWebResponseCalled = false; + var enrichWithHttpRequestMessageCalled = false; + var enrichWithHttpResponseMessageCalled = false; + var enrichWithExceptionCalled = false; var testUrl = HttpTestData.NormalizeValues(tc.Url, host, port); @@ -331,7 +331,7 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( var normalizedAttributes = activity.TagObjects.Where(kv => !kv.Key.StartsWith("otel.", StringComparison.Ordinal)).ToDictionary(x => x.Key, x => x.Value?.ToString()); - int numberOfTags = activity.Status == ActivityStatusCode.Error ? 5 : 4; + var numberOfTags = activity.Status == ActivityStatusCode.Error ? 5 : 4; var expectedAttributeCount = numberOfTags + (tc.ResponseExpected ? 2 : 0); @@ -489,11 +489,11 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( private static async Task CheckEnrichment(Sampler sampler, bool enrichExpected, string url) { - bool enrichWithHttpWebRequestCalled = false; - bool enrichWithHttpWebResponseCalled = false; + var enrichWithHttpWebRequestCalled = false; + var enrichWithHttpWebResponseCalled = false; - bool enrichWithHttpRequestMessageCalled = false; - bool enrichWithHttpResponseMessageCalled = false; + var enrichWithHttpRequestMessageCalled = false; + var enrichWithHttpResponseMessageCalled = false; using (Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index 8020526bde..9c035f97fa 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -63,8 +63,8 @@ public HttpWebRequestActivitySourceTests() void ProcessServerRequest(HttpListenerContext context) { - string redirects = context.Request.QueryString["redirects"]; - if (!string.IsNullOrWhiteSpace(redirects) && int.TryParse(redirects, out int parsedRedirects) && parsedRedirects > 0) + var redirects = context.Request.QueryString["redirects"]; + if (!string.IsNullOrWhiteSpace(redirects) && int.TryParse(redirects, out var parsedRedirects) && parsedRedirects > 0) { context.Response.Redirect(this.BuildRequestUrl(queryString: $"redirects={--parsedRedirects}")); context.Response.OutputStream.Close(); @@ -74,7 +74,7 @@ void ProcessServerRequest(HttpListenerContext context) string responseContent; if (context.Request.QueryString["skipRequestContent"] == null) { - using StreamReader readStream = new StreamReader(context.Request.InputStream); + using var readStream = new StreamReader(context.Request.InputStream); responseContent = readStream.ReadToEnd(); } @@ -83,12 +83,12 @@ void ProcessServerRequest(HttpListenerContext context) responseContent = $"{{\"Id\":\"{Guid.NewGuid()}\"}}"; } - string responseCode = context.Request.QueryString["responseCode"]; + var responseCode = context.Request.QueryString["responseCode"]; context.Response.StatusCode = !string.IsNullOrWhiteSpace(responseCode) ? int.Parse(responseCode) : 200; if (context.Response.StatusCode != 204) { - using StreamWriter writeStream = new StreamWriter(context.Response.OutputStream); + using var writeStream = new StreamWriter(context.Response.OutputStream); writeStream.Write(responseContent); } @@ -110,8 +110,8 @@ public void Dispose() [Fact] public void TestHttpDiagnosticListenerIsRegistered() { - bool listenerFound = false; - using ActivityListener activityListener = new ActivityListener + var listenerFound = false; + using var activityListener = new ActivityListener { ShouldListenTo = activitySource => { @@ -175,7 +175,7 @@ public async Task TestBasicReceiveAndResponseEvents(string method, string queryS Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be a response. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); @@ -215,7 +215,7 @@ public async Task TestBasicReceiveAndResponseEventsWithoutSampling(string method [InlineData("POST", 3)] public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int mode) { - string url = this.BuildRequestUrl(); + var url = this.BuildRequestUrl(); using var eventRecords = new ActivitySourceRecorder(); @@ -237,9 +237,9 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 2: { - object state = new object(); - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - IAsyncResult asyncResult = webRequest.BeginGetRequestStream( + var state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var asyncResult = webRequest.BeginGetRequestStream( ar => { Assert.Equal(state, ar.AsyncState); @@ -258,8 +258,8 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 3: { - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - object state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var state = new object(); webRequest.BeginGetRequestStream( ar => { @@ -283,7 +283,7 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int Assert.NotNull(stream); - using StreamWriter writer = new StreamWriter(stream); + using var writer = new StreamWriter(stream); writer.WriteLine("hello world"); } @@ -299,9 +299,9 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 2: { - object state = new object(); - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - IAsyncResult asyncResult = webRequest.BeginGetResponse( + var state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var asyncResult = webRequest.BeginGetResponse( ar => { Assert.Equal(state, ar.AsyncState); @@ -320,8 +320,8 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 3: { - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - object state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var state = new object(); webRequest.BeginGetResponse( ar => { @@ -345,7 +345,7 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int Assert.NotNull(webResponse); - using StreamReader reader = new StreamReader(webResponse.GetResponseStream()); + using var reader = new StreamReader(webResponse.GetResponseStream()); reader.ReadToEnd(); // Make sure response is not disposed. @@ -355,7 +355,7 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be a response. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); @@ -443,14 +443,14 @@ public async Task DoNotInjectTraceParentWhenPresent(string method) [InlineData("POST")] public async Task TestResponseWithoutContentEvents(string method) { - string url = this.BuildRequestUrl(queryString: "responseCode=204"); + var url = this.BuildRequestUrl(queryString: "responseCode=204"); using var eventRecords = new ActivitySourceRecorder(); // Send a random Http request to generate some events using (var client = new HttpClient()) { - using HttpResponseMessage response = method == "GET" + using var response = method == "GET" ? await client.GetAsync(new Uri(url)) : await client.PostAsync(new Uri(url), new StringContent("hello world")); } @@ -461,7 +461,7 @@ public async Task TestResponseWithoutContentEvents(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be a response. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); @@ -483,7 +483,7 @@ public async Task TestRedirectedRequest(string method) using (var client = new HttpClient()) { - using HttpResponseMessage response = method == "GET" + using var response = method == "GET" ? await client.GetAsync(new Uri(this.BuildRequestUrl(queryString: "redirects=10"))) : await client.PostAsync(new Uri(this.BuildRequestUrl(queryString: "redirects=10")), new StringContent("hello world")); } @@ -502,8 +502,8 @@ public async Task TestRedirectedRequest(string method) [InlineData("POST")] public async Task TestRequestWithException(string method) { - string host = Guid.NewGuid().ToString() + ".com"; - string url = method == "GET" + var host = Guid.NewGuid().ToString() + ".com"; + var url = method == "GET" ? $"http://{host}" : $"http://{host}"; @@ -527,10 +527,10 @@ public async Task TestRequestWithException(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be an exception. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(host, null, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, activity.Status); @@ -545,9 +545,9 @@ public async Task TestRequestWithException(string method) [InlineData("POST")] public async Task TestCanceledRequest(string method) { - string url = this.BuildRequestUrl(); + var url = this.BuildRequestUrl(); - CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); using var eventRecords = new ActivitySourceRecorder(_ => { cts.Cancel(); }); using (var client = new HttpClient()) @@ -566,10 +566,10 @@ public async Task TestCanceledRequest(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); @@ -584,7 +584,7 @@ public async Task TestCanceledRequest(string method) [InlineData("POST")] public async Task TestSecureTransportFailureRequest(string method) { - string url = "https://expired.badssl.com/"; + var url = "https://expired.badssl.com/"; using var eventRecords = new ActivitySourceRecorder(); @@ -605,10 +605,10 @@ public async Task TestSecureTransportFailureRequest(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags("expired.badssl.com", null, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); @@ -627,7 +627,7 @@ public async Task TestSecureTransportRetryFailureRequest(string method) // It should retry. What we want to test for is 1 start, 1 exception event even // though multiple are actually sent. - string url = this.BuildRequestUrl(useHttps: true); + var url = this.BuildRequestUrl(useHttps: true); using var eventRecords = new ActivitySourceRecorder(); @@ -647,10 +647,10 @@ public async Task TestSecureTransportRetryFailureRequest(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); @@ -691,9 +691,9 @@ public async Task TestMultipleConcurrentRequests() using var eventRecords = new ActivitySourceRecorder(); Dictionary> requestData = []; - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { - Uri uriWithRedirect = new Uri(this.BuildRequestUrl(queryString: $"q={i}&redirects=3")); + var uriWithRedirect = new Uri(this.BuildRequestUrl(queryString: $"q={i}&redirects=3")); requestData[uriWithRedirect] = null; } @@ -702,7 +702,7 @@ public async Task TestMultipleConcurrentRequests() using var httpClient = new HttpClient(); Dictionary> tasks = []; - CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); foreach (var url in requestData.Keys) { tasks.Add(url, httpClient.GetAsync(url, cts.Token)); @@ -729,7 +729,7 @@ await Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(async _ => // Check to make sure: We have a WebRequest and a WebResponse for each successful request foreach (var pair in eventRecords.Records) { - Activity activity = pair.Value; + var activity = pair.Value; Assert.True( pair.Key is "Start" or "Stop", @@ -739,7 +739,7 @@ await Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(async _ => private static Activity AssertFirstEventWasStart(ActivitySourceRecorder eventRecords) { - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair startEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var startEvent)); Assert.Equal("Start", startEvent.Key); return startEvent.Value; } @@ -778,7 +778,7 @@ private static void VerifyActivityStopTags(int statusCode, Activity activity) private static void ValidateBaggage(HttpWebRequest request) { - string[] baggage = request.Headers["baggage"].Split(','); + var baggage = request.Headers["baggage"].Split(','); Assert.Equal(3, baggage.Length); Assert.Contains("key=value", baggage); diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs index a314e456db..cdc717d00b 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs @@ -87,8 +87,8 @@ public async Task BacksOffIfAlreadyInstrumented() [Fact] public async Task RequestNotCollectedWhenInstrumentationFilterApplied() { - bool httpWebRequestFilterApplied = false; - bool httpRequestMessageFilterApplied = false; + var httpWebRequestFilterApplied = false; + var httpRequestMessageFilterApplied = false; var exportedItems = new List(); @@ -186,8 +186,8 @@ public async Task InjectsHeadersAsync() Assert.NotEqual(default, activity.Context.SpanId); #if NETFRAMEWORK - string traceparent = request.Headers.Get("traceparent"); - string tracestate = request.Headers.Get("tracestate"); + var traceparent = request.Headers.Get("traceparent"); + var tracestate = request.Headers.Get("tracestate"); Assert.Equal($"00-{activity.Context.TraceId}-{activity.Context.SpanId}-01", traceparent); Assert.Equal("k1=v1,k2=v2", tracestate); @@ -285,7 +285,7 @@ public void AddHttpClientInstrumentationUsesOptionsApi(string? name) { name ??= Options.DefaultName; - int configurationDelegateInvocations = 0; + var configurationDelegateInvocations = 0; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .ConfigureServices(services => @@ -305,7 +305,7 @@ public void AddHttpClientInstrumentationUsesOptionsApi(string? name) public async Task ReportsExceptionEventForNetworkFailures() { var exportedItems = new List(); - bool exceptionThrown = false; + var exceptionThrown = false; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation(o => o.RecordException = true) @@ -334,7 +334,7 @@ public async Task ReportsExceptionEventForNetworkFailures() public async Task ReportsExceptionEventOnErrorResponse() { var exportedItems = new List(); - bool exceptionThrown = false; + var exceptionThrown = false; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation(o => o.RecordException = true) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs index 24ebf2e3fe..7a6024d325 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs @@ -34,11 +34,11 @@ public void HttpOutCallsAreCollectedSuccessfully(HttpOutTestCase tc) out var host, out var port); - bool enrichWithHttpWebRequestCalled = false; - bool enrichWithHttpWebResponseCalled = false; - bool enrichWithHttpRequestMessageCalled = false; - bool enrichWithHttpResponseMessageCalled = false; - bool enrichWithExceptionCalled = false; + var enrichWithHttpWebRequestCalled = false; + var enrichWithHttpWebResponseCalled = false; + var enrichWithHttpRequestMessageCalled = false; + var enrichWithHttpResponseMessageCalled = false; + var enrichWithExceptionCalled = false; var exportedItems = new List(); using var tracerProvider = Sdk.CreateTracerProviderBuilder() @@ -100,11 +100,11 @@ public void HttpOutCallsAreCollectedSuccessfully(HttpOutTestCase tc) return HttpTestData.NormalizeValues(x.Value, host, port); }); - foreach (KeyValuePair tag in activity.TagObjects) + foreach (var tag in activity.TagObjects) { var tagValue = tag.Value?.ToString(); - if (!tc.SpanAttributes.TryGetValue(tag.Key, out string? value)) + if (!tc.SpanAttributes.TryGetValue(tag.Key, out var value)) { if (tag.Key == SpanAttributeConstants.StatusCodeKey) { diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs index 43a56ae26f..32feda077e 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs @@ -22,7 +22,7 @@ protected override async Task SendAsync( CancellationToken cancellationToken) { HttpResponseMessage? response = null; - for (int i = 0; i < this.maxRetries; i++) + for (var i = 0; i < this.maxRetries; i++) { response?.Dispose(); From 42a5e586f078298de82f17a719e0ef3f2fe032fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 09:28:30 +0100 Subject: [PATCH 11/12] Fix CA1515 --- .../Instrumentation/HttpClientInstrumentationBenchmarks.cs | 4 ++++ .../HttpOutTestCase.cs | 2 ++ .../HttpTestData.cs | 2 +- .../HttpWebRequestTests.cs | 7 +------ .../RepeatHandler.cs | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs b/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs index 5664716337..1905acb938 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs @@ -26,7 +26,9 @@ namespace OpenTelemetry.Instrumentation.Http.Benchmarks.Instrumentation; +#pragma warning disable CA1515 public class HttpClientInstrumentationBenchmarks +#pragma warning restore CA1515 { private static readonly Uri Url = new("http://localhost:5000"); @@ -36,7 +38,9 @@ public class HttpClientInstrumentationBenchmarks private MeterProvider? meterProvider; [Flags] +#pragma warning disable CA1515 public enum EnableInstrumentationOption +#pragma warning restore CA1515 { /// /// Instrumentation is not enabled for any signal. diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs index dd632eb9e5..43cdefd887 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs @@ -3,7 +3,9 @@ namespace OpenTelemetry.Instrumentation.Http.Tests; +#pragma warning disable CA1515 public class HttpOutTestCase +#pragma warning restore CA1515 { public HttpOutTestCase(string name, string method, string url, Dictionary? headers, int responseCode, string spanName, bool responseExpected, bool? recordException, string spanStatus, Dictionary spanAttributes) { diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs index 7f91eaaf0c..e139b23237 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs @@ -6,7 +6,7 @@ namespace OpenTelemetry.Instrumentation.Http.Tests; -public static class HttpTestData +internal static class HttpTestData { private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs index 7a6024d325..9e01f266c4 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs @@ -92,12 +92,7 @@ public void HttpOutCallsAreCollectedSuccessfully(HttpOutTestCase tc) x => x.Key, x => { - if (x.Key == "network.protocol.version") - { - return "1.1"; - } - - return HttpTestData.NormalizeValues(x.Value, host, port); + return x.Key == "network.protocol.version" ? "1.1" : HttpTestData.NormalizeValues(x.Value, host, port); }); foreach (var tag in activity.TagObjects) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs index 32feda077e..40143c2e6d 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs @@ -7,7 +7,7 @@ namespace OpenTelemetry.Tests; -public class RepeatHandler : DelegatingHandler +internal class RepeatHandler : DelegatingHandler { private readonly int maxRetries; From a228bcb895ffa5be6cb8da688ea4a73e3c072666 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Tue, 5 Nov 2024 22:07:21 +0100 Subject: [PATCH 12/12] Update src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs Co-authored-by: Mikel Blanchard --- .../HttpClientInstrumentation.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs index ff4b6bead0..4400a15f5b 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs @@ -43,7 +43,9 @@ public HttpClientInstrumentation(HttpClientTraceInstrumentationOptions options) // the framework will fall back to creating activity anyways due to active diagnostic source listener // To prevent this, isEnabled is implemented which will return false always // so that the sampler's decision is respected. - this.diagnosticSourceSubscriber = HttpHandlerDiagnosticListener.IsNet7OrGreater ? new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabledNet7OrGreater, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent) : new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabled, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); + this.diagnosticSourceSubscriber = HttpHandlerDiagnosticListener.IsNet7OrGreater + ? new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabledNet7OrGreater, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent) + : new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabled, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); this.diagnosticSourceSubscriber.Subscribe(); }