fix: message cache removal crash (#2682)

This commit is contained in:
Simon-Pierre Vivier 2024-05-09 10:38:55 -04:00 committed by GitHub
parent b643f4c4ae
commit fa26d05f8e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 42 additions and 4 deletions

View File

@ -1,8 +1,10 @@
{.used.}
import std/sets, stew/[results, byteutils], testutils/unittests
import std/[sets, random], stew/[results, byteutils], testutils/unittests
import ../../waku/waku_core, ../../waku/waku_api/message_cache, ./testlib/wakucore
randomize()
suite "MessageCache":
setup:
## Given
@ -209,3 +211,39 @@ suite "MessageCache":
check:
cache.messagesCount() == 2
test "fuzzing":
let testContentTopic1 = "contentTopic1"
let testContentTopic2 = "contentTopic2"
let cache = MessageCache.init(50)
cache.contentSubscribe(testContentTopic1)
cache.contentSubscribe(testContentTopic2)
for _ in 0 .. 10000:
let numb = rand(1.0)
if numb > 0.4:
let topic = if rand(1.0) > 0.5: testContentTopic1 else: testContentTopic2
let testMessage = fakeWakuMessage(contentTopic = topic)
cache.addMessage(DefaultPubsubTopic, testMessage)
elif numb > 0.1:
let topic = if rand(1.0) > 0.5: testContentTopic1 else: testContentTopic2
let clear = rand(1.0) > 0.5
discard cache.getAutoMessages(topic, clear)
elif numb > 0.05:
if rand(1.0) > 0.5:
cache.pubsubUnsubscribe(DefaultPubsubTopic)
else:
cache.pubsubSubscribe(DefaultPubsubTopic)
else:
let topic = if rand(1.0) > 0.5: testContentTopic1 else: testContentTopic2
if rand(1.0) > 0.5:
cache.contentUnsubscribe(topic)
else:
cache.contentSubscribe(topic)

View File

@ -134,7 +134,7 @@ proc pubsubUnsubscribe*(self: MessageCache, pubsubTopic: PubsubTopic) =
dec(j)
# check if messages on this pubsub topic are indexed by any content topic, if not remove them.
for mId in msgIndices:
for mId in msgIndices.sorted(SortOrder.Descending):
if not self.contentIndex.anyIt(it.msgIdx == mId):
self.removeMessage(mId)
@ -167,7 +167,7 @@ proc contentUnsubscribe*(self: MessageCache, contentTopic: ContentTopic) =
dec(j)
# check if messages on this content topic are indexed by any pubsub topic, if not remove them.
for mId in msgIndices:
for mId in msgIndices.sorted(SortOrder.Descending):
if not self.pubsubIndex.anyIt(it.msgIdx == mId):
self.removeMessage(mId)
@ -275,7 +275,7 @@ proc getAutoMessages*(
let messages = msgIndices.mapIt(self.messages[it])
if clear:
for idx in msgIndices.reversed:
for idx in msgIndices.sorted(SortOrder.Descending):
self.removeMessage(idx)
return ok(messages)