Ejemplo n.º 1
0
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
        {
            var serviceType = typeof(TService);

            if (ServiceContract.IsNativeGrpcService(serviceType))
            {
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug("Ignore service {0} binding: native grpc service.", serviceType.FullName);
                }

                return;
            }

            var filterContext = new ServiceMethodFilterRegistration(_serviceProvider);

            filterContext.Add(_rootConfiguration.GetFilters());
            filterContext.Add(_serviceConfiguration.GetFilters());

            var marshallerFactory = (_serviceConfiguration.MarshallerFactory ?? _rootConfiguration.DefaultMarshallerFactory).ThisOrDefault();
            var serviceBinder     = new AspNetCoreServiceMethodBinder <TService>(
                context,
                marshallerFactory,
                filterContext,
                _rootConfiguration.IsApiDescriptionRequested);

            CreateEndpointBinder().Bind(serviceBinder);
        }
Ejemplo n.º 2
0
 public AspNetCoreServiceMethodBinder(
     ServiceMethodProviderContext <TService> context,
     IMarshallerFactory marshallerFactory)
 {
     _context          = context;
     MarshallerFactory = marshallerFactory;
 }
 public void OnServiceMethodDiscovery(ServiceMethodProviderContext <GenericService> context)
 {
     context.AddDuplexStreamingMethod(
         GenericService.StreamingCallMethod,
         new List <object>(),
         GenericService.DuplexStreamingServerMethod);
 }
        internal List <IEndpointConventionBuilder> Build(IEndpointRouteBuilder endpointRouteBuilder)
        {
            Log.DiscoveringServiceMethods(_logger, typeof(TService));

            var serviceMethodProviderContext = new ServiceMethodProviderContext <TService>(_serverCallHandlerFactory);

            foreach (var serviceMethodProvider in _serviceMethodProviders)
            {
                serviceMethodProvider.OnServiceMethodDiscovery(serviceMethodProviderContext);
            }

            var endpointConventionBuilders = new List <IEndpointConventionBuilder>();

            if (serviceMethodProviderContext.Methods.Count > 0)
            {
                foreach (var method in serviceMethodProviderContext.Methods)
                {
                    var endpointBuilder = endpointRouteBuilder.Map(method.Pattern, method.RequestDelegate);

                    endpointBuilder.Add(ep =>
                    {
                        ep.DisplayName = $"gRPC - {method.Pattern.RawText}";

                        ep.Metadata.Add(new GrpcMethodMetadata(typeof(TService), method.Method));
                        foreach (var item in method.Metadata)
                        {
                            ep.Metadata.Add(item);
                        }
                    });

                    endpointConventionBuilders.Add(endpointBuilder);

                    // Report the last HttpMethodMetadata added. It's the metadata used by routing.
                    var httpMethod = method.Metadata.OfType <HttpMethodMetadata>().LastOrDefault();

                    Log.AddedServiceMethod(
                        _logger,
                        method.Method.Name,
                        method.Method.ServiceName,
                        method.Method.Type,
                        httpMethod?.HttpMethods ?? Array.Empty <string>(),
                        method.Pattern.RawText ?? string.Empty);
                }
            }
            else
            {
                Log.NoServiceMethodsDiscovered(_logger, typeof(TService));
            }

            CreateUnimplementedEndpoints(
                endpointRouteBuilder,
                _serviceMethodsRegistry,
                _serverCallHandlerFactory,
                serviceMethodProviderContext.Methods,
                endpointConventionBuilders);

            _serviceMethodsRegistry.Methods.AddRange(serviceMethodProviderContext.Methods);

            return(endpointConventionBuilders);
        }
 internal ProviderServiceBinder(ServiceMethodProviderContext <TService> context, Type declaringType)
 {
     _context            = context;
     _declaringType      = declaringType;
     _isIGrpcService     = typeof(IGrpcService).IsAssignableFrom(typeof(TService));
     _isIGrpcBaseService = typeof(IGrpcBaseService).IsAssignableFrom(typeof(TService));
 }
Ejemplo n.º 6
0
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
        {
            var bindMethodInfo = BindMethodFinder.GetBindMethod(typeof(TService));

            // Invoke BindService(ServiceBinderBase, BaseType)
            if (bindMethodInfo != null)
            {
                // The second parameter is always the service base type
                var serviceParameter = bindMethodInfo.GetParameters()[1];

                var binder = new ProviderServiceBinder <TService>(context, serviceParameter.ParameterType);

                try
                {
                    bindMethodInfo.Invoke(null, new object?[] { binder, null });
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException($"Error binding gRPC service '{typeof(TService).Name}'.", ex);
                }
            }
            else
            {
                Log.BindMethodNotFound(_logger, typeof(TService));
            }
        }
Ejemplo n.º 7
0
        void AddUnaryMethod <TRequest, TResponse>(ServiceMethodProviderContext <TService> context, string serviceName, MethodInfo method)
            where TRequest : class
            where TResponse : class
        {
            var serviceMethodAttribute = method.GetCustomAttribute <GrpcMethodAttribute>();

            var unaryMethod = new Method <TRequest, TResponse>(
                MethodType.Unary,
                serviceName,
                serviceMethodAttribute?.Name ?? method.Name,
                CreateRequestMarshaller <TRequest>(
                    serviceMethodAttribute?.RequestMarshallerType ?? FindRequestMarshaller <TRequest>(method)),
                CreateResponseMarshaller <TResponse>(
                    serviceMethodAttribute?.ResponseMarshallerType ?? FindResponseMarshaller <TResponse>(method)));

            context.AddUnaryMethod(
                unaryMethod,
                Array.Empty <object>(),
                _unaryServerMethodBuilder.Build <TRequest, TResponse>(method),
                options =>
            {
                foreach (var interceptor in FindInterceptors(method))
                {
                    options.Interceptors.Add(interceptor.InterceptorType, interceptor.Args);
                }
            });
        }
 void IServiceMethodProvider <TService> .OnServiceMethodDiscovery(
     ServiceMethodProviderContext <TService> context)
 {
     if (m_adapterFactory.TryGetDefinition <TService>(out var definition))
     {
         definition.Visit(new Adapter(m_logger, context));
     }
 }
 public void OnServiceMethodDiscovery(ServiceMethodProviderContext <NetGrpcServer> context)
 {
     context.AddUnaryMethod(GrpcMethodDefinition.Create <RpcObjectRequest, RpcServicesQueryResponse>(
                                GrpcCore.MethodType.Unary,
                                "SciTech.Rpc.RpcService", "QueryServices",
                                this.server.Serializer),
                            new List <object>(),
                            NetGrpcServer.QueryServices);// (s, request, context) => Task.FromResult(s.QueryServices(request)));
 }
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
        {
            var binder = new MagicOnionGlueServiceBinder <TService>(context);

            foreach (var methodHandler in _magicOnionServiceDefinition.MethodHandlers)
            {
                methodHandler.BindHandler(binder);
            }
        }
            void IServiceMethodProvider <TService> .OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
            {
                int count = Binder.Instance.Bind <TService>(context, _binderConfiguration);

                if (count != 0)
                {
                    _logger.Log(LogLevel.Information, "RPC services being provided by {0}: {1}", typeof(TService), count);
                }
            }
Ejemplo n.º 12
0
 public AspNetCoreServiceMethodBinder(
     ServiceMethodProviderContext <TService> context,
     IMarshallerFactory marshallerFactory,
     ServiceMethodFilterRegistration filterRegistration,
     bool requiresGrpcMarker)
 {
     _context            = context;
     _filterRegistration = filterRegistration;
     _requiresGrpcMarker = requiresGrpcMarker;
     MarshallerFactory   = marshallerFactory;
 }
Ejemplo n.º 13
0
        public ServiceMethodProviderContext OnServiceMethodDiscovery()
        {
            var context = new ServiceMethodProviderContext();
            var methods = DashboardActionRoute.GetMethods();

            foreach (var method in methods)
            {
                context.AddMethod(method);
            }
            return(context);
        }
Ejemplo n.º 14
0
        internal List <IEndpointConventionBuilder> Build(IEndpointRouteBuilder endpointRouteBuilder)
        {
            Log.DiscoveringServiceMethods(_logger, typeof(TService));

            var serviceMethodProviderContext = new ServiceMethodProviderContext <TService>(_serverCallHandlerFactory);

            foreach (var serviceMethodProvider in _serviceMethodProviders)
            {
                serviceMethodProvider.OnServiceMethodDiscovery(serviceMethodProviderContext);
            }

            var endpointConventionBuilders = new List <IEndpointConventionBuilder>();

            if (serviceMethodProviderContext.Methods.Count > 0)
            {
                foreach (var method in serviceMethodProviderContext.Methods)
                {
                    var pattern         = method.Method.FullName;
                    var endpointBuilder = endpointRouteBuilder.MapPost(pattern, method.RequestDelegate);

                    endpointBuilder.Add(ep =>
                    {
                        ep.DisplayName = $"gRPC - {pattern}";

                        ep.Metadata.Add(new GrpcMethodMetadata(typeof(TService), method.Method));
                        foreach (var item in method.Metadata)
                        {
                            ep.Metadata.Add(item);
                        }
                    });

                    endpointConventionBuilders.Add(endpointBuilder);

                    Log.AddedServiceMethod(_logger, method.Method.Name, method.Method.ServiceName, method.Method.Type, pattern);
                }
            }
            else
            {
                Log.NoServiceMethodsDiscovered(_logger, typeof(TService));
            }

            CreateUnimplementedEndpoints(
                endpointRouteBuilder,
                _serviceMethodsRegistry,
                _serverCallHandlerFactory,
                serviceMethodProviderContext.Methods);

            _serviceMethodsRegistry.Methods.AddRange(serviceMethodProviderContext.Methods);

            return(endpointConventionBuilders);
        }
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
        {
            var serviceType = typeof(TService);

            if (ServiceContract.IsNativeGrpcService(serviceType))
            {
                _logger.LogDebug("Ignore service {0} binding: native grpc service.", serviceType.FullName);
                return;
            }

            var marshallerFactory = (_serviceConfiguration.MarshallerFactory ?? _rootConfiguration.DefaultMarshallerFactory).ThisOrDefault();
            var serviceBinder     = new AspNetCoreServiceMethodBinder <TService>(context, marshallerFactory);

            CreateEndpointBinder().Bind(serviceBinder);
        }
Ejemplo n.º 16
0
            public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
            {
                // ignore any services that are known to be the default handler
                if (Attribute.IsDefined(typeof(TService), typeof(BindServiceMethodAttribute)))
                {
                    return;
                }

                // we support methods that match suitable signatures, where the method is on an
                // interface that TService implements, and the interface is marked [ServiceContract]
                foreach (var iType in ContractOperation.ExpandInterfaces(typeof(TService)))
                {
                    AddMethodsForService(context, iType);
                }
            }
Ejemplo n.º 17
0
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
        {
            var bindMethodInfo = BindMethodFinder.GetBindMethod(typeof(TService));

            // Invoke BindService(ServiceBinderBase, BaseType)
            if (bindMethodInfo != null)
            {
                // The second parameter is always the service base type
                var serviceParameter = bindMethodInfo.GetParameters()[1];

                ServiceDescriptor?serviceDescriptor = null;
                try
                {
                    serviceDescriptor = ServiceDescriptorHelpers.GetServiceDescriptor(bindMethodInfo.DeclaringType !);
                }
                catch (Exception ex)
                {
                    Log.ServiceDescriptorError(_logger, typeof(TService), ex);
                }

                if (serviceDescriptor != null)
                {
                    var binder = new HttpApiProviderServiceBinder <TService>(
                        context,
                        serviceParameter.ParameterType,
                        serviceDescriptor,
                        _globalOptions,
                        _serviceOptions,
                        _serviceProvider,
                        _loggerFactory,
                        _serviceActivator);

                    try
                    {
                        bindMethodInfo.Invoke(null, new object[] { binder, null });
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException($"Error binding gRPC service '{typeof(TService).Name}'.",
                                                            ex);
                    }
                }
            }
            else
            {
                Log.BindMethodNotFound(_logger, typeof(TService));
            }
        }
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TActivator> context)
        {
            var activatorType = typeof(TActivator);

            if (activatorType.IsGenericType &&
                activatorType.GetGenericTypeDefinition().Equals(typeof(NetGrpcServiceActivator <>)))
            {
                var serviceType = activatorType.GetGenericArguments()[0];

                //MethodInfo buildServiceStubMethod = typeof(NetGrpcServiceMethodProvider<TActivator>)
                //    .GetMethod(nameof(BuildServiceStub), BindingFlags.Instance | BindingFlags.NonPublic)!;

                var typedBuildServiceStubMethod = BuildServiceStubMethod.MakeGenericMethod(serviceType);
                typedBuildServiceStubMethod.Invoke(this, new object[] { context });
            }
        }
Ejemplo n.º 19
0
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <TService> context)
        {
            var serviceAttribute = typeof(TService).GetCustomAttribute <GrpcServiceAttribute>();

            if (serviceAttribute == null)
            {
                // we should allow this and treat the GrpcServiceAttribute as an override to the default
                // conventions but that means that we could potentially duplicate the methods as the
                // binder service works first
                return;
            }

            var serviceName = serviceAttribute.Name ?? typeof(TService).FullName;

            if (serviceName == null)
            {
                throw new ArgumentException("Could not determine Service Name.");
            }

            foreach (var(serviceMethod, serviceMethodAttribute) in FindMethods())
            {
                MethodInfo method;
                switch (serviceMethodAttribute.MethodType ?? GuessMethodType(serviceMethod))
                {
                case MethodType.Unary:
                    method = RegisterUnaryMethod
                             .MakeGenericMethod(
                        serviceMethodAttribute.RequestType ?? FindRequestType(MethodType.Unary, serviceMethod),
                        serviceMethodAttribute.ResponseType ?? FindResponseType(MethodType.Unary, serviceMethod));
                    break;

                case MethodType.ServerStreaming:
                    method = RegisterServerStreamingMethod
                             .MakeGenericMethod(
                        serviceMethodAttribute.RequestType ?? FindRequestType(MethodType.ServerStreaming, serviceMethod),
                        serviceMethodAttribute.ResponseType ?? FindResponseType(MethodType.ServerStreaming, serviceMethod));
                    break;

                //case MethodType.ClientStreaming:
                //case MethodType.DuplexStreaming:
                default:
                    continue;
                }

                method.Invoke(this, new object[] { context, serviceName, serviceMethod });
            }
        }
Ejemplo n.º 20
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 async Task OnServiceMethodDiscovery_ServiceWithDuplicateMethodNames_Success()
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddSingleton <GreeterServiceWithDuplicateNames>();

            var serverCallHandlerFactory = new ServerCallHandlerFactory <GreeterServiceWithDuplicateNames>(
                NullLoggerFactory.Instance,
                Options.Create <GrpcServiceOptions>(new GrpcServiceOptions()),
                Options.Create <GrpcServiceOptions <GreeterServiceWithDuplicateNames> >(new GrpcServiceOptions <GreeterServiceWithDuplicateNames>()),
                new TestGrpcServiceActivator <GreeterServiceWithDuplicateNames>());

            var provider = new BinderServiceMethodProvider <GreeterServiceWithDuplicateNames>(NullLoggerFactory.Instance);
            var context  = new ServiceMethodProviderContext <GreeterServiceWithDuplicateNames>(serverCallHandlerFactory);

            var httpContext = HttpContextHelpers.CreateContext();

            httpContext.RequestServices = services.BuildServiceProvider();

            // Act
            provider.OnServiceMethodDiscovery(context);

            // Assert
            Assert.AreEqual(2, context.Methods.Count);

            var methodModel = context.Methods[0];

            Assert.AreEqual("SayHello", methodModel.Method.Name);

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new HelloRequest
            {
                Name = "World"
            });
            ms.Seek(0, SeekOrigin.Begin);
            httpContext.Request.Body = ms;

            await methodModel.RequestDelegate(httpContext);

            // Expect 12 (unimplemented) from base type
            Assert.AreEqual("12", httpContext.Response.Headers["grpc-status"]);
        }
Ejemplo n.º 22
0
        public void OnServiceMethodDiscovery(ServiceMethodProviderContext <GrpcService> context)
        {
            // mapper
            var mapperValidator = _cfg.MapperValidator != null?Activator.CreateInstance(_cfg.MapperValidator) as IPropertyMapValidator : null;

            var mapper = _cqrs.CreateMapper(mapperValidator);

            // set server id for logging
            var serverId = !string.IsNullOrWhiteSpace(_cfg.ServerId) ? _cfg.ServerId : Assembly.GetEntryAssembly().FullName.Split(',')[0];

            // create methos
            var methodAddGeneric = GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).First(x => x.Name == nameof(AddMethod));

            _cqrs.ToCqrsChannelInfo().ToList().ForEach(x => {
                var method       = GrpcMethodFactoryUtil.CreateGrpcMethodGeneric(x);
                var invokeMethod = GrpcServerMethodFactoryUtil.CreateServerMethodGeneric(_container, serverId, x, mapper, _cfg.TimeoutMs);
                var methodAdd    = methodAddGeneric.MakeGenericMethod(x.ChReqType, x.ChRspEnvType);
                methodAdd.Invoke(this, new object[] { context, method, invokeMethod });
            });
        }
Ejemplo n.º 23
0
    private JsonTranscodingProviderServiceBinder <DynamicService> CreateJsonTranscodingBinder <TRequest, TResponse>(
        MethodDescriptor methodDescriptor,
        ServiceMethodProviderContext <DynamicService> context,
        DynamicServiceInvokerResolver invokerResolver)
        where TRequest : class, IMessage, new()
        where TResponse : class, IMessage, new()
    {
        var JsonTranscodingOptions = _serviceProvider.GetRequiredService <IOptions <GrpcJsonTranscodingOptions> >().Value;
        var binder = new JsonTranscodingProviderServiceBinder <DynamicService>(
            context,
            invokerResolver,
            methodDescriptor.Service,
            _serviceProvider.GetRequiredService <IOptions <GrpcServiceOptions> >().Value,
            _serviceProvider.GetRequiredService <IOptions <GrpcServiceOptions <DynamicService> > >().Value,
            _serviceProvider.GetRequiredService <ILoggerFactory>(),
            _serviceProvider.GetRequiredService <IGrpcServiceActivator <DynamicService> >(),
            JsonTranscodingOptions);

        return(binder);
    }
Ejemplo n.º 24
0
            private void AddMethodsForService(ServiceMethodProviderContext <TService> context, Type serviceContract)
            {
                bool isPublicContract = typeof(TService) == serviceContract;

                if (!ContractOperation.TryGetServiceName(serviceContract, out var serviceName, !isPublicContract))
                {
                    return;
                }
                _logger.Log(LogLevel.Trace, "pb-net processing {0}/{1} as {2}", typeof(TService).Name, serviceContract.Name, serviceName);
                object?[]? argsBuffer  = null;
                Type[]     typesBuffer = Array.Empty <Type>();

                int count = 0;

                foreach (var op in ContractOperation.FindOperations(serviceContract, isPublicContract))
                {
                    if (_invokers.TryGetValue((op.MethodType, op.Context, op.Result, op.Void), out var invoker) &&
                        AddMethod(op.From, op.To, op.Method, op.MethodType, invoker))
                    {
                        // yay!
                        count++;
                    }
        private void BuildServiceStub <TService>(ServiceMethodProviderContext <TActivator> context) where TService : class
        {
            var typedContext = context as ServiceMethodProviderContext <NetGrpcServiceActivator <TService> >;

            if (typedContext == null)
            {
                // This shouldn't happen, since OnServiceMethodDiscovery should have already checked the type
                throw new InvalidCastException("Unexpected failure when casting to ServiceMethodProviderContext<NetGrpcServiceActivator<TService>>.");
            }

            var serviceInfo = this.rpcServer.ServiceDefinitionsProvider.GetRegisteredServiceInfo(typeof(TService));

            if (serviceInfo == null)
            {
                throw new InvalidOperationException($"Service '{typeof(TService)}' not registered.");
            }

            var stubBuilder = new NetGrpcServiceStubBuilder <TService>(
                serviceInfo,
                this.serviceProvider.GetService <IOptions <RpcServiceOptions <TService> > >()?.Value);

            stubBuilder.Bind(this.rpcServer, typedContext);
        }
Ejemplo n.º 26
0
 public MagicOnionGlueServiceBinder(ServiceMethodProviderContext <TService> context)
 {
     _context = context;
 }
Ejemplo n.º 27
0
        internal void Bind(NetGrpcServer server, ServiceMethodProviderContext <NetGrpcServiceActivator <TService> > providerContext)
        {
            var binder = new NetGrpcServiceStubBuilder <TService> .Binder(providerContext);

            this.GenerateOperationHandlers(server, binder);
        }
Ejemplo n.º 28
0
 private void AddMethod <TChReq, TchRsp>(ServiceMethodProviderContext <GrpcService> context, Method <TChReq, TchRsp> method, UnaryServerMethod <GrpcService, TChReq, TchRsp> unaryServerMethod)
     where TChReq : class
     where TchRsp : class
 {
     context.AddUnaryMethod(method, new List <object>(), unaryServerMethod);
 }
 public Adapter(ILogger <CodeFirstServiceMethodProvider <TService> > logger,
                ServiceMethodProviderContext <TService> context)
 {
     m_logger  = logger;
     m_context = context;
 }
 internal ProviderServiceBinder(ServiceMethodProviderContext <TService> context, Type declaringType)
 {
     _context       = context;
     _declaringType = declaringType;
 }