Skip to content

Commit 4915ddd

Browse files
committed
perf: performance of RandomModelChangeGenerator
ReplicatedRepositoryTest.`sequential write from multiple clients` was failing because of the 60 s timeout on CI.
1 parent c475386 commit 4915ddd

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

model-api/src/commonMain/kotlin/org/modelix/model/test/RandomModelChangeGenerator.kt

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ package org.modelix.model.test
22

33
import org.modelix.model.api.INode
44
import org.modelix.model.api.addNewChild
5+
import org.modelix.model.api.async.IAsyncNode
6+
import org.modelix.model.api.async.asAsyncNode
57
import org.modelix.model.api.getAncestors
6-
import org.modelix.model.api.getDescendants
8+
import org.modelix.streams.IStream
9+
import org.modelix.streams.plus
710
import kotlin.random.Random
811

912
class RandomModelChangeGenerator(val rootNode: INode, private val rand: Random) {
@@ -91,8 +94,21 @@ class RandomModelChangeGenerator(val rootNode: INode, private val rand: Random)
9194
}
9295

9396
private fun getRandomNode(condition: (INode) -> Boolean = { true }, includeRoot: Boolean = true): INode? {
94-
val nodes = rootNode.getDescendants(includeRoot).filter(condition).toList()
95-
if (nodes.isEmpty()) return null
96-
return nodes[rand.nextInt(nodes.size)]
97+
return rootNode.asAsyncNode()
98+
.getDescendantsShuffled(rand, includeRoot)
99+
.map { it.asRegularNode() }
100+
.filter(condition)
101+
.firstOrNull()
102+
.getSynchronous()
103+
}
104+
}
105+
106+
fun IAsyncNode.getDescendantsShuffled(rand: Random, includeSelf: Boolean): IStream.Many<IAsyncNode> {
107+
return getAllChildren().toList().flatMap { children ->
108+
val children = children.shuffled(rand)
109+
val splitAt = rand.nextInt(children.size + 1)
110+
IStream.many(children.take(splitAt)).flatMap { it.getDescendantsShuffled(rand, true) } +
111+
(if (includeSelf) IStream.of(this) else IStream.empty()) +
112+
IStream.many(children.drop(splitAt)).flatMap { it.getDescendantsShuffled(rand, true) }
97113
}
98114
}

0 commit comments

Comments
 (0)