示例#1
0
        public static GrpcServiceOptions GetGrpcServiceOptions()
        {
            var opt = new GrpcServiceOptions();

            opt.AddPort("0.0.0.0", 50001);
            return(opt);
        }
        public ServerStreamingServerCallHandler(
            Method <TRequest, TResponse> method,
            ServerStreamingServerMethod <TService, TRequest, TResponse> invoker,
            GrpcServiceOptions serviceOptions,
            ILoggerFactory loggerFactory)
            : base(method, serviceOptions, loggerFactory)
        {
            _invoker = invoker;

            if (!ServiceOptions.Interceptors.IsEmpty)
            {
                ServerStreamingServerMethod <TRequest, TResponse> resolvedInvoker = async(resolvedRequest, responseStream, resolvedContext) =>
                {
                    var      activator = resolvedContext.GetHttpContext().RequestServices.GetRequiredService <IGrpcServiceActivator <TService> >();
                    TService?service   = null;
                    try
                    {
                        service = activator.Create();
                        await _invoker(service, resolvedRequest, responseStream, resolvedContext);
                    }
                    finally
                    {
                        if (service != null)
                        {
                            activator.Release(service);
                        }
                    }
                };

                var interceptorPipeline = new InterceptorPipelineBuilder <TRequest, TResponse>(ServiceOptions.Interceptors);
                _pipelineInvoker = interceptorPipeline.ServerStreamingPipeline(resolvedInvoker);
            }
        }
        public ServerStreamingServerCallHandler(
            Method <TRequest, TResponse> method,
            ServerStreamingServerMethod <TService, TRequest, TResponse> invoker,
            GrpcServiceOptions serviceOptions,
            ILoggerFactory loggerFactory,
            IGrpcServiceActivator <TService> serviceActivator,
            IServiceProvider serviceProvider)
            : base(method, serviceOptions, loggerFactory, serviceActivator, serviceProvider)
        {
            _invoker = invoker;

            if (ServiceOptions.HasInterceptors)
            {
                ServerStreamingServerMethod <TRequest, TResponse> resolvedInvoker = async(resolvedRequest, responseStream, resolvedContext) =>
                {
                    GrpcActivatorHandle <TService> serviceHandle = default;
                    try
                    {
                        serviceHandle = ServiceActivator.Create(resolvedContext.GetHttpContext().RequestServices);
                        await _invoker(serviceHandle.Instance, resolvedRequest, responseStream, resolvedContext);
                    }
                    finally
                    {
                        if (serviceHandle.Instance != null)
                        {
                            ServiceActivator.Release(serviceHandle);
                        }
                    }
                };

                var interceptorPipeline = new InterceptorPipelineBuilder <TRequest, TResponse>(ServiceOptions.Interceptors, ServiceProvider);
                _pipelineInvoker = interceptorPipeline.ServerStreamingPipeline(resolvedInvoker);
            }
        }
        public ServerCallHandlerFactory(ILoggerFactory loggerFactory, IOptions <GrpcServiceOptions> globalOptions, IOptions <GrpcServiceOptions <TService> > serviceOptions)
        {
            _loggerFactory = loggerFactory;

            var so = serviceOptions.Value;
            var go = globalOptions.Value;

            // This is required to get ensure that service methods without any explicit configuration
            // will continue to get the global configuration options
            _resolvedOptions = new GrpcServiceOptions
            {
                EnableDetailedErrors         = so.EnableDetailedErrors ?? go.EnableDetailedErrors,
                ReceiveMaxMessageSize        = so.ReceiveMaxMessageSize ?? go.ReceiveMaxMessageSize,
                SendMaxMessageSize           = so.SendMaxMessageSize ?? go.SendMaxMessageSize,
                ResponseCompressionAlgorithm = so.ResponseCompressionAlgorithm ?? go.ResponseCompressionAlgorithm,
                ResponseCompressionLevel     = so.ResponseCompressionLevel ?? go.ResponseCompressionLevel,
                CompressionProviders         = so._compressionProviders ?? go._compressionProviders ?? new List <ICompressionProvider>()
            };

            _resolvedOptions.Interceptors.AddRange(go.Interceptors);
            _resolvedOptions.Interceptors.AddRange(so.Interceptors);

            if (_resolvedOptions.ResponseCompressionAlgorithm != null)
            {
                var responseCompressionProvider = _resolvedOptions.CompressionProviders?.FirstOrDefault(p => string.Equals(_resolvedOptions.ResponseCompressionAlgorithm, p.EncodingName, StringComparison.Ordinal));
                if (responseCompressionProvider == null)
                {
                    throw new InvalidOperationException($"The configured response compression algorithm '{_resolvedOptions.ResponseCompressionAlgorithm}' does not have a matching compression provider.");
                }
            }
        }
示例#5
0
        public async Task WriteMessageAsync_GzipCompressed_WriteCompressedData()
        {
            // Arrange
            var serviceOptions = new GrpcServiceOptions
            {
                ResponseCompressionAlgorithm = "gzip",
                CompressionProviders         =
                {
                    new GzipCompressionProvider(System.IO.Compression.CompressionLevel.Fastest)
                }
            };

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers[GrpcProtocolConstants.MessageAcceptEncodingHeader] = "gzip";

            var context = HttpContextServerCallContextHelper.CreateServerCallContext(httpContext, serviceOptions);

            context.Initialize();

            var ms         = new MemoryStream();
            var pipeWriter = new StreamPipeWriter(ms);

            // Act
            await pipeWriter.WriteMessageAsync(new byte[] { 0x10 }, context, flush : true);

            // Assert
            var messageData = ms.ToArray();

            Assert.AreEqual(1, messageData[0]);  // compression
            Assert.AreEqual(21, messageData[4]); // message length
        }
示例#6
0
 public ClientStreamingServerCallHandler(
     Method <TRequest, TResponse> method,
     ClientStreamingServerMethod <TService, TRequest, TResponse> invoker,
     GrpcServiceOptions serviceOptions,
     ILoggerFactory loggerFactory) : base(method, serviceOptions, loggerFactory)
 {
     _invoker = invoker;
 }
        public void PostConfigure(string name, GrpcServiceOptions <TService> options)
        {
            var marshallerFactory = _serviceConfiguration.Value.MarshallerFactory ?? _rootConfiguration.Value.DefaultMarshallerFactory;

            PostConfigureGrpcServiceOptions.AddErrorHandler(
                options.Interceptors,
                _serviceConfiguration.Value.ErrorHandlerFactory,
                marshallerFactory);
        }
示例#8
0
 public static HttpContextServerCallContext CreateServerCallContext(
     HttpContext httpContext           = null,
     GrpcServiceOptions serviceOptions = null,
     ILogger logger = null)
 {
     return(new HttpContextServerCallContext(
                httpContext ?? new DefaultHttpContext(),
                serviceOptions ?? new GrpcServiceOptions(),
                logger ?? NullLogger.Instance));
 }
 public ServerCallHandlerFactory(
     ILoggerFactory loggerFactory,
     IOptions <GrpcServiceOptions> globalOptions,
     IOptions <GrpcServiceOptions <TService> > serviceOptions,
     IGrpcServiceActivator <TService> serviceActivator)
 {
     _loggerFactory    = loggerFactory;
     _serviceActivator = serviceActivator;
     _serviceOptions   = serviceOptions.Value;
     _globalOptions    = globalOptions.Value;
 }
示例#10
0
        static async Task Main(string[] args)
        {
            var o = new GrpcServiceOptions();

            o.AddPort("0.0.0.0", 50001);
            var options = new MiddlewareOptions();

            options.UseCallbackThrottling(1000);
            var host = NetRpcManager.CreateHost(o, options, new Contract <IService, Service>());
            await host.RunAsync();
        }
 protected ServerCallHandlerBase(
     Method <TRequest, TResponse> method,
     GrpcServiceOptions serviceOptions,
     ILoggerFactory loggerFactory,
     IGrpcServiceActivator <TService> serviceActivator,
     IServiceProvider serviceProvider)
 {
     Method           = method;
     ServiceOptions   = serviceOptions;
     ServiceActivator = serviceActivator;
     ServiceProvider  = serviceProvider;
     Logger           = loggerFactory.CreateLogger(typeof(TService));
 }
        /// <summary>
        /// Adds service method specific options to the specified <see cref="GrpcServiceOptions" />.
        /// </summary>
        /// <typeparam name="TService">The service type to configure the methods options on.</typeparam>
        /// <param name="serviceOptions">The <see cref="GrpcServiceOptions" /> to add the method options to.</param>
        /// <param name="name">The name of the method.</param>
        /// <param name="configure">A callback to configure the service options.</param>
        public static void AddMethodOptions <TService>(this GrpcServiceOptions <TService> serviceOptions, string name, Action <GrpcServiceMethodOptions> configure) where TService : class
        {
            if (serviceOptions == null)
            {
                throw new ArgumentNullException(nameof(serviceOptions));
            }

            var serviceMethodOptions = new GrpcServiceMethodOptions(name);

            configure(serviceMethodOptions);

            serviceOptions.Methods.Add(serviceMethodOptions);
        }
示例#13
0
        /// <summary>
        /// 添加jaeger中间件
        /// </summary>
        /// <param name="grpcServiceOptions"></param>
        /// <param name="conf"></param>
        private static void AddJaegerInterceptor(this GrpcServiceOptions grpcServiceOptions, IConfiguration conf)
        {
            var key           = "GrpcServer:Jaeger";
            var jaegerOptions = conf.GetSection(key).Get <JaegerOptions>();

            if (jaegerOptions == null || jaegerOptions.Enable == false)
            {
                return;
            }

            //添加jaeger中间件
            grpcServiceOptions.Interceptors.Add <JaegerTracingInterceptor>();
        }
示例#14
0
 public JsonTranscodingServiceMethodProvider(
     ILoggerFactory loggerFactory,
     IOptions <GrpcServiceOptions> globalOptions,
     IOptions <GrpcServiceOptions <TService> > serviceOptions,
     IGrpcServiceActivator <TService> serviceActivator,
     IOptions <GrpcJsonTranscodingOptions> JsonTranscodingOptions)
 {
     _logger                 = loggerFactory.CreateLogger <JsonTranscodingServiceMethodProvider <TService> >();
     _globalOptions          = globalOptions.Value;
     _serviceOptions         = serviceOptions.Value;
     _JsonTranscodingOptions = JsonTranscodingOptions.Value;
     _loggerFactory          = loggerFactory;
     _serviceActivator       = serviceActivator;
 }
示例#15
0
 public HttpApiServiceMethodProvider(
     ILoggerFactory loggerFactory,
     IOptions <GrpcServiceOptions> globalOptions,
     IOptions <GrpcServiceOptions <TService> > serviceOptions,
     IServiceProvider serviceProvider,
     IGrpcServiceActivator <TService> serviceActivator)
 {
     _logger           = loggerFactory.CreateLogger <HttpApiServiceMethodProvider <TService> >();
     _globalOptions    = globalOptions.Value;
     _serviceOptions   = serviceOptions.Value;
     _loggerFactory    = loggerFactory;
     _serviceProvider  = serviceProvider;
     _serviceActivator = serviceActivator;
 }
示例#16
0
        public ServerCallHandlerFactory(ILoggerFactory loggerFactory, IOptions <GrpcServiceOptions> globalOptions, IOptions <GrpcServiceOptions <TService> > serviceOptions)
        {
            _loggerFactory = loggerFactory;

            var so = serviceOptions.Value;
            var go = globalOptions.Value;

            // This is required to get ensure that service methods without any explicit configuration
            // will continue to get the global configuration options
            _resolvedOptions = new GrpcServiceOptions
            {
                EnableDetailedErrors  = so.EnableDetailedErrors ?? go.EnableDetailedErrors,
                ReceiveMaxMessageSize = so.ReceiveMaxMessageSize ?? go.ReceiveMaxMessageSize,
                SendMaxMessageSize    = so.SendMaxMessageSize ?? go.SendMaxMessageSize
            };
        }
        public ServerStreamingServerCallHandler(
            Method <TRequest, TResponse> method,
            ServerStreamingServerMethod <TService, TRequest, TResponse> invoker,
            GrpcServiceOptions serviceOptions,
            ILoggerFactory loggerFactory,
            IGrpcServiceActivator <TService> serviceActivator,
            IServiceProvider serviceProvider)
            : base(method, serviceOptions, loggerFactory, serviceActivator, serviceProvider)
        {
            _invoker = invoker;

            if (ServiceOptions.HasInterceptors)
            {
                var interceptorPipeline = new InterceptorPipelineBuilder <TRequest, TResponse>(ServiceOptions.Interceptors, ServiceProvider);
                _pipelineInvoker = interceptorPipeline.ServerStreamingPipeline(ResolvedInterceptorInvoker);
            }
        }
示例#18
0
        public ServerCallHandlerFactory(
            ILoggerFactory loggerFactory,
            IOptions <GrpcServiceOptions> globalOptions,
            IOptions <GrpcServiceOptions <TService> > serviceOptions,
            IGrpcServiceActivator <TService> serviceActivator,
            IServiceProvider serviceProvider)
        {
            _loggerFactory    = loggerFactory;
            _serviceActivator = serviceActivator;
            _serviceProvider  = serviceProvider;

            var so = serviceOptions.Value;
            var go = globalOptions.Value;

            // This is required to get ensure that service methods without any explicit configuration
            // will continue to get the global configuration options
            _resolvedOptions = new GrpcServiceOptions
            {
                EnableDetailedErrors         = so.EnableDetailedErrors ?? go.EnableDetailedErrors,
                MaxReceiveMessageSize        = so.MaxReceiveMessageSize ?? go.MaxReceiveMessageSize,
                MaxSendMessageSize           = so.MaxSendMessageSize ?? go.MaxSendMessageSize,
                ResponseCompressionAlgorithm = so.ResponseCompressionAlgorithm ?? go.ResponseCompressionAlgorithm,
                ResponseCompressionLevel     = so.ResponseCompressionLevel ?? go.ResponseCompressionLevel
            };

            var resolvedCompressionProviders = new Dictionary <string, ICompressionProvider>(StringComparer.Ordinal);

            AddCompressionProviders(resolvedCompressionProviders, so._compressionProviders);
            AddCompressionProviders(resolvedCompressionProviders, go._compressionProviders);
            _resolvedOptions.ResolvedCompressionProviders = resolvedCompressionProviders;

            _resolvedOptions.Interceptors.AddRange(go.Interceptors);
            _resolvedOptions.Interceptors.AddRange(so.Interceptors);
            _resolvedOptions.HasInterceptors = _resolvedOptions.Interceptors.Count > 0;

            _resolvedServiceMethods = so.Methods.ToDictionary(k => k.Name);

            if (_resolvedOptions.ResponseCompressionAlgorithm != null)
            {
                if (!_resolvedOptions.ResolvedCompressionProviders.TryGetValue(_resolvedOptions.ResponseCompressionAlgorithm, out var _))
                {
                    throw new InvalidOperationException($"The configured response compression algorithm '{_resolvedOptions.ResponseCompressionAlgorithm}' does not have a matching compression provider.");
                }
            }
        }
示例#19
0
 internal HttpApiProviderServiceBinder(
     ServiceMethodProviderContext <TService> context,
     Type declaringType,
     ServiceDescriptor serviceDescriptor,
     GrpcServiceOptions globalOptions,
     GrpcServiceOptions <TService> serviceOptions,
     IServiceProvider serviceProvider,
     ILoggerFactory loggerFactory,
     IGrpcServiceActivator <TService> serviceActivator)
 {
     _context           = context;
     _declaringType     = declaringType;
     _serviceDescriptor = serviceDescriptor;
     _globalOptions     = globalOptions;
     _serviceOptions    = serviceOptions;
     _serviceActivator  = serviceActivator;
     _logger            = loggerFactory.CreateLogger <HttpApiProviderServiceBinder <TService> >();
 }
        public static MethodOptions CreateMethodOptions(
            List <ICompressionProvider>?compressionProviders = null,
            string?responseCompressionAlgorithm       = null,
            CompressionLevel?responseCompressionLevel = null,
            int?maxSendMessageSize             = null,
            int?maxReceiveMessageSize          = null,
            InterceptorCollection?interceptors = null)
        {
            var serviceOptions = new GrpcServiceOptions();

            serviceOptions.CompressionProviders = compressionProviders ?? new List <ICompressionProvider>();
            serviceOptions.Interceptors.AddRange(interceptors ?? new InterceptorCollection());
            serviceOptions.MaxSendMessageSize           = maxSendMessageSize;
            serviceOptions.MaxReceiveMessageSize        = maxReceiveMessageSize;
            serviceOptions.ResponseCompressionAlgorithm = responseCompressionAlgorithm;
            serviceOptions.ResponseCompressionLevel     = responseCompressionLevel;

            return(MethodOptions.Create(new[] { serviceOptions }));
        }
    public async Task HandleCallAsync_ErrorWithDetailedErrors_DetailedErrorResponse()
    {
        // Arrange
        ServerStreamingServerMethod <JsonTranscodingGreeterService, HelloRequest, HelloReply> invoker = (s, r, w, c) =>
        {
            return(Task.FromException <HelloReply>(new Exception("Exception!")));
        };

        var pipe = new Pipe();

        var routeParameterDescriptors = new Dictionary <string, List <FieldDescriptor> >
        {
            ["name"] = new List <FieldDescriptor>(new[] { HelloRequest.Descriptor.FindFieldByNumber(HelloRequest.NameFieldNumber) })
        };
        var descriptorInfo = TestHelpers.CreateDescriptorInfo(routeParameterDescriptors: routeParameterDescriptors);
        var serviceOptions = new GrpcServiceOptions {
            EnableDetailedErrors = true
        };
        var callHandler = CreateCallHandler(invoker, descriptorInfo: descriptorInfo, serviceOptions: serviceOptions);
        var httpContext = TestHelpers.CreateHttpContext(bodyStream: pipe.Writer.AsStream());

        httpContext.Request.RouteValues["name"] = "TestName!";

        // Act
        var callTask = callHandler.HandleCallAsync(httpContext);

        // Assert
        var line = await ReadLineAsync(pipe.Reader).DefaultTimeout();

        using var responseJson = JsonDocument.Parse(line !);
        Assert.Equal("Exception was thrown by handler. Exception: Exception!", responseJson.RootElement.GetProperty("message").GetString());
        Assert.Equal("Exception was thrown by handler. Exception: Exception!", responseJson.RootElement.GetProperty("error").GetString());
        Assert.Equal(2, responseJson.RootElement.GetProperty("code").GetInt32());

        await callTask.DefaultTimeout();
    }
示例#22
0
        public async Task WriteMessageAsync_HasCustomCompressionLevel_WriteCompressedDataWithLevel()
        {
            // Arrange
            var mockCompressionProvider = new MockCompressionProvider();
            var serviceOptions          = new GrpcServiceOptions
            {
                ResponseCompressionAlgorithm = "Mock",
                ResponseCompressionLevel     = System.IO.Compression.CompressionLevel.Optimal,
                CompressionProviders         =
                {
                    mockCompressionProvider
                }
            };

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers[GrpcProtocolConstants.MessageAcceptEncodingHeader] = "Mock";

            var context = HttpContextServerCallContextHelper.CreateServerCallContext(httpContext, serviceOptions);

            context.Initialize();

            var ms         = new MemoryStream();
            var pipeWriter = PipeWriter.Create(ms);

            // Act
            await pipeWriter.WriteMessageAsync(new byte[] { 0x10 }, context, Marshaller.ContextualSerializer, canFlush : true);

            // Assert
            Assert.AreEqual(System.IO.Compression.CompressionLevel.Optimal, mockCompressionProvider.ArgumentCompression);

            var messageData = ms.ToArray();

            Assert.AreEqual(1, messageData[0]);  // compression
            Assert.AreEqual(21, messageData[4]); // message length
        }
 public ServerCallHandlerFactory(ILoggerFactory loggerFactory, IOptions <GrpcServiceOptions <TService> > serviceOptions)
 {
     _loggerFactory  = loggerFactory;
     _serviceOptions = serviceOptions.Value;
 }
示例#24
0
        public ClientStreamingServerCallHandler(Method <TRequest, TResponse> method, GrpcServiceOptions serviceOptions, ILoggerFactory loggerFactory) : base(method, serviceOptions, loggerFactory)
        {
            var handlerMethod = typeof(TService).GetMethod(Method.Name);

            _invoker = (ClientStreamingServerMethod)Delegate.CreateDelegate(typeof(ClientStreamingServerMethod), handlerMethod);
        }
 protected ServerCallHandlerBase(Method <TRequest, TResponse> method, GrpcServiceOptions serviceOptions, ILoggerFactory loggerFactory)
 {
     Method         = method;
     ServiceOptions = serviceOptions;
     Logger         = loggerFactory.CreateLogger(typeof(TService));
 }
示例#26
0
 public static GrpcServiceOptions AddValidation(this GrpcServiceOptions options)
 {
     options.EnableMessageValidation();
     return(options);
 }
示例#27
0
 public HttpContextStreamReader(HttpContext context, GrpcServiceOptions serviceOptions, Func <byte[], TRequest> deserializer)
 {
     _httpContext    = context;
     _serviceOptions = serviceOptions;
     _deserializer   = deserializer;
 }
示例#28
0
 /// <summary>
 ///     Add a validator interceptor that will perform validations on all incoming request messages if a validator
 ///     exists for the message type. Validators can be added by calling
 ///     <see cref="ServiceCollectionExtensions.AddValidator{TValidator}"/>.
 /// </summary>
 /// <param name="serviceOptions">the gRPC service options</param>
 /// <returns>the gRPC service options to allow chaining</returns>
 public static GrpcServiceOptions AddValidationInterceptor(this GrpcServiceOptions serviceOptions)
 {
     serviceOptions.Interceptors.Add <ValidationInterceptor>();
     return(serviceOptions);
 }
 protected override void ConfigureGrpcServiceOptions(GrpcServiceOptions options)
 {
     base.ConfigureGrpcServiceOptions(options);
     options.Interceptors.Add <AuthenticationInterceptor>();
 }
 internal HttpContextServerCallContext(HttpContext httpContext, GrpcServiceOptions serviceOptions, ILogger logger)
 {
     HttpContext    = httpContext;
     ServiceOptions = serviceOptions;
     _logger        = logger;
 }