Skip to content

Commit 9999be4

Browse files
mhuster23slisson
andcommitted
feat(model-client): add runWrite extension function
This function enables direct writing to a model-server branch without using ReplicatedModel. Co-authored-by: Sascha Lisson <[email protected]>
1 parent 6084aa6 commit 9999be4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

model-client/src/commonMain/kotlin/org/modelix/model/client2/ModelClientV2.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,18 @@ import kotlinx.coroutines.launch
3434
import kotlinx.serialization.json.Json
3535
import org.modelix.model.IVersion
3636
import org.modelix.model.api.IIdGenerator
37+
import org.modelix.model.api.INode
3738
import org.modelix.model.api.IdGeneratorDummy
39+
import org.modelix.model.api.TreePointer
40+
import org.modelix.model.api.getRootNode
3841
import org.modelix.model.client.IdGenerator
3942
import org.modelix.model.lazy.BranchReference
43+
import org.modelix.model.lazy.CLTree
4044
import org.modelix.model.lazy.CLVersion
4145
import org.modelix.model.lazy.ObjectStoreCache
4246
import org.modelix.model.lazy.RepositoryId
4347
import org.modelix.model.lazy.computeDelta
48+
import org.modelix.model.operations.OTBranch
4449
import org.modelix.model.persistent.HashUtil
4550
import org.modelix.model.persistent.MapBasedStore
4651
import org.modelix.model.server.api.v2.VersionDelta
@@ -307,3 +312,25 @@ private fun URLBuilder.appendPathSegmentsEncodingSlash(vararg components: String
307312
}
308313

309314
fun VersionDelta.getAllObjects(): Map<String, String> = objectsMap + objects.associateBy { HashUtil.sha256(it) }
315+
316+
/**
317+
* Performs a write transaction on the root node of the given branch.
318+
*/
319+
suspend fun <T> IModelClientV2.runWrite(branchRef: BranchReference, body: (INode) -> T): T {
320+
val client = this
321+
val baseVersion = client.pull(branchRef, null)
322+
val branch = OTBranch(TreePointer(baseVersion.getTree(), client.getIdGenerator()), client.getIdGenerator(), (client as ModelClientV2).store)
323+
val result = branch.computeWrite {
324+
body(branch.getRootNode())
325+
}
326+
val (ops, newTree) = branch.getPendingChanges()
327+
val newVersion = CLVersion.createRegularVersion(
328+
id = client.getIdGenerator().generate(),
329+
author = client.getUserId(),
330+
tree = newTree as CLTree,
331+
baseVersion = baseVersion as CLVersion?,
332+
operations = ops.map { it.getOriginalOp() }.toTypedArray(),
333+
)
334+
client.push(branchRef, newVersion, baseVersion)
335+
return result
336+
}

0 commit comments

Comments
 (0)