예제 #1
0
        /// <summary>
        /// Processes a wire message that contains a goodbye message, which is sent from a client to close the session.
        /// </summary>
        /// <param name="request">Wire message from client</param>
        private void ProcessGoodbyeMessage(WireMessage request)
        {
            var sharedSecret =
                MessageEncryption
                    ? SessionId.ToByteArray()
                    : null;

            var goodbyeMessage =
                _server.Serializer
                .Deserialize <GoodbyeMessage>(
                    _server.MessageEncryptionManager.GetDecryptedMessageData(
                        message: request,
                        serializer: _server.Serializer,
                        sharedSecret: sharedSecret,
                        sendersPublicKeyBlob: _clientPublicKeyBlob,
                        sendersPublicKeySize: _keyPair?.KeySize ?? 0));

            if (goodbyeMessage.SessionId != _sessionId)
            {
                return;
            }

            var resultMessage =
                _server.MessageEncryptionManager.CreateWireMessage(
                    messageType: request.MessageType,
                    serializedMessage: new byte[0],
                    serializer: _server.Serializer,
                    keyPair: _keyPair,
                    sharedSecret: sharedSecret,
                    uniqueCallKey: request.UniqueCallKey);

            _rawMessageTransport.SendMessage(_server.Serializer.Serialize(resultMessage));

            _server.SessionRepository.RemoveSession(_sessionId);
        }
예제 #2
0
        /// <summary>
        /// This request is used to close the Statement object in the Phoenix query server identified by the given IDs.
        /// </summary>
        public async Task <CloseStatementResponse> CloseStatementRequestAsync(string connectionId, uint statementId, RequestOptions options)
        {
            CloseStatementRequest req = new CloseStatementRequest
            {
                ConnectionId = connectionId,
                StatementId  = statementId
            };

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "CloseStatementRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "CloseStatementRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage            output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    CloseStatementResponse res    = CloseStatementResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #3
0
파일: Service.cs 프로젝트: dianatatu/REACH
 private void SendMessages()
 {
     while (true)
     {
         lock (mutex)
         {
             List <RMessage> newMessageQueue = new List <RMessage>();
             foreach (RMessage m in messageQueue)
             {
                 try
                 {
                     --timeout[m];
                     WireMessage.SendMessage(tcpClient, m);
                     timeout.Remove(m);
                 }
                 catch (Exception)
                 {
                     if (timeout[m] > 0)
                     {
                         newMessageQueue.Add(m);
                     }
                     else
                     {
                         // Send back the message
                         Context.FireCallback(m);
                         timeout.Remove(m);
                     }
                 }
             }
             messageQueue.Clear();
             messageQueue.AddRange(newMessageQueue);
         }
         Thread.Sleep(DELAY_TIME);
     }
 }
예제 #4
0
        /// <summary>
        /// This request is used to open a new Connection in the Phoenix query server.
        /// </summary>
        public async Task <OpenConnectionResponse> OpenConnectionRequestAsync(string connectionId, pbc::MapField <string, string> info, RequestOptions options)
        {
            OpenConnectionRequest req = new OpenConnectionRequest
            {
                ConnectionId = connectionId,
                Info         = info
            };

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "OpenConnectionRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "OpenConnectionRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage            output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    OpenConnectionResponse res    = OpenConnectionResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #5
0
파일: Service.cs 프로젝트: dianatatu/REACH
 private void ReceiveMessages()
 {
     if (tcpClient == null)
     {
         ConnectToServer();
     }
     while (true)
     {
         RMessage msg;
         do
         {
             msg = WireMessage.ReceiveMessage(tcpClient);
             // Pass the control to the Context, to find an
             // appropiate callback function
             if (msg != null)
             {
                 Context.FireCallback(msg);
             }
             else
             {
                 Context.FireCallback(new RMessage(MessageType.SERVER_OFFLINE_EVENT, null));
                 ConnectToServer();
             }
         } while (msg == null);
     }
 }
예제 #6
0
        private IEnumerable <WireMessage> DeserializeInternal(Stream stream)
        {
            using (var reader =
                       (IStreamReader)(stream as ChunkedStream)?.NewReader(0) ?? new BinaryStreamReader(stream))
            {
                var b = reader.ReadByte();
                if (b == NullFlag)
                {
                    return(null);
                }

                var count = reader.ReadInt32();
                if (count == 0)
                {
                    return(null);
                }

                var result = new WireMessage[count];
                for (var i = 0; i < count; i++)
                {
                    result[i] = Read(reader);
                }

                return(result);
            }
        }
예제 #7
0
        static void SerializeTest2()
        {
            var serializer = new DefaultRpcSerializer();

            var sw = new Stopwatch();

            Console.WriteLine("Press ESC to exit, any key to continue ...");

            while (ReadKey() != ConsoleKey.Escape)
            {
                Console.Clear();
                Console.WriteLine("Press ESC to exit, any key to continue ...");

                var message = new WireMessage
                {
                    Data        = "hello (fire & forget) - 000000",
                    MessageType = MessageType.Default
                };

                sw.Restart();

                for (var i = 0; i < loop; i++)
                {
                    serializer.Serialize(new WireMessage[] { message });
                }

                sw.Stop();

                Console.WriteLine("Ellapsed time (ms): " + sw.ElapsedMilliseconds);
                Console.WriteLine("Concurrency: " + (loop * 1000 / sw.ElapsedMilliseconds) + " call per sec");
            }
        }
예제 #8
0
        public void TestBinarySerializationReadAndWrite(WireMessage wireMessage)
        {
            byte[]      bytes  = SerializeHelper.BinarySerialize(wireMessage);
            WireMessage unWrap = SerializeHelper.BinaryRead <WireMessage>(new System.IO.MemoryStream(bytes));

            Assert.IsTrue(CompareWireMessage(wireMessage, unWrap));
        }
예제 #9
0
        internal static async Task WriteMessage(this Stream stream, WireMessage message, CancellationToken cancellationToken = default)
        {
            await stream.WriteBuffer(new[] { (byte)message.MessageType }, cancellationToken);

            await stream.WriteBuffer(BitConverter.GetBytes(message.Data.Length), cancellationToken);

            await stream.WriteBuffer(message.Data, cancellationToken);
        }
예제 #10
0
        private void StatusForm_Load(object sender, EventArgs e)
        {
            WireMessage myLogger = new WireMessage(WriteMessage);

            output      = new OutputWorker(myLogger);
            timerWorker = new TimerWorker();
            timerWorker.Run(output);
        }
예제 #11
0
        /// <summary>
        /// Processes a RPC result message from server.
        /// </summary>
        /// <param name="message">Deserialized WireMessage that contains a MethodCallResultMessage or a RemoteInvocationException</param>
        /// <exception cref="KeyNotFoundException">Thrown, when the received result is of a unknown call</exception>
        private void ProcessRpcResultMessage(WireMessage message)
        {
            byte[] sharedSecret =
                MessageEncryption
                    ? _sessionId.ToByteArray()
                    : null;

            Guid unqiueCallKey =
                message.UniqueCallKey == null
                    ? Guid.Empty
                    : new Guid(message.UniqueCallKey);

            if (!_activeCalls.TryGetValue(unqiueCallKey, out ClientRpcContext clientRpcContext))
            {
                throw new KeyNotFoundException("Received a result for a unknown call.");
            }

            clientRpcContext.Error = message.Error;

            if (message.Error)
            {
                var remoteException =
                    Serializer.Deserialize <RemoteInvocationException>(
                        MessageEncryptionManager.GetDecryptedMessageData(
                            message: message,
                            serializer: Serializer,
                            sharedSecret: sharedSecret,
                            sendersPublicKeyBlob: _serverPublicKeyBlob,
                            sendersPublicKeySize: _keyPair?.KeySize ?? 0));

                clientRpcContext.RemoteException = remoteException;
            }
            else
            {
                try
                {
                    var rawMessage =
                        MessageEncryptionManager.GetDecryptedMessageData(
                            message: message,
                            serializer: Serializer,
                            sharedSecret: sharedSecret,
                            sendersPublicKeyBlob: _serverPublicKeyBlob,
                            sendersPublicKeySize: _keyPair?.KeySize ?? 0);

                    var resultMessage =
                        Serializer
                        .Deserialize <MethodCallResultMessage>(rawMessage);

                    clientRpcContext.ResultMessage = resultMessage;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
            clientRpcContext.WaitHandle.Set();
        }
예제 #12
0
 public bool TryGetMessage(out WireMessage message)
 {
     message = null;
     if (!Disposed && _messageQueue.TryDequeue(out message))
     {
         Interlocked.Add(ref _count, -1L);
         return(true);
     }
     return(false);
 }
예제 #13
0
 public void WriteMessage(string message)
 {
     if (txtOutput.InvokeRequired)
     {
         WireMessage d = new WireMessage(WriteMessage);
         this.Invoke(d, new object[] { message });
     }
     else
     {
         txtOutput.AppendText(message + "\n");
     }
 }
예제 #14
0
 public void SendMessage(RMessage message)
 {
     try
     {
         WireMessage.SendMessage(connection, message);
     }
     catch (Exception)
     {
         // The connection is down, we destroy this ClientWorker
         CloseConnection();
         chatThread.Abort();
     }
 }
예제 #15
0
 private void StartChat()
 {
     while (true)
     {
         RMessage message = WireMessage.ReceiveMessage(connection);
         if (message == null)
         {
             CloseConnection();
             break;
         }
         Commander.OnNewMessage(message, connection);
     }
 }
예제 #16
0
        /// <summary>
        /// Processes a wire message that contains a authentication request message, which is sent from a client to request authentication of a set of credentials.
        /// </summary>
        /// <param name="request">Wire message from client</param>
        private void ProcessAuthenticationRequestMessage(WireMessage request)
        {
            if (_isAuthenticated)
            {
                return;
            }

            Identity = null;

            var sharedSecret =
                MessageEncryption
                    ? SessionId.ToByteArray()
                    : null;

            var authRequestMessage =
                _server.Serializer
                .Deserialize <AuthenticationRequestMessage>(
                    _server.MessageEncryptionManager.GetDecryptedMessageData(
                        message: request,
                        serializer: _server.Serializer,
                        sharedSecret: sharedSecret,
                        sendersPublicKeyBlob: _clientPublicKeyBlob,
                        sendersPublicKeySize: _keyPair?.KeySize ?? 0));

            _isAuthenticated = _server.Authenticate(authRequestMessage.Credentials, out var authenticatedIdentity);

            if (_isAuthenticated)
            {
                Identity = authenticatedIdentity;
            }

            var authResponseMessage =
                new AuthenticationResponseMessage
            {
                IsAuthenticated       = _isAuthenticated,
                AuthenticatedIdentity = authenticatedIdentity
            };

            var serializedAuthResponse = _server.Serializer.Serialize(authResponseMessage);

            var wireMessage =
                _server.MessageEncryptionManager.CreateWireMessage(
                    serializedMessage: serializedAuthResponse,
                    serializer: _server.Serializer,
                    sharedSecret: sharedSecret,
                    keyPair: _keyPair,
                    messageType: "auth_response");

            _rawMessageTransport.SendMessage(
                _server.Serializer.Serialize(wireMessage));
        }
예제 #17
0
        protected override Task SendMessage(WireMessage message, IRpcConnection conn)
        {
            try
            {
                ThrowIfDisposed();

                conn.Send(message);

                return(Completed);
            }
            catch (Exception e)
            {
                return(Task.FromException(e));
            }
        }
예제 #18
0
        public void TestCallFunction(WireMessage message, string expectedString)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                TextWriterTraceListener listener = new TextWriterTraceListener(stream);
                Trace.Listeners.Add(listener);

                ProcessActionCommandForServer.Invoke(_tcpServer, new object[] { message });
                Trace.Flush();

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream))
                {
                    Assert.AreEqual(expectedString, reader.ReadLine());
                }
            }
        }
예제 #19
0
        public bool TryGetMessage(int count, out IList messages)
        {
            messages = null;
            if (!Disposed)
            {
                var queueSize = (int)Interlocked.Read(ref _count);
                if (queueSize > 0)
                {
                    count = Math.Min(Math.Min(RpcConstants.MaxBulkMessageLength, Math.Max(1, count)), queueSize);

                    WireMessage message;
                    if (count == 1)
                    {
                        if (_messageQueue.TryDequeue(out message))
                        {
                            Interlocked.Add(ref _count, -1L);

                            messages = new WireMessage[] { message };
                            return(true);
                        }
                        return(false);
                    }

                    var list = new List <WireMessage>(count);

                    for (var i = 0; i < count; i++)
                    {
                        if (!_messageQueue.TryDequeue(out message))
                        {
                            break;
                        }

                        Interlocked.Add(ref _count, -1L);
                        list.Add(message);
                    }

                    if (list.Count > 0)
                    {
                        messages = list;
                        return(true);
                    }
                }
            }
            return(false);
        }
        public void BinarySerializerAdapter_should_deserialize_CompleteHandshakeWireMessage()
        {
            var sessionId = Guid.NewGuid();

            var completeHandshakeMessage =
                new WireMessage
            {
                MessageType = "complete_handshake",
                Data        = sessionId.ToByteArray()
            };

            var serializer = new BinarySerializerAdapter();
            var rawData    = serializer.Serialize(completeHandshakeMessage);

            var deserializedMessage = serializer.Deserialize <WireMessage>(rawData);

            Assert.Equal("complete_handshake", deserializedMessage.MessageType);
            Assert.Equal(sessionId, new Guid(deserializedMessage.Data));
        }
예제 #21
0
        private void VerifyTraceOutput(WireMessage message, IEnumerable <string> traceOutput)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                TextWriterTraceListener listener = new TextWriterTraceListener(stream);
                Trace.Listeners.Add(listener);

                ProcessActionCommandForServer.Invoke(_tcpServer, new object[] { message });
                Trace.Flush();

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream))
                {
                    foreach (string trace in traceOutput)
                    {
                        Assert.AreEqual(trace, reader.ReadLine());
                    }
                }
            }
        }
예제 #22
0
        /// <summary>
        /// This request is used to fetch the tables available in this database filtered by the provided criteria.
        /// </summary>
        public async Task <ResultSetResponse> TablesRequestAsync(string catalog, string schemaPattern, string tableNamePattern, pbc::RepeatedField <string> typeList, bool hasTypeList, string connectionId)
        {
            TablesRequest req = new TablesRequest
            {
                Catalog          = catalog,
                SchemaPattern    = schemaPattern,
                TableNamePattern = tableNamePattern,
                HasTypeList      = hasTypeList,
                ConnectionId     = connectionId
            };

            req.TypeList.AddRange(typeList);

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "TablesRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray()))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "TablesRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage       output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ResultSetResponse res    = ResultSetResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #23
0
        /// <summary>
        /// This request is used as a short-hand for create a Statement and fetching the first batch
        /// of results in a single call without any parameter substitution.
        /// </summary>
        public async Task <ExecuteResponse> PrepareAndExecuteRequestAsync(string connectionId, string sql, uint statementId, long maxRowsTotal, int firstFrameMaxSize, RequestOptions options)
        {
            PrepareAndExecuteRequest req = new PrepareAndExecuteRequest
            {
                Sql               = sql,
                ConnectionId      = connectionId,
                StatementId       = statementId,
                MaxRowsTotal      = maxRowsTotal,
                FirstFrameMaxSize = firstFrameMaxSize
            };

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "PrepareAndExecuteRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "PrepareAndExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage     output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteResponse res    = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #24
0
        /// <summary>
        /// This request is used as a short-hand for create a Statement and fetching the first batch 
        /// of results in a single call without any parameter substitution.
        /// </summary>
        public async Task<ExecuteResponse> PrepareAndExecuteRequestAsync(string connectionId, string sql, uint statementId, long maxRowsTotal, int firstFrameMaxSize, RequestOptions options)
        {
            PrepareAndExecuteRequest req = new PrepareAndExecuteRequest
            {
                Sql = sql,
                ConnectionId = connectionId,
                StatementId = statementId,
                MaxRowsTotal = maxRowsTotal,
                FirstFrameMaxSize = firstFrameMaxSize
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "PrepareAndExecuteRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "PrepareAndExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteResponse res = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
예제 #25
0
        /// <summary>
        /// This request is used to fetch the columns in this database.
        /// </summary>
        public async Task <ResultSetResponse> ColumnsRequestAsync(string catalog, string schemaPattern, string tableNamePattern, string columnNamePattern, string connectionId, RequestOptions options)
        {
            ColumnsRequest req = new ColumnsRequest
            {
                Catalog           = catalog,
                SchemaPattern     = schemaPattern,
                TableNamePattern  = tableNamePattern,
                ColumnNamePattern = columnNamePattern,
                ConnectionId      = connectionId
            };

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "ColumnsRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "ColumnsRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage       output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ResultSetResponse res    = ResultSetResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #26
0
        /// <summary>
        /// Processes a authentication response message from server.
        /// </summary>
        /// <param name="message">Deserialized WireMessage that contains a AuthenticationResponseMessage</param>
        private void ProcessAuthenticationResponseMessage(WireMessage message)
        {
            byte[] sharedSecret =
                MessageEncryption
                    ? _sessionId.ToByteArray()
                    : null;

            var authResponseMessage =
                Serializer
                .Deserialize <AuthenticationResponseMessage>(
                    MessageEncryptionManager.GetDecryptedMessageData(
                        message: message,
                        serializer: Serializer,
                        sharedSecret: sharedSecret,
                        sendersPublicKeyBlob: _serverPublicKeyBlob,
                        sendersPublicKeySize: _keyPair?.KeySize ?? 0));

            _isAuthenticated = authResponseMessage.IsAuthenticated;

            Identity = _isAuthenticated ? authResponseMessage.AuthenticatedIdentity : null;

            _authenticationCompletedWaitHandle.Set();
        }
예제 #27
0
        /// <summary>
        /// Processes a remote delegate invocation message from server.
        /// </summary>
        /// <param name="message">Deserialized WireMessage that contains a RemoteDelegateInvocationMessage</param>
        private void ProcessRemoteDelegateInvocationMessage(WireMessage message)
        {
            byte[] sharedSecret =
                MessageEncryption
                    ? _sessionId.ToByteArray()
                    : null;

            var delegateInvocationMessage =
                Serializer
                .Deserialize <RemoteDelegateInvocationMessage>(
                    MessageEncryptionManager.GetDecryptedMessageData(
                        message: message,
                        serializer: Serializer,
                        sharedSecret: sharedSecret,
                        sendersPublicKeyBlob: _serverPublicKeyBlob,
                        sendersPublicKeySize: _keyPair?.KeySize ?? 0));

            var localDelegate =
                _delegateRegistry.GetDelegateByHandlerKey(delegateInvocationMessage.HandlerKey);

            // Invoke local delegate with arguments from remote caller
            localDelegate.DynamicInvoke(delegateInvocationMessage.DelegateArguments);
        }
예제 #28
0
        /// <summary>
        /// This request is used to execute a PreparedStatement, optionally with values to bind to the parameters in the Statement.
        /// </summary>
        public async Task <ExecuteResponse> ExecuteRequestAsync(StatementHandle statementHandle, pbc::RepeatedField <TypedValue> parameterValues, ulong firstFrameMaxSize, bool hasParameterValues, RequestOptions options)
        {
            ExecuteRequest req = new ExecuteRequest
            {
                StatementHandle    = statementHandle,
                ParameterValues    = parameterValues,
                FirstFrameMaxSize  = firstFrameMaxSize,
                HasParameterValues = hasParameterValues
            };

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "ExecuteRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "ExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  statementHandle.ConnectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage     output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteResponse res    = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #29
0
        /// <summary>
        /// This request is used to execute a batch of updates against a PreparedStatement.
        /// </summary>
        public async Task <ExecuteBatchResponse> ExecuteBatchRequestAsync(string connectionId, uint statementId, pbc::RepeatedField <UpdateBatch> updates)
        {
            ExecuteBatchRequest req = new ExecuteBatchRequest
            {
                ConnectionId = connectionId,
                StatementId  = statementId
            };

            req.Updates.AddRange(updates);

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "ExecuteBatchRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray()))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "ExecuteBatchRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage          output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteBatchResponse res    = ExecuteBatchResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #30
0
        /// <summary>
        /// This request is used to fetch a batch of rows from a Statement previously created.
        /// </summary>
        public async Task <FetchResponse> FetchRequestAsync(string connectionId, uint statementId, ulong offset, int frameMaxSize)
        {
            FetchRequest req = new FetchRequest
            {
                ConnectionId = connectionId,
                StatementId  = statementId,
                Offset       = offset,
                FrameMaxSize = frameMaxSize
            };

            WireMessage msg = new WireMessage
            {
                Name           = Constants.WireMessagePrefix + "FetchRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray()))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res    = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                              string.Format(
                                  "FetchRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                                  connectionId,
                                  webResponse.WebResponse.StatusCode,
                                  res.ToString()));
                }
                else
                {
                    WireMessage   output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    FetchResponse res    = FetchResponse.Parser.ParseFrom(output.WrappedMessage);
                    return(res);
                }
            }
        }
예제 #31
0
        public void TestSendAndParse(WireMessage wireMessage)
        {
            Task task = Task.Run(() =>
            {
                while (!_serverWorker.MessageQueue.Any)
                {
                    _serverWorker.Start();
                }
                _serverWorker.Dispose();
            });

            _clientWorker.Start();
            _clientWorker.Send(wireMessage);
            task.Wait(5000);

            if (_serverWorker.MessageQueue.TryDequeue(out WireMessage message))
            {
                Assert.IsTrue(CompareWireMessage(message, wireMessage));
            }
            else
            {
                Assert.Fail("No asserting executed.");
            }
        }
예제 #32
0
        /// <summary>
        /// This request is used to fetch the columns in this database.
        /// </summary>
        public async Task<ResultSetResponse> ColumnsRequestAsync(string catalog, string schemaPattern, string tableNamePattern, string columnNamePattern, string connectionId, RequestOptions options)
        {
            ColumnsRequest req = new ColumnsRequest
            {
                Catalog = catalog,
                SchemaPattern = schemaPattern,
                TableNamePattern = tableNamePattern,
                ColumnNamePattern = columnNamePattern,
                ConnectionId = connectionId
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "ColumnsRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "ColumnsRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ResultSetResponse res = ResultSetResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
예제 #33
0
        /// <summary>
        /// This request is used to ensure that the client and server have a consistent view of the database properties.
        /// </summary>
        public async Task<ConnectionSyncResponse> ConnectionSyncRequestAsync(string connectionId, ConnectionProperties props, RequestOptions options)
        {
            ConnectionSyncRequest req = new ConnectionSyncRequest
            {
                ConnectionId = connectionId,
                ConnProps = props
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "ConnectionSyncRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "ConnectionSyncRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ConnectionSyncResponse res = ConnectionSyncResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
예제 #34
0
        /// <summary>
        /// This request is used to execute a PreparedStatement, optionally with values to bind to the parameters in the Statement.
        /// </summary>
        public async Task<ExecuteResponse> ExecuteRequestAsync(StatementHandle statementHandle, pbc::RepeatedField<TypedValue> parameterValues, ulong firstFrameMaxSize, bool hasParameterValues, RequestOptions options)
        {
            ExecuteRequest req = new ExecuteRequest
            {
                StatementHandle = statementHandle,
                ParameterValues = parameterValues,
                FirstFrameMaxSize = firstFrameMaxSize,
                HasParameterValues = hasParameterValues
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "ExecuteRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "ExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            statementHandle.ConnectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteResponse res = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
예제 #35
0
        /// <summary>
        /// This request is used to fetch a batch of rows from a Statement previously created.
        /// </summary>
        public async Task<FetchResponse> FetchRequestAsync(string connectionId, uint statementId, ulong offset, int frameMaxSize, RequestOptions options)
        {
            FetchRequest req = new FetchRequest
            {
                ConnectionId = connectionId,
                StatementId = statementId,
                Offset = offset,
                FrameMaxSize = frameMaxSize
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "FetchRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "FetchRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    FetchResponse res = FetchResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
예제 #36
0
        /// <summary>
        /// This request is used to execute a batch of updates against a PreparedStatement.
        /// </summary>
        public async Task<ExecuteBatchResponse> ExecuteBatchRequestAsync(string connectionId, uint statementId, pbc::RepeatedField<UpdateBatch> updates, RequestOptions options)
        {
            ExecuteBatchRequest req = new ExecuteBatchRequest
            {
                ConnectionId = connectionId,
                StatementId = statementId,
                Updates = updates
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "ExecuteBatchRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "ExecuteBatchRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteBatchResponse res = ExecuteBatchResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
예제 #37
0
        /// <summary>
        /// This request is used to open a new Connection in the Phoenix query server.
        /// </summary>
        public async Task<OpenConnectionResponse> OpenConnectionRequestAsync(string connectionId, pbc::MapField<string, string> info, RequestOptions options)
        {
            OpenConnectionRequest req = new OpenConnectionRequest
            {
                ConnectionId = connectionId,
                Info = info
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "OpenConnectionRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "OpenConnectionRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    OpenConnectionResponse res = OpenConnectionResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }