Skip to content

Commit

Permalink
[repo/WCF] Prepare to .NET9 (#2273)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kielek authored Oct 30, 2024
1 parent 2ca95ad commit e61cea4
Show file tree
Hide file tree
Showing 25 changed files with 167 additions and 201 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ internal static class ActivityHelper
/// <returns><see langword="true"/> if start has been called.</returns>
public static bool HasStarted(HttpContext context, out Activity? aspNetActivity)
{
object itemValue = context.Items[ContextKey];
var itemValue = context.Items[ContextKey];
if (itemValue is ContextHolder contextHolder)
{
aspNetActivity = contextHolder.Activity;
Expand All @@ -61,7 +61,7 @@ public static bool HasStarted(HttpContext context, out Activity? aspNetActivity)
/// <returns>New root activity.</returns>
public static Activity? StartAspNetActivity(TextMapPropagator textMapPropagator, HttpContext context, Action<Activity, HttpContext>? onRequestStartedCallback)
{
PropagationContext propagationContext = textMapPropagator.Extract(default, context.Request, HttpRequestHeaderValuesGetter);
var propagationContext = textMapPropagator.Extract(default, context.Request, HttpRequestHeaderValuesGetter);

KeyValuePair<string, object?>[]? tags;
if (context.Request?.Unvalidated?.Path is string path)
Expand All @@ -75,7 +75,7 @@ public static bool HasStarted(HttpContext context, out Activity? aspNetActivity)
tags = null;
}

Activity? activity = AspNetSource.StartActivity(TelemetryHttpModule.AspNetActivityName, ActivityKind.Server, propagationContext.ActivityContext, tags);
var activity = AspNetSource.StartActivity(TelemetryHttpModule.AspNetActivityName, ActivityKind.Server, propagationContext.ActivityContext, tags);

if (tags is not null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public void Init(HttpApplication context)
// OnExecuteRequestStep is available starting with 4.7.1
try
{
OnExecuteRequestStepMethodInfo.Invoke(context, new object[] { (Action<HttpContextBase, Action>)this.OnExecuteRequestStep });
OnExecuteRequestStepMethodInfo.Invoke(context, [(Action<HttpContextBase, Action>)this.OnExecuteRequestStep]);
}
catch (Exception e)
{
Expand All @@ -80,11 +80,11 @@ private void OnExecuteRequestStep(HttpContextBase context, Action step)
private void Application_EndRequest(object sender, EventArgs e)
{
AspNetTelemetryEventSource.Log.TraceCallback("Application_EndRequest");
bool trackActivity = true;
var trackActivity = true;

var context = ((HttpApplication)sender).Context;

if (!ActivityHelper.HasStarted(context, out Activity? aspNetActivity))
if (!ActivityHelper.HasStarted(context, out var aspNetActivity))
{
// Rewrite: In case of rewrite, a new request context is created, called the child request, and it goes through the entire IIS/ASP.NET integrated pipeline.
// The child request can be mapped to any of the handlers configured in IIS, and it's execution is no different than it would be if it was received via the HTTP stack.
Expand Down Expand Up @@ -119,7 +119,7 @@ private void Application_Error(object sender, EventArgs e)
var exception = context.Error;
if (exception != null)
{
if (!ActivityHelper.HasStarted(context, out Activity? aspNetActivity))
if (!ActivityHelper.HasStarted(context, out var aspNetActivity))
{
aspNetActivity = ActivityHelper.StartAspNetActivity(Options.TextMapPropagator, context, Options.OnRequestStartedCallback);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ internal static class AspNetParentSpanCorrector
private const string TelemetryHttpModuleOptionsTypeName = "OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModuleOptions, OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule";

private static readonly ReflectedInfo? ReflectedValues = Initialize();
private static readonly PropertyFetcher<object> RequestFetcher = new PropertyFetcher<object>("Request");
private static readonly PropertyFetcher<NameValueCollection> HeadersFetcher = new PropertyFetcher<NameValueCollection>("Headers");
private static readonly PropertyFetcher<object> RequestFetcher = new("Request");
private static readonly PropertyFetcher<NameValueCollection> HeadersFetcher = new("Headers");
private static bool isRegistered;

public static void Register()
Expand Down Expand Up @@ -63,11 +63,7 @@ private static void OnRequestStarted(Activity activity, object context)
{
try
{
var isReadOnlyProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
if (isReadOnlyProp == null)
{
throw new NotSupportedException("NameValueCollection.IsReadOnly property not found");
}
var isReadOnlyProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy) ?? throw new NotSupportedException("NameValueCollection.IsReadOnly property not found");

var setHeadersReadOnly = (Action<NameValueCollection, bool>)isReadOnlyProp.SetMethod.CreateDelegate(typeof(Action<NameValueCollection, bool>));

Expand Down Expand Up @@ -102,12 +98,7 @@ private static Func<object> GenerateSubscribeLambda()

var telemetryHttpModuleType = Type.GetType(TelemetryHttpModuleTypeName, true);
var telemetryHttpModuleOptionsType = Type.GetType(TelemetryHttpModuleOptionsTypeName, true);
var onRequestStartedProp = telemetryHttpModuleOptionsType.GetProperty("OnRequestStartedCallback");
if (onRequestStartedProp == null)
{
throw new NotSupportedException("TelemetryHttpModuleOptions.OnRequestStartedCallback property not found");
}

var onRequestStartedProp = telemetryHttpModuleOptionsType.GetProperty("OnRequestStartedCallback") ?? throw new NotSupportedException("TelemetryHttpModuleOptions.OnRequestStartedCallback property not found");
Func<Delegate, Delegate> addOurCallbackToDelegate = (existingCallback) =>
{
var myCallback = OnRequestStarted;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ public static RequestTelemetryState BeforeSendRequest(Message request, Uri? remo
return new RequestTelemetryState { SuppressionScope = SuppressDownstreamInstrumentation() };
}

Activity? activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity(
var activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity(
WcfInstrumentationActivitySource.OutgoingRequestActivityName,
ActivityKind.Client);
IDisposable? suppressionScope = SuppressDownstreamInstrumentation();
var suppressionScope = SuppressDownstreamInstrumentation();

if (activity != null)
{
Expand Down Expand Up @@ -125,7 +125,7 @@ public static void AfterRequestCompleted(Message? reply, RequestTelemetryState?
private static ActionMetadata GetActionMetadata(Message request, string action)
{
ActionMetadata? actionMetadata = null;
if (request.Properties.TryGetValue(TelemetryContextMessageProperty.Name, out object telemetryContextProperty))
if (request.Properties.TryGetValue(TelemetryContextMessageProperty.Name, out var telemetryContextProperty))
{
var actionMappings = (telemetryContextProperty as TelemetryContextMessageProperty)?.ActionMappings;
if (actionMappings != null && actionMappings.TryGetValue(action, out var metadata))
Expand All @@ -134,7 +134,7 @@ private static ActionMetadata GetActionMetadata(Message request, string action)
}
}

return actionMetadata != null ? actionMetadata : new ActionMetadata(
return actionMetadata ?? new ActionMetadata(
contractName: null,
operationName: action);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,18 @@ public static WebHeaderCollection GetHeaders(object httpRequestMessageProperty)
var constructor = type.GetConstructor(Type.EmptyTypes)
?? throw new NotSupportedException("HttpRequestMessageProperty public parameterless constructor was not found");

var headersProp = type.GetProperty("Headers", BindingFlags.Public | BindingFlags.Instance, null, typeof(WebHeaderCollection), Array.Empty<Type>(), null)
var headersProp = type.GetProperty("Headers", BindingFlags.Public | BindingFlags.Instance, null, typeof(WebHeaderCollection), [], null)
?? throw new NotSupportedException("HttpRequestMessageProperty.Headers property not found");

var nameProp = type.GetProperty("Name", BindingFlags.Public | BindingFlags.Static, null, typeof(string), Array.Empty<Type>(), null)
var nameProp = type.GetProperty("Name", BindingFlags.Public | BindingFlags.Static, null, typeof(string), [], null)
?? throw new NotSupportedException("HttpRequestMessageProperty.Name property not found");

if (nameProp.GetValue(null) is not string name)
{
throw new NotSupportedException("HttpRequestMessageProperty.Name property was null");
}

return new ReflectedInfo(
type: type,
name: name,
headersFetcher: new PropertyFetcher<WebHeaderCollection>("Headers"));
return nameProp.GetValue(null) is not string name
? throw new NotSupportedException("HttpRequestMessageProperty.Name property was null")
: new ReflectedInfo(
type: type,
name: name,
headersFetcher: new PropertyFetcher<WebHeaderCollection>("Headers"));
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ namespace OpenTelemetry.Instrumentation.Wcf.Implementation;

internal static class RequestTelemetryStateTracker
{
private static readonly Dictionary<string, Entry> OutstandingRequestStates = new Dictionary<string, Entry>();
private static readonly SortedSet<EntryTimeoutProperties> TimeoutQueue = new SortedSet<EntryTimeoutProperties>();
private static readonly Dictionary<string, Entry> OutstandingRequestStates = [];
private static readonly SortedSet<EntryTimeoutProperties> TimeoutQueue = [];
private static readonly object Sync = new();
private static readonly Timer Timer = new(OnTimer);
private static long currentTimerDueAt = Timeout.Infinite;
Expand Down Expand Up @@ -61,10 +61,7 @@ private static void OnTimer(object? state)
{
if (entryTimeoutProps.ExpiresAt <= now)
{
if (timedOutEntries == null)
{
timedOutEntries = new List<Tuple<EntryTimeoutProperties, Entry>>();
}
timedOutEntries ??= [];

timedOutEntries.Add(new(entryTimeoutProps, OutstandingRequestStates[entryTimeoutProps.MessageId]));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ internal TelemetryDispatchMessageInspector(IDictionary<string, ActionMetadata> a
var textMapPropagator = Propagators.DefaultTextMapPropagator;
var ctx = textMapPropagator.Extract(default, request, WcfInstrumentationActivitySource.MessageHeaderValuesGetter);

Activity? activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity(
var activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity(
WcfInstrumentationActivitySource.IncomingRequestActivityName,
ActivityKind.Server,
ctx.ActivityContext);
Expand All @@ -71,7 +71,7 @@ internal TelemetryDispatchMessageInspector(IDictionary<string, ActionMetadata> a
{
activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue);

if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata))
if (!this.actionMappings.TryGetValue(action, out var actionMetadata))
{
actionMetadata = new ActionMetadata(
contractName: null,
Expand Down Expand Up @@ -105,7 +105,7 @@ internal TelemetryDispatchMessageInspector(IDictionary<string, ActionMetadata> a
}
}

if (!(textMapPropagator is TraceContextPropagator))
if (textMapPropagator is not TraceContextPropagator)
{
Baggage.Current = ctx.Baggage;
}
Expand Down Expand Up @@ -139,7 +139,7 @@ public void BeforeSendReply(ref Message reply, object? correlationState)

activity.Stop();

if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator))
if (Propagators.DefaultTextMapPropagator is not TraceContextPropagator)
{
Baggage.Current = default;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace OpenTelemetry.Instrumentation.Wcf.Implementation;
[EventSource(Name = "OpenTelemetry-Instrumentation-Wcf")]
internal sealed class WcfInstrumentationEventSource : EventSource
{
public static readonly WcfInstrumentationEventSource Log = new WcfInstrumentationEventSource();
public static readonly WcfInstrumentationEventSource Log = new();

[NonEvent]
public void RequestFilterException(Exception ex)
Expand Down
20 changes: 8 additions & 12 deletions src/Shared/PropertyFetcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,9 @@ public PropertyFetcher(string propertyName)
/// <returns>Property fetched.</returns>
public T Fetch(object obj)
{
if (!this.TryFetch(obj, out T value))
{
throw new ArgumentException("Supplied object was null or did not match the expected type.", nameof(obj));
}

return value;
return !this.TryFetch(obj, out var value)
? throw new ArgumentException("Supplied object was null or did not match the expected type.", nameof(obj))
: value;
}

/// <summary>
Expand All @@ -59,12 +56,7 @@ public bool TryFetch(object obj, out T value)
if (this.innerFetcher == null)
{
var type = obj.GetType().GetTypeInfo();
var property = type.DeclaredProperties.FirstOrDefault(p => string.Equals(p.Name, this.propertyName, StringComparison.OrdinalIgnoreCase));
if (property == null)
{
property = type.GetProperty(this.propertyName);
}

var property = type.DeclaredProperties.FirstOrDefault(p => string.Equals(p.Name, this.propertyName, StringComparison.OrdinalIgnoreCase)) ?? type.GetProperty(this.propertyName);
this.innerFetcher = PropertyFetch.FetcherForProperty(property);
}

Expand Down Expand Up @@ -107,7 +99,11 @@ private sealed class TypedPropertyFetch<TDeclaredObject, TDeclaredProperty> : Pr

public TypedPropertyFetch(PropertyInfo property)
{
#if NET
this.propertyFetch = property.GetMethod.CreateDelegate<Func<TDeclaredObject, TDeclaredProperty>>();
#else
this.propertyFetch = (Func<TDeclaredObject, TDeclaredProperty>)property.GetMethod.CreateDelegate(typeof(Func<TDeclaredObject, TDeclaredProperty>));
#endif
}

public override bool TryFetch(object obj, out T value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void IncomingRequestHeadersAreOverwrittenWithAspNetParent()
var context = new FakeHttpContext();

var method = typeof(AspNetParentSpanCorrector).GetMethod("OnRequestStarted", BindingFlags.Static | BindingFlags.NonPublic);
method.Invoke(null, new object[] { aspNetActivity, context });
method.Invoke(null, [aspNetActivity, context]);

var headerVal = context.Request.Headers["traceparent"];
Assert.Contains(aspNetActivity.TraceId.ToString(), headerVal);
Expand All @@ -43,12 +43,12 @@ public void IncomingRequestHeadersAreOverwrittenWithAspNetParent()

private class FakeHttpContext
{
public FakeRequest Request { get; } = new FakeRequest();
public FakeRequest Request { get; } = new();
}

private class FakeRequest
{
public NameValueCollection Headers { get; } = new NameValueCollection();
public NameValueCollection Headers { get; } = [];
}
}
#endif
Loading

0 comments on commit e61cea4

Please sign in to comment.