public LightweightCommunicationErrorTests(IRpcSerializer serializer, RpcConnectionType connectionType) : base(serializer, connectionType) { }
private async Task <TResult> WaitForMessageResultAsync <TResult>(TChannel channel, IRpcSerializer serializer, int callId, CancellationToken cancellationToken) where TResult : RpcMessage { var re = new AsyncManualResetEvent(false); using (cancellationToken.Register(() => { re.Set(); })) { TResult result = default; RegisterMessageCallback(channel, (data, bareMsg) => { if (bareMsg.CallId == callId) { if (bareMsg is TResult msg) { result = msg; } else { result = serializer.DeserializeMessage <TResult>(data); } re.Set(); return(true); } return(false); }, true); await re.WaitAsync(); return(result); } }
public RpcMethodStub(IRpcSerializer serializer, RpcServerFaultHandler?faultHandler) { this.Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); this.FaultHandler = faultHandler; }
/// <summary> /// Takes the parsed header and envelope and applies correct type handler. /// </summary> /// <param name="header">The header.</param> /// <param name="envelope">The envelope.</param> /// <returns></returns> private async Task ApplyAsync(RpcHeader header, Envelope envelope) { if (header.Type == RpcMessageType.Single) { // find serializer for this request RpcRequest req = null; IRpcSerializer serializer = null; if (!RpcSerializer.Serializers.TryGetValue(header.Serializer, out serializer)) { throw new NotSupportedException("The serializer is not supported by RPC"); } // deserialize into a request RpcResponse res = null; try { req = serializer.DeserializeRequest(envelope.Body, (i, o) => RpcArgument.FromMember(GetMember(i, o))); } catch (KeyNotFoundException) { res = new RpcResponse("InterfaceNotFound", "The interface or operation could not be found", null); } catch (Exception ex) { res = new RpcResponse("ArgumentInvalid", string.Format("The request format is invalid: {0}", ex.Message), null); } // apply single request MemberInfo memberInfo = null; try { if (req != null) { memberInfo = GetMember(req.Interface, req.Operation); } } catch (KeyNotFoundException) { res = new RpcResponse("OperationNotFound", "The interface or operation could not be found", null); } // get operation information RpcOperationAttribute opAttr = null; if (memberInfo != null) { Type interfaceType = GetInterface(req.Interface); MemberInfo[] interfaceMember = interfaceType.GetMember(req.Operation); opAttr = interfaceMember[0].GetCustomAttribute <RpcOperationAttribute>(); } // get if no reply is enabled bool noReply = opAttr != null && opAttr.NoReply; // check if they have a response ID if no reply isn't enabled if (!noReply && envelope.ID == Guid.Empty) { res = new RpcResponse("InvalidOperation", "The envelope does not specify a correlation ID", null); } // apply request if we don't have a response already, typically an error if (res == null) { // setup context RpcContext.Current = new RpcContext() { Envelope = envelope }; // apply request res = await ApplyRequestAsync(req, memberInfo).ConfigureAwait(false); // destroy context RpcContext.Current = null; } // send response unless no-reply if (!noReply) { // serialize response byte[] resBody = serializer.SerializeResponse(res); // send reply string rpcHeader = new RpcHeader(RpcHeader.HEADER_VERSION, serializer.Name, RpcMessageType.Single).ToString(); Dictionary <string, object> headers = new Dictionary <string, object>(StringComparer.CurrentCultureIgnoreCase) { { RpcHeader.HEADER_NAME, rpcHeader }, { RpcHeader.HEADER_NAME_LEGACY, rpcHeader } }; // reply await envelope.ReplyAsync(resBody, headers).ConfigureAwait(false); } // throw exceptions } else { throw new NotImplementedException("Batched RPC is not supported currently"); } }
public object DecodeRpcCallResultMessage(IRpcChannel channel, IRpcObjectRepository localRepository, IRpcObjectRepository remoteRepository, IRpcSerializer serializer, RpcCallResultMessage message, Type resultType) { if (message.Type == RpcMessageType.Exception) { throw new TargetInvocationException((Exception)message.Result.Value); } return(DecodeRpcArgument(channel, localRepository, remoteRepository, serializer, message.Result, resultType)); }
public Invocation(string key, Type handlerTargetType, MethodInfo handlerMethodInfo, Type handlerParametersTupleType, IRpcSerializer rpcSerializer) { Key = key; HandlerTargetType = handlerTargetType; HandlerMethodInfo = handlerMethodInfo; HandlerParameterTupleType = handlerParametersTupleType; RpcSerializer = rpcSerializer; _fastInvokeHandler = DynamicProxyHelper.CreateFastInvokeHandler(HandlerMethodInfo); }
internal GrpcMethodsCache(IRpcSerializer serializer) { this.serializer = serializer; }
public GrpcErrorTests(IRpcSerializer serializer, RpcConnectionType connectionType) : base(serializer, connectionType) { }
public GrpcMessageSizeTests(IRpcSerializer serializer, RpcConnectionType connectionType) : base(serializer, connectionType) { }
public GrpcClientServerTests(IRpcSerializer serializer, RpcConnectionType connectionType) : base(serializer, connectionType) { }
internal static object QueryInternal(this FastRpcClient fastRpcClient, string title, ICustomTuple customTuple, Type returnType, IRpcSerializer rpcSerializer, string extention = null, bool throwIfErrorResponseCode = false) { if (rpcSerializer == null) { throw new ArgumentNullException(nameof(rpcSerializer)); } if (customTuple == null) { throw new ArgumentNullException(nameof(customTuple)); } var encoding = RpcExtentionSettings.DefaultEncoding; var response = fastRpcClient.Query( encoding.GetBytes(title), encoding.GetBytes(rpcSerializer.Serialize(customTuple)), extention == null ? FrameFormat.EmptyBytes : encoding.GetBytes(extention), throwIfErrorResponseCode); if (returnType == typeof(void)) { return(null); } var responseContent = response.ReadContentString(); if (string.IsNullOrEmpty(responseContent)) { return(null); } return(rpcSerializer.Deserialize(responseContent, returnType)); }
internal static async Task <TResponse> SendReceiveAsync <TRequest, TResponse>(LightweightMethodStub methodStub, TRequest request, IRpcSerializer serializer) where TRequest : class where TResponse : class { TResponse response; var context = new LightweightCallContext(new TestRpcEndPoint(), null, ImmutableArray <KeyValuePair <string, ImmutableArray <byte> > > .Empty, CancellationToken.None); var requestPipe = new Pipe(); var responsePipe = new Pipe(); var duplexPipe = new DirectDuplexPipe(requestPipe.Reader, responsePipe.Writer); await using (var pipeline = new TestPipeline(duplexPipe)) { var payload = new ReadOnlySequence <byte>(serializer.Serialize(request)); var frame = new LightweightRpcFrame(RpcFrameType.UnaryRequest, null, 1, methodStub.OperationName, RpcOperationFlags.None, 0, payload, null); await methodStub.HandleMessage(pipeline, frame, null, context); var readResult = await responsePipe.Reader.ReadAsync(); var buffer = readResult.Buffer; bool hasResponseFrame = LightweightRpcFrame.TryRead(ref buffer, 65536, out var responseFrame) == RpcFrameState.Full; Assert.IsTrue(hasResponseFrame); response = (TResponse)serializer.Deserialize(responseFrame.Payload, typeof(TResponse)); return(response); } }
internal static byte[] GetRequestData <TRequest>(string operationName, int messageNumber, TRequest request, IRpcSerializer serializer) where TRequest : class { byte[] requestData; using (var writer = new LightweightRpcFrameWriter(65536)) { var frame = new LightweightRpcFrame(RpcFrameType.UnaryRequest, messageNumber, operationName, RpcOperationFlags.None, 0, null); requestData = writer.WriteFrame(frame, request, serializer); } return(requestData); }
/// <summary> /// Constructs a RPC server request /// </summary> /// <param name="event">Event</param> /// <param name="handler">Handler for request</param> /// <param name="trigger">Trigger for request</param> /// <param name="serializer">Serializer for request</param> public ServerRpcRequest(string @event, IRpcHandler handler, IRpcTrigger trigger, IRpcSerializer serializer) : base(@event, handler, trigger, serializer) { }
protected CallbackTests(IRpcSerializer serializer, RpcConnectionType connectionType, bool roundTripCancellation) : base(serializer, connectionType) { this.RoundTripCancellation = roundTripCancellation; }
private async Task <IRpcServerChannel> CreateServer <T>(T instance, ChannelType channelType, IRpcSerializer serializer = null, TokenImpersonationLevel tokenImpersonationLevel = TokenImpersonationLevel.None, IRpcObjectRepository localRepository = null) where T : class { if (serializer == null) { serializer = new BinaryRpcSerializer(); } switch (channelType) { case ChannelType.Tcp: { var server = new TcpRpcServerChannel( serializer, new RpcMessageFactory(), IPAddress.Loopback, 11234, localRepository); if (instance != null) { server.ObjectRepository.RegisterSingleton(instance); } await server.ListenAsync(); return(server); } case ChannelType.NamedPipe: { _pipeName = Guid.NewGuid().ToString(); var server = new NamedPipeRpcServerChannel( serializer, new RpcMessageFactory(), _pipeName, localRepository: localRepository); if (instance != null) { server.ObjectRepository.RegisterSingleton(instance); } await server.ListenAsync(); return(server); } default: throw new NotSupportedException(); } }