public MockServiceHelper(string host = null) { this.host = host ?? "localhost"; serviceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName) .AddMethod(UnaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(ClientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(ServerStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(DuplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = defaultStatus; return ""; }); clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { context.Status = defaultStatus; return ""; }); serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { context.Status = defaultStatus; }); }
public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { return(base.UnaryServerHandler(request, context, continuation)); } catch (Exception ex) { var data = new Metadata(); data.Add("message", ex.Message); throw new RpcException(new Status(StatusCode.Unknown, "Unknown"), data); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { string calledMethod = context.Method.Split('/').Last(); Console.WriteLine($"{calledMethod}: {request}"); TResponse response = null; try { response = await base.UnaryServerHandler(request, context, continuation); } catch (Exception e) { Console.WriteLine($"{calledMethod}: {e.Message}"); Console.WriteLine($"{calledMethod}: {e.StackTrace}"); } Console.WriteLine($"{calledMethod}: {response}"); return(response); }
public UnaryServerCallHandler <TService, TRequest, TResponse> CreateUnary <TRequest, TResponse>(Method <TRequest, TResponse> method, UnaryServerMethod <TService, TRequest, TResponse> invoker) where TRequest : class where TResponse : class { var options = CreateMethodOptions(); var methodInvoker = new UnaryServerMethodInvoker <TService, TRequest, TResponse>(invoker, method, options, _serviceActivator); return(new UnaryServerCallHandler <TService, TRequest, TResponse>(methodInvoker, _loggerFactory)); }
public async override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { (string, string)tuple = InterceptCallContext(context); var watch = Stopwatch.StartNew(); var result = await continuation(request, context); Logger.Log.GrpcTrace(m_loggingContext, string.Format(RespondedLogFormat, tuple.Item1, tuple.Item2, context.Method, watch.ElapsedMilliseconds)); return(result); }
public override void AddMethod <TRequest, TResponse>( Method <TRequest, TResponse> method, UnaryServerMethod <TRequest, TResponse> handler) { callHandlers.Add(method.Name, ServerCalls.UnaryCall(method, handler)); }
public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { context.UserState["IntercepterRun"] = true; return(base.UnaryServerHandler(request, context, continuation)); }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { Stopwatch sw = new Stopwatch(); sw.Start(); TResponse response = null; Exception exception = null; try { response = await continuation(request, context); return(response); } catch (Exception ex) { exception = ex; throw; } finally { sw.Stop(); var log = new { begint_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ms"), cost = sw.ElapsedMilliseconds, interface_name = context.Method, request_content = request, response_content = response, source_ip = context.Peer, ex = exception?.Message }; _accessLogger.LogInformation(Newtonsoft.Json.JsonConvert.SerializeObject(log)); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { //拦截器,注入自己的异常处理逻辑 try { return(await base.UnaryServerHandler(request, context, continuation)); } catch (Exception ex) { var data = new Metadata { { "message", ex.Message } }; throw new RpcException(new Status(StatusCode.Unknown, "Unknon"), data); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { return(await continuation(request, context)); } catch (Exception ex) { Console.WriteLine(ex.ToString()); var response = Activator.CreateInstance <TResponse>(); TryProperty(response, "Code", MessageCode.DefaultError); TryProperty(response, "Message", "哎呀,服务开了个小差 (>﹏<)~!"); TryProperty(response, "Success", false); return(response); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { return(await base.UnaryServerHandler(request, context, continuation)); } catch (Exception exception) { context.Status = ExceptionHandler.Handle(exception, logger); return((TResponse)Activator.CreateInstance(typeof(TResponse))); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { return(await base.UnaryServerHandler(request, context, continuation)); } // 再次之前处理业务异常并返回 catch (Exception e) { _logger.LogWarning(e, "gRPC 服务调用过程出现未处理异常"); var metadata = new Metadata { { "message-bin", Encoding.UTF8.GetBytes(e.Message) } }; throw new RpcException(new Status(StatusCode.Internal, "未处理的异常信息"), metadata); } }
/// <summary> /// Adds a unary method to a service. /// </summary> /// <typeparam name="TRequest">Request message type for this method.</typeparam> /// <typeparam name="TResponse">Response message type for this method.</typeparam> /// <param name="method">The method description.</param> /// <param name="metadata">The method metadata. This metadata can be used by routing and middleware when invoking a gRPC method.</param> /// <param name="invoker">The method invoker that is executed when the method is called.</param> /// <param name="configure">The callback to override service method configuration.</param> public void AddUnaryMethod <TRequest, TResponse>(Method <TRequest, TResponse> method, IList <object> metadata, UnaryServerMethod <TService, TRequest, TResponse> invoker, Action <GrpcServiceMethodOptions> configure) where TRequest : class where TResponse : class { var callHandler = _serverCallHandlerFactory.CreateUnary <TRequest, TResponse>(method, invoker, configure); var methodModel = new MethodModel(method, metadata, callHandler.HandleCallAsync); Methods.Add(methodModel); }
/// <summary> /// Adds a unary method to a service. /// </summary> /// <typeparam name="TRequest">Request message type for this method.</typeparam> /// <typeparam name="TResponse">Response message type for this method.</typeparam> /// <param name="method">The method description.</param> /// <param name="metadata">The method metadata. This metadata can be used by routing and middleware when invoking a gRPC method.</param> /// <param name="invoker">The method invoker that is executed when the method is called.</param> public void AddUnaryMethod <TRequest, TResponse>(Method <TRequest, TResponse> method, IList <object> metadata, UnaryServerMethod <TService, TRequest, TResponse> invoker) where TRequest : class where TResponse : class { AddUnaryMethod(method, metadata, invoker, options => { }); }
public MockServiceHelper(string host = null, Marshaller <string> marshaller = null, IEnumerable <ChannelOption> channelOptions = null) { this.host = host ?? "localhost"; this.channelOptions = channelOptions; marshaller = marshaller ?? Marshallers.StringMarshaller; unaryMethod = new Method <string, string>( MethodType.Unary, ServiceName, "Unary", marshaller, marshaller); clientStreamingMethod = new Method <string, string>( MethodType.ClientStreaming, ServiceName, "ClientStreaming", marshaller, marshaller); serverStreamingMethod = new Method <string, string>( MethodType.ServerStreaming, ServiceName, "ServerStreaming", marshaller, marshaller); duplexStreamingMethod = new Method <string, string>( MethodType.DuplexStreaming, ServiceName, "DuplexStreaming", marshaller, marshaller); serviceDefinition = ServerServiceDefinition.CreateBuilder() .AddMethod(unaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod <string, string>(async(request, context) => { context.Status = defaultStatus; return(""); }); clientStreamingHandler = new ClientStreamingServerMethod <string, string>(async(requestStream, context) => { context.Status = defaultStatus; return(""); }); serverStreamingHandler = new ServerStreamingServerMethod <string, string>(async(request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod <string, string>(async(requestStream, responseStream, context) => { context.Status = defaultStatus; }); }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { return(await continuation(request, context)); } catch (ElwarkException ex) { throw new RpcException(new Status(StatusCode.FailedPrecondition, ex.Code)); } catch (ArgumentNullException ex) { var meta = new Metadata { new($"field-{ex.ParamName}", ex.Message) }; throw new RpcException(new Status(StatusCode.InvalidArgument, "InvalidModelState"), meta); } catch (ArgumentOutOfRangeException ex) { var meta = new Metadata { new($"field-{ex.ParamName}", ex.Message) }; throw new RpcException(new Status(StatusCode.InvalidArgument, "InvalidModelState"), meta); } catch (ValidationException ex) { var result = ex.Errors.GroupBy(x => x.PropertyName) .ToDictionary(x => $"field-{x.Key}", x => x.Select(t => t.ErrorCode)); var meta = new Metadata(); foreach (var(key, value) in result) { meta.Add(key, string.Join("|", value)); } throw new RpcException(new Status(StatusCode.InvalidArgument, "InvalidModelState"), meta); } catch (Exception ex) { throw new RpcException(new Status(StatusCode.Internal, "Unknown", ex)); } }
public UnaryServerCallHandler(Method <TRequest, TResponse> method, UnaryServerMethod <TService, TRequest, TResponse> invoker, GrpcServiceOptions serviceOptions, ILoggerFactory loggerFactory) : base(method, serviceOptions, loggerFactory) { _invoker = invoker; }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { SetCultureIfExist(context); SetActivityIDIfExist(context); var targetType = continuation.Target.GetType(); // Get the service type for the service we're calling a method in. var serviceType = targetType.GenericTypeArguments[0]; var serviceAspect = _grpcMethodInfo.GetAttributeFor(context.Method, serviceType); // if no service aspect is defined an empty one was generated by the GrpcMethodInfo => skip in this case the check. if (serviceAspect.Operations.Length > 0 && !_applicationContext.Principal.IsAuthorized(serviceAspect.Scope, serviceAspect.Operations)) { throw new RpcException(new Grpc.Core.Status(StatusCode.PermissionDenied, "You don't have the expected rights.")); } try { return(await continuation(request, context)); } catch (AppException ae) { throw new Google.Rpc.Status { Code = (int)StatusCode.Internal, Message = appSettings, Details = { new ErrorInfo { Reason = JsonSerializer.Serialize(ae.Messages) } } }.ToException(); } catch (RpcException rcp) { _logger.Technical().Exception(rcp).Log(); throw; } catch (Exception ex) { _logger.Technical().Exception(ex).Log(); throw new RpcException(new Grpc.Core.Status(StatusCode.Internal, "An error occurs.")); } }
public UnaryServerCallHandler(Method <TRequest, TResponse> method, UnaryServerMethod <TRequest, TResponse> handler) { this.method = method; this.handler = handler; }
public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { if (context.Method != GetFullMethodName(nameof(PeerService.PeerServiceBase.Connect))) { var peer = _peerPool.FindPeerByPublicKey(context.GetPublicKey()); if (peer == null && context.Method != GetFullMethodName(nameof(PeerService.PeerServiceBase.Ping))) { Logger.LogWarning($"Could not find peer {context.GetPublicKey()}"); return(Task.FromResult <TResponse>(null)); } context.RequestHeaders.Add(new Metadata.Entry(GrpcConstants.PeerInfoMetadataKey, $"{peer}")); } return(continuation(request, context)); }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { string calledMethod = context.Method.Split('/').Last(); context.UserState["user"] = null; // Do not authorize these methods: string[] whitelist = { "Login", "LoginWithToken", "RegisterAccount", "HealthCheck", }; if (!whitelist.Contains(calledMethod)) { // The endpoint requires authorization before performing. // Get JWT header Metadata.Entry entry = context.RequestHeaders.Get("authorization"); if (entry?.Value != null) { if (JwtManager.ValidateToken(entry.Value, out var uuid)) { // Validate user exists. DbUserModel dbUserModel = await DbUserModel.GetUserFromGuid(uuid); if (dbUserModel != null) { context.UserState["user"] = dbUserModel; } } } } // Do regular request and return var response = await base.UnaryServerHandler(request, context, continuation); return(response); }
public override void AddMethod <TRequest, TResponse>(Method <TRequest, TResponse> method, UnaryServerMethod <TRequest, TResponse> handler) { var model = _serviceModelFactory.CreateUnaryModel(method); var callHandler = _serverCallHandlerFactory.CreateUnary(method, model.Invoker); AddMethodCore(method, callHandler.HandleCallAsync, model.Metadata); }
public UnaryServerCallHandler(Method <TRequest, TResponse> method) : base(method) { var handlerMethod = typeof(TService).GetMethod(Method.Name); _invoker = (UnaryServerMethod)Delegate.CreateDelegate(typeof(UnaryServerMethod), handlerMethod); }
/// <summary> /// 单请求 /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="request"></param> /// <param name="context"></param> /// <param name="continuation"></param> /// <returns></returns> public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { return(continuation(request, context)); }
public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { byte[] certChain = context.AuthContext.Properties.ToList().FirstOrDefault(a => a.Name == "x509_pem_cert")?.ValueBytes; Assert.IsFalse(certChain == null || certChain.Length == 0, "Client didn't send TLS certificate"); byte[] certRAW = Certificate.ExtractDER(certChain.ToUTF8String()); byte[] origRAW = Certificate.ExtractDER(expectedClientCert.ToUTF8String()); bool equalCerts = StructuralComparisons.StructuralEqualityComparer.Equals(certRAW, origRAW); Assert.IsTrue(equalCerts, "Expected certificate doesn't match actual"); toggleHandshakeFunction(true); } catch (System.Exception e) { Assert.Fail($"Uncaught exception: {e.Message}"); } return(base.UnaryServerHandler(request, context, continuation)); }
/// <summary> /// /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="request"></param> /// <param name="context"></param> /// <param name="continuation"></param> /// <returns></returns> public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { System.Diagnostics.Debug.WriteLine(string.Format("[SERVICE][ExampleInterceptor:{0}] method={1} request={2}", Name, context.Method, request)); return(base.UnaryServerHandler(request, context, continuation)); }
public override Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { if (context.Method != GetFullMethodName(nameof(PeerService.PeerServiceBase.DoHandshake))) { // a method other than DoHandshake is being called var peer = _peerPool.FindPeerByPublicKey(context.GetPublicKey()); if (peer == null && context.Method != GetFullMethodName(nameof(PeerService.PeerServiceBase.Ping))) { Logger.LogWarning($"Could not find peer {context.GetPublicKey()}"); return(Task.FromResult <TResponse>(null)); } // check that the peers session is equal to one announced in the headers var sessionId = context.GetSessionId(); if (peer != null && !peer.InboundSessionId.BytesEqual(sessionId)) { if (peer.InboundSessionId == null) { Logger.LogWarning($"Wrong inbound session id {context.Peer}, {context.Method}"); return(Task.FromResult <TResponse>(null)); } if (sessionId == null) { Logger.LogWarning($"Wrong context session id {context.Peer}, {context.Method}, {peer}"); return(Task.FromResult <TResponse>(null)); } Logger.LogWarning($"Unequal session id, {context.Peer} ({peer.InboundSessionId.ToHex()} vs {sessionId.ToHex()}) {context.GetPublicKey()}"); return(Task.FromResult <TResponse>(null)); } context.RequestHeaders.Add(new Metadata.Entry(GrpcConstants.PeerInfoMetadataKey, $"{peer}")); } } catch (Exception e) { Logger.LogError(e, $"Auth interceptor error {context.Peer}, {context.Method}: "); throw; } return(continuation(request, context)); }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { LogCall(context); try { return(await continuation(request, context)); } catch (Exception e) { Status status; if (e is GirvsException girvsException) { status = new Status(ConverGrpcStatusCode(girvsException.StatusCode), e.Message); } else { status = new Status(StatusCode.Unknown, e.Message); } _logger.LogError(e, e.Message); throw new RpcException(status); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { await ValidateRequest(request); return(await continuation(request, context)); }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { _processor.BeginRequest(context); return(await Handler <TRequest, TResponse>(context, async() => { return await continuation(request, context); })); }
public MockServiceHelper(string host = null, Marshaller<string> marshaller = null, IEnumerable<ChannelOption> channelOptions = null) { this.host = host ?? "localhost"; this.channelOptions = channelOptions; marshaller = marshaller ?? Marshallers.StringMarshaller; unaryMethod = new Method<string, string>( MethodType.Unary, ServiceName, "Unary", marshaller, marshaller); clientStreamingMethod = new Method<string, string>( MethodType.ClientStreaming, ServiceName, "ClientStreaming", marshaller, marshaller); serverStreamingMethod = new Method<string, string>( MethodType.ServerStreaming, ServiceName, "ServerStreaming", marshaller, marshaller); duplexStreamingMethod = new Method<string, string>( MethodType.DuplexStreaming, ServiceName, "DuplexStreaming", marshaller, marshaller); serviceDefinition = ServerServiceDefinition.CreateBuilder() .AddMethod(unaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = defaultStatus; return ""; }); clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { context.Status = defaultStatus; return ""; }); serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { context.Status = defaultStatus; }); }
/// <summary> /// 拦截服务请求 /// </summary> public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { try { return(await continuation.Invoke(request, context)); } catch (RpcException) { throw; } catch (Exception exception) { Exception innerException = GetInnerException(exception); Status status = new Status(StatusCode.Aborted, innerException.Message, exception); throw new RpcException(status); } }