Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[repo/Grpc*] Prepare to .NET9 #2276

Merged
merged 22 commits into from
Oct 31, 2024
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,11 @@ private class ServerRpcScope<TRequest, TResponse> : RpcScope<TRequest, TResponse
var entry = metadata[i];
if (string.Equals(entry.Key, key, StringComparison.OrdinalIgnoreCase))
{
return new string[1] { entry.Value };
return [entry.Value];
}
}

return Enumerable.Empty<string>();
return [];
};

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public override void OnEventWritten(string name, object? payload)
this.OnStopActivity(activity, payload);
}

break;
default:
break;
}
}
Expand All @@ -70,7 +72,7 @@ public void OnStartActivity(Activity activity, object? payload)
}

// Ensure context propagation irrespective of sampling decision
if (!TryFetchRequest(payload, out HttpRequestMessage? request))
if (!TryFetchRequest(payload, out var request))
{
GrpcInstrumentationEventSource.Log.NullPayload(nameof(GrpcClientDiagnosticListener), nameof(this.OnStartActivity));
return;
Expand Down Expand Up @@ -134,7 +136,7 @@ public void OnStartActivity(Activity activity, object? payload)
{
var uriHostNameType = Uri.CheckHostName(requestUri.Host);

if (uriHostNameType == UriHostNameType.IPv4 || uriHostNameType == UriHostNameType.IPv6)
if (uriHostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6)
{
activity.SetTag(SemanticConventions.AttributeServerSocketAddress, requestUri.Host);
}
Expand Down Expand Up @@ -162,14 +164,16 @@ public void OnStartActivity(Activity activity, object? payload)
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The event source guarantees that top level properties are preserved")]
#endif
static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request)
=> StartRequestFetcher.TryFetch(payload, out request) && request != null;
{
return StartRequestFetcher.TryFetch(payload, out request) && request != null;
}
}

public void OnStopActivity(Activity activity, object? payload)
{
if (activity.IsAllDataRequested)
{
bool validConversion = GrpcTagHelper.TryGetGrpcStatusCodeFromActivity(activity, out int status);
var validConversion = GrpcTagHelper.TryGetGrpcStatusCodeFromActivity(activity, out var status);
if (validConversion)
{
if (activity.Status == ActivityStatusCode.Unset)
Expand All @@ -184,7 +188,7 @@ public void OnStopActivity(Activity activity, object? payload)
// Remove the grpc.status_code tag added by the gRPC .NET library
activity.SetTag(GrpcTagHelper.GrpcStatusCodeTagName, null);

if (TryFetchResponse(payload, out HttpResponseMessage? response))
if (TryFetchResponse(payload, out var response))
{
try
{
Expand All @@ -203,6 +207,8 @@ public void OnStopActivity(Activity activity, object? payload)
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The event source 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;
{
return StopResponseFetcher.TryFetch(payload, out response) && response != null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public class QuartzInstrumentationOptions
/// <summary>
/// Default traced operations.
/// </summary>
private static readonly IEnumerable<string> DefaultTracedOperations = new[]
{
private static readonly IEnumerable<string> DefaultTracedOperations =
[
OperationName.Job.Execute,
OperationName.Job.Veto,
};
OperationName.Job.Veto
];

/// <summary>
/// Gets or sets an action to enrich an Activity.
Expand All @@ -42,6 +42,6 @@ public class QuartzInstrumentationOptions
/// Gets or sets traced operations set.
/// </summary>
#pragma warning disable CA2227 // Collection properties should be read only
public HashSet<string> TracedOperations { get; set; } = new(DefaultTracedOperations);
public HashSet<string> TracedOperations { get; set; } = [.. DefaultTracedOperations];
#pragma warning restore CA2227 // Collection properties should be read only
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

using System.Diagnostics;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Core.Interceptors;

Expand Down Expand Up @@ -36,22 +35,22 @@ internal class FoobarService : Foobar.FoobarBase
/// <summary>
/// The default request message.
/// </summary>
internal static readonly FoobarRequest DefaultRequestMessage = new FoobarRequest { Message = "foo" };
internal static readonly FoobarRequest DefaultRequestMessage = new() { Message = "foo" };

/// <summary>
/// The default request message size.
/// </summary>
internal static readonly int DefaultRequestMessageSize = ((IMessage)DefaultRequestMessage).CalculateSize();
internal static readonly int DefaultRequestMessageSize = DefaultRequestMessage.CalculateSize();

/// <summary>
/// The default response message.
/// </summary>
internal static readonly FoobarResponse DefaultResponseMessage = new FoobarResponse { Message = "bar" };
internal static readonly FoobarResponse DefaultResponseMessage = new() { Message = "bar" };

/// <summary>
/// The default request message size.
/// </summary>
internal static readonly int DefaultResponseMessageSize = ((IMessage)DefaultResponseMessage).CalculateSize();
internal static readonly int DefaultResponseMessageSize = DefaultResponseMessage.CalculateSize();

/// <summary>
/// Starts the specified service.
Expand Down Expand Up @@ -226,15 +225,20 @@ private void CheckForFailure(ServerCallContext context)
var failureDescription = context.RequestHeaders.GetValue(RequestHeaderErrorDescription);
if (failureStatusCodeString != null)
{
throw new RpcException(new Status((StatusCode)Enum.Parse(typeof(StatusCode), failureStatusCodeString), failureDescription ?? string.Empty));
#if NET
var statusCode = Enum.Parse<StatusCode>(failureStatusCodeString);
#else
var statusCode = (StatusCode)Enum.Parse(typeof(StatusCode), failureStatusCodeString);
#endif
throw new RpcException(new Status(statusCode, failureDescription ?? string.Empty));
}
}

/// <summary>
/// Wraps server shutdown with an IDisposable pattern.
/// </summary>
/// <seealso cref="IDisposable" />
public sealed class DisposableServer : IDisposable
internal sealed class DisposableServer : IDisposable
{
/// <summary>
/// The server.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class GrpcCoreClientInterceptorTests
/// <summary>
/// The default metadata func.
/// </summary>
private static readonly Func<Metadata> DefaultMetadataFunc = () => new Metadata { new Metadata.Entry("foo", "bar") };
private static readonly Func<Metadata> DefaultMetadataFunc = () => [new Metadata.Entry("foo", "bar")];

/// <summary>
/// Validates a successful AsyncUnary call.
Expand Down Expand Up @@ -327,7 +327,7 @@ internal static void ValidateCommonActivityTags(
Assert.Contains(activity.TagObjects, t => t.Key == SemanticConventions.AttributeRpcGrpcStatusCode && (int?)t.Value == (int)expectedStatusCode);

// Cancelled is not an error.
if (expectedStatusCode != StatusCode.OK && expectedStatusCode != StatusCode.Cancelled)
if (expectedStatusCode is not StatusCode.OK and not StatusCode.Cancelled)
{
Assert.Equal(ActivityStatusCode.Error, activity.Status);
}
Expand Down Expand Up @@ -495,11 +495,10 @@ private static async Task TestHandlerFailure(
var client = FoobarService.ConstructRpcClient(
serverUriString ?? server.UriString,
new ClientTracingInterceptor(interceptorOptions),
new List<Metadata.Entry>
{
[
new(FoobarService.RequestHeaderFailWithStatusCode, statusCode.ToString()),
new(FoobarService.RequestHeaderErrorDescription, "fubar"),
});
new(FoobarService.RequestHeaderErrorDescription, "fubar")
]);

using var activityListener = new InterceptorActivityListener(testTags);
await Assert.ThrowsAsync<RpcException>(async () => await clientRequestFunc(client, null).ConfigureAwait(false));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,7 @@ private static async Task TestHandlerSuccess(Func<Foobar.FoobarClient, Metadata?
{
var client = FoobarService.ConstructRpcClient(
server.UriString,
additionalMetadata: new List<Metadata.Entry>
{
new Metadata.Entry("traceparent", FoobarService.DefaultTraceparentWithSampling),
});
additionalMetadata: [new Metadata.Entry("traceparent", FoobarService.DefaultTraceparentWithSampling)]);

await clientRequestFunc(client, additionalMetadata).ConfigureAwait(false);

Expand All @@ -152,12 +149,12 @@ private static async Task TestHandlerFailure(Func<Foobar.FoobarClient, Metadata?
using var activityListener = new InterceptorActivityListener(testTags);
var client = FoobarService.ConstructRpcClient(
server.UriString,
additionalMetadata: new List<Metadata.Entry>
{
additionalMetadata:
[
new Metadata.Entry("traceparent", FoobarService.DefaultTraceparentWithSampling),
new Metadata.Entry(FoobarService.RequestHeaderFailWithStatusCode, StatusCode.ResourceExhausted.ToString()),
new Metadata.Entry(FoobarService.RequestHeaderErrorDescription, "fubar"),
});
]);

await Assert.ThrowsAsync<RpcException>(async () => await clientRequestFunc(client, additionalMetadata).ConfigureAwait(false));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

namespace OpenTelemetry.Instrumentation.Grpc.Tests;

public class GrpcServer<TService> : IDisposable
internal class GrpcServer<TService> : IDisposable
where TService : class
{
private static readonly Random GlobalRandom = new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,18 @@ internal static class ClientTestHelpers
public static HttpClient CreateTestClient(Func<HttpRequestMessage, Task<HttpResponseMessage>> sendAsync, Uri? baseAddress = null)
{
var handler = TestHttpMessageHandler.Create(sendAsync);
var httpClient = new HttpClient(handler);
httpClient.BaseAddress = baseAddress ?? new Uri("https://localhost");
var httpClient = new HttpClient(handler)
{
BaseAddress = baseAddress ?? new Uri("https://localhost"),
};

return httpClient;
}

public static Task<StreamContent> CreateResponseContent<TResponse>(TResponse response, ICompressionProvider? compressionProvider = null)
where TResponse : IMessage<TResponse>
{
return CreateResponseContentCore(new[] { response }, compressionProvider);
return CreateResponseContentCore([response], compressionProvider);
}

public static async Task WriteResponseAsync<TResponse>(Stream ms, TResponse response, ICompressionProvider? compressionProvider)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace OpenTelemetry.Instrumentation.Grpc.Tests.GrpcTestHelpers;

public class TestHttpMessageHandler : HttpMessageHandler
internal class TestHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public static void EnsureTrailingHeaders(this HttpResponseMessage responseMessag

private class ResponseTrailers : HttpHeaders
{
public static readonly ResponseTrailers Empty = new ResponseTrailers();
public static readonly ResponseTrailers Empty = [];
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public partial class GrpcTests
[InlineData("http://[::1]", false)]
public void GrpcClientCallsAreCollectedSuccessfully(string baseAddress, bool shouldEnrich = true)
{
bool enrichWithHttpRequestMessageCalled = false;
bool enrichWithHttpResponseMessageCalled = false;
var enrichWithHttpRequestMessageCalled = false;
var enrichWithHttpResponseMessageCalled = false;

var uri = new Uri($"{baseAddress}:1234");
var uriHostNameType = Uri.CheckHostName(uri.Host);
Expand Down Expand Up @@ -88,7 +88,7 @@ public void GrpcClientCallsAreCollectedSuccessfully(string baseAddress, bool sho
Assert.Equal("greet.Greeter", activity.GetTagValue(SemanticConventions.AttributeRpcService));
Assert.Equal("SayHello", activity.GetTagValue(SemanticConventions.AttributeRpcMethod));

if (uriHostNameType == UriHostNameType.IPv4 || uriHostNameType == UriHostNameType.IPv6)
if (uriHostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6)
{
Assert.Equal(uri.Host, activity.GetTagValue(SemanticConventions.AttributeServerSocketAddress));
Assert.Null(activity.GetTagValue(SemanticConventions.AttributeServerAddress));
Expand Down Expand Up @@ -246,11 +246,10 @@ public void GrpcPropagatesContextWithSuppressInstrumentationOptionSetToTrue()
var propagator = new CustomTextMapPropagator();
propagator.InjectValues.Add("customField", context => "customValue");

Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([
new TraceContextPropagator(),
propagator,
}));
propagator
]));

using (Sdk.CreateTracerProviderBuilder()
.AddSource("test-source")
Expand Down Expand Up @@ -288,11 +287,10 @@ public void GrpcPropagatesContextWithSuppressInstrumentationOptionSetToTrue()
}
finally
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([
new TraceContextPropagator(),
new BaggagePropagator(),
}));
new BaggagePropagator()
]));
}
}

Expand All @@ -305,7 +303,7 @@ public void GrpcDoesNotPropagateContextWithSuppressInstrumentationOptionSetToFal
var exportedItems = new List<Activity>();
using var source = new ActivitySource("test-source");

bool isPropagatorCalled = false;
var isPropagatorCalled = false;
var propagator = new CustomTextMapPropagator
{
Injected = (context) => isPropagatorCalled = true,
Expand Down Expand Up @@ -342,11 +340,10 @@ public void GrpcDoesNotPropagateContextWithSuppressInstrumentationOptionSetToFal
}
finally
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([
new TraceContextPropagator(),
new BaggagePropagator(),
}));
new BaggagePropagator()
]));
}
}

Expand All @@ -360,15 +357,13 @@ public void GrpcClientInstrumentationRespectsSdkSuppressInstrumentation()

using var source = new ActivitySource("test-source");

bool isPropagatorCalled = false;
var propagator = new CustomTextMapPropagator();
propagator.Injected = (context) => isPropagatorCalled = true;
var isPropagatorCalled = false;
var propagator = new CustomTextMapPropagator { Injected = _ => isPropagatorCalled = true };

Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([
new TraceContextPropagator(),
propagator,
}));
propagator
]));

using (Sdk.CreateTracerProviderBuilder()
.AddSource("test-source")
Expand All @@ -395,20 +390,19 @@ public void GrpcClientInstrumentationRespectsSdkSuppressInstrumentation()
}
finally
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[]
{
Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([
new TraceContextPropagator(),
new BaggagePropagator(),
}));
new BaggagePropagator()
]));
}
}
#endif

[Fact]
public void AddGrpcClientInstrumentationNamedOptionsSupported()
{
int defaultExporterOptionsConfigureOptionsInvocations = 0;
int namedExporterOptionsConfigureOptionsInvocations = 0;
var defaultExporterOptionsConfigureOptionsInvocations = 0;
var namedExporterOptionsConfigureOptionsInvocations = 0;

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureServices(services =>
Expand Down
Loading
Loading