From 5e4d58a8070139f4b26289d0ff791325bc78f684 Mon Sep 17 00:00:00 2001 From: Andrea Maria Piana Date: Thu, 30 Jul 2020 21:14:47 +0200 Subject: [PATCH] Fix lastMessage when receive an emoji out of order --- protocol/chat.go | 10 +++++++--- protocol/chat_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/protocol/chat.go b/protocol/chat.go index dcd6124b9..94ee89395 100644 --- a/protocol/chat.go +++ b/protocol/chat.go @@ -219,15 +219,19 @@ func (c *Chat) NextClockAndTimestamp(timesource TimeSource) (uint64, uint64) { func (c *Chat) UpdateFromMessage(message *Message, timesource TimeSource) error { c.Timestamp = int64(timesource.GetCurrentTime()) - if c.LastClockValue <= message.Clock { + higherClock := c.LastClockValue <= message.Clock + // If the clock is higher, or last message is nil, we set the message + if higherClock || c.LastMessage == nil { jsonMessage, err := json.Marshal(message) if err != nil { return err } - - c.LastClockValue = message.Clock c.LastMessage = jsonMessage } + // If the clock is higher we set the clock + if higherClock { + c.LastClockValue = message.Clock + } return nil } diff --git a/protocol/chat_test.go b/protocol/chat_test.go index 45b1ca382..132873d56 100644 --- a/protocol/chat_test.go +++ b/protocol/chat_test.go @@ -70,3 +70,34 @@ func (s *ChatTestSuite) TestValidateChat() { } } + +func (s *ChatTestSuite) TestUpdateFromMessage() { + + // Base case, clock is higher + message := &Message{} + chat := &Chat{} + + message.Clock = 1 + s.Require().NoError(chat.UpdateFromMessage(message, &testTimeSource{})) + s.Require().NotNil(chat.LastMessage) + s.Require().Equal(uint64(1), chat.LastClockValue) + + // Clock is lower and lastMessage is not nil + message = &Message{} + lastMessage := []byte("test") + chat = &Chat{LastClockValue: 2, LastMessage: lastMessage} + + message.Clock = 1 + s.Require().NoError(chat.UpdateFromMessage(message, &testTimeSource{})) + s.Require().Equal(lastMessage, chat.LastMessage) + s.Require().Equal(uint64(2), chat.LastClockValue) + + // Clock is lower and lastMessage is nil + message = &Message{} + chat = &Chat{LastClockValue: 2} + + message.Clock = 1 + s.Require().NoError(chat.UpdateFromMessage(message, &testTimeSource{})) + s.Require().NotNil(chat.LastMessage) + s.Require().Equal(uint64(2), chat.LastClockValue) +}