private TMessageType ReadMessage(Message message, IServiceProvider serviceProvider) { TMessageType payload; var bodyObject = JObject.Parse(Encoding.UTF8.GetString(message.Body)); var rawPayload = bodyObject["Payload"]; if (rawPayload.Type == JTokenType.String) { payload = _serializer.DeserializeMessage(rawPayload.ToString()); } else if (rawPayload.Type == JTokenType.Object) { payload = _serializer.DeserializeMessage((JObject)rawPayload); } else { throw new InternalErrorException($"Unexpected payload: {rawPayload.ToString()}"); } if (payload == null) { throw new InternalErrorException($"Unknown SB payload"); } return(payload); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var ctx = await _listener.GetContextAsync(); try { using (var scope = _serviceScopeFactory.CreateScope()) { var serviceProvider = scope.ServiceProvider; string json = await new StreamReader(ctx.Request.InputStream).ReadToEndAsync(); var message = _serializer.DeserializeMessage(json) ?? throw new InternalErrorException($"Failed to parse message"); await ConsumeMessageAsync(message, serviceProvider); ctx.Response.StatusCode = 200; byte[] bytes = System.Text.Encoding.UTF8.GetBytes("ok"); ctx.Response.OutputStream.Write(bytes, 0, bytes.Length); } } catch (Exception ex) { var error = $"Error occurred consuming {ex.Message}"; ctx.Response.StatusCode = 500; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(error); ctx.Response.OutputStream.Write(bytes, 0, bytes.Length); } ctx.Response.OutputStream.Close(); } }
private void ProcessMessage(ReceivedMessage receivedMessage) { try { var senderHostId = HostMapping.GetHostIdForSocket(receivedMessage.SenderSocket); int receipentHostId; BaseMessage deserializedMessage; logger.Debug("[CS] Received message from host with id = {senderHostId}", senderHostId); if (!HostMapping.IsHostGameMaster(senderHostId)) { // TODO: Decide what should be done if GameMaster has not connected yet (NoGameMaster) receipentHostId = HostMapping.GetGameMasterHostId(); deserializedMessage = MessageSerializer.DeserializeMessage(receivedMessage.SerializedMessage); deserializedMessage.SetAgentId(senderHostId); } else { deserializedMessage = MessageSerializer.DeserializeMessage(receivedMessage.SerializedMessage, true); receipentHostId = deserializedMessage.AgentId; } logger.Debug("[CS] Message type = {id} (id = {indId})", deserializedMessage.MessageId, (int)deserializedMessage.MessageId); logger.Debug("[CS] Forwarding to host with id = {recipent}", receipentHostId); var receipentSocket = HostMapping.GetSocketForHostId(receipentHostId); NetworkComponent.SendMessage(receipentSocket, deserializedMessage); } catch (JsonSerializationException e) { logger.Error("[CS] {message}", e.Message); } catch (CommunicationErrorException e) { logger.Error("[CS] {message}", e.Message); // Socket has been closed or is invalid if (e.Type == CommunicationExceptionType.InvalidSocket) { if (receivedMessage.SenderSocket == null) { return; } var senderHostId = HostMapping.GetHostIdForSocket(receivedMessage.SenderSocket); // Message should be sent to GameMaster but error occured - abort if (!HostMapping.IsHostGameMaster(senderHostId)) { throw; } } } }
public void DeserializeMessage_ShouldReturnDerivedTypeMessage() { foreach (var message in messages) { var serialized = MessageSerializer.SerializeMessage(message); dynamic deserialized = MessageSerializer.DeserializeMessage(serialized); Assert.IsTrue(MessagingTestHelper.IsMessagePayloadDerived(deserialized)); } }
public void MessageSerializer_ShouldDeserializeAllTypesCorrectly() { foreach (var message in messages) { var serialized = MessageSerializer.SerializeMessage(message); var deserialized = MessageSerializer.DeserializeMessage(serialized); } Assert.Pass(); }
public void DeserializeMessage_ShouldNotThrowIfSetToThrowButAgentIdSet() { foreach (var message in messages) { var serialized = MessageSerializer.SerializeMessage(message); var deserialized = MessageSerializer.DeserializeMessage(serialized, true); } Assert.Pass(); }
public void DeserializeMessage_ShouldNotChangeValue() { foreach (var message in messages) { var serialized = MessageSerializer.SerializeMessage(message); var deserialized = MessageSerializer.DeserializeMessage(serialized); var newSerialized = MessageSerializer.SerializeMessage(deserialized); Assert.AreEqual(serialized, newSerialized); } }
public void DeserializeMessage_ShouldNotSetUnrequiredFieldsForUndefinedError() { var message = MessageFactory.GetMessage(new UndefinedError(null, null)); var serialized = MessageSerializer.SerializeMessage(message); dynamic deserialized = MessageSerializer.DeserializeMessage(serialized); var payload = deserialized.Payload as UndefinedError; Assert.IsNull(payload.Position); Assert.IsNull(payload.HoldingPiece); }
public void DeserializeMessage_ShouldThrowIfSetToThrowWithoutAgentId() { foreach (var message in messages) { var serialized = MessagingTestHelper.SerializeWithoutProperties(message, "agentID"); Assert.Throws <JsonSerializationException>(() => MessageSerializer.DeserializeMessage(serialized, true)); } Assert.Pass(); }
public void MessageSerializer_ShouldSetAgentIdToZeroIfNotProvided() { foreach (var message in messages) { var serialized = MessagingTestHelper.SerializeWithoutProperties(message, "agentID"); var deserialized = MessageSerializer.DeserializeMessage(serialized); Assert.AreEqual(0, deserialized.AgentId); } Assert.Pass(); }
public void DeserializeMessage_ShouldReturnDerivedTypeMessageAfterAddingToList() { var deserializedMessages = new List <BaseMessage>(); foreach (var message in messages) { var serialized = MessageSerializer.SerializeMessage(message); deserializedMessages.Add(MessageSerializer.DeserializeMessage(serialized)); } foreach (var deserializedMessage in deserializedMessages) { dynamic dynamicMessage = deserializedMessage; Assert.IsTrue(MessagingTestHelper.IsMessagePayloadDerived(dynamicMessage)); } }
private void Configure() { _websocket.OnMessage += (sender, e) => { var msg = MessageSerializer.DeserializeMessage(e.Data); switch (msg.Type) { case MessageType.Message: if (msg.Sender == _repo.CurrentReceiver.Login) { DispatchIt(() => _repo.Messages.Add(msg)); } else { DispatchIt(() => _repo.History[msg.Sender].Add(msg)); } break; case MessageType.Error: DispatchIt(() => _repo.Messages.Add(msg)); break; } }; }