Skip to content

Commit

Permalink
[repo/OWIN] Prepare to .NET9 (#2291)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kielek authored Nov 4, 2024
1 parent 5acf5e6 commit cd8f08a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ private static void BeginRequest(IOwinContext owinContext)
var textMapPropagator = Propagators.DefaultTextMapPropagator;
var ctx = textMapPropagator.Extract(default, owinContext.Request, OwinRequestHeaderValuesGetter);

Activity? activity = OwinInstrumentationActivitySource.ActivitySource.StartActivity(
var activity = OwinInstrumentationActivitySource.ActivitySource.StartActivity(
OwinInstrumentationActivitySource.IncomingRequestActivityName,
ActivityKind.Server,
ctx.ActivityContext);
Expand All @@ -103,7 +103,7 @@ private static void BeginRequest(IOwinContext owinContext)
activity.SetTag(SemanticConventions.AttributeUrlQuery, request.Query);
activity.SetTag(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme);

if (request.Headers.TryGetValue("User-Agent", out string[] userAgent) && userAgent.Length > 0)
if (request.Headers.TryGetValue("User-Agent", out var userAgent) && userAgent.Length > 0)
{
activity.SetTag(SemanticConventions.AttributeUserAgentOriginal, userAgent[0]);
}
Expand All @@ -124,7 +124,7 @@ private static void BeginRequest(IOwinContext owinContext)
}
}

if (!(textMapPropagator is TraceContextPropagator))
if (textMapPropagator is not TraceContextPropagator)
{
Baggage.Current = ctx.Baggage;
}
Expand All @@ -136,7 +136,7 @@ private static void BeginRequest(IOwinContext owinContext)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void RequestEnd(IOwinContext owinContext, Exception? exception, long startTimestamp)
{
if (owinContext.Environment.TryGetValue(ContextKey, out object context)
if (owinContext.Environment.TryGetValue(ContextKey, out var context)
&& context is Activity activity)
{
if (Activity.Current != activity)
Expand Down Expand Up @@ -191,7 +191,7 @@ private static void RequestEnd(IOwinContext owinContext, Exception? exception, l
new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode));
}

if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator))
if (Propagators.DefaultTextMapPropagator is not TraceContextPropagator)
{
Baggage.Current = default;
}
Expand All @@ -209,21 +209,4 @@ private static void RequestEnd(IOwinContext owinContext, Exception? exception, l
new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode));
}
}

/// <summary>
/// Gets the OpenTelemetry standard uri tag value for a span based on its request <see cref="Uri"/>.
/// </summary>
/// <param name="uri"><see cref="Uri"/>.</param>
/// <returns>Span uri value.</returns>
private static string GetUriTagValueFromRequestUri(Uri uri, bool disableQueryRedaction)
{
if (string.IsNullOrEmpty(uri.UserInfo) && disableQueryRedaction)
{
return uri.OriginalString;
}

var query = disableQueryRedaction ? uri.Query : RedactionHelper.GetRedactedQueryString(uri.Query);

return string.Concat(uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath, query, uri.Fragment);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class DiagnosticsMiddlewareTests : IDisposable

public DiagnosticsMiddlewareTests()
{
Random random = new Random();
var random = new Random();
var retryCount = 5;
do
{
Expand Down Expand Up @@ -60,7 +60,7 @@ public DiagnosticsMiddlewareTests()
return next();
});

HttpConfiguration config = new HttpConfiguration();
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
Expand Down Expand Up @@ -120,8 +120,8 @@ public async Task OutgoingRequestInstrumentationTest(
bool generateRemoteException = false,
bool recordException = false)
{
List<Activity> stoppedActivities = new List<Activity>();
List<Metric> exportedMetrics = new List<Metric>();
List<Activity> stoppedActivities = [];
List<Metric> exportedMetrics = [];

var builder = Sdk.CreateTracerProviderBuilder()
.AddInMemoryExporter(stoppedActivities);
Expand All @@ -135,9 +135,9 @@ public async Task OutgoingRequestInstrumentationTest(
{
if (enrich)
{
if (!enrichmentException)
{
options.Enrich = (activity, eventName, context, exception) =>
options.Enrich = enrichmentException
? (_, _, _, _) => throw new Exception("Error while enriching activity")
: (activity, eventName, _, _) =>
{
switch (eventName)
{
Expand All @@ -147,13 +147,10 @@ public async Task OutgoingRequestInstrumentationTest(
case OwinEnrichEventType.EndRequest:
activity.SetTag("client.endrequest", nameof(OwinEnrichEventType.EndRequest));
break;
default:
break;
}
};
}
else
{
options.Enrich = (activity, eventName, context, exception) => throw new Exception("Error while enriching activity");
}
}

options.Filter = _ => !filter;
Expand All @@ -166,12 +163,12 @@ public async Task OutgoingRequestInstrumentationTest(
meterBuilder.AddOwinInstrumentation();
}

using TracerProvider tracerProvider = builder.Build();
using MeterProvider meterProvider = meterBuilder.Build();
using var tracerProvider = builder.Build();
using var meterProvider = meterBuilder.Build();

using HttpClient client = new HttpClient();
using var client = new HttpClient();

Uri requestUri = generateRemoteException
var requestUri = generateRemoteException
? new Uri($"{this.serviceBaseUri}exception")
: new Uri($"{this.serviceBaseUri}api/test");

Expand All @@ -192,7 +189,7 @@ Owin has finished to inspect the activity status. */
Assert.NotEmpty(stoppedActivities);
Assert.Single(stoppedActivities);

Activity activity = stoppedActivities[0];
var activity = stoppedActivities[0];
Assert.Equal(OwinInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName);

Assert.Equal(requestUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == SemanticConventions.AttributeServerAddress).Value);
Expand Down Expand Up @@ -257,6 +254,8 @@ Owin has finished to inspect the activity status. */
case SemanticConventions.AttributeHttpResponseStatusCode:
Assert.Equal(generateRemoteException ? 500 : 200, tag.Value);
break;
default:
break;
}
}
}
Expand Down Expand Up @@ -295,7 +294,7 @@ public async Task QueryParametersAreRedacted(
Environment.SetEnvironmentVariable("OTEL_DOTNET_EXPERIMENTAL_OWIN_DISABLE_URL_QUERY_REDACTION", "true");
}

List<Activity> stoppedActivities = new List<Activity>();
List<Activity> stoppedActivities = [];

var builder = Sdk.CreateTracerProviderBuilder()
.ConfigureServices(services =>
Expand All @@ -316,10 +315,10 @@ public async Task QueryParametersAreRedacted(
.AddOwinInstrumentation()
.Build();

using HttpClient client = new HttpClient();
using var client = new HttpClient();

Uri requestUri = new Uri($"{this.serviceBaseUri}{actualPath}");
Uri expectedRequestUri = new Uri($"{this.serviceBaseUri}{expectedPath}");
var requestUri = new Uri($"{this.serviceBaseUri}{actualPath}");
var expectedRequestUri = new Uri($"{this.serviceBaseUri}{expectedPath}");

this.requestCompleteHandle.Reset();

Expand All @@ -340,7 +339,7 @@ Owin has finished to inspect the activity status. */
Assert.NotEmpty(stoppedActivities);
Assert.Single(stoppedActivities);

Activity activity = stoppedActivities[0];
var activity = stoppedActivities[0];
Assert.Equal(OwinInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName);

Assert.Equal(requestUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == SemanticConventions.AttributeServerAddress).Value);
Expand All @@ -356,7 +355,7 @@ Owin has finished to inspect the activity status. */

private List<MetricPoint> GetMetricPoints(Metric metric)
{
List<MetricPoint> metricPoints = new();
List<MetricPoint> metricPoints = [];

foreach (var metricPoint in metric.GetMetricPoints())
{
Expand Down

0 comments on commit cd8f08a

Please sign in to comment.