Exemplo n.º 1
0
        public List <Method> Serialize(IMethodImpl method, DocumentConfig documentConfig, IRegion region = null)
        {
            List <Method> methods = new List <Method>();

            foreach (var type in method.Types)
            {
                var methodConfig = new MethodConfig(method, this, type, documentConfig, region);

                if (!methodConfig.MethodRequired)
                {
                    continue;
                }

                methods.Add(BuildMethod(methodConfig));

                //Query methods don't require any other request types
                if (methodConfig.MethodType == MethodType.Query || methodConfig.MethodType == MethodType.Watch)
                {
                    break;
                }

                if (methodConfig.NeedsTokenInterfaceOverload)
                {
                    var tokenConfig = methodConfig.GetTokenOverloadConfig();

                    methods.Add(BuildMethod(tokenConfig));
                }
            }

            return(methods);
        }
Exemplo n.º 2
0
        private async void gRPCStartIPCTry()
        {
            //Config retry
            var methodConfig = new MethodConfig
            {
                Names       = { MethodName.Default },
                RetryPolicy = new RetryPolicy
                {
                    MaxAttempts          = 10,
                    InitialBackoff       = TimeSpan.FromSeconds(10),
                    MaxBackoff           = TimeSpan.FromSeconds(100),
                    BackoffMultiplier    = 1.5,
                    RetryableStatusCodes = { Grpc.Core.StatusCode.Unavailable }
                }
            };

            AppendText("Starting IPC gRPC");
            var SocketPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "socket.tmp");

            AppendText($"Tmp path is {SocketPath}");

            var channel = GrpcConnectionFactory.CreateUdsChannel(methodConfig);
            var client  = new Greeter.GreeterClient(channel);

            var response = await client.SayHelloAsync(new HelloRequest { Name = "First IPC gRPC" });

            AppendText(response.Message);
        }
Exemplo n.º 3
0
        private void AddMethod(ApiConfig config, string name, AffinityConfig.Types.Command command, string affinityKey)
        {
            MethodConfig method = new MethodConfig();

            method.Name.Add(name);
            method.Affinity = new AffinityConfig
            {
                Command     = command,
                AffinityKey = affinityKey
            };
            config.Method.Add(method);
        }
Exemplo n.º 4
0
        private Method BuildMethod(MethodConfig methodConfig)
        {
            var w = new SourceWriter();

            MethodDef def = this;

            var builder = new MethodRunner(methodConfig, w);

            builder.WriteMethod();

            return(new Method(methodConfig.Method.Name, methodConfig.MethodType, w.ToString()));
        }
Exemplo n.º 5
0
        void IPolicyConfigControl.ReadFromConfig(PolicyConfig config)
        {
            MethodConfig controlConfig = config.MethodConfig;

            Visibilities.Bind(controlConfig.VisibilitiesToCheck);

            GenericParametersOptionCheckBox.Checked = controlConfig.GenericParameterDocumentationRequired;
            ParametersOptionCheckBox.Checked        = controlConfig.ParameterDocumentationRequired;
            OverridesOptionCheckBox.Checked         = controlConfig.DocumentOverrides;
            ExplicitOptionCheckBox.Checked          = controlConfig.ExplicitInterfaceMethodDocumentationRequired;
            InterfaceOptionCheckBox.Checked         = controlConfig.InterfaceDeclarationDocumentationRequired;
            ReturnsDocumentationTagCheckBox.Checked = controlConfig.ResultDocumentationRequired;
            SampleDocumentationTagCheckBox.Checked  = controlConfig.SampleDocumentationRequired;
            SummaryDocumentationTagCheckBox.Checked = controlConfig.SummaryDocumentationRequired;
        }
Exemplo n.º 6
0
        void IPolicyConfigControl.WriteToConfig(PolicyConfig config)
        {
            MethodConfig controlConfig = config.MethodConfig;

            controlConfig.VisibilitiesToCheck = Visibilities.GetVisibilites();

            controlConfig.GenericParameterDocumentationRequired = GenericParametersOptionCheckBox.Checked;
            controlConfig.ParameterDocumentationRequired        = ParametersOptionCheckBox.Checked;
            controlConfig.DocumentOverrides = OverridesOptionCheckBox.Checked;
            controlConfig.ExplicitInterfaceMethodDocumentationRequired = ExplicitOptionCheckBox.Checked;
            controlConfig.InterfaceDeclarationDocumentationRequired    = InterfaceOptionCheckBox.Checked;
            controlConfig.ResultDocumentationRequired  = ReturnsDocumentationTagCheckBox.Checked;
            controlConfig.SampleDocumentationRequired  = SampleDocumentationTagCheckBox.Checked;
            controlConfig.SummaryDocumentationRequired = SummaryDocumentationTagCheckBox.Checked;
        }
Exemplo n.º 7
0
        public CitiesClient(GrpcClientFactory grpcClientFactory)
        {
            var defaultMethodConfig = new MethodConfig
            {
                Names       = { MethodName.Default },
                RetryPolicy = new RetryPolicy
                {
                    MaxAttempts          = 5,
                    InitialBackoff       = TimeSpan.FromSeconds(1),
                    MaxBackoff           = TimeSpan.FromSeconds(5),
                    BackoffMultiplier    = 1.5,
                    RetryableStatusCodes = { StatusCode.Unavailable }
                }
            };

            _client = grpcClientFactory.CreateClient <Cities.CitiesClient>(nameof(Cities));
        }
Exemplo n.º 8
0
        public static void SetupGrpc(this IServiceCollection services, IConfiguration configuration)
        {
            GrpcOptions = services.GetTypedOptions <GrpcOptions>(configuration, "Grpc");

            if (!GrpcOptions.EnableGrpc || string.IsNullOrEmpty(GrpcOptions.GrpcServer))
            {
                return;
            }

            services.AddGrpc(options =>
            {
                options.MaxReceiveMessageSize = GrpcOptions.MaxReceiveMessageSize * 1024 * 1024; // 16 MB
            });

            var defaultMethodConfig = new MethodConfig
            {
                Names       = { MethodName.Default },
                RetryPolicy = GetRetryPolicy(GrpcOptions.RetryPatternOptions)
            };

            if (GrpcOptions.UseDevCertificate)
            {
                var httpHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = GetBypass
                };

                services.AddSingleton(GrpcChannel.ForAddress(GrpcOptions.GrpcServer, new GrpcChannelOptions {
                    HttpHandler = httpHandler, ServiceConfig = new ServiceConfig {
                        MethodConfigs = { defaultMethodConfig }
                    }
                }));
            }
            else
            {
                services.AddSingleton(GrpcChannel.ForAddress(GrpcOptions.GrpcServer, new GrpcChannelOptions
                {
                    ServiceConfig = new ServiceConfig {
                        MethodConfigs = { defaultMethodConfig }
                    }
                }));
            }
        }
Exemplo n.º 9
0
        public static GrpcChannel CreateUdsChannel(MethodConfig methodConfig)
        {
            var udsEndPoint        = new UnixDomainSocketEndPoint(SocketPath);
            var connectionFactory  = new UnixDomainSocketConnectionFactory(udsEndPoint);
            var socketsHttpHandler = new SocketsHttpHandler
            {
                ConnectCallback = connectionFactory.ConnectAsync
            };

            var options = new GrpcChannelOptions
            {
                HttpHandler = socketsHttpHandler
            };

            options.ServiceConfig = new ServiceConfig();
            options.ServiceConfig.MethodConfigs.Add(methodConfig);

            return(GrpcChannel.ForAddress("http://localhost", options));
        }
Exemplo n.º 10
0
        protected override Node VisitMethodCall(MethodCallExpression m)
        {
            SqlLikeType type;

            if (Enum.TryParse(m.Method.Name, true, out type))
            {
                Expression objExp = m.Object;
                var        args   = m.Arguments;
                if (objExp != null)
                {
                    var member     = m.Object as MemberExpression;
                    var fieldValue = ExpressionHelper.GetExpressionValue(args.FirstOrDefault());
                    var node       = new MemberNode(member);
                    return(new LikeNode(type, node, fieldValue));
                }
                else
                {
                    if (args != null && args.Count > 1)
                    {
                        var values = ExpressionHelper.GetExpressionValue(args.FirstOrDefault());
                        var member = args[1] as MemberExpression;
                        var node   = new MemberNode(member);
                        return(new InNode(node, values));
                    }
                }
                throw new NotSupportedException("不能解析该MethodCall_Lambda表达式");
            }
            else
            {
                var handler = MethodConfig.GetMethodHandler(m.Method.DeclaringType, m.Method.Name);
                if (handler != null)
                {
                    return(handler(m.Object, m.Arguments, m));
                }
                else
                {
                    var value = ExpressionHelper.GetMethodCallValue(m);
                    return(new ValueNode(value));
                }
            }
        }
Exemplo n.º 11
0
        static async Task RunCalculate()
        {
            var defaultMethodConfig = new MethodConfig
            {
                Names         = { MethodName.Default },
                HedgingPolicy = new HedgingPolicy
                {
                    MaxAttempts         = 5,
                    HedgingDelay        = TimeSpan.FromSeconds(5),
                    NonFatalStatusCodes = { StatusCode.Unavailable }
                }
            };

            using var channel = GrpcChannel.ForAddress("https://localhost:8001", new GrpcChannelOptions()
            {
                ServiceConfig = new ServiceConfig { MethodConfigs = { defaultMethodConfig } }
            });
            channel.Intercept(new GrpcClientLoggingInterceptor());
            var client = new Calculator.CalculatorClient(channel);
            await client.CalcAsync(new CalculatorRequest()
            {
                Num1 = 10, Op = "+", Num2 = 12
            });

            await client.CalcAsync(new CalculatorRequest()
            {
                Num1 = 10, Op = "-", Num2 = 12
            });

            await client.CalcAsync(new CalculatorRequest()
            {
                Num1 = 10, Op = "*", Num2 = 12
            });

            await client.CalcAsync(new CalculatorRequest()
            {
                Num1 = 20, Op = "/", Num2 = 5
            });
        }
Exemplo n.º 12
0
        public static IServiceCollection AddGrpcClients(this IServiceCollection services, IConfiguration configuration)
        {
            var servicesSettings = configuration.GetSection("Services").Get <Settings.Services>();
            var retrySettings    = configuration.GetSection("Retry").Get <RetrySettings>();

            var retryPolicy = retrySettings.Enabled ? new RetryPolicy
            {
                MaxAttempts          = retrySettings.Count,
                InitialBackoff       = TimeSpan.FromSeconds(1),
                MaxBackoff           = TimeSpan.FromSeconds(5),
                BackoffMultiplier    = 1.5,
                RetryableStatusCodes =
                {
                    StatusCode.Unavailable,
                    StatusCode.FailedPrecondition,
                    StatusCode.Aborted
                }
            } : default;

            var defaultMethodConfig = new MethodConfig
            {
                Names       = { MethodName.Default },
                RetryPolicy = retryPolicy
            };

            var serviceConfig = new ServiceConfig
            {
                MethodConfigs = { defaultMethodConfig }
            };


            services.AddGrpcClient <Basket.BasketClient>(options =>
            {
                options.Address = new Uri(servicesSettings.Basket.BaseUrl);
                options.ChannelOptionsActions.Add(channelOptions => channelOptions.ServiceConfig = serviceConfig);
            });

            return(services);
        }
Exemplo n.º 13
0
        private static GrpcChannel CreateChannel()
        {
            var methodConfig = new MethodConfig
            {
                Names       = { MethodName.Default },
                RetryPolicy = new RetryPolicy
                {
                    MaxAttempts          = 5,
                    InitialBackoff       = TimeSpan.FromSeconds(0.5),
                    MaxBackoff           = TimeSpan.FromSeconds(0.5),
                    BackoffMultiplier    = 1,
                    RetryableStatusCodes = { StatusCode.Unavailable }
                }
            };

            return(GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
            {
                ServiceConfig = new ServiceConfig {
                    MethodConfigs = { methodConfig }
                }
            }));
        }
Exemplo n.º 14
0
        public static void AddGrpcCitiesClient(this IServiceCollection services, IConfiguration configuration)
        {
            var defaultMethodConfig = new MethodConfig
            {
                Names       = { MethodName.Default },
                RetryPolicy = new RetryPolicy
                {
                    MaxAttempts          = 5,
                    InitialBackoff       = TimeSpan.FromSeconds(1),
                    MaxBackoff           = TimeSpan.FromSeconds(5),
                    BackoffMultiplier    = 1.5,
                    RetryableStatusCodes = { StatusCode.Unavailable }
                }
            };

            services.AddGrpcClient <Cities.CitiesClient>("Cities", o =>
            {
                o.Address = new Uri("http://citiesgrpcservice:80"); //TODO add to settings
                //o.Address = new Uri("http://localhost:8681"); //TODO add to settings
            })
            .ConfigureChannel(o =>
            {
                //o.cre
                o.ServiceConfig = new ServiceConfig {
                    MethodConfigs = { defaultMethodConfig }
                };
            })
            //.EnableCallContextPropagation(o => o.SuppressContextNotFoundErrors = true)
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                var handler = new HttpClientHandler();
                return(handler);
            });

            services.AddScoped <ICitiesClient, CitiesClient>();
        }
Exemplo n.º 15
0
 public MethodXmlDocBuilder(MethodConfig methodConfig)
 {
     this.methodConfig = methodConfig;
     xmlHelper         = new XmlHelper(methodConfig);
 }
Exemplo n.º 16
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Grpc client started ...");

            var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Debug);
            });

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            //var defaultMethodConfig = new MethodConfig
            //{
            //    Names = { MethodName.Default },
            //    RetryPolicy = new RetryPolicy
            //    {
            //        MaxAttempts = 5,
            //        InitialBackoff = TimeSpan.FromSeconds(1),
            //        MaxBackoff = TimeSpan.FromSeconds(5),
            //        BackoffMultiplier = 1.5,
            //        RetryableStatusCodes = { StatusCode.Unavailable }
            //    }
            //};

            //var channel = GrpcChannel.ForAddress("http://localhost:5000",
            //    new GrpcChannelOptions
            //    {
            //        LoggerFactory = loggerFactory,
            //        ServiceConfig = new ServiceConfig
            //        {
            //            MethodConfigs = { defaultMethodConfig }
            //        }
            //    });

            var defaultMethodConfig = new MethodConfig
            {
                Names         = { MethodName.Default },
                HedgingPolicy = new HedgingPolicy
                {
                    MaxAttempts         = 5,
                    NonFatalStatusCodes = { StatusCode.Unavailable }
                }
            };

            var channel = GrpcChannel.ForAddress("http://localhost:5000", new GrpcChannelOptions
            {
                LoggerFactory = loggerFactory,
                ServiceConfig = new ServiceConfig {
                    MethodConfigs = { defaultMethodConfig }
                }
            });

            //拦截器
            var invoker = channel.Intercept(new ClientLoggerInterceptor());

            var client = new Greeter.GreeterClient(invoker);
            var reply  = await client.SayHelloAsync(
                new HelloRequest { Name = "GreeterClient" }, deadline : DateTime.UtcNow.AddSeconds(5));

            Console.WriteLine("Greeting: " + reply.Message);

            //var token = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            //using var replyStreamServer = client.StreamingServer(
            //    new HelloRequest { Name = "StreamingServer" },
            //    cancellationToken: token.Token);
            //try
            //{
            //    await foreach (var item in replyStreamServer.ResponseStream.ReadAllAsync(token.Token))
            //    {
            //        Console.WriteLine(item.Message);
            //    }
            //}
            //catch (RpcException exc)
            //{
            //    Console.WriteLine(exc.Message);
            //}

            //using var replyStreamClient = client.StreamingClient();

            //foreach (var name in new[] { "Stacking", "Client", "Stream" })
            //{
            //    await replyStreamClient.RequestStream.WriteAsync(new HelloRequest
            //    {
            //        Name = name
            //    });
            //}

            //await replyStreamClient.RequestStream.CompleteAsync();
            //var response = await replyStreamClient.ResponseAsync;

            //Console.WriteLine(response.Count);
            //Console.WriteLine(response.Message);


            //using var replyStreamWays = client.StreamingWays();
            //for (int i = 0; i < 5; i++)
            //{
            //    await replyStreamWays.RequestStream.WriteAsync(new HelloRequest
            //    {
            //        Name = "StreamWaysName " + i,
            //    });
            //}

            //while (await replyStreamWays.ResponseStream.MoveNext())
            //{
            //    try
            //    {
            //        Console.WriteLine($"Response Return:{replyStreamWays.ResponseStream.Current.Message}");
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //    }
            //}

            //await replyStreamWays.RequestStream.CompleteAsync();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 17
0
        protected override void Process(ISymbol symbol, PolicyConfig policyConfig, IViolationReporter violationReporter)
        {
            IMethodSymbol methodSymbol = (IMethodSymbol)symbol;
            MethodConfig  config       = policyConfig.MethodConfig;

            if (methodSymbol.IsOverride && !config.DocumentOverrides)
            {
                return;
            }

            if (methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation && !config.ExplicitInterfaceMethodDocumentationRequired)
            {
                return;
            }

            if (!AnyVisibilityMatches(symbol.DeclaredAccessibility, config.VisibilitiesToCheck) && methodSymbol.MethodKind != MethodKind.ExplicitInterfaceImplementation)
            {
                return;
            }

            // skip compiler generated methods for which there is no source code
            if (symbol.IsImplicitlyDeclared)
            {
                return;
            }

            // skip special method kinds
            if (!AllowedMethodKinds.Contains(methodSymbol.MethodKind))
            {
                return;
            }

            IDocumentationComment documentation = symbol.GetDocumentationComment();

            if (config.SampleDocumentationRequired && string.IsNullOrWhiteSpace(documentation.ExampleText))
            {
                violationReporter.Report(ViolationFromSymbol(ViolationMessage.MissingSampleDocumentation, symbol));
            }

            if (config.SummaryDocumentationRequired && string.IsNullOrWhiteSpace(documentation.SummaryText))
            {
                violationReporter.Report(ViolationFromSymbol(ViolationMessage.MissingSummaryDocumentation, symbol));
            }

            if (config.ResultDocumentationRequired && !methodSymbol.ReturnsVoid && string.IsNullOrWhiteSpace(documentation.ReturnsText))
            {
                violationReporter.Report(ViolationFromSymbol(ViolationMessage.MissingReturnsDocumentation, symbol));
            }

            if (config.ParameterDocumentationRequired && !methodSymbol.Parameters.IsEmpty)
            {
                foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters)
                {
                    if (string.IsNullOrWhiteSpace(documentation.GetParameterText(parameterSymbol.Name)))
                    {
                        violationReporter.Report(ViolationFromSymbol(string.Format(ViolationMessage.MissingParameter, parameterSymbol.Name), symbol));
                    }
                }
            }

            if (config.GenericParameterDocumentationRequired && !methodSymbol.TypeParameters.IsEmpty)
            {
                foreach (ITypeParameterSymbol typeParameter in methodSymbol.TypeParameters)
                {
                    if (string.IsNullOrWhiteSpace(documentation.GetTypeParameterText(typeParameter.Name)))
                    {
                        violationReporter.Report(ViolationFromSymbol(string.Format("Missing documentation for type parameter with name '{0}'", typeParameter.Name), symbol));
                    }
                }
            }
        }