From 5322d6b81364c506f00ae85d4d98cf6abaa787e4 Mon Sep 17 00:00:00 2001 From: Varorbc Date: Sat, 7 Sep 2024 14:08:07 +0800 Subject: [PATCH 1/9] precompile condition clean (#2528) --- .../GrpcAspNetCoreServer/Program.cs | 11 +---- .../GrpcAspNetCoreServer/Startup.cs | 12 +---- .../benchmarkapps/GrpcClient/ClientOptions.cs | 6 +-- .../GrpcClient/NamedPipeConnectionFactory.cs | 6 +-- perf/benchmarkapps/GrpcClient/Program.cs | 11 +---- .../UnixDomainSocketConnectionFactory.cs | 6 +-- .../GrpcEndpointRouteBuilderExtensions.cs | 6 +-- .../GrpcMethodMetadata.cs | 9 +--- .../IGrpcServiceActivator.cs | 8 +-- .../InterceptorCollection.cs | 12 +---- .../InterceptorRegistration.cs | 12 +---- .../ClientStreamingServerCallHandler.cs | 6 +-- .../DuplexStreamingServerCallHandler.cs | 6 +-- .../CallHandlers/ServerCallHandlerBase.cs | 11 +---- .../ServerStreamingServerCallHandler.cs | 6 +-- .../CallHandlers/UnaryServerCallHandler.cs | 8 +-- .../Internal/DefaultGrpcServiceActivator.cs | 8 +-- .../Internal/GrpcProtocolConstants.cs | 49 +------------------ .../Internal/GrpcServiceOptionsSetup.cs | 5 +- .../Internal/HttpContextServerCallContext.cs | 2 - .../Internal/HttpContextStreamWriter.cs | 2 - .../Internal/PipeExtensions.cs | 4 -- .../Internal/ServerCallHandlerFactory.cs | 8 +-- .../Model/IServiceMethodProvider.cs | 8 +-- .../Internal/BinderServiceModelProvider.cs | 8 +-- .../Model/Internal/ProviderServiceBinder.cs | 6 +-- .../Model/Internal/ServiceRouteBuilder.cs | 8 +-- .../Model/ServiceMethodProviderContext.cs | 8 +-- .../Internal/GrpcWebProtocolConstants.cs | 7 +-- src/Shared/Server/BindMethodFinder.cs | 4 +- .../ClientStreamingServerMethodInvoker.cs | 8 +-- .../DuplexStreamingServerMethodInvoker.cs | 8 +-- src/Shared/Server/ServerMethodInvokerBase.cs | 8 +-- .../ServerStreamingServerMethodInvoker.cs | 8 +-- src/Shared/Server/UnaryServerMethodInvoker.cs | 8 +-- .../Balancer/BalancerHelpers.cs | 4 -- .../Balancer/RoundRobinBalancerTests.cs | 2 - .../Client/CompressionTests.cs | 4 +- .../FunctionalTests/Client/ConnectionTests.cs | 10 ---- test/FunctionalTests/Client/HedgingTests.cs | 2 - test/FunctionalTests/Client/RetryTests.cs | 2 - test/FunctionalTests/Client/StreamingTests.cs | 2 - test/FunctionalTests/Client/TelemetryTests.cs | 17 +------ test/FunctionalTests/Client/UnaryTests.cs | 2 - .../Infrastructure/GrpcHttpHelper.cs | 2 - .../Infrastructure/GrpcTestFixture.cs | 26 +--------- .../Infrastructure/TestServerEndpointName.cs | 6 +-- .../UnixDomainSocketConnectionFactory.cs | 4 +- .../Server/CompressionTests.cs | 25 +--------- .../TestServer/Helpers/GrpcTestFixture.cs | 6 --- .../Web/Client/ConnectionTests.cs | 10 ---- .../Web/GrpcWebFunctionalTestBase.cs | 4 -- .../CallHandlerTests.cs | 21 -------- .../GrpcServicesExtensionsTests.cs | 7 +-- .../HttpContextServerCallContextTests.cs | 4 -- test/Shared/MessageHelpers.cs | 12 ++--- 56 files changed, 62 insertions(+), 413 deletions(-) diff --git a/perf/benchmarkapps/GrpcAspNetCoreServer/Program.cs b/perf/benchmarkapps/GrpcAspNetCoreServer/Program.cs index 9fd395c26..f729a660f 100644 --- a/perf/benchmarkapps/GrpcAspNetCoreServer/Program.cs +++ b/perf/benchmarkapps/GrpcAspNetCoreServer/Program.cs @@ -120,13 +120,8 @@ public static IHostBuilder CreateHostBuilder(string[] args) { Console.WriteLine($"Console Logging enabled with level '{logLevel}'"); - loggerFactory -#if NET5_0_OR_GREATER - .AddSimpleConsole(o => o.TimestampFormat = "ss.ffff ") -#else - .AddConsole(o => o.TimestampFormat = "ss.ffff ") -#endif - .SetMinimumLevel(logLevel); + loggerFactory.AddSimpleConsole(o => o.TimestampFormat = "ss.ffff ") + .SetMinimumLevel(logLevel); } }) .UseDefaultServiceProvider((context, options) => @@ -163,7 +158,6 @@ private static void ConfigureListenOptions(ListenOptions listenOptions, IConfigu } }); } -#if NET6_0_OR_GREATER else if (protocol.Equals("h3", StringComparison.OrdinalIgnoreCase)) { listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; @@ -177,7 +171,6 @@ private static void ConfigureListenOptions(ListenOptions listenOptions, IConfigu } }); } -#endif else if (protocol.Equals("h2c", StringComparison.OrdinalIgnoreCase)) { listenOptions.Protocols = HttpProtocols.Http2; diff --git a/perf/benchmarkapps/GrpcAspNetCoreServer/Startup.cs b/perf/benchmarkapps/GrpcAspNetCoreServer/Startup.cs index bf590136e..cb9ba210a 100644 --- a/perf/benchmarkapps/GrpcAspNetCoreServer/Startup.cs +++ b/perf/benchmarkapps/GrpcAspNetCoreServer/Startup.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -21,9 +21,7 @@ using Grpc.Shared; using Grpc.Testing; using Grpc.Tests.Shared; -#if NET5_0_OR_GREATER using Microsoft.AspNetCore.Authentication.Certificate; -#endif using Newtonsoft.Json; namespace GrpcAspNetCoreServer; @@ -41,10 +39,8 @@ public void ConfigureServices(IServiceCollection services) { services.AddGrpc(o => { -#if NET5_0_OR_GREATER // Small performance benefit to not add catch-all routes to handle UNIMPLEMENTED for unknown services o.IgnoreUnknownServices = true; -#endif }); services.Configure(c => { @@ -54,7 +50,6 @@ public void ConfigureServices(IServiceCollection services) services.AddSingleton(); services.AddControllers(); -#if NET5_0_OR_GREATER bool.TryParse(_config["enableCertAuth"], out var enableCertAuth); if (enableCertAuth) { @@ -67,7 +62,6 @@ public void ConfigureServices(IServiceCollection services) options.AllowedCertificateTypes = CertificateTypes.All; }); } -#endif } public void Configure(IApplicationBuilder app, IHostApplicationLifetime applicationLifetime) @@ -83,14 +77,12 @@ public void Configure(IApplicationBuilder app, IHostApplicationLifetime applicat app.UseRouting(); -#if NET5_0_OR_GREATER bool.TryParse(_config["enableCertAuth"], out var enableCertAuth); if (enableCertAuth) { app.UseAuthentication(); app.UseAuthorization(); } -#endif #if GRPC_WEB bool.TryParse(_config["enableGrpcWeb"], out var enableGrpcWeb); @@ -139,12 +131,10 @@ public void Configure(IApplicationBuilder app, IHostApplicationLifetime applicat private void ConfigureAuthorization(IEndpointConventionBuilder builder) { -#if NET5_0_OR_GREATER bool.TryParse(_config["enableCertAuth"], out var enableCertAuth); if (enableCertAuth) { builder.RequireAuthorization(); } -#endif } } diff --git a/perf/benchmarkapps/GrpcClient/ClientOptions.cs b/perf/benchmarkapps/GrpcClient/ClientOptions.cs index 425338661..44ed9f882 100644 --- a/perf/benchmarkapps/GrpcClient/ClientOptions.cs +++ b/perf/benchmarkapps/GrpcClient/ClientOptions.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -23,10 +23,8 @@ namespace GrpcClient; public class ClientOptions { public Uri? Url { get; set; } -#if NET5_0_OR_GREATER public string? UdsFileName { get; set; } public string? NamedPipeName { get; set; } -#endif public int Connections { get; set; } public int Warmup { get; set; } public int Duration { get; set; } @@ -41,4 +39,4 @@ public class ClientOptions public GrpcClientType GrpcClientType { get; set; } public int Streams { get; set; } public int Deadline { get; set; } -} \ No newline at end of file +} diff --git a/perf/benchmarkapps/GrpcClient/NamedPipeConnectionFactory.cs b/perf/benchmarkapps/GrpcClient/NamedPipeConnectionFactory.cs index ea261cf39..0839ea507 100644 --- a/perf/benchmarkapps/GrpcClient/NamedPipeConnectionFactory.cs +++ b/perf/benchmarkapps/GrpcClient/NamedPipeConnectionFactory.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -19,8 +19,6 @@ using System.IO.Pipes; using System.Security.Principal; -#if NET5_0_OR_GREATER - namespace GrpcClient; public class NamedPipeConnectionFactory @@ -56,5 +54,3 @@ public async ValueTask ConnectAsync(SocketsHttpConnectionContext _, } } } - -#endif diff --git a/perf/benchmarkapps/GrpcClient/Program.cs b/perf/benchmarkapps/GrpcClient/Program.cs index 88275c5f9..7e86b3a4b 100644 --- a/perf/benchmarkapps/GrpcClient/Program.cs +++ b/perf/benchmarkapps/GrpcClient/Program.cs @@ -465,10 +465,6 @@ private static ChannelBase CreateChannel(string target) var address = useTls ? "https://" : "http://"; address += target; -#if NETCOREAPP3_1 - AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); -#endif - var httpClientHandler = new SocketsHttpHandler(); httpClientHandler.UseProxy = false; httpClientHandler.AllowAutoRedirect = false; @@ -479,7 +475,7 @@ private static ChannelBase CreateChannel(string target) var clientCertificates = X509CertificateLoader.LoadPkcs12CollectionFromFile(certPath, "1111"); httpClientHandler.SslOptions.ClientCertificates = clientCertificates; } -#if NET5_0_OR_GREATER + if (!string.IsNullOrEmpty(_options.UdsFileName)) { var connectionFactory = new UnixDomainSocketConnectionFactory(new UnixDomainSocketEndPoint(ResolveUdsPath(_options.UdsFileName))); @@ -490,7 +486,6 @@ private static ChannelBase CreateChannel(string target) var connectionFactory = new NamedPipeConnectionFactory(_options.NamedPipeName); httpClientHandler.ConnectCallback = connectionFactory.ConnectAsync; } -#endif httpClientHandler.SslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) => true; @@ -509,11 +504,7 @@ private static ChannelBase CreateChannel(string target) return GrpcChannel.ForAddress(address, new GrpcChannelOptions { -#if NET5_0_OR_GREATER HttpHandler = httpMessageHandler, -#else - HttpClient = new HttpClient(httpMessageHandler), -#endif LoggerFactory = _loggerFactory, HttpVersion = versionOverride }); diff --git a/perf/benchmarkapps/GrpcClient/UnixDomainSocketConnectionFactory.cs b/perf/benchmarkapps/GrpcClient/UnixDomainSocketConnectionFactory.cs index 3d1548336..e4e39b2b1 100644 --- a/perf/benchmarkapps/GrpcClient/UnixDomainSocketConnectionFactory.cs +++ b/perf/benchmarkapps/GrpcClient/UnixDomainSocketConnectionFactory.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -19,8 +19,6 @@ using System.Net; using System.Net.Sockets; -#if NET5_0_OR_GREATER - namespace GrpcClient; public class UnixDomainSocketConnectionFactory @@ -48,5 +46,3 @@ public async ValueTask ConnectAsync(SocketsHttpConnectionContext _, Canc } } } - -#endif diff --git a/src/Grpc.AspNetCore.Server/GrpcEndpointRouteBuilderExtensions.cs b/src/Grpc.AspNetCore.Server/GrpcEndpointRouteBuilderExtensions.cs index 93f4993be..f583a2c4c 100644 --- a/src/Grpc.AspNetCore.Server/GrpcEndpointRouteBuilderExtensions.cs +++ b/src/Grpc.AspNetCore.Server/GrpcEndpointRouteBuilderExtensions.cs @@ -36,11 +36,7 @@ public static class GrpcEndpointRouteBuilderExtensions /// The service type to map requests to. /// The to add the route to. /// A for endpoints associated with the service. - public static GrpcServiceEndpointConventionBuilder MapGrpcService< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService>(this IEndpointRouteBuilder builder) where TService : class + public static GrpcServiceEndpointConventionBuilder MapGrpcService<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService>(this IEndpointRouteBuilder builder) where TService : class { ArgumentNullThrowHelper.ThrowIfNull(builder); diff --git a/src/Grpc.AspNetCore.Server/GrpcMethodMetadata.cs b/src/Grpc.AspNetCore.Server/GrpcMethodMetadata.cs index cd3577376..d37d9e6a2 100644 --- a/src/Grpc.AspNetCore.Server/GrpcMethodMetadata.cs +++ b/src/Grpc.AspNetCore.Server/GrpcMethodMetadata.cs @@ -33,12 +33,7 @@ public sealed class GrpcMethodMetadata /// /// The implementing service type. /// The method representation. - public GrpcMethodMetadata( -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - Type serviceType, - IMethod method) + public GrpcMethodMetadata([DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] Type serviceType, IMethod method) { ArgumentNullThrowHelper.ThrowIfNull(serviceType); ArgumentNullThrowHelper.ThrowIfNull(method); @@ -50,9 +45,7 @@ public GrpcMethodMetadata( /// /// Gets the implementing service type. /// -#if NET5_0_OR_GREATER [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif public Type ServiceType { get; } /// diff --git a/src/Grpc.AspNetCore.Server/IGrpcServiceActivator.cs b/src/Grpc.AspNetCore.Server/IGrpcServiceActivator.cs index 7a99052f4..b36e9fc22 100644 --- a/src/Grpc.AspNetCore.Server/IGrpcServiceActivator.cs +++ b/src/Grpc.AspNetCore.Server/IGrpcServiceActivator.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -25,11 +25,7 @@ namespace Grpc.AspNetCore.Server; /// A activator abstraction. /// /// The service type. -public interface IGrpcServiceActivator< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TGrpcService> where TGrpcService : class +public interface IGrpcServiceActivator<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TGrpcService> where TGrpcService : class { /// /// Creates a service. diff --git a/src/Grpc.AspNetCore.Server/InterceptorCollection.cs b/src/Grpc.AspNetCore.Server/InterceptorCollection.cs index c8e93e216..fec8bc61a 100644 --- a/src/Grpc.AspNetCore.Server/InterceptorCollection.cs +++ b/src/Grpc.AspNetCore.Server/InterceptorCollection.cs @@ -33,11 +33,7 @@ public class InterceptorCollection : Collection /// /// The interceptor type. /// The list of arguments to pass to the interceptor constructor when creating an instance. - public void Add< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(InterceptorRegistration.InterceptorAccessibility)] -#endif - TInterceptor>(params object[] args) where TInterceptor : Interceptor + public void Add<[DynamicallyAccessedMembers(InterceptorRegistration.InterceptorAccessibility)] TInterceptor>(params object[] args) where TInterceptor : Interceptor { Add(typeof(TInterceptor), args); } @@ -47,11 +43,7 @@ public void Add< /// /// The interceptor type. /// The list of arguments to pass to the interceptor constructor when creating an instance. - public void Add( -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(InterceptorRegistration.InterceptorAccessibility)] -#endif - Type interceptorType, params object[] args) + public void Add([DynamicallyAccessedMembers(InterceptorRegistration.InterceptorAccessibility)] Type interceptorType, params object[] args) { ArgumentNullThrowHelper.ThrowIfNull(interceptorType); diff --git a/src/Grpc.AspNetCore.Server/InterceptorRegistration.cs b/src/Grpc.AspNetCore.Server/InterceptorRegistration.cs index 2e6d23412..b57f378b3 100644 --- a/src/Grpc.AspNetCore.Server/InterceptorRegistration.cs +++ b/src/Grpc.AspNetCore.Server/InterceptorRegistration.cs @@ -28,17 +28,11 @@ namespace Grpc.AspNetCore.Server; /// public class InterceptorRegistration { -#if NET5_0_OR_GREATER internal const DynamicallyAccessedMemberTypes InterceptorAccessibility = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods; -#endif internal object[] _args; - internal InterceptorRegistration( -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(InterceptorAccessibility)] -#endif - Type type, object[] arguments) + internal InterceptorRegistration([DynamicallyAccessedMembers(InterceptorAccessibility)]Type type, object[] arguments) { ArgumentNullThrowHelper.ThrowIfNull(type); ArgumentNullThrowHelper.ThrowIfNull(arguments); @@ -58,9 +52,7 @@ internal InterceptorRegistration( /// /// Get the type of the interceptor. /// -#if NET5_0_OR_GREATER [DynamicallyAccessedMembers(InterceptorAccessibility)] -#endif public Type Type { get; } /// @@ -71,12 +63,10 @@ internal InterceptorRegistration( private IGrpcInterceptorActivator? _interceptorActivator; private ObjectFactory? _factory; -#if NET5_0_OR_GREATER [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Type parameter members are preserved with DynamicallyAccessedMembers on InterceptorRegistration.Type property.")] [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "Type definition is explicitly specified and type argument is always an Interceptor type.")] -#endif internal IGrpcInterceptorActivator GetActivator(IServiceProvider serviceProvider) { // Not thread safe. Side effect is resolving the service twice. diff --git a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ClientStreamingServerCallHandler.cs b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ClientStreamingServerCallHandler.cs index 61655c71a..f6d9bb155 100644 --- a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ClientStreamingServerCallHandler.cs +++ b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ClientStreamingServerCallHandler.cs @@ -24,11 +24,7 @@ namespace Grpc.AspNetCore.Server.Internal.CallHandlers; -internal class ClientStreamingServerCallHandler< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerCallHandlerBase +internal class ClientStreamingServerCallHandler<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerCallHandlerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/DuplexStreamingServerCallHandler.cs b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/DuplexStreamingServerCallHandler.cs index 9513ab1b6..cc5318511 100644 --- a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/DuplexStreamingServerCallHandler.cs +++ b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/DuplexStreamingServerCallHandler.cs @@ -23,11 +23,7 @@ namespace Grpc.AspNetCore.Server.Internal.CallHandlers; -internal class DuplexStreamingServerCallHandler< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerCallHandlerBase +internal class DuplexStreamingServerCallHandler<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerCallHandlerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerCallHandlerBase.cs b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerCallHandlerBase.cs index 3596d3131..f4db8601f 100644 --- a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerCallHandlerBase.cs +++ b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerCallHandlerBase.cs @@ -30,11 +30,7 @@ namespace Grpc.AspNetCore.Server.Internal.CallHandlers; -internal abstract class ServerCallHandlerBase< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> +internal abstract class ServerCallHandlerBase<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> where TService : class where TRequest : class where TResponse : class @@ -60,10 +56,7 @@ public Task HandleCallAsync(HttpContext httpContext) } if (!GrpcProtocolConstants.IsHttp2(httpContext.Request.Protocol) -#if NET6_0_OR_GREATER - && !GrpcProtocolConstants.IsHttp3(httpContext.Request.Protocol) -#endif - ) + && !GrpcProtocolConstants.IsHttp3(httpContext.Request.Protocol)) { return ProcessNonHttp2Request(httpContext); } diff --git a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerStreamingServerCallHandler.cs b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerStreamingServerCallHandler.cs index e29c58be5..404822f98 100644 --- a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerStreamingServerCallHandler.cs +++ b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/ServerStreamingServerCallHandler.cs @@ -23,11 +23,7 @@ namespace Grpc.AspNetCore.Server.Internal.CallHandlers; -internal class ServerStreamingServerCallHandler< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerCallHandlerBase +internal class ServerStreamingServerCallHandler<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerCallHandlerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/UnaryServerCallHandler.cs b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/UnaryServerCallHandler.cs index d959f9dc2..499dc6491 100644 --- a/src/Grpc.AspNetCore.Server/Internal/CallHandlers/UnaryServerCallHandler.cs +++ b/src/Grpc.AspNetCore.Server/Internal/CallHandlers/UnaryServerCallHandler.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -24,11 +24,7 @@ namespace Grpc.AspNetCore.Server.Internal.CallHandlers; -internal class UnaryServerCallHandler< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerCallHandlerBase +internal class UnaryServerCallHandler<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerCallHandlerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Grpc.AspNetCore.Server/Internal/DefaultGrpcServiceActivator.cs b/src/Grpc.AspNetCore.Server/Internal/DefaultGrpcServiceActivator.cs index 2bba1f8bb..e911697c8 100644 --- a/src/Grpc.AspNetCore.Server/Internal/DefaultGrpcServiceActivator.cs +++ b/src/Grpc.AspNetCore.Server/Internal/DefaultGrpcServiceActivator.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -21,11 +21,7 @@ namespace Grpc.AspNetCore.Server.Internal; -internal sealed class DefaultGrpcServiceActivator< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TGrpcService> : IGrpcServiceActivator where TGrpcService : class +internal sealed class DefaultGrpcServiceActivator<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TGrpcService> : IGrpcServiceActivator where TGrpcService : class { private static readonly Lazy _objectFactory = new Lazy(static () => ActivatorUtilities.CreateFactory(typeof(TGrpcService), Type.EmptyTypes)); diff --git a/src/Grpc.AspNetCore.Server/Internal/GrpcProtocolConstants.cs b/src/Grpc.AspNetCore.Server/Internal/GrpcProtocolConstants.cs index b9fe5afaa..269cf9a4c 100644 --- a/src/Grpc.AspNetCore.Server/Internal/GrpcProtocolConstants.cs +++ b/src/Grpc.AspNetCore.Server/Internal/GrpcProtocolConstants.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -28,51 +28,16 @@ internal static class GrpcProtocolConstants internal const string GrpcContentType = "application/grpc"; internal const string GrpcWebContentType = "application/grpc-web"; internal const string GrpcWebTextContentType = "application/grpc-web-text"; - -#if NET5_0_OR_GREATER internal static readonly string Http2Protocol = HttpProtocol.Http2; -#else - internal const string Http2Protocol = "HTTP/2"; - internal const string Http20Protocol = "HTTP/2.0"; // This is what IIS sets -#endif - -#if NET5_0_OR_GREATER internal static readonly string TimeoutHeader = HeaderNames.GrpcTimeout; -#else - internal const string TimeoutHeader = "grpc-timeout"; -#endif - -#if NET5_0_OR_GREATER internal static readonly string MessageEncodingHeader = HeaderNames.GrpcEncoding; -#else - internal const string MessageEncodingHeader = "grpc-encoding"; -#endif - -#if NET5_0_OR_GREATER internal static readonly string MessageAcceptEncodingHeader = HeaderNames.GrpcAcceptEncoding; -#else - internal const string MessageAcceptEncodingHeader = "grpc-accept-encoding"; -#endif - internal const string CompressionRequestAlgorithmHeader = "grpc-internal-encoding-request"; - -#if NET5_0_OR_GREATER internal static readonly string StatusTrailer = HeaderNames.GrpcStatus; -#else - internal const string StatusTrailer = "grpc-status"; -#endif - -#if NET5_0_OR_GREATER internal static readonly string MessageTrailer = HeaderNames.GrpcMessage; -#else - internal const string MessageTrailer = "grpc-message"; -#endif - internal const string IdentityGrpcEncoding = "identity"; internal const int Http2ResetStreamCancel = 0x8; -#if NET6_0_OR_GREATER internal const int Http3ResetStreamCancel = 0x010c; -#endif internal static readonly HashSet FilteredHeaders = new HashSet(StringComparer.OrdinalIgnoreCase) { @@ -97,20 +62,14 @@ internal static class GrpcProtocolConstants [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsHttp2(string protocol) { -#if NET5_0_OR_GREATER return HttpProtocol.IsHttp2(protocol); -#else - return protocol == Http2Protocol || protocol == Http20Protocol; -#endif } -#if NET6_0_OR_GREATER [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsHttp3(string protocol) { return HttpProtocol.IsHttp3(protocol); } -#endif internal static bool IsGrpcEncodingIdentity(string encoding) { @@ -120,14 +79,8 @@ internal static bool IsGrpcEncodingIdentity(string encoding) internal static int GetCancelErrorCode(string protocol) { -#if NET6_0_OR_GREATER return IsHttp3(protocol) ? Http3ResetStreamCancel : Http2ResetStreamCancel; -#else - return Http2ResetStreamCancel; -#endif } -#if NET5_0_OR_GREATER internal const DynamicallyAccessedMemberTypes ServiceAccessibility = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods; -#endif } diff --git a/src/Grpc.AspNetCore.Server/Internal/GrpcServiceOptionsSetup.cs b/src/Grpc.AspNetCore.Server/Internal/GrpcServiceOptionsSetup.cs index dd1ada872..f2fad234e 100644 --- a/src/Grpc.AspNetCore.Server/Internal/GrpcServiceOptionsSetup.cs +++ b/src/Grpc.AspNetCore.Server/Internal/GrpcServiceOptionsSetup.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -39,9 +39,8 @@ public void Configure(GrpcServiceOptions options) if (options._compressionProviders == null || options._compressionProviders.Count == 0) { options.CompressionProviders.Add(new GzipCompressionProvider(CompressionLevel.Fastest)); -#if NET6_0_OR_GREATER + options.CompressionProviders.Add(new DeflateCompressionProvider(CompressionLevel.Fastest)); -#endif } } } diff --git a/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs b/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs index 5e1d51fa2..f4ef272e0 100644 --- a/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs +++ b/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs @@ -411,14 +411,12 @@ public void Initialize(ISystemClock? clock = null) private Activity? GetHostActivity() { -#if NET6_0_OR_GREATER // Feature always returns the host activity var feature = HttpContext.Features.Get(); if (feature != null) { return feature.Activity; } -#endif // If feature isn't available, or not supported, then fallback to Activity.Current. var activity = Activity.Current; diff --git a/src/Grpc.AspNetCore.Server/Internal/HttpContextStreamWriter.cs b/src/Grpc.AspNetCore.Server/Internal/HttpContextStreamWriter.cs index b6a67f9fd..8a96d9fa1 100644 --- a/src/Grpc.AspNetCore.Server/Internal/HttpContextStreamWriter.cs +++ b/src/Grpc.AspNetCore.Server/Internal/HttpContextStreamWriter.cs @@ -62,13 +62,11 @@ public Task WriteAsync(TResponse message) return WriteCoreAsync(message, CancellationToken.None); } -#if NET5_0_OR_GREATER // Explicit implementation because this WriteAsync has a default interface implementation. Task IAsyncStreamWriter.WriteAsync(TResponse message, CancellationToken cancellationToken) { return WriteCoreAsync(message, cancellationToken); } -#endif private async Task WriteCoreAsync(TResponse message, CancellationToken cancellationToken) { diff --git a/src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs b/src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs index ed2796638..e1f23326f 100644 --- a/src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs +++ b/src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs @@ -20,9 +20,7 @@ using System.Buffers.Binary; using System.Diagnostics; using System.IO.Pipelines; -#if NET6_0_OR_GREATER using System.Runtime.CompilerServices; -#endif using Grpc.Core; using Grpc.Net.Compression; using Microsoft.Extensions.Logging; @@ -293,9 +291,7 @@ public static async ValueTask ReadSingleMessageAsync(this PipeReader input /// Message deserializer. /// The cancellation token. /// Complete message data or null if the stream is complete. -#if NET6_0_OR_GREATER [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] -#endif public static async ValueTask ReadStreamMessageAsync(this PipeReader input, HttpContextServerCallContext serverCallContext, Func deserializer, CancellationToken cancellationToken = default) where T : class { diff --git a/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs b/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs index c1426dd18..9d41c3520 100644 --- a/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs +++ b/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -31,11 +31,7 @@ namespace Grpc.AspNetCore.Server.Internal; /// /// Creates server call handlers. Provides a place to get services that call handlers will use. /// -internal partial class ServerCallHandlerFactory< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService> where TService : class +internal partial class ServerCallHandlerFactory<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService> where TService : class { private readonly ILoggerFactory _loggerFactory; private readonly IGrpcServiceActivator _serviceActivator; diff --git a/src/Grpc.AspNetCore.Server/Model/IServiceMethodProvider.cs b/src/Grpc.AspNetCore.Server/Model/IServiceMethodProvider.cs index d5778cc23..b771149bc 100644 --- a/src/Grpc.AspNetCore.Server/Model/IServiceMethodProvider.cs +++ b/src/Grpc.AspNetCore.Server/Model/IServiceMethodProvider.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -31,11 +31,7 @@ namespace Grpc.AspNetCore.Server.Model; /// instances are invoked in the order they are registered. /// /// -public interface IServiceMethodProvider< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService> where TService : class +public interface IServiceMethodProvider<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService> where TService : class { /// /// Called to execute the provider. diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs b/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs index 68473e105..db6fce070 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -24,11 +24,7 @@ namespace Grpc.AspNetCore.Server.Model.Internal; -internal class BinderServiceMethodProvider< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService> : IServiceMethodProvider where TService : class +internal class BinderServiceMethodProvider<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService> : IServiceMethodProvider where TService : class { private readonly ILogger> _logger; diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs b/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs index f570dae64..84be01989 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs @@ -24,11 +24,7 @@ namespace Grpc.AspNetCore.Server.Model.Internal; -internal class ProviderServiceBinder< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService> : ServiceBinderBase where TService : class +internal class ProviderServiceBinder<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService> : ServiceBinderBase where TService : class { private readonly ServiceMethodProviderContext _context; private readonly Type _declaringType; diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs b/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs index 7be1f3ba1..83d8875ae 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs @@ -19,21 +19,15 @@ using System.Diagnostics.CodeAnalysis; using Grpc.AspNetCore.Server.Internal; using Grpc.Core; -using Grpc.Shared; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; -using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.Extensions.Logging; using Log = Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilderLog; namespace Grpc.AspNetCore.Server.Model.Internal; -internal class ServiceRouteBuilder< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService> where TService : class +internal class ServiceRouteBuilder<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService> where TService : class { private readonly IEnumerable> _serviceMethodProviders; private readonly ServerCallHandlerFactory _serverCallHandlerFactory; diff --git a/src/Grpc.AspNetCore.Server/Model/ServiceMethodProviderContext.cs b/src/Grpc.AspNetCore.Server/Model/ServiceMethodProviderContext.cs index 476f50053..9b283bc22 100644 --- a/src/Grpc.AspNetCore.Server/Model/ServiceMethodProviderContext.cs +++ b/src/Grpc.AspNetCore.Server/Model/ServiceMethodProviderContext.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -29,11 +29,7 @@ namespace Grpc.AspNetCore.Server.Model; /// A context for . /// /// Service type for the context. -public class ServiceMethodProviderContext< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService> where TService : class +public class ServiceMethodProviderContext<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService> where TService : class { private readonly ServerCallHandlerFactory _serverCallHandlerFactory; diff --git a/src/Grpc.AspNetCore.Web/Internal/GrpcWebProtocolConstants.cs b/src/Grpc.AspNetCore.Web/Internal/GrpcWebProtocolConstants.cs index f1d1f4161..512256506 100644 --- a/src/Grpc.AspNetCore.Web/Internal/GrpcWebProtocolConstants.cs +++ b/src/Grpc.AspNetCore.Web/Internal/GrpcWebProtocolConstants.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -25,10 +25,5 @@ internal static class GrpcWebProtocolConstants internal const string GrpcContentType = "application/grpc"; internal const string GrpcWebContentType = "application/grpc-web"; internal const string GrpcWebTextContentType = "application/grpc-web-text"; - -#if NET5_0_OR_GREATER internal static readonly string Http2Protocol = HttpProtocol.Http2; -#else - internal const string Http2Protocol = "HTTP/2"; -#endif } diff --git a/src/Shared/Server/BindMethodFinder.cs b/src/Shared/Server/BindMethodFinder.cs index 45d3c8c3f..d48fdb90d 100644 --- a/src/Shared/Server/BindMethodFinder.cs +++ b/src/Shared/Server/BindMethodFinder.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -65,10 +65,8 @@ internal static class BindMethodFinder return null; } -#if NET5_0_OR_GREATER [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Fallback doesn't have BindServiceMethodAttribute so can't be verified.")] -#endif internal static MethodInfo? GetBindMethodFallback(Type serviceType) { // Search for the generated service base class diff --git a/src/Shared/Server/ClientStreamingServerMethodInvoker.cs b/src/Shared/Server/ClientStreamingServerMethodInvoker.cs index 9b2c7498c..efbad4804 100644 --- a/src/Shared/Server/ClientStreamingServerMethodInvoker.cs +++ b/src/Shared/Server/ClientStreamingServerMethodInvoker.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -31,11 +31,7 @@ namespace Grpc.Shared.Server; /// Service type for this method. /// Request message type for this method. /// Response message type for this method. -internal sealed class ClientStreamingServerMethodInvoker< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerMethodInvokerBase +internal sealed class ClientStreamingServerMethodInvoker<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerMethodInvokerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Shared/Server/DuplexStreamingServerMethodInvoker.cs b/src/Shared/Server/DuplexStreamingServerMethodInvoker.cs index 33aa1f0e9..e195fb88f 100644 --- a/src/Shared/Server/DuplexStreamingServerMethodInvoker.cs +++ b/src/Shared/Server/DuplexStreamingServerMethodInvoker.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -31,11 +31,7 @@ namespace Grpc.Shared.Server; /// Service type for this method. /// Request message type for this method. /// Response message type for this method. -internal sealed class DuplexStreamingServerMethodInvoker< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerMethodInvokerBase +internal sealed class DuplexStreamingServerMethodInvoker<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerMethodInvokerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Shared/Server/ServerMethodInvokerBase.cs b/src/Shared/Server/ServerMethodInvokerBase.cs index 247a069c2..b2afd3ef4 100644 --- a/src/Shared/Server/ServerMethodInvokerBase.cs +++ b/src/Shared/Server/ServerMethodInvokerBase.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -29,11 +29,7 @@ namespace Grpc.Shared.Server; /// Service type for this method. /// Request message type for this method. /// Response message type for this method. -internal abstract class ServerMethodInvokerBase< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> +internal abstract class ServerMethodInvokerBase<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> where TRequest : class where TResponse : class where TService : class diff --git a/src/Shared/Server/ServerStreamingServerMethodInvoker.cs b/src/Shared/Server/ServerStreamingServerMethodInvoker.cs index db93b7cc4..268e17463 100644 --- a/src/Shared/Server/ServerStreamingServerMethodInvoker.cs +++ b/src/Shared/Server/ServerStreamingServerMethodInvoker.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -31,11 +31,7 @@ namespace Grpc.Shared.Server; /// Service type for this method. /// Request message type for this method. /// Response message type for this method. -internal sealed class ServerStreamingServerMethodInvoker< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerMethodInvokerBase +internal sealed class ServerStreamingServerMethodInvoker<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerMethodInvokerBase where TRequest : class where TResponse : class where TService : class diff --git a/src/Shared/Server/UnaryServerMethodInvoker.cs b/src/Shared/Server/UnaryServerMethodInvoker.cs index c81c3d7a0..cbd1115fc 100644 --- a/src/Shared/Server/UnaryServerMethodInvoker.cs +++ b/src/Shared/Server/UnaryServerMethodInvoker.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -32,11 +32,7 @@ namespace Grpc.Shared.Server; /// Service type for this method. /// Request message type for this method. /// Response message type for this method. -internal sealed class UnaryServerMethodInvoker< -#if NET5_0_OR_GREATER - [DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] -#endif - TService, TRequest, TResponse> : ServerMethodInvokerBase +internal sealed class UnaryServerMethodInvoker<[DynamicallyAccessedMembers(GrpcProtocolConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerMethodInvokerBase where TRequest : class where TResponse : class where TService : class diff --git a/test/FunctionalTests/Balancer/BalancerHelpers.cs b/test/FunctionalTests/Balancer/BalancerHelpers.cs index 9fc61edf1..2406c40eb 100644 --- a/test/FunctionalTests/Balancer/BalancerHelpers.cs +++ b/test/FunctionalTests/Balancer/BalancerHelpers.cs @@ -238,7 +238,6 @@ public TestSubchannelTransportFactory(TimeSpan socketPingInterval, TimeSpan? con public ISubchannelTransport Create(Subchannel subchannel) { -#if NET5_0_OR_GREATER return new SocketConnectivitySubchannelTransport( subchannel, _socketPingInterval, @@ -246,9 +245,6 @@ public ISubchannelTransport Create(Subchannel subchannel) _connectionIdleTimeout, subchannel._manager.LoggerFactory, _socketConnect); -#else - return new PassiveSubchannelTransport(subchannel); -#endif } } } diff --git a/test/FunctionalTests/Balancer/RoundRobinBalancerTests.cs b/test/FunctionalTests/Balancer/RoundRobinBalancerTests.cs index 9f79cf7e2..19686b10d 100644 --- a/test/FunctionalTests/Balancer/RoundRobinBalancerTests.cs +++ b/test/FunctionalTests/Balancer/RoundRobinBalancerTests.cs @@ -17,7 +17,6 @@ #endregion #if SUPPORT_LOAD_BALANCING -#if NET5_0_OR_GREATER using System; using System.Collections.Generic; @@ -462,4 +461,3 @@ Task UnaryMethod(HelloRequest request, ServerCallContext context) } #endif -#endif diff --git a/test/FunctionalTests/Client/CompressionTests.cs b/test/FunctionalTests/Client/CompressionTests.cs index 27d745262..1444355fd 100644 --- a/test/FunctionalTests/Client/CompressionTests.cs +++ b/test/FunctionalTests/Client/CompressionTests.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -31,9 +31,7 @@ public class CompressionTests : FunctionalTestBase { [TestCase("identity")] [TestCase("gzip")] -#if NET6_0_OR_GREATER [TestCase("deflate")] -#endif public async Task SendCompressedMessage_ServiceCompressionConfigured_ResponseGzipEncoding(string algorithmName) { // Arrange diff --git a/test/FunctionalTests/Client/ConnectionTests.cs b/test/FunctionalTests/Client/ConnectionTests.cs index a5c118577..578230229 100644 --- a/test/FunctionalTests/Client/ConnectionTests.cs +++ b/test/FunctionalTests/Client/ConnectionTests.cs @@ -55,24 +55,17 @@ public async Task ALPN_ProtocolDowngradedToHttp1_ThrowErrorFromServer() // Assert Assert.AreEqual(StatusCode.Internal, ex.StatusCode); -#if NET5_0_OR_GREATER var debugException = ex.Status.DebugException!; Assert.AreEqual("The SSL connection could not be established, see inner exception.", debugException.Message); -#else - Assert.AreEqual("Request protocol 'HTTP/1.1' is not supported.", ex.Status.Detail); -#endif } -#if NET5_0_OR_GREATER [Test] public async Task UnixDomainSockets() { Task UnaryUds(HelloRequest request, ServerCallContext context) { -#if NET6_0_OR_GREATER var endPoint = (UnixDomainSocketEndPoint)context.GetHttpContext().Features.Get()!.Socket.LocalEndPoint!; Assert.NotNull(endPoint); -#endif return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); } @@ -96,7 +89,6 @@ Task UnaryUds(HelloRequest request, ServerCallContext context) // Assert Assert.AreEqual("Hello John", response.Message); } -#endif #if NET7_0_OR_GREATER [Test] @@ -122,7 +114,6 @@ public async Task Http3() } #endif -#if NET5_0_OR_GREATER [Test] public async Task ShareSocketsHttpHandler() { @@ -200,5 +191,4 @@ Task Unary(HelloRequest request, ServerCallContext context) var expected = $"CONNECT {http.address.Host}:{http.address.Port} HTTP/1.1"; Assert.AreEqual(expected, proxyServer.Requests[0].RequestLine); } -#endif } diff --git a/test/FunctionalTests/Client/HedgingTests.cs b/test/FunctionalTests/Client/HedgingTests.cs index 6bbd10c4e..e23f06255 100644 --- a/test/FunctionalTests/Client/HedgingTests.cs +++ b/test/FunctionalTests/Client/HedgingTests.cs @@ -679,7 +679,6 @@ await call.RequestStream.WriteAsync( Assert.AreEqual(1, serverAbortCount); } -#if NET5_0_OR_GREATER [Test] public async Task ClientStreaming_WriteAsyncCancellationBefore_ClientAbort() { @@ -949,5 +948,4 @@ async Task ClientStreamingWithReadFailures(IAsyncStreamReader ClientStreamingWithReadFailures(IAsyncStreamReader ClientStreamingWithReadFailures(IAsyncStreamReader UnaryTelemetryHeader(HelloRequest request, ServerCallContext context) { - telemetryHeader = context.RequestHeaders.GetValue( -#if NET5_0_OR_GREATER - "traceparent" -#else - "request-id" -#endif - ); + telemetryHeader = context.RequestHeaders.GetValue("traceparent"); return Task.FromResult(new HelloReply()); } @@ -82,7 +74,6 @@ Task UnaryTelemetryHeader(HelloRequest request, ServerCallContext co var client = CreateClient(clientType, method, handler); // Act -#if NET5_0_OR_GREATER var result = new List>(); using var allSubscription = new AllListenersObserver(new Dictionary>> @@ -90,21 +81,17 @@ Task UnaryTelemetryHeader(HelloRequest request, ServerCallContext co ["HttpHandlerDiagnosticListener"] = new ObserverToList>(result) }); using (DiagnosticListener.AllListeners.Subscribe(allSubscription)) -#endif { await client.UnaryCall(new HelloRequest()).ResponseAsync.DefaultTimeout(); } // Assert Assert.IsNotNull(telemetryHeader); - -#if NET5_0_OR_GREATER Assert.AreEqual(4, result.Count); Assert.AreEqual("System.Net.Http.HttpRequestOut.Start", result[0].Key); Assert.AreEqual("System.Net.Http.Request", result[1].Key); Assert.AreEqual("System.Net.Http.HttpRequestOut.Stop", result[2].Key); Assert.AreEqual("System.Net.Http.Response", result[3].Key); -#endif } private TestClient CreateClient(ClientType clientType, Method method, HttpMessageHandler? handler) diff --git a/test/FunctionalTests/Client/UnaryTests.cs b/test/FunctionalTests/Client/UnaryTests.cs index bc58012ff..368919615 100644 --- a/test/FunctionalTests/Client/UnaryTests.cs +++ b/test/FunctionalTests/Client/UnaryTests.cs @@ -128,7 +128,6 @@ Task UnaryThrowError(HelloRequest request, ServerCallContext context Assert.AreEqual(expectedServerCulture, serverCulture); } -#if NET5_0_OR_GREATER [Test] public async Task MaxConcurrentStreams_StartConcurrently_AdditionalConnectionsCreated() { @@ -226,7 +225,6 @@ async Task UnaryThrowError(HelloRequest request, ServerCallContext c } } } -#endif [Test] public async Task Health_Check_Success() diff --git a/test/FunctionalTests/Infrastructure/GrpcHttpHelper.cs b/test/FunctionalTests/Infrastructure/GrpcHttpHelper.cs index f631e498b..c32b4ab0e 100644 --- a/test/FunctionalTests/Infrastructure/GrpcHttpHelper.cs +++ b/test/FunctionalTests/Infrastructure/GrpcHttpHelper.cs @@ -24,9 +24,7 @@ public static HttpRequestMessage Create(string url, HttpMethod? method = null) { var request = new HttpRequestMessage(method ?? HttpMethod.Post, url); request.Version = new Version(2, 0); -#if NET5_0_OR_GREATER request.VersionPolicy = HttpVersionPolicy.RequestVersionExact; -#endif return request; } diff --git a/test/FunctionalTests/Infrastructure/GrpcTestFixture.cs b/test/FunctionalTests/Infrastructure/GrpcTestFixture.cs index 6c2c61e14..5422fcfba 100644 --- a/test/FunctionalTests/Infrastructure/GrpcTestFixture.cs +++ b/test/FunctionalTests/Infrastructure/GrpcTestFixture.cs @@ -73,9 +73,7 @@ public static IPEndpointInfoContainer Create(ListenOptions listenOptions, bool i public class GrpcTestFixture : IDisposable where TStartup : class { -#if NET5_0_OR_GREATER private readonly string _socketPath = Path.GetTempFileName(); -#endif private readonly InProcessTestServer _server; public GrpcTestFixture( @@ -143,7 +141,6 @@ public GrpcTestFixture( urls[TestServerEndpointName.Http1WithTls] = IPEndpointInfoContainer.Create(listenOptions, isHttps: true); }); -#if NET5_0_OR_GREATER if (File.Exists(_socketPath)) { File.Delete(_socketPath); @@ -155,9 +152,7 @@ public GrpcTestFixture( urls[TestServerEndpointName.UnixDomainSocket] = new SocketsEndpointInfoContainer(_socketPath); }); -#endif -#if NET6_0_OR_GREATER if (RequireHttp3Attribute.IsSupported(out _)) { var http3Port = Convert.ToInt32(context.Configuration["Http3Port"], CultureInfo.InvariantCulture); @@ -175,16 +170,13 @@ public GrpcTestFixture( urls[TestServerEndpointName.Http3WithTls] = IPEndpointInfoContainer.Create(listenOptions, isHttps: true); }); } -#endif }); _server.StartServer(); DynamicGrpc = _server.Host!.Services.GetRequiredService(); -#if !NET5_0 AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); -#endif (Client, Handler) = CreateHttpCore(defaultClientEndpointName); } @@ -221,7 +213,6 @@ public HttpClient CreateClient(TestServerEndpointName? endpointName = null, Dele configureHandler?.Invoke(socketsHttpHandler); -#if NET5_0_OR_GREATER if (endpointName == TestServerEndpointName.UnixDomainSocket) { var udsEndPoint = new UnixDomainSocketEndPoint(_server.GetUrl(endpointName.Value)); @@ -229,7 +220,6 @@ public HttpClient CreateClient(TestServerEndpointName? endpointName = null, Dele socketsHttpHandler.ConnectCallback = connectionFactory.ConnectAsync; } -#endif HttpClient client; HttpMessageHandler handler; @@ -243,23 +233,19 @@ public HttpClient CreateClient(TestServerEndpointName? endpointName = null, Dele handler = socketsHttpHandler; } -#if NET6_0_OR_GREATER if (endpointName == TestServerEndpointName.Http3WithTls) { // TODO(JamesNK): There is a bug with SocketsHttpHandler and HTTP/3 that prevents calls // upgrading from 2 to 3. Force HTTP/3 calls to require that protocol. handler = new Http3DelegatingHandler(handler); } -#endif client = new HttpClient(handler); if (endpointName == TestServerEndpointName.Http2) { client.DefaultRequestVersion = new Version(2, 0); -#if NET5_0_OR_GREATER client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher; -#endif } client.BaseAddress = CalculateBaseAddress(endpointName.Value); @@ -269,12 +255,10 @@ public HttpClient CreateClient(TestServerEndpointName? endpointName = null, Dele private Uri CalculateBaseAddress(TestServerEndpointName endpointName) { -#if NET5_0_OR_GREATER if (endpointName == TestServerEndpointName.UnixDomainSocket) { return new Uri("http://localhost"); } -#endif return new Uri(_server.GetUrl(endpointName)); } @@ -287,14 +271,10 @@ public Uri GetUrl(TestServerEndpointName endpointName) case TestServerEndpointName.Http2: case TestServerEndpointName.Http1WithTls: case TestServerEndpointName.Http2WithTls: -#if NET6_0_OR_GREATER case TestServerEndpointName.Http3WithTls: -#endif return new Uri(_server.GetUrl(endpointName)); -#if NET5_0_OR_GREATER case TestServerEndpointName.UnixDomainSocket: return new Uri("http://localhost"); -#endif default: throw new ArgumentException("Unexpected value: " + endpointName, nameof(endpointName)); } @@ -310,16 +290,13 @@ public void Dispose() { Client.Dispose(); _server.Dispose(); -#if NET5_0_OR_GREATER if (File.Exists(_socketPath)) { File.Delete(_socketPath); } -#endif } -#if NET6_0_OR_GREATER -private class Http3DelegatingHandler : DelegatingHandler + private class Http3DelegatingHandler : DelegatingHandler { public Http3DelegatingHandler(HttpMessageHandler innerHandler) { @@ -333,5 +310,4 @@ protected override Task SendAsync(HttpRequestMessage reques return base.SendAsync(request, cancellationToken); } } -#endif } diff --git a/test/FunctionalTests/Infrastructure/TestServerEndpointName.cs b/test/FunctionalTests/Infrastructure/TestServerEndpointName.cs index 07b2afb35..6af5d65ee 100644 --- a/test/FunctionalTests/Infrastructure/TestServerEndpointName.cs +++ b/test/FunctionalTests/Infrastructure/TestServerEndpointName.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -24,10 +24,6 @@ public enum TestServerEndpointName Http1, Http2WithTls, Http1WithTls, -#if NET5_0_OR_GREATER UnixDomainSocket, -#endif -#if NET6_0_OR_GREATER Http3WithTls, -#endif } diff --git a/test/FunctionalTests/Infrastructure/UnixDomainSocketConnectionFactory.cs b/test/FunctionalTests/Infrastructure/UnixDomainSocketConnectionFactory.cs index f36f32f9d..10e56e483 100644 --- a/test/FunctionalTests/Infrastructure/UnixDomainSocketConnectionFactory.cs +++ b/test/FunctionalTests/Infrastructure/UnixDomainSocketConnectionFactory.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -16,7 +16,6 @@ #endregion -#if NET5_0_OR_GREATER using System; using System.IO; using System.Net; @@ -52,4 +51,3 @@ public async ValueTask ConnectAsync(SocketsHttpConnectionContext _, Canc } } } -#endif diff --git a/test/FunctionalTests/Server/CompressionTests.cs b/test/FunctionalTests/Server/CompressionTests.cs index 856e39140..a683d1510 100644 --- a/test/FunctionalTests/Server/CompressionTests.cs +++ b/test/FunctionalTests/Server/CompressionTests.cs @@ -79,9 +79,7 @@ async Task UnaryEnableCompression(HelloRequest request, ServerCallCo } [TestCase("gzip")] -#if NET6_0_OR_GREATER [TestCase("deflate")] -#endif public async Task SendCompressedMessage_UnaryEnabledInCall_CompressedMessageReturned(string algorithmName) { async Task UnaryEnableCompression(HelloRequest request, ServerCallContext context) @@ -128,9 +126,7 @@ async Task UnaryEnableCompression(HelloRequest request, ServerCallCo } [TestCase("gzip")] -#if NET6_0_OR_GREATER [TestCase("deflate")] -#endif public async Task SendCompressedMessage_ServerStreamingEnabledInCall_CompressedMessageReturned(string algorithmName) { async Task ServerStreamingEnableCompression(HelloRequest request, IServerStreamWriter responseStream, ServerCallContext context) @@ -191,9 +187,7 @@ async Task ServerStreamingEnableCompression(HelloRequest request, IServerStreamW } [TestCase("gzip")] -#if NET6_0_OR_GREATER [TestCase("deflate")] -#endif public async Task SendCompressedMessage_ServiceHasNoCompressionConfigured_ResponseIdentityEncoding(string algorithmName) { // Arrange @@ -222,9 +216,7 @@ public async Task SendCompressedMessage_ServiceHasNoCompressionConfigured_Respon } [TestCase("gzip")] -#if NET6_0_OR_GREATER [TestCase("deflate")] -#endif public async Task SendCompressedMessageWithIdentity_ReturnInternalError(string algorithmName) { // Arrange @@ -291,12 +283,7 @@ public async Task SendUnsupportedEncodingHeaderWithUncompressedMessage_ReturnUnc public async Task SendCompressedMessageWithUnsupportedEncoding_ReturnUnimplemented() { // Arrange - var expectedError = -#if NET6_0_OR_GREATER - "Unsupported grpc-encoding value 'DOES_NOT_EXIST'. Supported encodings: identity, gzip, deflate"; -#else - "Unsupported grpc-encoding value 'DOES_NOT_EXIST'. Supported encodings: identity, gzip"; -#endif + var expectedError = "Unsupported grpc-encoding value 'DOES_NOT_EXIST'. Supported encodings: identity, gzip, deflate"; SetExpectedErrorsFilter(writeContext => { @@ -335,11 +322,7 @@ public async Task SendCompressedMessageWithUnsupportedEncoding_ReturnUnimplement // Assert Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); -#if NET6_0_OR_GREATER Assert.AreEqual("identity,gzip,deflate", response.Headers.GetValues(GrpcProtocolConstants.MessageAcceptEncodingHeader).Single()); -#else - Assert.AreEqual("identity,gzip", response.Headers.GetValues(GrpcProtocolConstants.MessageAcceptEncodingHeader).Single()); -#endif response.AssertTrailerStatus(StatusCode.Unimplemented, expectedError); @@ -389,9 +372,7 @@ public override long Position } [TestCase("gzip")] -#if NET6_0_OR_GREATER [TestCase("deflate")] -#endif public async Task SendCompressedMessageWithoutEncodingHeader_ServerErrorResponse(string algorithmName) { // Arrange @@ -432,9 +413,7 @@ public async Task SendCompressedMessageWithoutEncodingHeader_ServerErrorResponse [TestCase("gzip", "gzip", true)] [TestCase("gzip", "identity, gzip", true)] [TestCase("gzip", "gzip ", true)] -#if NET6_0_OR_GREATER [TestCase("deflate", "deflate", false)] -#endif public async Task SendCompressedMessageAndReturnResultWithNoCompressFlag_ResponseNotCompressed(string algorithmName, string messageAcceptEncoding, bool algorithmSupportedByServer) { // Arrange @@ -473,9 +452,7 @@ public async Task SendCompressedMessageAndReturnResultWithNoCompressFlag_Respons } [TestCase("gzip", true)] -#if NET6_0_OR_GREATER [TestCase("deflate", false)] -#endif public async Task SendUncompressedMessageToServiceWithCompression_ResponseCompressed(string algorithmName, bool algorithmSupportedByServer) { // Arrange diff --git a/test/FunctionalTests/TestServer/Helpers/GrpcTestFixture.cs b/test/FunctionalTests/TestServer/Helpers/GrpcTestFixture.cs index cb5782671..a7c931592 100644 --- a/test/FunctionalTests/TestServer/Helpers/GrpcTestFixture.cs +++ b/test/FunctionalTests/TestServer/Helpers/GrpcTestFixture.cs @@ -58,14 +58,10 @@ public GrpcTestFixture(Action? initialConfigureServices) _host = builder.Start(); _server = _host.GetTestServer(); -#if !NET5_0 // Need to set the response version to 2.0. // Required because of this TestServer issue - https://github.com/aspnet/AspNetCore/issues/16940 var handler = new ResponseVersionHandler(); handler.InnerHandler = _server.CreateHandler(); -#else - var handler = _server.CreateHandler(); -#endif var client = new HttpClient(handler); client.BaseAddress = new Uri("http://localhost"); @@ -84,7 +80,6 @@ public void Dispose() _server.Dispose(); } -#if !NET5_0 private class ResponseVersionHandler : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) @@ -95,7 +90,6 @@ protected override async Task SendAsync(HttpRequestMessage return response; } } -#endif public IDisposable GetTestContext() { diff --git a/test/FunctionalTests/Web/Client/ConnectionTests.cs b/test/FunctionalTests/Web/Client/ConnectionTests.cs index f544f029e..fcd47eaa6 100644 --- a/test/FunctionalTests/Web/Client/ConnectionTests.cs +++ b/test/FunctionalTests/Web/Client/ConnectionTests.cs @@ -70,23 +70,15 @@ private static IEnumerable ConnectionTestData() yield return new TestCaseData(TestServerEndpointName.Http2, "2.0", true); yield return new TestCaseData(TestServerEndpointName.Http2, "1.1", false); yield return new TestCaseData(TestServerEndpointName.Http2, null, true); -#if NET5_0_OR_GREATER // Specifing HTTP/2 doesn't work when the server is using TLS with HTTP/1.1 // Caused by using HttpVersionPolicy.RequestVersionOrHigher setting yield return new TestCaseData(TestServerEndpointName.Http1WithTls, "2.0", false); -#else - yield return new TestCaseData(TestServerEndpointName.Http1WithTls, "2.0", true); -#endif yield return new TestCaseData(TestServerEndpointName.Http1WithTls, "1.1", true); yield return new TestCaseData(TestServerEndpointName.Http1WithTls, null, true); yield return new TestCaseData(TestServerEndpointName.Http2WithTls, "2.0", true); -#if NET5_0_OR_GREATER // Specifing HTTP/1.1 does work when the server is using TLS with HTTP/2 // Caused by using HttpVersionPolicy.RequestVersionOrHigher setting yield return new TestCaseData(TestServerEndpointName.Http2WithTls, "1.1", true); -#else - yield return new TestCaseData(TestServerEndpointName.Http2WithTls, "1.1", false); -#endif yield return new TestCaseData(TestServerEndpointName.Http2WithTls, null, true); #if NET7_0_OR_GREATER yield return new TestCaseData(TestServerEndpointName.Http3WithTls, null, true); @@ -107,13 +99,11 @@ public async Task SendValidRequest_WithConnectionOptionsOnChannel(TestServerEndp private async Task SendRequestWithConnectionOptionsCore(TestServerEndpointName endpointName, string? version, bool success, bool setVersionOnHandler) { -#if NET6_0_OR_GREATER if (endpointName == TestServerEndpointName.Http3WithTls && !RequireHttp3Attribute.IsSupported(out var message)) { Assert.Ignore(message); } -#endif SetExpectedErrorsFilter(writeContext => { diff --git a/test/FunctionalTests/Web/GrpcWebFunctionalTestBase.cs b/test/FunctionalTests/Web/GrpcWebFunctionalTestBase.cs index 4e6cabc5e..8dc8c2385 100644 --- a/test/FunctionalTests/Web/GrpcWebFunctionalTestBase.cs +++ b/test/FunctionalTests/Web/GrpcWebFunctionalTestBase.cs @@ -40,13 +40,11 @@ protected GrpcWebFunctionalTestBase(GrpcTestMode grpcTestMode, TestServerEndpoin GrpcTestMode = grpcTestMode; EndpointName = endpointName; -#if NET6_0_OR_GREATER if (endpointName == TestServerEndpointName.Http3WithTls && !RequireHttp3Attribute.IsSupported(out var message)) { Assert.Ignore(message); } -#endif } protected HttpClient CreateGrpcWebClient() @@ -71,12 +69,10 @@ protected HttpClient CreateGrpcWebClient() { protocol = new Version(1, 1); } -#if NET6_0_OR_GREATER else if (EndpointName == TestServerEndpointName.Http3WithTls) { protocol = new Version(3, 0); } -#endif else { protocol = new Version(2, 0); diff --git a/test/Grpc.AspNetCore.Server.Tests/CallHandlerTests.cs b/test/Grpc.AspNetCore.Server.Tests/CallHandlerTests.cs index 369495fbb..4f3af453a 100644 --- a/test/Grpc.AspNetCore.Server.Tests/CallHandlerTests.cs +++ b/test/Grpc.AspNetCore.Server.Tests/CallHandlerTests.cs @@ -150,27 +150,6 @@ public async Task ProtocolValidation_InvalidProtocol_FailureLogged() Assert.AreEqual("Request protocol of 'HTTP/1.1' is not supported.", log!.Message); } -#if !NET5_0_OR_GREATER - // .NET Core 3.0 + IIS returned HTTP/2.0 as the protocol - [Test] - public async Task ProtocolValidation_IISHttp2Protocol_Success() - { - // Arrange - var testSink = new TestSink(); - var testLoggerFactory = new TestLoggerFactory(testSink, true); - - var httpContext = HttpContextHelpers.CreateContext(protocol: GrpcProtocolConstants.Http20Protocol); - var call = CreateHandler(MethodType.ClientStreaming, testLoggerFactory); - - // Act - await call.HandleCallAsync(httpContext).DefaultTimeout(); - - // Assert - var log = testSink.Writes.SingleOrDefault(w => w.EventId.Name == "UnsupportedRequestProtocol"); - Assert.IsNull(log); - } -#endif - #if NET8_0_OR_GREATER [TestCase(MethodType.Unary, false)] [TestCase(MethodType.ClientStreaming, true)] diff --git a/test/Grpc.AspNetCore.Server.Tests/GrpcServicesExtensionsTests.cs b/test/Grpc.AspNetCore.Server.Tests/GrpcServicesExtensionsTests.cs index a1f3ad5fc..f5f756ca0 100644 --- a/test/Grpc.AspNetCore.Server.Tests/GrpcServicesExtensionsTests.cs +++ b/test/Grpc.AspNetCore.Server.Tests/GrpcServicesExtensionsTests.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -48,14 +48,9 @@ public void AddGrpc_ConfigureOptions_OptionsSet() Assert.AreEqual(GrpcServiceOptionsSetup.DefaultReceiveMaxMessageSize, options.MaxReceiveMessageSize); Assert.AreEqual(1, options.MaxSendMessageSize); -#if NET6_0_OR_GREATER Assert.AreEqual(2, options.CompressionProviders.Count); Assert.AreEqual("gzip", options.CompressionProviders[0].EncodingName); Assert.AreEqual("deflate", options.CompressionProviders[1].EncodingName); -#else - Assert.AreEqual(1, options.CompressionProviders.Count); - Assert.AreEqual("gzip", options.CompressionProviders[0].EncodingName); -#endif } [Test] diff --git a/test/Grpc.AspNetCore.Server.Tests/HttpContextServerCallContextTests.cs b/test/Grpc.AspNetCore.Server.Tests/HttpContextServerCallContextTests.cs index 63f357cff..fd4a6aff8 100644 --- a/test/Grpc.AspNetCore.Server.Tests/HttpContextServerCallContextTests.cs +++ b/test/Grpc.AspNetCore.Server.Tests/HttpContextServerCallContextTests.cs @@ -603,9 +603,7 @@ public void RequestHeaders_ManyHttpRequestHeaders_HeadersFiltered(string headerN } [TestCase("HTTP/2", GrpcProtocolConstants.Http2ResetStreamCancel)] -#if NET6_0_OR_GREATER [TestCase("HTTP/3", GrpcProtocolConstants.Http3ResetStreamCancel)] -#endif public Task EndCallAsync_LongRunningDeadlineAbort_WaitsUntilDeadlineAbortIsFinished( string protocol, int expectedResetCode) @@ -618,9 +616,7 @@ public Task EndCallAsync_LongRunningDeadlineAbort_WaitsUntilDeadlineAbortIsFinis } [TestCase("HTTP/2", GrpcProtocolConstants.Http2ResetStreamCancel)] -#if NET6_0_OR_GREATER [TestCase("HTTP/3", GrpcProtocolConstants.Http3ResetStreamCancel)] -#endif public Task ProcessHandlerErrorAsync_LongRunningDeadlineAbort_WaitsUntilDeadlineAbortIsFinished( string protocol, int expectedResetCode) diff --git a/test/Shared/MessageHelpers.cs b/test/Shared/MessageHelpers.cs index 8858d18b3..7534a58cd 100644 --- a/test/Shared/MessageHelpers.cs +++ b/test/Shared/MessageHelpers.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -30,12 +30,10 @@ namespace Grpc.Tests.Shared; internal static class MessageHelpers { private static readonly List DefaultProviders = new List - { - new GzipCompressionProvider(CompressionLevel.Fastest), -#if NET6_0_OR_GREATER - new DeflateCompressionProvider(CompressionLevel.Fastest), -#endif - }; + { + new GzipCompressionProvider(CompressionLevel.Fastest), + new DeflateCompressionProvider(CompressionLevel.Fastest), + }; public static Marshaller GetMarshaller(MessageParser parser) where TMessage : IMessage => Marshallers.Create(r => r.ToByteArray(), data => parser.ParseFrom(data)); From 3ed9fb9f31474b4d1318051123a37d9b6f68cda4 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 7 Sep 2024 14:08:46 +0800 Subject: [PATCH 2/9] Log server cancellation errors at info level (#2527) --- src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs | 10 +++++++++- .../Internal/HttpContextServerCallContext.cs | 11 ++++++++++- test/FunctionalTests/Client/StreamingTests.cs | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs b/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs index b93fde101..884a6021d 100644 --- a/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs +++ b/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -104,6 +104,9 @@ internal static class GrpcServerLog private static readonly Action _deadlineStopped = LoggerMessage.Define(LogLevel.Trace, new EventId(27, "DeadlineStopped"), "Request deadline stopped."); + private static readonly Action _serviceMethodCanceled = + LoggerMessage.Define(LogLevel.Information, new EventId(28, "ServiceMethodCanceled"), "Service method '{ServiceMethod}' canceled."); + internal static void DeadlineStopped(ILogger logger) { _deadlineStopped(logger, null); @@ -238,4 +241,9 @@ public static void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining) { _deadlineTimerRescheduled(logger, remaining, null); } + + public static void ServiceMethodCanceled(ILogger logger, string serviceMethod, Exception ex) + { + _serviceMethodCanceled(logger, serviceMethod, ex); + } } diff --git a/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs b/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs index f4ef272e0..7f26bc046 100644 --- a/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs +++ b/src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs @@ -193,7 +193,16 @@ private void ProcessHandlerError(Exception ex, string method) } else { - GrpcServerLog.ErrorExecutingServiceMethod(Logger, method, ex); + if (ex is OperationCanceledException or IOException && CancellationTokenCore.IsCancellationRequested) + { + // Request cancellation can cause OCE and IOException. + // When the request has been canceled log these error types at the info-level to avoid creating error-level noise. + GrpcServerLog.ServiceMethodCanceled(Logger, method, ex); + } + else + { + GrpcServerLog.ErrorExecutingServiceMethod(Logger, method, ex); + } var message = ErrorMessageHelper.BuildErrorMessage("Exception was thrown by handler.", ex, Options.EnableDetailedErrors); diff --git a/test/FunctionalTests/Client/StreamingTests.cs b/test/FunctionalTests/Client/StreamingTests.cs index 8bc2c7d6e..dbe7194c7 100644 --- a/test/FunctionalTests/Client/StreamingTests.cs +++ b/test/FunctionalTests/Client/StreamingTests.cs @@ -429,7 +429,7 @@ async Task ClientStreamedData(IAsyncStreamReader requ AssertHasLog(LogLevel.Information, "GrpcStatusError", "Call failed with gRPC error status. Status code: 'Cancelled', Message: ''."); await TestHelpers.AssertIsTrueRetryAsync( - () => HasLog(LogLevel.Error, "ErrorExecutingServiceMethod", "Error when executing service method 'ClientStreamedDataTimeout'."), + () => HasLog(LogLevel.Information, "ServiceMethodCanceled", "Service method 'ClientStreamedDataTimeout' canceled."), "Wait for server error so it doesn't impact other tests.").DefaultTimeout(); } From de9a82fe8eae0d40b70edbe04a766e3ac0ad8d54 Mon Sep 17 00:00:00 2001 From: Noam Greenberg <106929496+wabalubdub@users.noreply.github.com> Date: Thu, 12 Sep 2024 17:31:10 +0300 Subject: [PATCH 3/9] Update logging to use generated logs (#2531) --- .../GrpcHealthChecksPublisher.cs | 21 +- .../ContextPropagationInterceptor.cs | 13 +- .../GrpcReflectionServiceExtensions.cs | 11 +- .../Internal/GrpcServerLog.cs | 254 ++++-------------- .../Internal/ServerCallHandlerFactory.cs | 20 +- .../Internal/BinderServiceModelProvider.cs | 11 +- .../Model/Internal/ServiceRouteBuilder.cs | 26 +- .../Internal/GrpcWebMiddleware.cs | 33 +-- src/Grpc.Net.Client/Balancer/DnsResolver.cs | 44 +-- .../Balancer/Internal/BalancerHttpHandler.cs | 18 +- .../Balancer/Internal/ConnectionManager.cs | 116 ++------ .../SocketConnectivitySubchannelTransport.cs | 155 +++-------- .../Balancer/PickFirstBalancer.cs | 17 +- .../Balancer/PollingResolver.cs | 66 ++--- src/Grpc.Net.Client/Balancer/Subchannel.cs | 177 ++++-------- .../Balancer/SubchannelsLoadBalancer.cs | 52 ++-- src/Grpc.Net.Client/GrpcChannel.cs | 13 +- .../Internal/ClientStreamWriterBase.cs | 29 +- src/Grpc.Net.Client/Internal/GrpcCallLog.cs | 238 ++++------------ .../Internal/HttpContentClientStreamReader.cs | 11 +- .../Internal/Retry/ChannelRetryThrottling.cs | 13 +- .../Internal/Retry/RetryCallBaseLog.cs | 121 ++------- .../Internal/GrpcCallInvokerFactory.cs | 13 +- 23 files changed, 384 insertions(+), 1088 deletions(-) diff --git a/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs b/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs index 36ecd8a28..7fee5bfe5 100644 --- a/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs +++ b/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs @@ -25,7 +25,7 @@ namespace Grpc.AspNetCore.HealthChecks; -internal sealed class GrpcHealthChecksPublisher : IHealthCheckPublisher +internal sealed partial class GrpcHealthChecksPublisher : IHealthCheckPublisher { private readonly HealthServiceImpl _healthService; private readonly ILogger _logger; @@ -75,22 +75,13 @@ public Task PublishAsync(HealthReport report, CancellationToken cancellationToke return Task.CompletedTask; } - private static class Log + private static partial class Log { - private static readonly Action _evaluatingPublishedHealthReport = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "EvaluatingPublishedHealthReport"), "Evaluating {HealthReportEntryCount} published health report entries against {ServiceMappingCount} service mappings."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "EvaluatingPublishedHealthReport", Message = "Evaluating {HealthReportEntryCount} published health report entries against {ServiceMappingCount} service mappings.")] + public static partial void EvaluatingPublishedHealthReport(ILogger logger, int healthReportEntryCount, int serviceMappingCount); - private static readonly Action _serviceMappingStatusUpdated = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "ServiceMappingStatusUpdated"), "Service '{ServiceName}' status updated to {Status}. {EntriesCount} health report entries evaluated."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "ServiceMappingStatusUpdated", Message = "Service '{ServiceName}' status updated to {Status}. {EntriesCount} health report entries evaluated.")] + public static partial void ServiceMappingStatusUpdated(ILogger logger, string serviceName, HealthCheckResponse.Types.ServingStatus status, int entriesCount); - public static void EvaluatingPublishedHealthReport(ILogger logger, int healthReportEntryCount, int serviceMappingCount) - { - _evaluatingPublishedHealthReport(logger, healthReportEntryCount, serviceMappingCount, null); - } - - public static void ServiceMappingStatusUpdated(ILogger logger, string serviceName, HealthCheckResponse.Types.ServingStatus status, int entriesCount) - { - _serviceMappingStatusUpdated(logger, serviceName, status, entriesCount, null); - } } } diff --git a/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs b/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs index d2baa257b..651996b96 100644 --- a/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs +++ b/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs @@ -30,7 +30,7 @@ namespace Grpc.AspNetCore.ClientFactory; /// The interceptor gets the request from IHttpContextAccessor, which is a singleton. /// IHttpContextAccessor uses an async local value. /// -internal class ContextPropagationInterceptor : Interceptor +internal partial class ContextPropagationInterceptor : Interceptor { private readonly GrpcContextPropagationOptions _options; private readonly IHttpContextAccessor _httpContextAccessor; @@ -258,15 +258,10 @@ public async Task MoveNext(CancellationToken cancellationToken) } } - private static class Log + private static partial class Log { - private static readonly Action _propagateServerCallContextFailure = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "PropagateServerCallContextFailure"), "Unable to propagate server context values to the call. {ErrorMessage}"); - - public static void PropagateServerCallContextFailure(ILogger logger, string errorMessage) - { - _propagateServerCallContextFailure(logger, errorMessage, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "PropagateServerCallContextFailure", Message = "Unable to propagate server context values to the call. {ErrorMessage}")] + public static partial void PropagateServerCallContextFailure(ILogger logger, string errorMessage); } // Store static callbacks so delegates are allocated once diff --git a/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs b/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs index c8e3770f8..a236ab412 100644 --- a/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs +++ b/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs @@ -31,7 +31,7 @@ namespace Microsoft.Extensions.DependencyInjection; /// /// Extension methods for the gRPC reflection services. /// -public static class GrpcReflectionServiceExtensions +public static partial class GrpcReflectionServiceExtensions { /// /// Adds gRPC reflection services to the specified . @@ -150,14 +150,13 @@ public static IServiceCollection AddGrpcReflection(this IServiceCollection servi return baseType; } - private static class Log + private static partial class Log { - private static readonly Action _serviceDescriptorNotResolved = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "ServiceDescriptorNotResolved"), "Could not resolve service descriptor for '{ServiceType}'. The service metadata will not be exposed by the reflection service."); - + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "ServiceDescriptorNotResolved", Message = "Could not resolve service descriptor for '{ServiceType}'. The service metadata will not be exposed by the reflection service.")] + private static partial void ServiceDescriptorNotResolved(ILogger logger, string serviceType); public static void ServiceDescriptorNotResolved(ILogger logger, Type serviceType) { - _serviceDescriptorNotResolved(logger, serviceType.FullName ?? string.Empty, null); + ServiceDescriptorNotResolved(logger, serviceType.FullName ?? string.Empty); } } } diff --git a/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs b/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs index 884a6021d..73e991554 100644 --- a/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs +++ b/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs @@ -21,229 +21,89 @@ namespace Grpc.AspNetCore.Server.Internal; -internal static class GrpcServerLog +internal static partial class GrpcServerLog { - private static readonly Action _unableToDisableMaxRequestBodySize = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "UnableToDisableMaxRequestBodySizeLimit"), "Unable to disable the max request body size limit."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "UnableToDisableMaxRequestBodySizeLimit", Message = "Unable to disable the max request body size limit.")] + public static partial void UnableToDisableMaxRequestBodySize(ILogger logger); - private static readonly Action _unsupportedRequestContentType = - LoggerMessage.Define(LogLevel.Information, new EventId(2, "UnsupportedRequestContentType"), "Request content-type of '{ContentType}' is not supported."); + [LoggerMessage(Level = LogLevel.Information, EventId = 2, EventName = "UnsupportedRequestContentType", Message = "Request content-type of '{ContentType}' is not supported.")] + public static partial void UnsupportedRequestContentType(ILogger logger, string? contentType); - private static readonly Action _unsupportedRequestProtocol = - LoggerMessage.Define(LogLevel.Information, new EventId(3, "UnsupportedRequestProtocol"), "Request protocol of '{Protocol}' is not supported."); + [LoggerMessage(Level = LogLevel.Information, EventId = 3, EventName = "UnsupportedRequestProtocol", Message = "Request protocol of '{Protocol}' is not supported.")] + public static partial void UnsupportedRequestProtocol(ILogger logger, string? protocol); - private static readonly Action _deadlineExceeded = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "DeadlineExceeded"), "Request with timeout of {Timeout} has exceeded its deadline."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 4, EventName = "DeadlineExceeded", Message = "Request with timeout of {Timeout} has exceeded its deadline.")] + public static partial void DeadlineExceeded(ILogger logger, TimeSpan timeout); - private static readonly Action _invalidTimeoutIgnored = - LoggerMessage.Define(LogLevel.Debug, new EventId(5, "InvalidTimeoutIgnored"), "Invalid grpc-timeout header value '{Timeout}' has been ignored."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 5, EventName = "InvalidTimeoutIgnored", Message = "Invalid grpc-timeout header value '{Timeout}' has been ignored.")] + public static partial void InvalidTimeoutIgnored(ILogger logger, string timeout); - private static readonly Action _errorExecutingServiceMethod = - LoggerMessage.Define(LogLevel.Error, new EventId(6, "ErrorExecutingServiceMethod"), "Error when executing service method '{ServiceMethod}'."); + [LoggerMessage(Level = LogLevel.Error, EventId = 6, EventName = "ErrorExecutingServiceMethod", Message = "Error when executing service method '{ServiceMethod}'.")] + public static partial void ErrorExecutingServiceMethod(ILogger logger, string serviceMethod, Exception ex); - private static readonly Action _rpcConnectionError = - LoggerMessage.Define(LogLevel.Information, new EventId(7, "RpcConnectionError"), "Error status code '{StatusCode}' with detail '{Detail}' raised."); + [LoggerMessage(Level = LogLevel.Information, EventId = 7, EventName = "RpcConnectionError", Message = "Error status code '{StatusCode}' with detail '{Detail}' raised.")] + public static partial void RpcConnectionError(ILogger logger, StatusCode statusCode, string detail, Exception? debugException); - private static readonly Action _encodingNotInAcceptEncoding = - LoggerMessage.Define(LogLevel.Debug, new EventId(8, "EncodingNotInAcceptEncoding"), "Request grpc-encoding header value '{GrpcEncoding}' is not in grpc-accept-encoding."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 8, EventName = "EncodingNotInAcceptEncoding", Message = "Request grpc-encoding header value '{GrpcEncoding}' is not in grpc-accept-encoding.")] + public static partial void EncodingNotInAcceptEncoding(ILogger logger, string grpcEncoding); - private static readonly Action _deadlineCancellationError = - LoggerMessage.Define(LogLevel.Error, new EventId(9, "DeadlineCancellationError"), "Error occurred while trying to cancel the request due to deadline exceeded."); + [LoggerMessage(Level = LogLevel.Error, EventId = 9, EventName = "DeadlineCancellationError", Message = "Error occurred while trying to cancel the request due to deadline exceeded.")] + public static partial void DeadlineCancellationError(ILogger logger, Exception ex); - private static readonly Action _readingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(10, "ReadingMessage"), "Reading message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 10, EventName = "ReadingMessage", Message = "Reading message.")] + public static partial void ReadingMessage(ILogger logger); - private static readonly Action _noMessageReturned = - LoggerMessage.Define(LogLevel.Trace, new EventId(11, "NoMessageReturned"), "No message returned."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 11, EventName = "NoMessageReturned", Message = "No message returned.")] + public static partial void NoMessageReturned(ILogger logger); - private static readonly Action _deserializingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(12, "DeserializingMessage"), "Deserializing {MessageLength} byte message to '{MessageType}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 12, EventName = "DeserializingMessage", Message = "Deserializing {MessageLength} byte message to '{MessageType}'.")] + public static partial void DeserializingMessage(ILogger logger, int messageLength, Type messageType); - private static readonly Action _receivedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(13, "ReceivedMessage"), "Received message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 13, EventName = "ReceivedMessage", Message = "Received message.")] + public static partial void ReceivedMessage(ILogger logger); - private static readonly Action _errorReadingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(14, "ErrorReadingMessage"), "Error reading message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 14, EventName = "ErrorReadingMessage", Message = "Error reading message.")] + public static partial void ErrorReadingMessage(ILogger logger, Exception ex); - private static readonly Action _sendingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(15, "SendingMessage"), "Sending message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 15, EventName = "SendingMessage", Message = "Sending message.")] + public static partial void SendingMessage(ILogger logger); - private static readonly Action _messageSent = - LoggerMessage.Define(LogLevel.Trace, new EventId(16, "MessageSent"), "Message sent."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 16, EventName = "MessageSent", Message = "Message sent.")] + public static partial void MessageSent(ILogger logger); - private static readonly Action _errorSendingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(17, "ErrorSendingMessage"), "Error sending message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 17, EventName = "ErrorSendingMessage", Message = "Error sending message.")] + public static partial void ErrorSendingMessage(ILogger logger, Exception ex); - private static readonly Action _serializedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(18, "SerializedMessage"), "Serialized '{MessageType}' to {MessageLength} byte message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 18, EventName = "SerializedMessage", Message = "Serialized '{MessageType}' to {MessageLength} byte message.")] + public static partial void SerializedMessage(ILogger logger, Type messageType, int messageLength); - private static readonly Action _compressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(19, "CompressingMessage"), "Compressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 19, EventName = "CompressingMessage", Message = "Compressing message with '{MessageEncoding}' encoding.")] + public static partial void CompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _decompressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(20, "DecompressingMessage"), "Decompressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 20, EventName = "DecompressingMessage", Message = "Decompressing message with '{MessageEncoding}' encoding.")] + public static partial void DecompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _resettingResponse = - LoggerMessage.Define(LogLevel.Debug, new EventId(21, "ResettingResponse"), "Resetting response stream with error code {ErrorCode}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 21, EventName = "ResettingResponse", Message = "Resetting response stream with error code {ErrorCode}.")] + public static partial void ResettingResponse(ILogger logger, int errorCode); - private static readonly Action _abortingResponse = - LoggerMessage.Define(LogLevel.Debug, new EventId(22, "AbortingResponse"), "IHttpResetFeature is not available so unable to cleanly reset response stream. Aborting response stream."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 22, EventName = "AbortingResponse", Message = "IHttpResetFeature is not available so unable to cleanly reset response stream. Aborting response stream.")] + public static partial void AbortingResponse(ILogger logger); - private static readonly Action _unhandledCorsPreflightRequest = - LoggerMessage.Define(LogLevel.Information, new EventId(23, "UnhandledCorsPreflightRequest"), "Unhandled CORS preflight request received. CORS may not be configured correctly in the application."); + [LoggerMessage(Level = LogLevel.Information, EventId = 23, EventName = "UnhandledCorsPreflightRequest", Message = "Unhandled CORS preflight request received. CORS may not be configured correctly in the application.")] + public static partial void UnhandledCorsPreflightRequest(ILogger logger); - private static readonly Action _deadlineTimeoutTooLong = - LoggerMessage.Define(LogLevel.Debug, new EventId(24, "DeadlineTimeoutTooLong"), "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 24, EventName = "DeadlineTimeoutTooLong", Message = "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used.")] + public static partial void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout); - private static readonly Action _deadlineTimerRescheduled = - LoggerMessage.Define(LogLevel.Trace, new EventId(25, "DeadlineTimerRescheduled"), "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 25, EventName = "DeadlineTimerRescheduled", Message = "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled.")] + public static partial void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining); - private static readonly Action _deadlineStarted = - LoggerMessage.Define(LogLevel.Trace, new EventId(26, "DeadlineStarted"), "Request deadline timeout of {Timeout} started."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 26, EventName = "DeadlineStarted", Message = "Request deadline timeout of {Timeout} started.")] + public static partial void DeadlineStarted(ILogger logger, TimeSpan timeout); - private static readonly Action _deadlineStopped = - LoggerMessage.Define(LogLevel.Trace, new EventId(27, "DeadlineStopped"), "Request deadline stopped."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 27, EventName = "DeadlineStopped", Message = "Request deadline stopped.")] + internal static partial void DeadlineStopped(ILogger logger); - private static readonly Action _serviceMethodCanceled = - LoggerMessage.Define(LogLevel.Information, new EventId(28, "ServiceMethodCanceled"), "Service method '{ServiceMethod}' canceled."); - - internal static void DeadlineStopped(ILogger logger) - { - _deadlineStopped(logger, null); - } - - public static void DeadlineStarted(ILogger logger, TimeSpan timeout) - { - _deadlineStarted(logger, timeout, null); - } - - public static void DeadlineExceeded(ILogger logger, TimeSpan timeout) - { - _deadlineExceeded(logger, timeout, null); - } - - public static void InvalidTimeoutIgnored(ILogger logger, string timeout) - { - _invalidTimeoutIgnored(logger, timeout, null); - } - - public static void ErrorExecutingServiceMethod(ILogger logger, string serviceMethod, Exception ex) - { - _errorExecutingServiceMethod(logger, serviceMethod, ex); - } - - public static void RpcConnectionError(ILogger logger, StatusCode statusCode, string detail, Exception? debugException) - { - _rpcConnectionError(logger, statusCode, detail, debugException); - } - - public static void EncodingNotInAcceptEncoding(ILogger logger, string grpcEncoding) - { - _encodingNotInAcceptEncoding(logger, grpcEncoding, null); - } - - public static void DeadlineCancellationError(ILogger logger, Exception ex) - { - _deadlineCancellationError(logger, ex); - } - - public static void UnableToDisableMaxRequestBodySize(ILogger logger) - { - _unableToDisableMaxRequestBodySize(logger, null); - } - - public static void UnsupportedRequestContentType(ILogger logger, string? contentType) - { - _unsupportedRequestContentType(logger, contentType, null); - } - - public static void UnsupportedRequestProtocol(ILogger logger, string? protocol) - { - _unsupportedRequestProtocol(logger, protocol, null); - } - - public static void ReadingMessage(ILogger logger) - { - _readingMessage(logger, null); - } - - public static void NoMessageReturned(ILogger logger) - { - _noMessageReturned(logger, null); - } - - public static void DeserializingMessage(ILogger logger, int messageLength, Type messageType) - { - _deserializingMessage(logger, messageLength, messageType, null); - } - - public static void ReceivedMessage(ILogger logger) - { - _receivedMessage(logger, null); - } - - public static void ErrorReadingMessage(ILogger logger, Exception ex) - { - _errorReadingMessage(logger, ex); - } - - public static void SendingMessage(ILogger logger) - { - _sendingMessage(logger, null); - } - - public static void MessageSent(ILogger logger) - { - _messageSent(logger, null); - } - - public static void ErrorSendingMessage(ILogger logger, Exception ex) - { - _errorSendingMessage(logger, ex); - } - - public static void SerializedMessage(ILogger logger, Type messageType, int messageLength) - { - _serializedMessage(logger, messageType, messageLength, null); - } - - public static void CompressingMessage(ILogger logger, string messageEncoding) - { - _compressingMessage(logger, messageEncoding, null); - } - - public static void DecompressingMessage(ILogger logger, string messageEncoding) - { - _decompressingMessage(logger, messageEncoding, null); - } - - public static void ResettingResponse(ILogger logger, int errorCode) - { - _resettingResponse(logger, errorCode, null); - } - - public static void AbortingResponse(ILogger logger) - { - _abortingResponse(logger, null); - } - - public static void UnhandledCorsPreflightRequest(ILogger logger) - { - _unhandledCorsPreflightRequest(logger, null); - } - - public static void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout) - { - _deadlineTimeoutTooLong(logger, timeout, null); - } - - public static void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining) - { - _deadlineTimerRescheduled(logger, remaining, null); - } - - public static void ServiceMethodCanceled(ILogger logger, string serviceMethod, Exception ex) - { - _serviceMethodCanceled(logger, serviceMethod, ex); - } + [LoggerMessage(Level = LogLevel.Information, EventId = 28, EventName = "ServiceMethodCanceled", Message = "Service method '{ServiceMethod}' canceled.")] + public static partial void ServiceMethodCanceled(ILogger logger, string serviceMethod, Exception ex); } diff --git a/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs b/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs index 9d41c3520..95d545942 100644 --- a/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs +++ b/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs @@ -154,21 +154,11 @@ public RequestDelegate CreateUnimplementedService() } } -internal static class ServerCallHandlerFactoryLog +internal static partial class ServerCallHandlerFactoryLog { - private static readonly Action _serviceUnimplemented = - LoggerMessage.Define(LogLevel.Information, new EventId(1, "ServiceUnimplemented"), "Service '{ServiceName}' is unimplemented."); + [LoggerMessage(Level = LogLevel.Information, EventId = 1, EventName = "ServiceUnimplemented", Message = "Service '{ServiceName}' is unimplemented.")] + public static partial void ServiceUnimplemented(ILogger logger, string serviceName); - private static readonly Action _methodUnimplemented = - LoggerMessage.Define(LogLevel.Information, new EventId(2, "MethodUnimplemented"), "Method '{MethodName}' is unimplemented."); - - public static void ServiceUnimplemented(ILogger logger, string serviceName) - { - _serviceUnimplemented(logger, serviceName, null); - } - - public static void MethodUnimplemented(ILogger logger, string methodName) - { - _methodUnimplemented(logger, methodName, null); - } + [LoggerMessage(Level = LogLevel.Information, EventId = 2, EventName = "MethodUnimplemented", Message = "Method '{MethodName}' is unimplemented.")] + public static partial void MethodUnimplemented(ILogger logger, string methodName); } diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs b/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs index db6fce070..101ee27e6 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs @@ -61,13 +61,8 @@ public void OnServiceMethodDiscovery(ServiceMethodProviderContext cont } } -internal static class BinderServiceMethodProviderLog +internal static partial class BinderServiceMethodProviderLog { - private static readonly Action _bindMethodNotFound = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "BindMethodNotFound"), "Could not find bind method for {ServiceType}."); - - public static void BindMethodNotFound(ILogger logger, Type serviceType) - { - _bindMethodNotFound(logger, serviceType, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "BindMethodNotFound", Message = "Could not find bind method for {ServiceType}.")] + public static partial void BindMethodNotFound(ILogger logger, Type serviceType); } diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs b/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs index 83d8875ae..dc3613ffa 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs @@ -156,16 +156,10 @@ private static IEndpointConventionBuilder CreateUnimplementedEndpoint(IEndpointR } } -internal static class ServiceRouteBuilderLog +internal static partial class ServiceRouteBuilderLog { - private static readonly Action _addedServiceMethod = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "AddedServiceMethod"), "Added gRPC method '{MethodName}' to service '{ServiceName}'. Method type: {MethodType}, HTTP method: {HttpMethod}, route pattern: '{RoutePattern}'."); - - private static readonly Action _discoveringServiceMethods = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "DiscoveringServiceMethods"), "Discovering gRPC methods for {ServiceType}."); - - private static readonly Action _noServiceMethodsDiscovered = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "NoServiceMethodsDiscovered"), "No gRPC methods discovered for {ServiceType}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "AddedServiceMethod", Message = "Added gRPC method '{MethodName}' to service '{ServiceName}'. Method type: {MethodType}, HTTP method: {HttpMethod}, route pattern: '{RoutePattern}'.")] + private static partial void AddedServiceMethod(ILogger logger, string methodName, string serviceName, MethodType methodType, string HttpMethod, string routePattern); public static void AddedServiceMethod(ILogger logger, string methodName, string serviceName, MethodType methodType, IReadOnlyList httpMethods, string routePattern) { @@ -174,17 +168,13 @@ public static void AddedServiceMethod(ILogger logger, string methodName, string // There should be one HTTP method here, but concat in case someone has overriden metadata. var allHttpMethods = string.Join(',', httpMethods); - _addedServiceMethod(logger, methodName, serviceName, methodType, allHttpMethods, routePattern, null); + AddedServiceMethod(logger, methodName, serviceName, methodType, allHttpMethods, routePattern); } } - public static void DiscoveringServiceMethods(ILogger logger, Type serviceType) - { - _discoveringServiceMethods(logger, serviceType, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "DiscoveringServiceMethods", Message = "Discovering gRPC methods for {ServiceType}.")] + public static partial void DiscoveringServiceMethods(ILogger logger, Type serviceType); - public static void NoServiceMethodsDiscovered(ILogger logger, Type serviceType) - { - _noServiceMethodsDiscovered(logger, serviceType, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "NoServiceMethodsDiscovered", Message = "No gRPC methods discovered for {ServiceType}.")] + public static partial void NoServiceMethodsDiscovered(ILogger logger, Type serviceType); } diff --git a/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs b/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs index ece1298f3..a10ba975f 100644 --- a/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs +++ b/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -24,7 +24,7 @@ namespace Grpc.AspNetCore.Web.Internal; -internal sealed class GrpcWebMiddleware +internal sealed partial class GrpcWebMiddleware { private readonly GrpcWebOptions _options; private readonly ILogger _logger; @@ -158,30 +158,15 @@ private static bool TryGetWebMode(string? contentType, out ServerGrpcWebMode mod return false; } - private static class Log + private static partial class Log { - private static readonly Action _detectedGrpcWebRequest = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "DetectedGrpcWebRequest"), "Detected gRPC-Web request from content-type '{ContentType}'."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "DetectedGrpcWebRequest", Message = "Detected gRPC-Web request from content-type '{ContentType}'.")] + public static partial void DetectedGrpcWebRequest(ILogger logger, string contentType); - private static readonly Action _grpcWebRequestNotProcessed = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "GrpcWebRequestNotProcessed"), $"gRPC-Web request not processed. gRPC-Web must be enabled by placing the [EnableGrpcWeb] attribute on a service or method, or enable for all services in the app with {nameof(GrpcWebOptions)}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "GrpcWebRequestNotProcessed", Message = $"gRPC-Web request not processed. gRPC-Web must be enabled by placing the [EnableGrpcWeb] attribute on a service or method, or enable for all services in the app with {nameof(GrpcWebOptions)}.")] + public static partial void GrpcWebRequestNotProcessed(ILogger logger); - private static readonly Action _sendingGrpcWebResponse = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "SendingGrpcWebResponse"), "Sending gRPC-Web response with content-type '{ContentType}'."); - - public static void DetectedGrpcWebRequest(ILogger logger, string contentType) - { - _detectedGrpcWebRequest(logger, contentType, null); - } - - public static void GrpcWebRequestNotProcessed(ILogger logger) - { - _grpcWebRequestNotProcessed(logger, null); - } - - public static void SendingGrpcWebResponse(ILogger logger, string contentType) - { - _sendingGrpcWebResponse(logger, contentType, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "SendingGrpcWebResponse", Message = "Sending gRPC-Web response with content-type '{ContentType}'.")] + public static partial void SendingGrpcWebResponse(ILogger logger, string contentType); } } diff --git a/src/Grpc.Net.Client/Balancer/DnsResolver.cs b/src/Grpc.Net.Client/Balancer/DnsResolver.cs index 2ae026594..d8cb1b39e 100644 --- a/src/Grpc.Net.Client/Balancer/DnsResolver.cs +++ b/src/Grpc.Net.Client/Balancer/DnsResolver.cs @@ -145,50 +145,30 @@ private void OnTimerCallback(object? state) } } -internal static class DnsResolverLog +internal static partial class DnsResolverLog { - private static readonly Action _startingRateLimitDelay = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "StartingRateLimitDelay"), "Starting rate limit delay of {DelayDuration}. DNS resolution rate limit is once every {RateLimitDuration}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "StartingRateLimitDelay", Message = "Starting rate limit delay of {DelayDuration}. DNS resolution rate limit is once every {RateLimitDuration}.")] + public static partial void StartingRateLimitDelay(ILogger logger, TimeSpan delayDuration, TimeSpan rateLimitDuration); - private static readonly Action _startingDnsQuery = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "StartingDnsQuery"), "Starting DNS query to get hosts from '{DnsAddress}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "StartingDnsQuery", Message = "Starting DNS query to get hosts from '{DnsAddress}'.")] + public static partial void StartingDnsQuery(ILogger logger, string dnsAddress); - private static readonly Action _receivedDnsResults = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ReceivedDnsResults"), "Received {ResultCount} DNS results from '{DnsAddress}'. Results: {DnsResults}"); - - private static readonly Action _errorQueryingDns = - LoggerMessage.Define(LogLevel.Error, new EventId(4, "ErrorQueryingDns"), "Error querying DNS hosts for '{DnsAddress}'."); - - private static readonly Action _errorFromRefreshInterval = - LoggerMessage.Define(LogLevel.Error, new EventId(5, "ErrorFromRefreshIntervalTimer"), "Error from refresh interval timer."); - - public static void StartingRateLimitDelay(ILogger logger, TimeSpan delayDuration, TimeSpan rateLimitDuration) - { - _startingRateLimitDelay(logger, delayDuration, rateLimitDuration, null); - } - - public static void StartingDnsQuery(ILogger logger, string dnsAddress) - { - _startingDnsQuery(logger, dnsAddress, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ReceivedDnsResults", Message = "Received {ResultCount} DNS results from '{DnsAddress}'. Results: {DnsResults}")] + private static partial void ReceivedDnsResults(ILogger logger, int resultCount, string dnsAddress, string dnsResults); public static void ReceivedDnsResults(ILogger logger, int resultCount, string dnsAddress, IList dnsResults) { if (logger.IsEnabled(LogLevel.Debug)) { - _receivedDnsResults(logger, resultCount, dnsAddress, string.Join(", ", dnsResults), null); + ReceivedDnsResults(logger, resultCount, dnsAddress, string.Join(", ", dnsResults)); } } - public static void ErrorQueryingDns(ILogger logger, string dnsAddress, Exception ex) - { - _errorQueryingDns(logger, dnsAddress, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 4, EventName = "ErrorQueryingDns", Message = "Error querying DNS hosts for '{DnsAddress}'.")] + public static partial void ErrorQueryingDns(ILogger logger, string dnsAddress, Exception ex); - public static void ErrorFromRefreshInterval(ILogger logger, Exception ex) - { - _errorFromRefreshInterval(logger, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 5, EventName = "ErrorFromRefreshIntervalTimer", Message = "Error from refresh interval timer.")] + public static partial void ErrorFromRefreshInterval(ILogger logger, Exception ex); } /// diff --git a/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs b/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs index 33bb1d8b5..37bc3c7e9 100644 --- a/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs +++ b/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs @@ -29,7 +29,7 @@ namespace Grpc.Net.Client.Balancer.Internal; -internal class BalancerHttpHandler : DelegatingHandler +internal partial class BalancerHttpHandler : DelegatingHandler { private static readonly object SetupLock = new object(); @@ -171,24 +171,20 @@ protected override async Task SendAsync( } } - internal static class Log + internal static partial class Log { - private static readonly Action _sendingRequest = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "SendingRequest"), "Sending request {RequestUri}."); - private static readonly Action _startingConnectCallback = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "StartingConnectCallback"), "Starting connect callback for {Endpoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "SendingRequest", Message = "Sending request {RequestUri}.")] + public static partial void SendingRequest(ILogger logger, Uri requestUri); - public static void SendingRequest(ILogger logger, Uri requestUri) - { - _sendingRequest(logger, requestUri, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "StartingConnectCallback", Message = "Starting connect callback for {Endpoint}.")] + private static partial void StartingConnectCallback(ILogger logger, string endpoint); public static void StartingConnectCallback(ILogger logger, DnsEndPoint endpoint) { if (logger.IsEnabled(LogLevel.Trace)) { - _startingConnectCallback(logger, $"{endpoint.Host}:{endpoint.Port}", null); + StartingConnectCallback(logger, $"{endpoint.Host}:{endpoint.Port}"); } } } diff --git a/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs b/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs index b64a4557c..3512d9b45 100644 --- a/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs +++ b/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs @@ -469,114 +469,54 @@ public void Dispose() } } -internal static class ConnectionManagerLog +internal static partial class ConnectionManagerLog { - private static readonly Action _resolverUnsupportedLoadBalancingConfig = - LoggerMessage.Define(LogLevel.Warning, new EventId(1, "ResolverUnsupportedLoadBalancingConfig"), "Service config returned by the resolver contains unsupported load balancer policies: {LoadBalancingConfigs}. Load balancer unchanged."); - - private static readonly Action _resolverServiceConfigNotUsed = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "ResolverServiceConfigNotUsed"), "Service config returned by the resolver not used."); - - private static readonly Action _channelStateUpdated = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ChannelStateUpdated"), "Channel state updated to {State}."); - - private static readonly Action _channelPickerUpdated = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "ChannelPickerUpdated"), "Channel picker updated."); - - private static readonly Action _pickStarted = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "PickStarted"), "Pick started."); - - private static readonly Action _pickResultSuccessful = - LoggerMessage.Define(LogLevel.Debug, new EventId(6, "PickResultSuccessful"), "Successfully picked subchannel id '{SubchannelId}' with address {CurrentAddress}. Transport status: {TransportStatus}"); - - private static readonly Action _pickResultSubchannelNoCurrentAddress = - LoggerMessage.Define(LogLevel.Debug, new EventId(7, "PickResultSubchannelNoCurrentAddress"), "Picked subchannel id '{SubchannelId}' doesn't have a current address."); - - private static readonly Action _pickResultQueued = - LoggerMessage.Define(LogLevel.Debug, new EventId(8, "PickResultQueued"), "Picked queued."); - - private static readonly Action _pickResultFailure = - LoggerMessage.Define(LogLevel.Debug, new EventId(9, "PickResultFailure"), "Picked failure with status: {Status}"); - - private static readonly Action _pickResultFailureWithWaitForReady = - LoggerMessage.Define(LogLevel.Debug, new EventId(10, "PickResultFailureWithWaitForReady"), "Picked failure with status: {Status}. Retrying because wait for ready is enabled."); - - private static readonly Action _pickWaiting = - LoggerMessage.Define(LogLevel.Trace, new EventId(11, "PickWaiting"), "Waiting for a new picker."); - - private static readonly Action _resolverServiceConfigFallback = - LoggerMessage.Define(LogLevel.Debug, new EventId(12, "ResolverServiceConfigFallback"), "Falling back to previously loaded service config. Resolver failure when retreiving or parsing service config with status: {Status}"); - - private static readonly Action _pickResultSubchannelNotReady = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "PickResultSubchannelNotReady"), "Picked subchannel id '{SubchannelId}' with address {CurrentAddress} doesn't have a ready state. Subchannel state: {State}"); + [LoggerMessage(Level = LogLevel.Warning, EventId = 1, EventName = "ResolverUnsupportedLoadBalancingConfig", Message = "Service config returned by the resolver contains unsupported load balancer policies: {LoadBalancingConfigs}. Load balancer unchanged.")] + private static partial void ResolverUnsupportedLoadBalancingConfig(ILogger logger, string loadBalancingConfigs); public static void ResolverUnsupportedLoadBalancingConfig(ILogger logger, IList loadBalancingConfigs) { if (logger.IsEnabled(LogLevel.Warning)) { var loadBalancingConfigText = string.Join(", ", loadBalancingConfigs.Select(c => $"'{c.PolicyName}'")); - _resolverUnsupportedLoadBalancingConfig(logger, loadBalancingConfigText, null); + ResolverUnsupportedLoadBalancingConfig(logger, loadBalancingConfigText); } } - public static void ResolverServiceConfigNotUsed(ILogger logger) - { - _resolverServiceConfigNotUsed(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "ResolverServiceConfigNotUsed", Message = "Service config returned by the resolver not used.")] + public static partial void ResolverServiceConfigNotUsed(ILogger logger); - public static void ChannelStateUpdated(ILogger logger, ConnectivityState connectivityState) - { - _channelStateUpdated(logger, connectivityState, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ChannelStateUpdated", Message = "Channel state updated to {State}.")] + public static partial void ChannelStateUpdated(ILogger logger, ConnectivityState state); - public static void ChannelPickerUpdated(ILogger logger) - { - _channelPickerUpdated(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 4, EventName = "ChannelPickerUpdated", Message = "Channel picker updated.")] + public static partial void ChannelPickerUpdated(ILogger logger); - public static void PickStarted(ILogger logger) - { - _pickStarted(logger, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "PickStarted", Message = "Pick started.")] + public static partial void PickStarted(ILogger logger); - public static void PickResultSuccessful(ILogger logger, string subchannelId, BalancerAddress currentAddress, TransportStatus transportStatus) - { - _pickResultSuccessful(logger, subchannelId, currentAddress, transportStatus, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 6, EventName = "PickResultSuccessful", Message = "Successfully picked subchannel id '{SubchannelId}' with address {CurrentAddress}. Transport status: {TransportStatus}")] + public static partial void PickResultSuccessful(ILogger logger, string subchannelId, BalancerAddress currentAddress, TransportStatus transportStatus); - public static void PickResultSubchannelNoCurrentAddress(ILogger logger, string subchannelId) - { - _pickResultSubchannelNoCurrentAddress(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 7, EventName = "PickResultSubchannelNoCurrentAddress", Message = "Picked subchannel id '{SubchannelId}' doesn't have a current address.")] + public static partial void PickResultSubchannelNoCurrentAddress(ILogger logger, string subchannelId); - public static void PickResultQueued(ILogger logger) - { - _pickResultQueued(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 8, EventName = "PickResultQueued", Message = "Picked queued.")] + public static partial void PickResultQueued(ILogger logger); - public static void PickResultFailure(ILogger logger, Status status) - { - _pickResultFailure(logger, status, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 9, EventName = "PickResultFailure", Message = "Picked failure with status: {Status}")] + public static partial void PickResultFailure(ILogger logger, Status status); - public static void PickResultFailureWithWaitForReady(ILogger logger, Status status) - { - _pickResultFailureWithWaitForReady(logger, status, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 10, EventName = "PickResultFailureWithWaitForReady", Message = "Picked failure with status: {Status}. Retrying because wait for ready is enabled.")] + public static partial void PickResultFailureWithWaitForReady(ILogger logger, Status status); - public static void PickWaiting(ILogger logger) - { - _pickWaiting(logger, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 11, EventName = "PickWaiting", Message = "Waiting for a new picker.")] + public static partial void PickWaiting(ILogger logger); - public static void ResolverServiceConfigFallback(ILogger logger, Status status) - { - _resolverServiceConfigFallback(logger, status, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 12, EventName = "ResolverServiceConfigFallback", Message = "Falling back to previously loaded service config. Resolver failure when retreiving or parsing service config with status: {Status}")] + public static partial void ResolverServiceConfigFallback(ILogger logger, Status status); - public static void PickResultSubchannelNotReady(ILogger logger, string subchannelId, BalancerAddress currentAddress, ConnectivityState state) - { - _pickResultSubchannelNotReady(logger, subchannelId, currentAddress, state, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "PickResultSubchannelNotReady", Message = "Picked subchannel id '{SubchannelId}' with address {CurrentAddress} doesn't have a ready state. Subchannel state: {State}")] + public static partial void PickResultSubchannelNotReady(ILogger logger, string subchannelId, BalancerAddress currentAddress, ConnectivityState state); } #endif diff --git a/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs b/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs index b54666d88..f1f3ffab3 100644 --- a/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs +++ b/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs @@ -544,142 +544,57 @@ public void Dispose() } } -internal static class SocketConnectivitySubchannelTransportLog +internal static partial class SocketConnectivitySubchannelTransportLog { - private static readonly Action _connectingSocket = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ConnectingSocket"), "Subchannel id '{SubchannelId}' connecting socket to {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ConnectingSocket", Message = "Subchannel id '{SubchannelId}' connecting socket to {EndPoint}.")] + public static partial void ConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _connectedSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "ConnectedSocket"), "Subchannel id '{SubchannelId}' connected to socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "ConnectedSocket", Message = "Subchannel id '{SubchannelId}' connected to socket {EndPoint}.")] + public static partial void ConnectedSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _errorConnectingSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ErrorConnectingSocket"), "Subchannel id '{SubchannelId}' error connecting to socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ErrorConnectingSocket", Message = "Subchannel id '{SubchannelId}' error connecting to socket {EndPoint}.")] + public static partial void ErrorConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex); - private static readonly Action _checkingSocket = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "CheckingSocket"), "Subchannel id '{SubchannelId}' checking socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "CheckingSocket", Message = "Subchannel id '{SubchannelId}' checking socket {EndPoint}.")] + public static partial void CheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _errorCheckingSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(5, "ErrorCheckingSocket"), "Subchannel id '{SubchannelId}' error checking socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 5, EventName = "ErrorCheckingSocket", Message = "Subchannel id '{SubchannelId}' error checking socket {EndPoint}.")] + public static partial void ErrorCheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex); - private static readonly Action _errorSocketTimer = - LoggerMessage.Define(LogLevel.Error, new EventId(6, "ErrorSocketTimer"), "Subchannel id '{SubchannelId}' unexpected error in check socket timer."); + [LoggerMessage(Level = LogLevel.Error, EventId = 6, EventName = "ErrorSocketTimer", Message = "Subchannel id '{SubchannelId}' unexpected error in check socket timer.")] + public static partial void ErrorSocketTimer(ILogger logger, string subchannelId, Exception ex); - private static readonly Action _creatingStream = - LoggerMessage.Define(LogLevel.Trace, new EventId(7, "CreatingStream"), "Subchannel id '{SubchannelId}' creating stream for {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 7, EventName = "CreatingStream", Message = "Subchannel id '{SubchannelId}' creating stream for {EndPoint}.")] + public static partial void CreatingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _disposingStream = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "DisposingStream"), "Subchannel id '{SubchannelId}' disposing stream for {EndPoint}. Transport has {ActiveStreams} active streams."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "DisposingStream", Message = "Subchannel id '{SubchannelId}' disposing stream for {EndPoint}. Transport has {ActiveStreams} active streams.")] + public static partial void DisposingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, int activeStreams); - private static readonly Action _disposingTransport = - LoggerMessage.Define(LogLevel.Trace, new EventId(9, "DisposingTransport"), "Subchannel id '{SubchannelId}' disposing transport."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 9, EventName = "DisposingTransport", Message = "Subchannel id '{SubchannelId}' disposing transport.")] + public static partial void DisposingTransport(ILogger logger, string subchannelId); - private static readonly Action _errorOnDisposingStream = - LoggerMessage.Define(LogLevel.Error, new EventId(10, "ErrorOnDisposingStream"), "Subchannel id '{SubchannelId}' unexpected error when reacting to transport stream dispose."); + [LoggerMessage(Level = LogLevel.Error, EventId = 10, EventName = "ErrorOnDisposingStream", Message = "Subchannel id '{SubchannelId}' unexpected error when reacting to transport stream dispose.")] + public static partial void ErrorOnDisposingStream(ILogger logger, string subchannelId, Exception ex); - private static readonly Action _connectingOnCreateStream = - LoggerMessage.Define(LogLevel.Trace, new EventId(11, "ConnectingOnCreateStream"), "Subchannel id '{SubchannelId}' doesn't have a connected socket available. Connecting new stream socket for {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 11, EventName = "ConnectingOnCreateStream", Message = "Subchannel id '{SubchannelId}' doesn't have a connected socket available. Connecting new stream socket for {EndPoint}.")] + public static partial void ConnectingOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _streamCreated = - LoggerMessage.Define(LogLevel.Trace, new EventId(12, "StreamCreated"), "Subchannel id '{SubchannelId}' created stream for {EndPoint} with {BufferedBytes} buffered bytes. Transport has {ActiveStreams} active streams."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 12, EventName = "StreamCreated", Message = "Subchannel id '{SubchannelId}' created stream for {EndPoint} with {BufferedBytes} buffered bytes. Transport has {ActiveStreams} active streams.")] + public static partial void StreamCreated(ILogger logger, string subchannelId, DnsEndPoint endPoint, int bufferedBytes, int activeStreams); - private static readonly Action _errorPollingSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "ErrorPollingSocket"), "Subchannel id '{SubchannelId}' error checking socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "ErrorPollingSocket", Message = "Subchannel id '{SubchannelId}' error checking socket {EndPoint}.")] + public static partial void ErrorPollingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex); - private static readonly Action _socketPollBadState = - LoggerMessage.Define(LogLevel.Debug, new EventId(14, "SocketPollBadState"), "Subchannel id '{SubchannelId}' socket {EndPoint} is in a bad state and can't be used."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 14, EventName = "SocketPollBadState", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is in a bad state and can't be used.")] + public static partial void SocketPollBadState(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _socketReceivingAvailable = - LoggerMessage.Define(LogLevel.Trace, new EventId(15, "SocketReceivingAvailable"), "Subchannel id '{SubchannelId}' socket {EndPoint} is receiving {ReadBytesAvailableCount} available bytes."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 15, EventName = "SocketReceivingAvailable", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is receiving {ReadBytesAvailableCount} available bytes.")] + public static partial void SocketReceivingAvailable(ILogger logger, string subchannelId, DnsEndPoint endPoint, int readBytesAvailableCount); - private static readonly Action _closingUnusableSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(16, "ClosingUnusableSocket"), "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it can't be used. Socket lifetime of {SocketLifetime}. The socket either can't receive data or it has received unexpected data."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 16, EventName = "ClosingUnusableSocket", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it can't be used. Socket lifetime of {SocketLifetime}. The socket either can't receive data or it has received unexpected data.")] + public static partial void ClosingUnusableSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketLifetime); - private static readonly Action _closingSocketFromIdleTimeoutOnCreateStream = - LoggerMessage.Define(LogLevel.Debug, new EventId(16, "ClosingSocketFromIdleTimeoutOnCreateStream"), "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it exceeds the idle timeout of {SocketIdleTimeout}."); - - public static void ConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _connectingSocket(logger, subchannelId, endPoint, null); - } - - public static void ConnectedSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _connectedSocket(logger, subchannelId, endPoint, null); - } - - public static void ErrorConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex) - { - _errorConnectingSocket(logger, subchannelId, endPoint, ex); - } - - public static void CheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _checkingSocket(logger, subchannelId, endPoint, null); - } - - public static void ErrorCheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex) - { - _errorCheckingSocket(logger, subchannelId, endPoint, ex); - } - - public static void ErrorSocketTimer(ILogger logger, string subchannelId, Exception ex) - { - _errorSocketTimer(logger, subchannelId, ex); - } - - public static void CreatingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _creatingStream(logger, subchannelId, endPoint, null); - } - - public static void DisposingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, int activeStreams) - { - _disposingStream(logger, subchannelId, endPoint, activeStreams, null); - } - - public static void DisposingTransport(ILogger logger, string subchannelId) - { - _disposingTransport(logger, subchannelId, null); - } - - public static void ErrorOnDisposingStream(ILogger logger, string subchannelId, Exception ex) - { - _errorOnDisposingStream(logger, subchannelId, ex); - } - - public static void ConnectingOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _connectingOnCreateStream(logger, subchannelId, endPoint, null); - } - - public static void StreamCreated(ILogger logger, string subchannelId, DnsEndPoint endPoint, int bufferedBytes, int activeStreams) - { - _streamCreated(logger, subchannelId, endPoint, bufferedBytes, activeStreams, null); - } - - public static void ErrorPollingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex) - { - _errorPollingSocket(logger, subchannelId, endPoint, ex); - } - - public static void SocketPollBadState(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _socketPollBadState(logger, subchannelId, endPoint, null); - } - - public static void SocketReceivingAvailable(ILogger logger, string subchannelId, DnsEndPoint endPoint, int readBytesAvailableCount) - { - _socketReceivingAvailable(logger, subchannelId, endPoint, readBytesAvailableCount, null); - } - - public static void ClosingUnusableSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketLifetime) - { - _closingUnusableSocket(logger, subchannelId, endPoint, socketLifetime, null); - } - - public static void ClosingSocketFromIdleTimeoutOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketIdleTimeout) - { - _closingSocketFromIdleTimeoutOnCreateStream(logger, subchannelId, endPoint, socketIdleTimeout, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 17, EventName = "ClosingSocketFromIdleTimeoutOnCreateStream", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it exceeds the idle timeout of {SocketIdleTimeout}.")] + public static partial void ClosingSocketFromIdleTimeoutOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketIdleTimeout); } #endif diff --git a/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs b/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs index 16a8a8f31..88f4cfead 100644 --- a/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs +++ b/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs @@ -200,23 +200,18 @@ public override PickResult Pick(PickContext context) } } -internal static class PickFirstBalancerLog +internal static partial class PickFirstBalancerLog { - private static readonly Action _processingSubchannelStateChanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ProcessingSubchannelStateChanged"), "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'."); - - private static readonly Action _ignoredSubchannelStateChange = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "IgnoredSubchannelStateChange"), "Ignored state change because of unknown subchannel id '{SubchannelId}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ProcessingSubchannelStateChanged", Message = "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'.")] + private static partial void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, string Detail, Exception? DebugException); public static void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, Status status) { - _processingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); + ProcessingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); } - public static void IgnoredSubchannelStateChange(ILogger logger, string subchannelId) - { - _ignoredSubchannelStateChange(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "IgnoredSubchannelStateChange", Message = "Ignored state change because of unknown subchannel id '{SubchannelId}'.")] + public static partial void IgnoredSubchannelStateChange(ILogger logger, string subchannelId); } /// diff --git a/src/Grpc.Net.Client/Balancer/PollingResolver.cs b/src/Grpc.Net.Client/Balancer/PollingResolver.cs index 0973f9339..0f7650d88 100644 --- a/src/Grpc.Net.Client/Balancer/PollingResolver.cs +++ b/src/Grpc.Net.Client/Balancer/PollingResolver.cs @@ -36,7 +36,7 @@ namespace Grpc.Net.Client.Balancer; /// Note: Experimental API that can change or be removed without any prior notice. /// /// -public abstract class PollingResolver : Resolver +public abstract partial class PollingResolver : Resolver { // Internal for testing internal Task _resolveTask = Task.CompletedTask; @@ -256,70 +256,70 @@ protected override void Dispose(bool disposing) _disposed = true; } - internal static class Log + internal static partial class Log { - private static readonly Action _resolverRefreshRequested = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ResolverRefreshRequested"), "{ResolveType} refresh requested."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ResolverRefreshRequested", Message = "{ResolveType} refresh requested.")] + private static partial void ResolverRefreshRequested(ILogger logger, string resolveType); - private static readonly Action _resolverRefreshIgnored = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "ResolverRefreshIgnored"), "{ResolveType} refresh ignored because resolve is already in progress."); - - private static readonly Action _resolveError = - LoggerMessage.Define(LogLevel.Error, new EventId(3, "ResolveError"), "Error resolving {ResolveType}."); - - private static readonly Action _resolveResult = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "ResolveResult"), "{ResolveType} result with status code '{StatusCode}' and {AddressCount} addresses."); - - private static readonly Action _startingResolveBackoff = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "StartingResolveBackoff"), "{ResolveType} starting resolve backoff of {BackoffDuration}."); - - private static readonly Action _errorRetryingResolve = - LoggerMessage.Define(LogLevel.Error, new EventId(6, "ErrorRetryingResolve"), "{ResolveType} error retrying resolve."); - - private static readonly Action _resolveTaskCompleted = - LoggerMessage.Define(LogLevel.Trace, new EventId(7, "ResolveTaskCompleted"), "{ResolveType} resolve task completed."); - - private static readonly Action _resolveStarting = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "ResolveStarting"), "{ResolveType} resolve starting."); - public static void ResolverRefreshRequested(ILogger logger, Type resolverType) { - _resolverRefreshRequested(logger, resolverType.Name, null); + ResolverRefreshRequested(logger, resolverType.Name); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "ResolverRefreshIgnored", Message = "{ResolveType} refresh ignored because resolve is already in progress.")] + private static partial void ResolverRefreshIgnored(ILogger logger, string resolveType); + public static void ResolverRefreshIgnored(ILogger logger, Type resolverType) { - _resolverRefreshIgnored(logger, resolverType.Name, null); + ResolverRefreshIgnored(logger, resolverType.Name); } + [LoggerMessage(Level = LogLevel.Error, EventId = 3, EventName = "ResolveError", Message = "Error resolving {ResolveType}.")] + private static partial void ResolveError(ILogger logger, string resolveType, Exception ex); + public static void ResolveError(ILogger logger, Type resolverType, Exception ex) { - _resolveError(logger, resolverType.Name, ex); + ResolveError(logger, resolverType.Name, ex); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "ResolveResult", Message = "{ResolveType} result with status code '{StatusCode}' and {AddressCount} addresses.")] + private static partial void ResolveResult(ILogger logger, string resolveType, StatusCode statusCode, int addressCount); + public static void ResolveResult(ILogger logger, Type resolverType, StatusCode statusCode, int addressCount) { - _resolveResult(logger, resolverType.Name, statusCode, addressCount, null); + ResolveResult(logger, resolverType.Name, statusCode, addressCount); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "StartingResolveBackoff", Message = "{ResolveType} starting resolve backoff of {BackoffDuration}.")] + private static partial void StartingResolveBackoff(ILogger logger, string resolveType, TimeSpan BackoffDuration); + public static void StartingResolveBackoff(ILogger logger, Type resolverType, TimeSpan delay) { - _startingResolveBackoff(logger, resolverType.Name, delay, null); + StartingResolveBackoff(logger, resolverType.Name, delay); } + [LoggerMessage(Level = LogLevel.Error, EventId = 6, EventName = "ErrorRetryingResolve", Message = "{ResolveType} error retrying resolve.")] + private static partial void ErrorRetryingResolve(ILogger logger, string resolveType, Exception ex); + public static void ErrorRetryingResolve(ILogger logger, Type resolverType, Exception ex) { - _errorRetryingResolve(logger, resolverType.Name, ex); + ErrorRetryingResolve(logger, resolverType.Name, ex); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 7, EventName = "ResolveTaskCompleted", Message = "{ResolveType} resolve task completed.")] + private static partial void ResolveTaskCompleted(ILogger logger, string resolveType); + public static void ResolveTaskCompleted(ILogger logger, Type resolverType) { - _resolveTaskCompleted(logger, resolverType.Name, null); + ResolveTaskCompleted(logger, resolverType.Name); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "ResolveStarting", Message = "{ResolveType} resolve starting.")] + private static partial void ResolveStarting(ILogger logger, string resolveType); + public static void ResolveStarting(ILogger logger, Type resolverType) { - _resolveStarting(logger, resolverType.Name, null); + ResolveStarting(logger, resolverType.Name); } } } diff --git a/src/Grpc.Net.Client/Balancer/Subchannel.cs b/src/Grpc.Net.Client/Balancer/Subchannel.cs index dcfdcd8a5..db0a2ee42 100644 --- a/src/Grpc.Net.Client/Balancer/Subchannel.cs +++ b/src/Grpc.Net.Client/Balancer/Subchannel.cs @@ -544,174 +544,87 @@ public void Dispose() } } -internal static class SubchannelLog +internal static partial class SubchannelLog { - private static readonly Action _subchannelCreated = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "SubchannelCreated"), "Subchannel id '{SubchannelId}' created with addresses: {Addresses}"); - - private static readonly Action _addressesUpdatedWhileConnecting = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "AddressesUpdatedWhileConnecting"), "Subchannel id '{SubchannelId}' is connecting when its addresses are updated. Restarting connect."); - - private static readonly Action _connectedAddressNotInUpdatedAddresses = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ConnectedAddressNotInUpdatedAddresses"), "Subchannel id '{SubchannelId}' current address '{CurrentAddress}' is not in the updated addresses."); - - private static readonly Action _connectionRequested = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "ConnectionRequested"), "Subchannel id '{SubchannelId}' connection requested."); - - private static readonly Action _connectionRequestedInNonIdleState = - LoggerMessage.Define(LogLevel.Debug, new EventId(5, "ConnectionRequestedInNonIdleState"), "Subchannel id '{SubchannelId}' connection requested in non-idle state of {State}."); - - private static readonly Action _connectingTransport = - LoggerMessage.Define(LogLevel.Debug, new EventId(6, "ConnectingTransport"), "Subchannel id '{SubchannelId}' connecting to transport."); - - private static readonly Action _startingConnectBackoff = - LoggerMessage.Define(LogLevel.Trace, new EventId(7, "StartingConnectBackoff"), "Subchannel id '{SubchannelId}' starting connect backoff of {BackoffDuration}."); - - private static readonly Action _connectBackoffInterrupted = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "ConnectBackoffInterrupted"), "Subchannel id '{SubchannelId}' connect backoff interrupted."); - - private static readonly Action _connectCanceled = - LoggerMessage.Define(LogLevel.Debug, new EventId(9, "ConnectCanceled"), "Subchannel id '{SubchannelId}' connect canceled."); - - private static readonly Action _connectError = - LoggerMessage.Define(LogLevel.Error, new EventId(10, "ConnectError"), "Subchannel id '{SubchannelId}' unexpected error while connecting to transport."); - - private static readonly Action _subchannelStateChanged = - LoggerMessage.Define(LogLevel.Debug, new EventId(11, "SubchannelStateChanged"), "Subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'."); - - private static readonly Action _stateChangedRegistrationCreated = - LoggerMessage.Define(LogLevel.Trace, new EventId(12, "StateChangedRegistrationCreated"), "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' created."); - - private static readonly Action _stateChangedRegistrationRemoved = - LoggerMessage.Define(LogLevel.Trace, new EventId(13, "StateChangedRegistrationRemoved"), "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' removed."); - - private static readonly Action _executingStateChangedRegistration = - LoggerMessage.Define(LogLevel.Trace, new EventId(14, "ExecutingStateChangedRegistration"), "Subchannel id '{SubchannelId}' executing state changed registration '{RegistrationId}'."); - - private static readonly Action _noStateChangedRegistrations = - LoggerMessage.Define(LogLevel.Trace, new EventId(15, "NoStateChangedRegistrations"), "Subchannel id '{SubchannelId}' has no state changed registrations."); - - private static readonly Action _subchannelPreserved = - LoggerMessage.Define(LogLevel.Trace, new EventId(16, "SubchannelPreserved"), "Subchannel id '{SubchannelId}' matches address '{Address}' and is preserved."); - - private static readonly Action _cancelingConnect = - LoggerMessage.Define(LogLevel.Debug, new EventId(17, "CancelingConnect"), "Subchannel id '{SubchannelId}' canceling connect."); - - private static readonly Action _connectBackoffComplete = - LoggerMessage.Define(LogLevel.Trace, new EventId(18, "ConnectBackoffComplete"), "Subchannel id '{SubchannelId}' connect backoff complete."); - - private static readonly Action _addressesUpdated = - LoggerMessage.Define(LogLevel.Trace, new EventId(19, "AddressesUpdated"), "Subchannel id '{SubchannelId}' updated with addresses: {Addresses}"); - - private static readonly Action _queuingConnect = - LoggerMessage.Define(LogLevel.Debug, new EventId(20, "QueuingConnect"), "Subchannel id '{SubchannelId}' queuing connect because a connect is already in progress."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "SubchannelCreated", Message = "Subchannel id '{SubchannelId}' created with addresses: {Addresses}")] + private static partial void SubchannelCreated(ILogger logger, string subchannelId, string addresses); public static void SubchannelCreated(ILogger logger, string subchannelId, IReadOnlyList addresses) { if (logger.IsEnabled(LogLevel.Debug)) { var addressesText = string.Join(", ", addresses.Select(a => a.EndPoint.Host + ":" + a.EndPoint.Port)); - _subchannelCreated(logger, subchannelId, addressesText, null); + SubchannelCreated(logger, subchannelId, addressesText); } } - public static void AddressesUpdatedWhileConnecting(ILogger logger, string subchannelId) - { - _addressesUpdatedWhileConnecting(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "AddressesUpdatedWhileConnecting", Message = "Subchannel id '{SubchannelId}' is connecting when its addresses are updated. Restarting connect.")] + public static partial void AddressesUpdatedWhileConnecting(ILogger logger, string subchannelId); - public static void ConnectedAddressNotInUpdatedAddresses(ILogger logger, string subchannelId, BalancerAddress currentAddress) - { - _connectedAddressNotInUpdatedAddresses(logger, subchannelId, currentAddress, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ConnectedAddressNotInUpdatedAddresses", Message = "Subchannel id '{SubchannelId}' current address '{CurrentAddress}' is not in the updated addresses.")] + public static partial void ConnectedAddressNotInUpdatedAddresses(ILogger logger, string subchannelId, BalancerAddress currentAddress); - public static void ConnectionRequested(ILogger logger, string subchannelId) - { - _connectionRequested(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "ConnectionRequested", Message = "Subchannel id '{SubchannelId}' connection requested.")] + public static partial void ConnectionRequested(ILogger logger, string subchannelId); - public static void ConnectionRequestedInNonIdleState(ILogger logger, string subchannelId, ConnectivityState state) - { - _connectionRequestedInNonIdleState(logger, subchannelId, state, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 5, EventName = "ConnectionRequestedInNonIdleState", Message = "Subchannel id '{SubchannelId}' connection requested in non-idle state of {State}.")] + public static partial void ConnectionRequestedInNonIdleState(ILogger logger, string subchannelId, ConnectivityState state); - public static void ConnectingTransport(ILogger logger, string subchannelId) - { - _connectingTransport(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 6, EventName = "ConnectingTransport", Message = "Subchannel id '{SubchannelId}' connecting to transport.")] + public static partial void ConnectingTransport(ILogger logger, string subchannelId); - public static void StartingConnectBackoff(ILogger logger, string subchannelId, TimeSpan delay) - { - _startingConnectBackoff(logger, subchannelId, delay, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 7, EventName = "StartingConnectBackoff", Message = "Subchannel id '{SubchannelId}' starting connect backoff of {BackoffDuration}.")] + public static partial void StartingConnectBackoff(ILogger logger, string subchannelId, TimeSpan BackoffDuration); - public static void ConnectBackoffInterrupted(ILogger logger, string subchannelId) - { - _connectBackoffInterrupted(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "ConnectBackoffInterrupted", Message = "Subchannel id '{SubchannelId}' connect backoff interrupted.")] + public static partial void ConnectBackoffInterrupted(ILogger logger, string subchannelId); - public static void ConnectCanceled(ILogger logger, string subchannelId) - { - _connectCanceled(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 9, EventName = "ConnectCanceled", Message = "Subchannel id '{SubchannelId}' connect canceled.")] + public static partial void ConnectCanceled(ILogger logger, string subchannelId); - public static void ConnectError(ILogger logger, string subchannelId, Exception ex) - { - _connectError(logger, subchannelId, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 10, EventName = "ConnectError", Message = "Subchannel id '{SubchannelId}' unexpected error while connecting to transport.")] + public static partial void ConnectError(ILogger logger, string subchannelId, Exception ex); + + [LoggerMessage(Level = LogLevel.Debug, EventId = 11, EventName = "SubchannelStateChanged", Message = "Subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'.")] + private static partial void SubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, string Detail, Exception? DebugException); public static void SubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, Status status) { - _subchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); + SubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); } - public static void ExecutingStateChangedRegistration(ILogger logger, string subchannelId, string registrationId) - { - _executingStateChangedRegistration(logger, subchannelId, registrationId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 12, EventName = "StateChangedRegistrationCreated", Message = "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' created.")] + public static partial void StateChangedRegistrationCreated(ILogger logger, string subchannelId, string registrationId); - public static void NoStateChangedRegistrations(ILogger logger, string subchannelId) - { - _noStateChangedRegistrations(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 13, EventName = "StateChangedRegistrationRemoved", Message = "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' removed.")] + public static partial void StateChangedRegistrationRemoved(ILogger logger, string subchannelId, string registrationId); - public static void StateChangedRegistrationCreated(ILogger logger, string subchannelId, string registrationId) - { - _stateChangedRegistrationCreated(logger, subchannelId, registrationId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 14, EventName = "ExecutingStateChangedRegistration", Message = "Subchannel id '{SubchannelId}' executing state changed registration '{RegistrationId}'.")] + public static partial void ExecutingStateChangedRegistration(ILogger logger, string subchannelId, string registrationId); - public static void StateChangedRegistrationRemoved(ILogger logger, string subchannelId, string registrationId) - { - _stateChangedRegistrationRemoved(logger, subchannelId, registrationId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 15, EventName = "NoStateChangedRegistrations", Message = "Subchannel id '{SubchannelId}' has no state changed registrations.")] + public static partial void NoStateChangedRegistrations(ILogger logger, string subchannelId); - public static void SubchannelPreserved(ILogger logger, string subchannelId, BalancerAddress address) - { - _subchannelPreserved(logger, subchannelId, address, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 16, EventName = "SubchannelPreserved", Message = "Subchannel id '{SubchannelId}' matches address '{Address}' and is preserved.")] + public static partial void SubchannelPreserved(ILogger logger, string subchannelId, BalancerAddress address); - public static void CancelingConnect(ILogger logger, string subchannelId) - { - _cancelingConnect(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 17, EventName = "CancelingConnect", Message = "Subchannel id '{SubchannelId}' canceling connect.")] + public static partial void CancelingConnect(ILogger logger, string subchannelId); - public static void ConnectBackoffComplete(ILogger logger, string subchannelId) - { - _connectBackoffComplete(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 18, EventName = "ConnectBackoffComplete", Message = "Subchannel id '{SubchannelId}' connect backoff complete.")] + public static partial void ConnectBackoffComplete(ILogger logger, string subchannelId); + [LoggerMessage(Level = LogLevel.Trace, EventId = 19, EventName = "AddressesUpdated", Message = "Subchannel id '{SubchannelId}' updated with addresses: {Addresses}")] + private static partial void AddressesUpdated(ILogger logger, string subchannelId, string addresses); public static void AddressesUpdated(ILogger logger, string subchannelId, IReadOnlyList addresses) { if (logger.IsEnabled(LogLevel.Trace)) { var addressesText = string.Join(", ", addresses.Select(a => a.EndPoint.Host + ":" + a.EndPoint.Port)); - _addressesUpdated(logger, subchannelId, addressesText, null); + AddressesUpdated(logger, subchannelId, addressesText); } } - - public static void QueuingConnect(ILogger logger, string subchannelId) - { - _queuingConnect(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 20, EventName = "QueuingConnect", Message = "Subchannel id '{SubchannelId}' queuing connect because a connect is already in progress.")] + public static partial void QueuingConnect(ILogger logger, string subchannelId); } #endif diff --git a/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs b/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs index f5fccf828..5f27c347b 100644 --- a/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs +++ b/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs @@ -336,56 +336,36 @@ public void UpdateKnownState(ConnectivityState knownState) } } -internal static class SubchannelsLoadBalancerLog +internal static partial class SubchannelsLoadBalancerLog { - private static readonly Action _processingSubchannelStateChanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ProcessingSubchannelStateChanged"), "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'."); - - private static readonly Action _ignoredSubchannelStateChange = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "IgnoredSubchannelStateChange"), "Ignored state change because of unknown subchannel id '{SubchannelId}'."); - - private static readonly Action _connectionsUnchanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(3, "ConnectionsUnchanged"), "Connections unchanged."); - - private static readonly Action _refreshingResolverForSubchannel = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "RefreshingResolverForSubchannel"), "Refreshing resolver because subchannel id '{SubchannelId}' is in state {State}."); - - private static readonly Action _requestingConnectionForSubchannel = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "RequestingConnectionForSubchannel"), "Requesting connection for subchannel id '{SubchannelId}' because it is in state {State}."); - - private static readonly Action _creatingReadyPicker = - LoggerMessage.Define(LogLevel.Trace, new EventId(6, "CreatingReadyPicker"), "Creating ready picker with {SubchannelCount} subchannels: {Subchannels}"); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ProcessingSubchannelStateChanged", Message = "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'.")] + private static partial void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, string Detail, Exception? DebugException); public static void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, Status status) { - _processingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); + ProcessingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); } - public static void IgnoredSubchannelStateChange(ILogger logger, string subchannelId) - { - _ignoredSubchannelStateChange(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "IgnoredSubchannelStateChange", Message = "Ignored state change because of unknown subchannel id '{SubchannelId}'.")] + public static partial void IgnoredSubchannelStateChange(ILogger logger, string subchannelId); - public static void ConnectionsUnchanged(ILogger logger) - { - _connectionsUnchanged(logger, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 3, EventName = "ConnectionsUnchanged", Message = "Connections unchanged.")] + public static partial void ConnectionsUnchanged(ILogger logger); - public static void RefreshingResolverForSubchannel(ILogger logger, string subchannelId, ConnectivityState state) - { - _refreshingResolverForSubchannel(logger, subchannelId, state, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "RefreshingResolverForSubchannel", Message = "Refreshing resolver because subchannel id '{SubchannelId}' is in state {State}.")] + public static partial void RefreshingResolverForSubchannel(ILogger logger, string subchannelId, ConnectivityState state); - public static void RequestingConnectionForSubchannel(ILogger logger, string subchannelId, ConnectivityState state) - { - _requestingConnectionForSubchannel(logger, subchannelId, state, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "RequestingConnectionForSubchannel", Message = "Requesting connection for subchannel id '{SubchannelId}' because it is in state {State}.")] + public static partial void RequestingConnectionForSubchannel(ILogger logger, string subchannelId, ConnectivityState state); + + [LoggerMessage(Level = LogLevel.Trace, EventId = 6, EventName = "CreatingReadyPicker", Message = "Creating ready picker with {SubchannelCount} subchannels: {Subchannels}")] + private static partial void CreatingReadyPicker(ILogger logger, int subchannelCount, string subchannels); public static void CreatingReadyPicker(ILogger logger, List readySubchannels) { if (logger.IsEnabled(LogLevel.Trace)) { - _creatingReadyPicker(logger, readySubchannels.Count, string.Join(", ", readySubchannels.Select(s => $"id '{s.Id}' ({string.Join(",", s.GetAddresses())})")), null); + CreatingReadyPicker(logger, readySubchannels.Count, string.Join(", ", readySubchannels.Select(s => $"id '{s.Id}' ({string.Join(",", s.GetAddresses())})"))); } } } diff --git a/src/Grpc.Net.Client/GrpcChannel.cs b/src/Grpc.Net.Client/GrpcChannel.cs index e046854a1..05e170e04 100644 --- a/src/Grpc.Net.Client/GrpcChannel.cs +++ b/src/Grpc.Net.Client/GrpcChannel.cs @@ -39,7 +39,7 @@ namespace Grpc.Net.Client; /// a remote call so in general you should reuse a single channel for as many calls as possible. /// [DebuggerDisplay("{DebuggerToString(),nq}")] -public sealed class GrpcChannel : ChannelBase, IDisposable +public sealed partial class GrpcChannel : ChannelBase, IDisposable { internal const int DefaultMaxReceiveMessageSize = 1024 * 1024 * 4; // 4 MB #if SUPPORT_LOAD_BALANCING @@ -934,15 +934,10 @@ public override int GetHashCode() => (Method != null ? StringComparer.Ordinal.GetHashCode(Method) : 0); } - private static class Log + private static partial class Log { - private static readonly Action _addressPathUnused = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "AddressPathUnused"), "The path in the channel's address '{Address}' won't be used when making gRPC calls. A DelegatingHandler can be used to include a path with gRPC calls. See https://aka.ms/aspnet/grpc/subdir for details."); - - public static void AddressPathUnused(ILogger logger, string address) - { - _addressPathUnused(logger, address, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "AddressPathUnused", Message = "The path in the channel's address '{Address}' won't be used when making gRPC calls. A DelegatingHandler can be used to include a path with gRPC calls. See https://aka.ms/aspnet/grpc/subdir for details.")] + public static partial void AddressPathUnused(ILogger logger, string address); } private readonly record struct HttpHandlerContext(HttpHandlerType HttpHandlerType, TimeSpan? ConnectTimeout = null, TimeSpan? ConnectionIdleTimeout = null); diff --git a/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs b/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs index a70049eac..c8b89dddd 100644 --- a/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs +++ b/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs @@ -76,29 +76,14 @@ protected bool IsWriteInProgressUnsynchronized } } -internal static class ClientStreamWriterBaseLog +internal static partial class ClientStreamWriterBaseLog { - private static readonly Action _completingClientStream = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "CompletingClientStream"), "Completing client stream."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "CompletingClientStream", Message = "Completing client stream.")] + public static partial void CompletingClientStream(ILogger logger); - private static readonly Action _writeMessageError = - LoggerMessage.Define(LogLevel.Error, new EventId(2, "WriteMessageError"), "Error writing message."); + [LoggerMessage(Level = LogLevel.Error, EventId = 2, EventName = "WriteMessageError", Message = "Error writing message.")] + public static partial void WriteMessageError(ILogger logger, Exception ex); - private static readonly Action _completeClientStreamError = - LoggerMessage.Define(LogLevel.Error, new EventId(3, "CompleteClientStreamError"), "Error completing client stream."); - - public static void CompletingClientStream(ILogger logger) - { - _completingClientStream(logger, null); - } - - public static void WriteMessageError(ILogger logger, Exception ex) - { - _writeMessageError(logger, ex); - } - - public static void CompleteClientStreamError(ILogger logger, Exception ex) - { - _completeClientStreamError(logger, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 3, EventName = "CompleteClientStreamError", Message = "Error completing client stream.")] + public static partial void CompleteClientStreamError(ILogger logger, Exception ex); } diff --git a/src/Grpc.Net.Client/Internal/GrpcCallLog.cs b/src/Grpc.Net.Client/Internal/GrpcCallLog.cs index 9404b85f2..7156f6574 100644 --- a/src/Grpc.Net.Client/Internal/GrpcCallLog.cs +++ b/src/Grpc.Net.Client/Internal/GrpcCallLog.cs @@ -21,216 +21,88 @@ namespace Grpc.Net.Client.Internal; -internal static class GrpcCallLog +internal static partial class GrpcCallLog { - private static readonly Action _startingCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "StartingCall"), "Starting gRPC call. Method type: '{MethodType}', URI: '{Uri}'."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "StartingCall", Message = "Starting gRPC call. Method type: '{MethodType}', URI: '{Uri}'.")] + public static partial void StartingCall(ILogger logger, MethodType methodType, Uri uri); - private static readonly Action _responseHeadersReceived = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "ResponseHeadersReceived"), "Response headers received."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "ResponseHeadersReceived", Message = "Response headers received.")] + public static partial void ResponseHeadersReceived(ILogger logger); - private static readonly Action _grpcStatusError = - LoggerMessage.Define(LogLevel.Information, new EventId(3, "GrpcStatusError"), "Call failed with gRPC error status. Status code: '{StatusCode}', Message: '{StatusMessage}'."); + [LoggerMessage(Level = LogLevel.Information, EventId = 3, EventName = "GrpcStatusError", Message = "Call failed with gRPC error status. Status code: '{StatusCode}', Message: '{StatusMessage}'.")] + public static partial void GrpcStatusError(ILogger logger, StatusCode statusCode, string statusMessage, Exception? debugException); - private static readonly Action _finishedCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "FinishedCall"), "Finished gRPC call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 4, EventName = "FinishedCall", Message = "Finished gRPC call.")] + public static partial void FinishedCall(ILogger logger); - private static readonly Action _startingDeadlineTimeout = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "StartingDeadlineTimeout"), "Starting deadline timeout. Duration: {DeadlineTimeout}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "StartingDeadlineTimeout", Message = "Starting deadline timeout. Duration: {DeadlineTimeout}.")] + public static partial void StartingDeadlineTimeout(ILogger logger, TimeSpan deadlineTimeout); - private static readonly Action _errorStartingCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(6, "ErrorStartingCall"), "Error starting gRPC call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 6, EventName = "ErrorStartingCall", Message = "Error starting gRPC call.")] + public static partial void ErrorStartingCall(ILogger logger); - private static readonly Action _deadlineExceeded = - LoggerMessage.Define(LogLevel.Warning, new EventId(7, "DeadlineExceeded"), "gRPC call deadline exceeded."); + [LoggerMessage(Level = LogLevel.Warning, EventId = 7, EventName = "DeadlineExceeded", Message = "gRPC call deadline exceeded.")] + public static partial void DeadlineExceeded(ILogger logger); - private static readonly Action _canceledCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(8, "CanceledCall"), "gRPC call canceled."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 8, EventName = "CanceledCall", Message = "gRPC call canceled.")] + public static partial void CanceledCall(ILogger logger); - private static readonly Action _messageNotReturned = - LoggerMessage.Define(LogLevel.Debug, new EventId(9, "MessageNotReturned"), "Message not returned from unary or client streaming call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 9, EventName = "MessageNotReturned", Message = "Message not returned from unary or client streaming call.")] + public static partial void MessageNotReturned(ILogger logger); // 10, 11 unused. - private static readonly Action _callCredentialsNotUsed = - LoggerMessage.Define(LogLevel.Warning, new EventId(12, "CallCredentialsNotUsed"), "The configured CallCredentials were not used because the call does not use TLS."); + [LoggerMessage(Level = LogLevel.Warning, EventId = 12, EventName = "CallCredentialsNotUsed", Message = "The configured CallCredentials were not used because the call does not use TLS.")] + public static partial void CallCredentialsNotUsed(ILogger logger); - private static readonly Action _readingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "ReadingMessage"), "Reading message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "ReadingMessage", Message = "Reading message.")] + public static partial void ReadingMessage(ILogger logger); - private static readonly Action _noMessageReturned = - LoggerMessage.Define(LogLevel.Trace, new EventId(14, "NoMessageReturned"), "No message returned."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 14, EventName = "NoMessageReturned", Message = "No message returned.")] + public static partial void NoMessageReturned(ILogger logger); - private static readonly Action _deserializingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(15, "DeserializingMessage"), "Deserializing {MessageLength} byte message to '{MessageType}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 15, EventName = "DeserializingMessage", Message = "Deserializing {MessageLength} byte message to '{MessageType}'.")] + public static partial void DeserializingMessage(ILogger logger, int messageLength, Type messageType); - private static readonly Action _receivedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(16, "ReceivedMessage"), "Received message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 16, EventName = "ReceivedMessage", Message = "Received message.")] + public static partial void ReceivedMessage(ILogger logger); - private static readonly Action _errorReadingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(17, "ErrorReadingMessage"), "Error reading message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 17, EventName = "ErrorReadingMessage", Message = "Error reading message.")] + public static partial void ErrorReadingMessage(ILogger logger, Exception ex); - private static readonly Action _sendingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(18, "SendingMessage"), "Sending message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 18, EventName = "SendingMessage", Message = "Sending message.")] + public static partial void SendingMessage(ILogger logger); - private static readonly Action _messageSent = - LoggerMessage.Define(LogLevel.Trace, new EventId(19, "MessageSent"), "Message sent."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 19, EventName = "MessageSent", Message = "Message sent.")] + public static partial void MessageSent(ILogger logger); - private static readonly Action _errorSendingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(20, "ErrorSendingMessage"), "Error sending message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 20, EventName = "ErrorSendingMessage", Message = "Error sending message.")] + public static partial void ErrorSendingMessage(ILogger logger, Exception ex); - private static readonly Action _serializedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(21, "SerializedMessage"), "Serialized '{MessageType}' to {MessageLength} byte message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 21, EventName = "SerializedMessage", Message = "Serialized '{MessageType}' to {MessageLength} byte message.")] + public static partial void SerializedMessage(ILogger logger, Type messageType, int messageLength); - private static readonly Action _compressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(22, "CompressingMessage"), "Compressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 22, EventName = "CompressingMessage", Message = "Compressing message with '{MessageEncoding}' encoding.")] + public static partial void CompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _decompressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(23, "DecompressingMessage"), "Decompressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 23, EventName = "DecompressingMessage", Message = "Decompressing message with '{MessageEncoding}' encoding.")] + public static partial void DecompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _deadlineTimeoutTooLong = - LoggerMessage.Define(LogLevel.Debug, new EventId(24, "DeadlineTimeoutTooLong"), "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 24, EventName = "DeadlineTimeoutTooLong", Message = "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used.")] + public static partial void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout); - private static readonly Action _deadlineTimerRescheduled = - LoggerMessage.Define(LogLevel.Trace, new EventId(25, "DeadlineTimerRescheduled"), "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 25, EventName = "DeadlineTimerRescheduled", Message = "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled.")] + public static partial void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining); - private static readonly Action _errorParsingTrailers = - LoggerMessage.Define(LogLevel.Error, new EventId(26, "ErrorParsingTrailers"), "Error parsing trailers."); + [LoggerMessage(Level = LogLevel.Error, EventId = 26, EventName = "ErrorParsingTrailers", Message = "Error parsing trailers.")] + public static partial void ErrorParsingTrailers(ILogger logger, Exception ex); - private static readonly Action _errorExceedingDeadline = - LoggerMessage.Define(LogLevel.Error, new EventId(27, "ErrorExceedingDeadline"), "Error exceeding deadline."); + [LoggerMessage(Level = LogLevel.Error, EventId = 27, EventName = "ErrorExceedingDeadline", Message = "Error exceeding deadline.")] + public static partial void ErrorExceedingDeadline(ILogger logger, Exception ex); - private static readonly Action _invalidGrpcStatusInHeader = - LoggerMessage.Define(LogLevel.Error, new EventId(28, "InvalidGrpcStatusInHeader"), "Header contains an OK gRPC status. This is invalid for unary or client streaming calls because a status in the header indicates there is no response body. " + - "A message in the response body is required for unary and client streaming calls."); + [LoggerMessage(Level = LogLevel.Error, EventId = 28, EventName = "InvalidGrpcStatusInHeader", + Message = "Header contains an OK gRPC status. This is invalid for unary or client streaming calls because a status in the header indicates there is no response body." + + " A message in the response body is required for unary and client streaming calls.")] + public static partial void InvalidGrpcStatusInHeader(ILogger logger); - public static void StartingCall(ILogger logger, MethodType methodType, Uri uri) - { - _startingCall(logger, methodType, uri, null); - } - - public static void ResponseHeadersReceived(ILogger logger) - { - _responseHeadersReceived(logger, null); - } - - public static void GrpcStatusError(ILogger logger, StatusCode status, string message, Exception? debugException) - { - _grpcStatusError(logger, status, message, debugException); - } - - public static void FinishedCall(ILogger logger) - { - _finishedCall(logger, null); - } - - public static void StartingDeadlineTimeout(ILogger logger, TimeSpan deadlineTimeout) - { - _startingDeadlineTimeout(logger, deadlineTimeout, null); - } - - public static void ErrorStartingCall(ILogger logger) - { - _errorStartingCall(logger, null); - } - - public static void DeadlineExceeded(ILogger logger) - { - _deadlineExceeded(logger, null); - } - - public static void CanceledCall(ILogger logger) - { - _canceledCall(logger, null); - } - - public static void MessageNotReturned(ILogger logger) - { - _messageNotReturned(logger, null); - } - - public static void CallCredentialsNotUsed(ILogger logger) - { - _callCredentialsNotUsed(logger, null); - } - - public static void ReadingMessage(ILogger logger) - { - _readingMessage(logger, null); - } - - public static void NoMessageReturned(ILogger logger) - { - _noMessageReturned(logger, null); - } - - public static void DeserializingMessage(ILogger logger, int messageLength, Type messageType) - { - _deserializingMessage(logger, messageLength, messageType, null); - } - - public static void ReceivedMessage(ILogger logger) - { - _receivedMessage(logger, null); - } - - public static void ErrorReadingMessage(ILogger logger, Exception ex) - { - _errorReadingMessage(logger, ex); - } - - public static void SendingMessage(ILogger logger) - { - _sendingMessage(logger, null); - } - - public static void MessageSent(ILogger logger) - { - _messageSent(logger, null); - } - - public static void ErrorSendingMessage(ILogger logger, Exception ex) - { - _errorSendingMessage(logger, ex); - } - - public static void SerializedMessage(ILogger logger, Type messageType, int messageLength) - { - _serializedMessage(logger, messageType, messageLength, null); - } - - public static void CompressingMessage(ILogger logger, string messageEncoding) - { - _compressingMessage(logger, messageEncoding, null); - } - - public static void DecompressingMessage(ILogger logger, string messageEncoding) - { - _decompressingMessage(logger, messageEncoding, null); - } - - public static void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout) - { - _deadlineTimeoutTooLong(logger, timeout, null); - } - - public static void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining) - { - _deadlineTimerRescheduled(logger, remaining, null); - } - - public static void ErrorParsingTrailers(ILogger logger, Exception ex) - { - _errorParsingTrailers(logger, ex); - } - - public static void ErrorExceedingDeadline(ILogger logger, Exception ex) - { - _errorExceedingDeadline(logger, ex); - } - - public static void InvalidGrpcStatusInHeader(ILogger logger) - { - _invalidGrpcStatusInHeader(logger, null); - } } diff --git a/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs b/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs index d38002909..7ec3a1534 100644 --- a/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs +++ b/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs @@ -275,13 +275,8 @@ public HttpContentClientStreamReaderDebugView(HttpContentClientStreamReader _readMessageError = - LoggerMessage.Define(LogLevel.Error, new EventId(1, "ReadMessageError"), "Error reading message."); - - public static void ReadMessageError(ILogger logger, Exception ex) - { - _readMessageError(logger, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 1, EventName = "ReadMessageError", Message = "Error reading message.")] + public static partial void ReadMessageError(ILogger logger, Exception ex); } diff --git a/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs b/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs index 2cbe4d3fd..17c52c84a 100644 --- a/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs +++ b/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs @@ -21,7 +21,7 @@ namespace Grpc.Net.Client.Internal.Retry; -internal class ChannelRetryThrottling +internal partial class ChannelRetryThrottling { private readonly object _lock = new object(); private readonly double _tokenRatio; @@ -83,14 +83,9 @@ private void UpdateRetryThrottlingActive() } } - private static class Log + private static partial class Log { - private static readonly Action _retryThrottlingActiveChanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "RetryThrottlingActiveChanged"), "Retry throttling active state changed. New value: {RetryThrottlingActive}"); - - public static void RetryThrottlingActiveChanged(ILogger logger, bool isRetryThrottlingActive) - { - _retryThrottlingActiveChanged(logger, isRetryThrottlingActive, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "RetryThrottlingActiveChanged", Message = "Retry throttling active state changed. New value: {RetryThrottlingActive}")] + public static partial void RetryThrottlingActiveChanged(ILogger logger, bool retryThrottlingActive); } } diff --git a/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs b/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs index a06390f73..e5b96c3f2 100644 --- a/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs +++ b/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -21,109 +21,44 @@ namespace Grpc.Net.Client.Internal.Retry; -internal static class RetryCallBaseLog +internal static partial class RetryCallBaseLog { - private static readonly Action _retryEvaluated = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "RetryEvaluated"), "Evaluated retry for failed gRPC call. Status code: '{StatusCode}', Attempt: {AttemptCount}, Retry: {WillRetry}"); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "RetryEvaluated", Message = "Evaluated retry for failed gRPC call. Status code: '{StatusCode}', Attempt: {AttemptCount}, Retry: {WillRetry}")] + internal static partial void RetryEvaluated(ILogger logger, StatusCode statusCode, int attemptCount, bool willRetry); - private static readonly Action _retryPushbackReceived = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "RetryPushbackReceived"), "Retry pushback of '{RetryPushback}' received from the failed gRPC call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "RetryPushbackReceived", Message = "Retry pushback of '{RetryPushback}' received from the failed gRPC call.")] + internal static partial void RetryPushbackReceived(ILogger logger, string retryPushback); - private static readonly Action _startingRetryDelay = - LoggerMessage.Define(LogLevel.Trace, new EventId(3, "StartingRetryDelay"), "Starting retry delay of {DelayDuration}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 3, EventName = "StartingRetryDelay", Message = "Starting retry delay of {DelayDuration}.")] + internal static partial void StartingRetryDelay(ILogger logger, TimeSpan delayDuration); - private static readonly Action _errorRetryingCall = - LoggerMessage.Define(LogLevel.Error, new EventId(4, "ErrorRetryingCall"), "Error retrying gRPC call."); + [LoggerMessage(Level = LogLevel.Error, EventId = 4, EventName = "ErrorRetryingCall", Message = "Error retrying gRPC call.")] + internal static partial void ErrorRetryingCall(ILogger logger, Exception ex); - private static readonly Action _sendingBufferedMessages = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "SendingBufferedMessages"), "Sending {MessageCount} buffered messages from previous failed gRPC calls."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "SendingBufferedMessages", Message = "Sending {MessageCount} buffered messages from previous failed gRPC calls.")] + internal static partial void SendingBufferedMessages(ILogger logger, int messageCount); - private static readonly Action _messageAddedToBuffer = - LoggerMessage.Define(LogLevel.Trace, new EventId(6, "MessageAddedToBuffer"), "Message with {MessageSize} bytes added to the buffer. There are {CallBufferSize} bytes buffered for this call."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 6, EventName = "MessageAddedToBuffer", Message = "Message with {MessageSize} bytes added to the buffer. There are {CallBufferSize} bytes buffered for this call.")] + internal static partial void MessageAddedToBuffer(ILogger logger, int messageSize, long callBufferSize); - private static readonly Action _callCommited = - LoggerMessage.Define(LogLevel.Debug, new EventId(7, "CallCommited"), "Call commited. Reason: {CommitReason}"); + [LoggerMessage(Level = LogLevel.Debug, EventId = 7, EventName = "CallCommited", Message = "Call commited. Reason: {CommitReason}")] + internal static partial void CallCommited(ILogger logger, CommitReason commitReason); - private static readonly Action _startingRetryWorker = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "StartingRetryWorker"), "Starting retry worker."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "StartingRetryWorker", Message = "Starting retry worker.")] + internal static partial void StartingRetryWorker(ILogger logger); - private static readonly Action _stoppingRetryWorker = - LoggerMessage.Define(LogLevel.Trace, new EventId(9, "StoppingRetryWorker"), "Stopping retry worker."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 9, EventName = "StoppingRetryWorker", Message = "Stopping retry worker.")] + internal static partial void StoppingRetryWorker(ILogger logger); - private static readonly Action _maxAttemptsLimited = - LoggerMessage.Define(LogLevel.Debug, new EventId(10, "MaxAttemptsLimited"), "The method has {ServiceConfigMaxAttempts} attempts specified in the service config. The number of attempts has been limited by channel configuration to {ChannelMaxAttempts}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 10, EventName = "MaxAttemptsLimited", Message = "The method has {ServiceConfigMaxAttempts} attempts specified in the service config. The number of attempts has been limited by channel configuration to {ChannelMaxAttempts}.")] + internal static partial void MaxAttemptsLimited(ILogger logger, int serviceConfigMaxAttempts, int channelMaxAttempts); - private static readonly Action _additionalCallsBlockedByRetryThrottling = - LoggerMessage.Define(LogLevel.Debug, new EventId(11, "AdditionalCallsBlockedByRetryThrottling"), "Additional calls blocked by retry throttling."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 11, EventName = "AdditionalCallsBlockedByRetryThrottling", Message = "Additional calls blocked by retry throttling.")] + internal static partial void AdditionalCallsBlockedByRetryThrottling(ILogger logger); - private static readonly Action _startingAttempt = - LoggerMessage.Define(LogLevel.Debug, new EventId(12, "StartingAttempt"), "Starting attempt {AttemptCount}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 12, EventName = "StartingAttempt", Message = "Starting attempt {AttemptCount}.")] + internal static partial void StartingAttempt(ILogger logger, int AttemptCount); - private static readonly Action _canceledRetry = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "CanceledRetry"), "gRPC retry call canceled."); - - internal static void RetryEvaluated(ILogger logger, StatusCode statusCode, int attemptCount, bool willRetry) - { - _retryEvaluated(logger, statusCode, attemptCount, willRetry, null); - } - - internal static void RetryPushbackReceived(ILogger logger, string retryPushback) - { - _retryPushbackReceived(logger, retryPushback, null); - } - - internal static void StartingRetryDelay(ILogger logger, TimeSpan delayDuration) - { - _startingRetryDelay(logger, delayDuration, null); - } - - internal static void ErrorRetryingCall(ILogger logger, Exception ex) - { - _errorRetryingCall(logger, ex); - } - - internal static void SendingBufferedMessages(ILogger logger, int messageCount) - { - _sendingBufferedMessages(logger, messageCount, null); - } - - internal static void MessageAddedToBuffer(ILogger logger, int messageSize, long callBufferSize) - { - _messageAddedToBuffer(logger, messageSize, callBufferSize, null); - } - - internal static void CallCommited(ILogger logger, CommitReason commitReason) - { - _callCommited(logger, commitReason, null); - } - - internal static void StartingRetryWorker(ILogger logger) - { - _startingRetryWorker(logger, null); - } - - internal static void StoppingRetryWorker(ILogger logger) - { - _stoppingRetryWorker(logger, null); - } - - internal static void MaxAttemptsLimited(ILogger logger, int serviceConfigMaxAttempts, int channelMaxAttempts) - { - _maxAttemptsLimited(logger, serviceConfigMaxAttempts, channelMaxAttempts, null); - } - - internal static void AdditionalCallsBlockedByRetryThrottling(ILogger logger) - { - _additionalCallsBlockedByRetryThrottling(logger, null); - } - - internal static void StartingAttempt(ILogger logger, int attempts) - { - _startingAttempt(logger, attempts, null); - } - - internal static void CanceledRetry(ILogger logger) - { - _canceledRetry(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "CanceledRetry", Message = "gRPC retry call canceled.")] + internal static partial void CanceledRetry(ILogger logger); } diff --git a/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs b/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs index 8b46cbb86..b63816785 100644 --- a/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs +++ b/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs @@ -31,7 +31,7 @@ namespace Grpc.Net.ClientFactory.Internal; internal readonly record struct EntryKey(string Name, Type Type); -internal class GrpcCallInvokerFactory +internal partial class GrpcCallInvokerFactory { private readonly ILoggerFactory _loggerFactory; private readonly IOptionsMonitor _grpcClientFactoryOptionsMonitor; @@ -251,14 +251,9 @@ protected override Task SendAsync(HttpRequestMessage reques } } - private static class Log + private static partial class Log { - private static readonly Action _httpClientActionsPartiallySupported = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "HttpClientActionsPartiallySupported"), "The ConfigureHttpClient method is used to configure gRPC client '{ClientName}'. ConfigureHttpClient is partially supported when creating gRPC clients and only some HttpClient properties such as BaseAddress and DefaultRequestHeaders are applied to the gRPC client."); - - public static void HttpClientActionsPartiallySupported(ILogger logger, string clientName) - { - _httpClientActionsPartiallySupported(logger, clientName, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "HttpClientActionsPartiallySupported", Message = "The ConfigureHttpClient method is used to configure gRPC client '{ClientName}'. ConfigureHttpClient is partially supported when creating gRPC clients and only some HttpClient properties such as BaseAddress and DefaultRequestHeaders are applied to the gRPC client.")] + public static partial void HttpClientActionsPartiallySupported(ILogger logger, string clientName); } } From b1df3e4c76792212a0401e1ae17114867fd6663b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 21:54:20 +0800 Subject: [PATCH 4/9] Bump serve-static from 1.14.2 to 1.16.2 in /examples/Spar/Server/ClientApp (#2536) Bumps [serve-static](https://github.com/expressjs/serve-static) from 1.14.2 to 1.16.2. - [Release notes](https://github.com/expressjs/serve-static/releases) - [Changelog](https://github.com/expressjs/serve-static/blob/v1.16.2/HISTORY.md) - [Commits](https://github.com/expressjs/serve-static/compare/v1.14.2...v1.16.2) --- updated-dependencies: - dependency-name: serve-static dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Spar/Server/ClientApp/package-lock.json | 179 ++++++++++-------- 1 file changed, 99 insertions(+), 80 deletions(-) diff --git a/examples/Spar/Server/ClientApp/package-lock.json b/examples/Spar/Server/ClientApp/package-lock.json index 8e0c650ae..6215cf0cb 100644 --- a/examples/Spar/Server/ClientApp/package-lock.json +++ b/examples/Spar/Server/ClientApp/package-lock.json @@ -3613,12 +3613,12 @@ } }, "node_modules/depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "dev": true, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, "node_modules/des.js": { @@ -3632,10 +3632,14 @@ } }, "node_modules/destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", - "dev": true + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } }, "node_modules/diffie-hellman": { "version": "5.0.3", @@ -3769,7 +3773,7 @@ "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "dev": true }, "node_modules/electron-to-chromium": { @@ -3800,9 +3804,9 @@ "dev": true }, "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", "dev": true, "engines": { "node": ">= 0.8" @@ -3910,7 +3914,7 @@ "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", "dev": true }, "node_modules/escape-string-regexp": { @@ -3991,7 +3995,7 @@ "node_modules/etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", "dev": true, "engines": { "node": ">= 0.6" @@ -4311,7 +4315,7 @@ "node_modules/fresh": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", "dev": true, "engines": { "node": ">= 0.6" @@ -4956,19 +4960,19 @@ } }, "node_modules/http-errors": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", - "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dev": true, "dependencies": { - "depd": "~1.1.2", + "depd": "2.0.0", "inherits": "2.0.4", "setprototypeof": "1.2.0", - "statuses": ">= 1.5.0 < 2", + "statuses": "2.0.1", "toidentifier": "1.0.1" }, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, "node_modules/http-signature": { @@ -6344,9 +6348,9 @@ } }, "node_modules/on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "dev": true, "dependencies": { "ee-first": "1.1.1" @@ -7825,24 +7829,24 @@ } }, "node_modules/send": { - "version": "0.17.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.17.2.tgz", - "integrity": "sha512-UJYB6wFSJE3G00nEivR5rgWp8c2xXvJ3OPWPhmuteU0IKj8nKbG3DrjiOmLwpnHGYWAVwA69zmTm++YG0Hmwww==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", "dev": true, "dependencies": { "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", + "depd": "2.0.0", + "destroy": "1.2.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "0.5.2", - "http-errors": "1.8.1", + "http-errors": "2.0.0", "mime": "1.6.0", "ms": "2.1.3", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "range-parser": "~1.2.1", - "statuses": "~1.5.0" + "statuses": "2.0.1" }, "engines": { "node": ">= 0.8.0" @@ -7860,9 +7864,18 @@ "node_modules/send/node_modules/debug/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/send/node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -7879,15 +7892,15 @@ } }, "node_modules/serve-static": { - "version": "1.14.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.2.tgz", - "integrity": "sha512-+TMNA9AFxUEGuC0z2mevogSnn9MXKb4fa7ngeRMJaaGv8vTwnIEkKi+QGvPt33HSnf8pRS+WGM0EbMtCJLKMBQ==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", "dev": true, "dependencies": { - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.17.2" + "send": "0.19.0" }, "engines": { "node": ">= 0.8.0" @@ -8414,12 +8427,12 @@ } }, "node_modules/statuses": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, "node_modules/stealthy-require": { @@ -12133,9 +12146,9 @@ "dev": true }, "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "dev": true }, "des.js": { @@ -12149,9 +12162,9 @@ } }, "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", "dev": true }, "diffie-hellman": { @@ -12274,7 +12287,7 @@ "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "dev": true }, "electron-to-chromium": { @@ -12307,9 +12320,9 @@ } }, "encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", "dev": true }, "entities": { @@ -12389,7 +12402,7 @@ "escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", "dev": true }, "escape-string-regexp": { @@ -12440,7 +12453,7 @@ "etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", "dev": true }, "events": { @@ -12708,7 +12721,7 @@ "fresh": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", "dev": true }, "fs.realpath": { @@ -13198,15 +13211,15 @@ } }, "http-errors": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", - "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dev": true, "requires": { - "depd": "~1.1.2", + "depd": "2.0.0", "inherits": "2.0.4", "setprototypeof": "1.2.0", - "statuses": ">= 1.5.0 < 2", + "statuses": "2.0.1", "toidentifier": "1.0.1" } }, @@ -14294,9 +14307,9 @@ } }, "on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "dev": true, "requires": { "ee-first": "1.1.1" @@ -15519,24 +15532,24 @@ "dev": true }, "send": { - "version": "0.17.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.17.2.tgz", - "integrity": "sha512-UJYB6wFSJE3G00nEivR5rgWp8c2xXvJ3OPWPhmuteU0IKj8nKbG3DrjiOmLwpnHGYWAVwA69zmTm++YG0Hmwww==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", "dev": true, "requires": { "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", + "depd": "2.0.0", + "destroy": "1.2.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "0.5.2", - "http-errors": "1.8.1", + "http-errors": "2.0.0", "mime": "1.6.0", "ms": "2.1.3", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "range-parser": "~1.2.1", - "statuses": "~1.5.0" + "statuses": "2.0.1" }, "dependencies": { "debug": { @@ -15551,11 +15564,17 @@ "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true } } }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "dev": true + }, "ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -15571,15 +15590,15 @@ "dev": true }, "serve-static": { - "version": "1.14.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.2.tgz", - "integrity": "sha512-+TMNA9AFxUEGuC0z2mevogSnn9MXKb4fa7ngeRMJaaGv8vTwnIEkKi+QGvPt33HSnf8pRS+WGM0EbMtCJLKMBQ==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", "dev": true, "requires": { - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.17.2" + "send": "0.19.0" } }, "set-value": { @@ -16017,9 +16036,9 @@ } }, "statuses": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true }, "stealthy-require": { From df3d8dc9964b4a80c3ea5ad1bd54a98da92fb6a3 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Tue, 1 Oct 2024 14:24:32 +0800 Subject: [PATCH 5/9] Update to Grpc.Tools 2.67.0-pre1 (#2547) --- Directory.Packages.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 10504653f..e12fc9bfb 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,7 +5,7 @@ 8.0.6 7.0.5 6.0.33 - 2.63.0 + 2.66.0 1.6.0 1.8.1 1.8.0-beta.1 @@ -33,7 +33,7 @@ - + From 490894cdedb34b43c32dc576d5745c41223764b6 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Wed, 2 Oct 2024 08:10:26 +0800 Subject: [PATCH 6/9] Cleanup gRPC unit testing helpers in tester sample (#2548) --- .../UnitTests/Helpers/TestServerCallContext.cs | 5 +---- .../UnitTests/Helpers/TestServerStreamWriter.cs | 16 +++++++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerCallContext.cs b/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerCallContext.cs index 1f4cbd3bf..ddc4aa405 100644 --- a/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerCallContext.cs +++ b/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerCallContext.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -22,8 +22,6 @@ using System.Threading.Tasks; using Grpc.Core; -// TODO(JamesNK): Remove nullable override after Grpc.Core.Api update -#pragma warning disable CS8764 // Nullability of return type doesn't match overridden member (possibly because of nullability attributes). namespace Tests.Server.UnitTests.Helpers { public class TestServerCallContext : ServerCallContext @@ -81,4 +79,3 @@ public static TestServerCallContext Create(Metadata? requestHeaders = null, Canc } } } -#pragma warning restore CS8764 // Nullability of return type doesn't match overridden member (possibly because of nullability attributes). diff --git a/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerStreamWriter.cs b/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerStreamWriter.cs index 08163f12a..a00d8cf79 100644 --- a/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerStreamWriter.cs +++ b/examples/Tester/Tests/Server/UnitTests/Helpers/TestServerStreamWriter.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -22,8 +22,6 @@ using System.Threading.Tasks; using Grpc.Core; -// TODO(JamesNK): Remove nullable override after Grpc.Core.Api update -#pragma warning disable CS8766 // Nullability of reference types in return type doesn't match implicitly implemented member (possibly because of nullability attributes). namespace Tests.Server.UnitTests.Helpers { public class TestServerStreamWriter : IServerStreamWriter where T : class @@ -63,8 +61,12 @@ public IAsyncEnumerable ReadAllAsync() } } - public Task WriteAsync(T message) + public Task WriteAsync(T message, CancellationToken cancellationToken) { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } if (_serverCallContext.CancellationToken.IsCancellationRequested) { return Task.FromCanceled(_serverCallContext.CancellationToken); @@ -77,6 +79,10 @@ public Task WriteAsync(T message) return Task.CompletedTask; } + + public Task WriteAsync(T message) + { + return WriteAsync(message, CancellationToken.None); + } } } -#pragma warning restore CS8766 // Nullability of reference types in return type doesn't match implicitly implemented member (possibly because of nullability attributes). From 0f2ffdc03edcd832e6f83a9deb73e2d57c0b8dbf Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Wed, 9 Oct 2024 10:01:33 +0800 Subject: [PATCH 7/9] Fix UpdateBalancingState not called when address attributes are modified (#2553) --- examples/Container/Backend/Dockerfile | 4 +- examples/Container/Frontend/Dockerfile | 4 +- global.json | 2 +- .../Balancer/SubchannelsLoadBalancer.cs | 5 +- .../Balancer/SubchannelsLoadBalancerTests.cs | 199 ++++++++++++++++++ .../InteropTestsGrpcWebWebsite/Dockerfile | 4 +- testassets/InteropTestsWebsite/Dockerfile | 4 +- 7 files changed, 212 insertions(+), 10 deletions(-) create mode 100644 test/Grpc.Net.Client.Tests/Balancer/SubchannelsLoadBalancerTests.cs diff --git a/examples/Container/Backend/Dockerfile b/examples/Container/Backend/Dockerfile index 78b8007d5..7c0429870 100644 --- a/examples/Container/Backend/Dockerfile +++ b/examples/Container/Backend/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/nightly/sdk:9.0-preview AS build-env +FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build-env WORKDIR /app # Copy everything @@ -8,7 +8,7 @@ RUN dotnet restore examples/Container/Backend RUN dotnet publish examples/Container/Backend -c Release -o out # Build runtime image -FROM mcr.microsoft.com/dotnet/nightly/aspnet:9.0-preview +FROM mcr.microsoft.com/dotnet/aspnet:9.0 WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "Backend.dll"] \ No newline at end of file diff --git a/examples/Container/Frontend/Dockerfile b/examples/Container/Frontend/Dockerfile index 23403110c..017712b23 100644 --- a/examples/Container/Frontend/Dockerfile +++ b/examples/Container/Frontend/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/nightly/sdk:9.0-preview AS build-env +FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build-env WORKDIR /app # Copy everything @@ -8,7 +8,7 @@ RUN dotnet restore examples/Container/Frontend RUN dotnet publish examples/Container/Frontend -c Release -o out # Build runtime image -FROM mcr.microsoft.com/dotnet/nightly/aspnet:9.0-preview +FROM mcr.microsoft.com/dotnet/aspnet:9.0 WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "Frontend.dll"] \ No newline at end of file diff --git a/global.json b/global.json index 67d91a4f9..0344c423c 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "9.0.100-preview.7.24407.12", + "version": "9.0.100-rc.2.24474.11", "rollForward": "latestFeature" } } diff --git a/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs b/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs index 5f27c347b..73b88f7e1 100644 --- a/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs +++ b/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs @@ -122,6 +122,7 @@ public override void UpdateChannelState(ChannelState state) var allUpdatedSubchannels = new List(); var newSubchannels = new List(); + var hasModifiedSubchannels = false; var currentSubchannels = _addressSubchannels.ToList(); // The state's addresses is the new authoritative list of addresses. @@ -150,6 +151,8 @@ public override void UpdateChannelState(ChannelState state) address, newOrCurrentSubchannel.LastKnownState); newOrCurrentSubchannel.Subchannel.UpdateAddresses(new[] { address }); + + hasModifiedSubchannels = true; } SubchannelLog.SubchannelPreserved(_logger, newOrCurrentSubchannel.Subchannel.Id, address); @@ -171,7 +174,7 @@ public override void UpdateChannelState(ChannelState state) // This can all be removed. var removedSubConnections = currentSubchannels; - if (removedSubConnections.Count == 0 && newSubchannels.Count == 0) + if (removedSubConnections.Count == 0 && newSubchannels.Count == 0 && !hasModifiedSubchannels) { SubchannelsLoadBalancerLog.ConnectionsUnchanged(_logger); return; diff --git a/test/Grpc.Net.Client.Tests/Balancer/SubchannelsLoadBalancerTests.cs b/test/Grpc.Net.Client.Tests/Balancer/SubchannelsLoadBalancerTests.cs new file mode 100644 index 000000000..533ce0e3f --- /dev/null +++ b/test/Grpc.Net.Client.Tests/Balancer/SubchannelsLoadBalancerTests.cs @@ -0,0 +1,199 @@ +#region Copyright notice and license + +// Copyright 2019 The gRPC Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +#if SUPPORT_LOAD_BALANCING +using System.Net; +using Grpc.Core; +using Grpc.Net.Client.Balancer; +using Grpc.Net.Client.Balancer.Internal; +using Grpc.Tests.Shared; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Grpc.Net.Client.Tests.Infrastructure.Balancer; + +[TestFixture] +public class SubchannelsLoadBalancerTests +{ + [Test] + public void UpdateChannelState_AddressMatchAndAttributesDifferent_UpdateState() + { + // Arrange + const string host1 = "127.0.0.1"; + const string host2 = "127.0.0.2"; + const int port = 80; + + const string attributeKey = "key1"; + + var controller = new CustomChannelControlHelper(); + var balancer = new CustomBalancer(controller, NullLoggerFactory.Instance); + + // create 2 addresses with some attributes + var address1 = new BalancerAddress(host1, port); + address1.Attributes.TryAdd(attributeKey, 20); // <-- difference + + var address2 = new BalancerAddress(host2, port); + address2.Attributes.TryAdd(attributeKey, 80); // <-- difference + + var state1 = new ChannelState( + status: new Status(), + addresses: [address1, address2], + loadBalancingConfig: null, + attributes: new BalancerAttributes()); + + // create 2 addresses with the same hosts and ports as previous but with other attribute values + var address3 = new BalancerAddress(host1, port); + address3.Attributes.TryAdd(attributeKey, 40); // <-- difference + + var address4 = new BalancerAddress(host2, port); + address4.Attributes.TryAdd(attributeKey, 60); // <-- difference + + var state2 = new ChannelState( + status: new Status(), + addresses: [address3, address4], + loadBalancingConfig: null, + attributes: new BalancerAttributes()); + + // Act + // first update with `address1` and `address2` + balancer.UpdateChannelState(state1); + + // remember count of `IChannelControlHelper.UpdateState()` calls + var updateStateCallsCount1 = controller.UpdateStateCallsCount; + + // second update with `address3` and `address4` + // which differs from `address1` and `address2` _only_ in attributes values + balancer.UpdateChannelState(state2); + + // get count of `IChannelControlHelper.UpdateState()` calls after second update + var updateStateCallsCount2 = controller.UpdateStateCallsCount; + + // Assert + Assert.True( + updateStateCallsCount2 > updateStateCallsCount1, + "`IChannelControlHelper.UpdateState()` was not called from `SubchannelsLoadBalancer.UpdateChannelState()`"); + } +} + +file class CustomBalancer( + IChannelControlHelper controller, + ILoggerFactory loggerFactory) + : SubchannelsLoadBalancer(controller, loggerFactory) +{ + protected override SubchannelPicker CreatePicker(IReadOnlyList readySubchannels) + { + return new CustomPicker(readySubchannels); + } +} + +file class CustomPicker : SubchannelPicker +{ + private IReadOnlyList readySubchannels; + + public CustomPicker(IReadOnlyList readySubchannels) + { + this.readySubchannels = readySubchannels; + } + + public override PickResult Pick(PickContext context) + { + return PickResult.ForSubchannel(readySubchannels[0]); + } +} + +file class CustomChannelControlHelper : IChannelControlHelper +{ + public int UpdateStateCallsCount { get; private set; } + + public Subchannel CreateSubchannel(SubchannelOptions options) + { + var subchannelTransportFactory = new CustomSubchannelTransportFactory(); + + var manager = new ConnectionManager( + new CustomResolver(), + true, + NullLoggerFactory.Instance, + new CustomBackoffPolicyFactory(), + subchannelTransportFactory, + []); + + return ((IChannelControlHelper)manager).CreateSubchannel(options); + } + + public void UpdateState(BalancerState state) + { + UpdateStateCallsCount++; + } + + public void RefreshResolver() { } +} + +file class CustomResolver() : PollingResolver(NullLoggerFactory.Instance) +{ + protected override Task ResolveAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } +} + +file class CustomBackoffPolicyFactory : IBackoffPolicyFactory +{ + public IBackoffPolicy Create() + { + return new CustomBackoffPolicy(); + } +} + +file class CustomBackoffPolicy : IBackoffPolicy +{ + public TimeSpan NextBackoff() + { + return TimeSpan.Zero; + } +} + +file class CustomSubchannelTransportFactory : ISubchannelTransportFactory +{ + public ISubchannelTransport Create(Subchannel subchannel) + { + return new CustomSubchannelTransport(); + } +} + +file class CustomSubchannelTransport : ISubchannelTransport +{ + public void Dispose() { } + + public DnsEndPoint? CurrentEndPoint { get; } + public TimeSpan? ConnectTimeout { get; } + public TransportStatus TransportStatus { get; } + + public ValueTask GetStreamAsync(DnsEndPoint endPoint, CancellationToken cancellationToken) + { + return ValueTask.FromResult(new MemoryStream()); + } + + public ValueTask TryConnectAsync(ConnectContext context, int attempt) + { + return ValueTask.FromResult(ConnectResult.Success); + } + + public void Disconnect() { } +} + +#endif diff --git a/testassets/InteropTestsGrpcWebWebsite/Dockerfile b/testassets/InteropTestsGrpcWebWebsite/Dockerfile index c8ecbf5c2..9a71faacf 100644 --- a/testassets/InteropTestsGrpcWebWebsite/Dockerfile +++ b/testassets/InteropTestsGrpcWebWebsite/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/nightly/sdk:9.0-preview AS build-env +FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build-env WORKDIR /app # Copy everything @@ -8,7 +8,7 @@ RUN dotnet restore testassets/InteropTestsGrpcWebWebsite RUN dotnet publish testassets/InteropTestsGrpcWebWebsite -c Release -o out # Build runtime image -FROM mcr.microsoft.com/dotnet/nightly/aspnet:9.0-preview +FROM mcr.microsoft.com/dotnet/aspnet:9.0 WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "InteropTestsGrpcWebWebsite.dll", "--urls", "http://+:80"] diff --git a/testassets/InteropTestsWebsite/Dockerfile b/testassets/InteropTestsWebsite/Dockerfile index 16e916257..59cdeb214 100644 --- a/testassets/InteropTestsWebsite/Dockerfile +++ b/testassets/InteropTestsWebsite/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/nightly/sdk:9.0-preview AS build-env +FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build-env WORKDIR /app # Copy everything @@ -8,7 +8,7 @@ RUN dotnet restore testassets/InteropTestsWebsite RUN dotnet publish testassets/InteropTestsWebsite --framework net9.0 -c Release -o out -p:LatestFramework=true # Build runtime image -FROM mcr.microsoft.com/dotnet/nightly/aspnet:9.0-preview +FROM mcr.microsoft.com/dotnet/aspnet:9.0 WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "InteropTestsWebsite.dll", "--port_http1", "80"] \ No newline at end of file From b88713e83f3c75282678fdc15bf830fa78bfff2c Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Wed, 9 Oct 2024 13:52:55 +0800 Subject: [PATCH 8/9] Update Grpc.Tools to 2.67.0 (#2554) --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e12fc9bfb..9819d45ec 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -33,7 +33,7 @@ - + From a2eed32f3cbff0d029aaf800100a7b3837af83e9 Mon Sep 17 00:00:00 2001 From: apolcyn Date: Mon, 21 Oct 2024 21:45:49 -0700 Subject: [PATCH 9/9] Bump version for 2.67 RC (#2555) * bump version for 2.67 RC * Fix System.Text.Json vulnerability warning (#2556) * Fix build --------- Co-authored-by: James Newton-King --- Directory.Packages.props | 5 +++-- build/version.props | 4 ++-- src/Grpc.Core.Api/VersionInfo.cs | 4 ++-- src/dotnet-grpc/dotnet-grpc.csproj | 3 ++- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 9819d45ec..9a3224d64 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,7 +1,7 @@ true - 9.0.0-preview.5.24306.11 + 9.0.0-rc.2.24474.3 8.0.6 7.0.5 6.0.33 @@ -9,7 +9,7 @@ 1.6.0 1.8.1 1.8.0-beta.1 - 9.0.0-preview.5.24306.7 + 9.0.0-rc.2.24473.5 6.0.0 @@ -82,6 +82,7 @@ + diff --git a/build/version.props b/build/version.props index 75373120d..db7cbe5c4 100644 --- a/build/version.props +++ b/build/version.props @@ -2,13 +2,13 @@ - 2.66.0-dev + 2.67.0-pre1 2.0.0.0 - 2.66.0.0 + 2.67.0.0 diff --git a/src/Grpc.Core.Api/VersionInfo.cs b/src/Grpc.Core.Api/VersionInfo.cs index d4b472b99..5e43f7b8d 100644 --- a/src/Grpc.Core.Api/VersionInfo.cs +++ b/src/Grpc.Core.Api/VersionInfo.cs @@ -36,10 +36,10 @@ public static class VersionInfo /// /// Current AssemblyFileVersion of gRPC C# assemblies /// - public const string CurrentAssemblyFileVersion = "2.66.0.0"; + public const string CurrentAssemblyFileVersion = "2.67.0.0"; /// /// Current version of gRPC C# /// - public const string CurrentVersion = "2.66.0-dev"; + public const string CurrentVersion = "2.67.0-pre1"; } diff --git a/src/dotnet-grpc/dotnet-grpc.csproj b/src/dotnet-grpc/dotnet-grpc.csproj index 3b246baeb..c48025ae9 100644 --- a/src/dotnet-grpc/dotnet-grpc.csproj +++ b/src/dotnet-grpc/dotnet-grpc.csproj @@ -1,4 +1,4 @@ - + Command line tool for gRPC projects gRPC RPC CLI @@ -26,6 +26,7 @@ +