public void DeserializesMessageCorrectly_ConnectionKey(string connectionKey) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("connectionKey")); expectedMessage.AddRange(SerializeString(connectionKey)); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal(connectionKey, target.ConnectionKey); }
public void DeserializesMessageCorrectly_Id(string id) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("id")); expectedMessage.AddRange(SerializeString(id)); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal(id, target.Id); }
private void HandleProtocolMessageResponse(ProtocolMessage message) { switch (message) { case TranslationResponse translationResponse: HandleTranslationResponse(translationResponse); break; case TranslationError translationResponse: HandleTranslationError(translationResponse); break; default: break; } }
public void DeserializesMessageCorrectly_Action(ProtocolMessage.MessageAction action) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("action")); expectedMessage.Add((byte)action); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal(action, target.Action); }
public void DeserializesMessageCorrectly_ConnectionId(string connectionId) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("connectionId")); expectedMessage.AddRange(SerializeString(connectionId)); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert target.Should().NotBeNull(); Assert.Equal(connectionId, target.ConnectionId); }
public void DeserializesMessageCorrectly_ConnectionSerial(long connectionSerial) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("connectionSerial")); expectedMessage.Add(BitConverter.GetBytes(connectionSerial).First()); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert target.Should().NotBeNull(); Assert.Equal <long>(connectionSerial, target.ConnectionSerial.Value); }
public Result EncodeProtocolMessage(ProtocolMessage protocolMessage, ChannelOptions channelOptions) { var options = channelOptions ?? new ChannelOptions(); var result = Result.Ok(); foreach (var message in protocolMessage.Messages) { result = Result.Combine(result, EncodePayload(message, options)); } foreach (var presence in protocolMessage.Presence) { result = Result.Combine(result, EncodePayload(presence, options)); } return(result); }
static public void getBalance() { ProtocolMessage.setWaitFor(ProtocolMessageCode.balance); // Return the balance for the matching address using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.Write(Node.walletStorage.getPrimaryAddress().Length); writer.Write(Node.walletStorage.getPrimaryAddress()); NetworkClientManager.broadcastData(new char[] { 'M' }, ProtocolMessageCode.getBalance, mw.ToArray(), null); } } ProtocolMessage.wait(30); }
public void SerializesMessageCorrectly_MsgSerial(long msgSerial) { // Arrange ProtocolMessage message = new ProtocolMessage() { MsgSerial = msgSerial }; StringBuilder expectedMessage = new StringBuilder(); expectedMessage.Append("{\"action\":0") .AppendFormat(",\"msgSerial\":{0}", msgSerial) .Append("}"); // Act Serialize(message).Should().Be(expectedMessage.ToString()); }
public void DeserializesMessageCorrectly_MsgSerial(long serial) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("msgSerial")); expectedMessage.Add(BitConverter.GetBytes(serial).First()); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal <long>(serial, target.MsgSerial); }
private void startWalletStateSync() { HashSet <string> all_neighbors = new HashSet <string>(NetworkClientManager.getConnectedClients(true).Concat(NetworkServer.getConnectedClients(true))); if (all_neighbors.Count < 1) { Logging.info(String.Format("Wallet state synchronization from storage.")); return; } Random r = new Random(); syncNeighbor = all_neighbors.ElementAt(r.Next(all_neighbors.Count)); Logging.info(String.Format("Starting wallet state synchronization from {0}", syncNeighbor)); ProtocolMessage.syncWalletStateNeighbor(syncNeighbor); }
public override async Task <bool> OnMessageReceived(ProtocolMessage message, RealtimeState state) { switch (message.Action) { case ProtocolMessage.MessageAction.Auth: Context.ExecuteCommand(RetryAuthCommand.Create(false).TriggeredBy("ConnectedState.OnMessageReceived()")); return(true); case ProtocolMessage.MessageAction.Connected: Context.ExecuteCommand(SetConnectedStateCommand.Create(message, isUpdate: true).TriggeredBy("ConnectedState.OnMessageReceived()")); return(true); case ProtocolMessage.MessageAction.Close: Context.ExecuteCommand(SetClosedStateCommand.Create(message.Error).TriggeredBy("ConnectedState.OnMessageReceived()")); return(true); case ProtocolMessage.MessageAction.Disconnected: if (message.Error?.IsTokenError ?? false) { if (Context.ShouldWeRenewToken(message.Error, state)) { Context.ExecuteCommand(RetryAuthCommand.Create(message.Error, true).TriggeredBy("ConnectedState.OnMessageReceived()")); } else { Context.ExecuteCommand(SetFailedStateCommand.Create(message.Error).TriggeredBy("ConnectedState.OnMessageReceived()")); } return(true); } Context.ExecuteCommand(SetDisconnectedStateCommand.Create(message.Error).TriggeredBy("ConnectedState.OnMessageReceived()")); return(true); case ProtocolMessage.MessageAction.Error: // an error message may signify an error state in the connection or in a channel // Only handle connection errors here. if (message.Channel.IsEmpty()) { Context.ExecuteCommand(SetFailedStateCommand.Create(message.Error).TriggeredBy("ConnectedState.OnMessageReceived()")); } return(true); } return(false); }
public override async Task <bool> OnMessageReceived(ProtocolMessage message) { switch (message.Action) { case ProtocolMessage.MessageAction.Auth: TaskUtils.RunInBackground(Context.RetryAuthentication(updateState: false), e => Logger.Warning(e.Message)); return(true); case ProtocolMessage.MessageAction.Connected: await Context.SetState(new ConnectionConnectedState(Context, new ConnectionInfo(message), message.Error, Logger) { IsUpdate = true }); return(true); case ProtocolMessage.MessageAction.Close: await Context.SetState(new ConnectionClosedState(Context, message.Error, Logger)); return(true); case ProtocolMessage.MessageAction.Disconnected: if (await Context.CanUseFallBackUrl(message.Error)) { Context.Connection.Key = null; await Context.SetState(new ConnectionDisconnectedState(Context, message.Error, Logger) { RetryInstantly = true }); } if (await Context.RetryBecauseOfTokenError(message.Error)) { return(true); } await Context.SetState(new ConnectionDisconnectedState(Context, message.Error, Logger)); return(true); case ProtocolMessage.MessageAction.Error: // an error message may signify an error state in the connection or in a channel // Only handle connection errors here. if (message.Channel.IsEmpty()) { await Context.SetState(new ConnectionFailedState(Context, message.Error, Logger)); } return(true); } return(false); }
private void SendBroadcastMessages(ProtocolMessage message, BroadcastMessage broadcastMessage) { try { var innerMessage = message.FromProtocolMessage <ProtocolMessage>(); var isOwnerOfBroadcast = innerMessage.PeerId.Equals(_peerId); if (isOwnerOfBroadcast) { innerMessage = innerMessage.Sign(_signer, _signingContext); message.Value = innerMessage.ToByteString(); } // The fan out is how many peers to broadcast to var fanOut = isOwnerOfBroadcast ? BroadcastOwnerMaximumGossipPeersPerRound : (int)Math.Max(GetMaxGossipCycles(broadcastMessage), MaxGossipPeersPerRound); var peersToGossip = GetRandomPeers(fanOut); var correlationId = innerMessage.CorrelationId.ToCorrelationId(); //CLEAN UP foreach (var peerIdentifier in peersToGossip) { _logger.Verbose("Broadcasting message {message}", message); var protocolMessage = message.Clone(); protocolMessage.PeerId = _peerId; _peerClient.SendMessage(new MessageDto( protocolMessage, peerIdentifier) ); } var updateCount = (uint)peersToGossip.Count; if (updateCount <= 0) { return; } broadcastMessage.BroadcastCount += updateCount; UpdatePendingRequest(correlationId, broadcastMessage); } catch (Exception e) { _logger.Error(e, nameof(SendBroadcastMessages)); } }
public async Task WhenSendingMessage_AckCallbackCalled_ForMultipleMessages() { // Arrange var client = await GetConnectedClient(); var callbacks = new List <ValueTuple <bool, ErrorInfo> >(); var message1 = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test"); var message2 = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test"); var message3 = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test"); var awaiter = new TaskCompletionAwaiter(); Action <bool, ErrorInfo> GetCallback(int forCount) => (ack, err) => { if (callbacks.Count == forCount) { callbacks.Add((ack, err)); } if (callbacks.Count == 3) { awaiter.SetCompleted(); } }; var ackMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Ack) { MsgSerial = 0, Count = 3 }; // Act client.Workflow.QueueAck(message1, GetCallback(0)); client.Workflow.QueueAck(message2, GetCallback(1)); client.Workflow.QueueAck(message3, GetCallback(2)); client.ExecuteCommand(ProcessMessageCommand.Create(ackMessage)); await client.ProcessCommands(); await awaiter.Task; // Assert callbacks.Count.Should().Be(3); Assert.True(callbacks.TrueForAll(c => c.Item1)); // Ack Assert.True(callbacks.TrueForAll(c => c.Item2 == null)); // No error }
private void PrintMessage(ProtocolMessage message) { switch (message) { case ChangeMessage change: Console.WriteLine($"Change :: {change.File}"); break; case RenameMessage rename: Console.WriteLine($"Rename :: {rename.File} -> {rename.NewName}"); break; case DeleteMessage delete: Console.WriteLine($"Delete :: {delete.File}"); break; } }
private ProtocolMessage SetupTestProtocolmessage(string connectionId = null, DateTimeOffset?timestamp = null, Message[] messages = null) { var protocolMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "test") { ConnectionId = connectionId, Timestamp = timestamp, Id = "protocolMessageId", Messages = messages ?? new[] { new Message("message1", "data"), new Message("message2", "data"), new Message("message3", "data"), } }; return(protocolMessage); }
private void OnWebSocketMessageReceived(object sender, WebSocketMessage e) { using (EneterTrace.Entering()) { ProtocolMessage aProtocolMessage = myProtocolFormatter.DecodeMessage((Stream)e.InputStream); MessageContext aMessageContext = new MessageContext(aProtocolMessage, myIpAddress); try { myResponseMessageHandler(aMessageContext); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } }
public void WhenSendingNotAPresenceOrDataMessage_MsgSerialNotIncremented(ProtocolMessage.MessageAction messageAction) { // Arrange var targetMessage1 = new ProtocolMessage(messageAction, "Test"); var targetMessage2 = new ProtocolMessage(messageAction, "Test"); var targetMessage3 = new ProtocolMessage(messageAction, "Test"); // Act _ackProcessor.QueueIfNecessary(targetMessage1, null); _ackProcessor.QueueIfNecessary(targetMessage2, null); _ackProcessor.QueueIfNecessary(targetMessage3, null); // Assert Assert.Equal(0, targetMessage1.MsgSerial); Assert.Equal(0, targetMessage2.MsgSerial); Assert.Equal(0, targetMessage3.MsgSerial); }
public void Init() { _channel = new EmbeddedChannel( new DatagramPacketEncoder <IMessage>(new ProtobufEncoder()) ); var senderPid = PeerIdHelper.GetPeerId("sender", IPAddress.Loopback, 10000 ); _recipientPid = PeerIdHelper.GetPeerId("sender", IPAddress.Loopback, 20000 ); _protocolMessageSigned = new PingRequest().ToSignedProtocolMessage(senderPid, (byte[])default);
private static void SetMessageIdConnectionIdAndTimestamp(ProtocolMessage protocolMessage, IMessage message, int i) { if (message.Id.IsEmpty()) { message.Id = $"{protocolMessage.Id}:{i}"; } if (message.ConnectionId.IsEmpty()) { message.ConnectionId = protocolMessage.ConnectionId; } if (message.Timestamp.HasValue == false) { message.Timestamp = protocolMessage.Timestamp; } }
public Task <bool> OnMessageReceived(ProtocolMessage message, RealtimeState state) { var canHandle = CanHandleMessage(message); if (canHandle && message.Id.IsNotEmpty()) { var pingRequest = state.PingRequests.FirstOrDefault(x => x.Id.EqualsTo(message.Id)); if (pingRequest != null) { state.PingRequests.Remove(pingRequest); TryCallback(pingRequest.Callback, GetElapsedTime(pingRequest), null); } } return(Task.FromResult(canHandle)); }
public void Send(ProtocolMessage message, Action <bool, ErrorInfo> callback = null, ChannelOptions channelOptions = null) { if (Logger.IsDebug) { Logger.Debug($"Current state: {Connection.State}. Sending message: {message}"); } var result = VerifyMessageHasCompatibleClientId(message); if (result.IsFailure) { callback?.Invoke(false, result.Error); return; } //Encode message/presence payloads Handler.EncodeProtocolMessage(message, channelOptions); if (State.CanSend) { SendMessage(message, callback); return; } if (State.CanQueue) { if (Options.QueueMessages) { lock (_pendingQueueLock) { if (Logger.IsDebug) { Logger.Debug($"Queuing message with action: {message.Action}. Connection State: {ConnectionState}"); } PendingMessages.Enqueue(new MessageAndCallback(message, callback)); } } else { throw new AblyException($"Current state is [{State.State}] which supports queuing but Options.QueueMessages is set to False."); } return; } throw new AblyException($"The current state [{State.State}] does not allow messages to be sent."); }
public async Task OnTransportMessageReceived(ProtocolMessage message) { if (_inTransitionToState != null) { if (Logger.IsDebug) { Logger.Debug($"InState transition to '{_inTransitionToState}'. Queuing tranport message until state updates"); } lock (_transportQueueLock) _queuedTransportMessages.Add(message); } else { await ProcessTransportMessage(message); } }
public void DeserializesMessageCorrectly_Flags(int flags) { // Arrange List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("flags")); expectedMessage.Add((byte)flags); // Act ProtocolMessage target = MsgPackHelper.Deserialise <ProtocolMessage>(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal <byte>((byte)flags, (byte)target.Flags); }
/// <summary> /// Takes a message and turns it into a byte array /// Can be seen as serialization /// </summary> /// <param name="message">The message to be serialized</param> /// <returns>The byte array</returns> public static byte[] EncodeMessage(ProtocolMessage message) { List <byte> data = new List <byte> { message.ControllerID, message.MsgID, (byte)message.Command }; data.AddRange(message.CommandData); data.Add(Crc.Calculate(data.ToArray())); data = AddEscapeCharacters(data); data.Insert(0, Stx); data.Add(Etx); return(data.ToArray()); }
public void DeserializesMessageCorrectly_ConnectionId(string connectionId) { // Arrange MsgPackMessageSerializer serializer = new MsgPackMessageSerializer(); List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("connectionId")); expectedMessage.AddRange(SerializeString(connectionId)); // Act ProtocolMessage target = serializer.DeserializeProtocolMessage(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal <string>(connectionId, target.ConnectionId); }
public void DeserializesMessageCorrectly_Count(int count) { // Arrange MsgPackMessageSerializer serializer = new MsgPackMessageSerializer(); List <byte> expectedMessage = new List <byte>(); expectedMessage.Add(0x81); expectedMessage.AddRange(SerializeString("count")); expectedMessage.Add(BitConverter.GetBytes(count).First()); // Act ProtocolMessage target = serializer.DeserializeProtocolMessage(expectedMessage.ToArray()); // Assert Assert.NotNull(target); Assert.Equal <int>(count, target.Count); }
protected virtual void HandleReceived(ProtocolMessage message) { switch (message.ActionId) { case ActionType.InvalidAction: this.Log(LogLevel.Warning, "Invalid action received"); break; case ActionType.LogMessage: this.Log((LogLevel)(int)message.Data, "Verilated: '{0}'", asyncEventsSocket.ReceiveString()); break; case ActionType.Interrupt: HandleInterrupt(message); break; } }
WhenMessageReceivedAndFailsVcdiffDecoding_ShouldSendAttachProtocolMessageWithLastSuccessfulChannelSerial() { var(realtime, c) = await GetClientAndChannel(); RealtimeChannel channel = (RealtimeChannel)c; channel.SetChannelState(ChannelState.Attached); var successfulProtocolMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Message) { Channel = channel.Name, ChannelSerial = "testSerial", Messages = new[] { new Message { Data = "test", Encoding = string.Empty }, }, }; realtime.ExecuteCommand(ProcessMessageCommand.Create(successfulProtocolMessage)); var awaiter = new TaskCompletionAwaiter(); channel.On(ChannelEvent.Attaching, change => { awaiter.Tick(); }); realtime.ExecuteCommand(ProcessMessageCommand.Create( new ProtocolMessage(ProtocolMessage.MessageAction.Message) { Channel = channel.Name, Messages = new[] { new Message { Extras = CreateExtrasWithDelta(new DeltaExtras("1", string.Empty)) }, }, })); await awaiter.Task; await realtime.ProcessCommands(); var fakeTransport = FakeTransportFactory.LastCreatedTransport; var lastMessageSend = fakeTransport.LastMessageSend; lastMessageSend.Should().NotBeNull(); lastMessageSend.Action.Should().Be(ProtocolMessage.MessageAction.Attach); lastMessageSend.ChannelSerial.Should().Be("testSerial"); }
/// <summary> /// Test the factory. /// </summary> /// <param name="message">The message.</param> public void TestFactory(ProtocolMessage message) { ProtocolMessageFactory factory = new ProtocolMessageFactory(); ProtocolMessage message2 = factory.CreateMessage(new ProtocolMessageContainer(message)); }
/// <summary> /// Sends a message to peer. /// </summary> /// <param name="peer">The peer.</param> /// <param name="message">The message.</param> /// <param name="onCompleteHandler">On complete handler.</param> private static void SendMessage(Peer peer, ProtocolMessage message, AtomicMessageSender.OnCompleteHandler onCompleteHandler = null) { if (peer == null) { return; } AtomicMessageSender sender = new Network.AtomicMessageSender(peer); if (onCompleteHandler != null) { sender.OnComplete += onCompleteHandler; } byte[] bytesMessage = new ProtocolMessageContainer(message).SerializeAsBytes(); sender.SendBytes(bytesMessage); // TODO on error }
/// <summary> /// Initializes a new instance of the <see cref="ProtocolMessageContainer"/> class. /// Create a container from ProtocolMessage. /// </summary> /// <param name="message">The message.</param> public ProtocolMessageContainer(ProtocolMessage message) { this.Type = message.Type; this.Data = message.SerializeAsBytes(); }