From 5803b176881b2f06b3b3c0d80f7267a91ec0cb24 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 15 Jun 2026 22:49:04 +0100 Subject: [PATCH] Add Kotlin schema catalog ergonomics --- packages/cultmesh-kotlin/README.md | 28 +++ .../kotlin/org/gamecult/cultmesh/CultMesh.kt | 196 ++++++++++++++++++ 2 files changed, 224 insertions(+) diff --git a/packages/cultmesh-kotlin/README.md b/packages/cultmesh-kotlin/README.md index 53119388..42cd90b8 100644 --- a/packages/cultmesh-kotlin/README.md +++ b/packages/cultmesh-kotlin/README.md @@ -58,6 +58,34 @@ val note = target.require(notes, "note:1") raw bytes re-enter the typed cache through the same document definitions that local Kotlin callers use. +Schema catalogs are also first-class, so Kotlin peers can publish and consume +descriptor responses instead of hand-assembling maps: + +```kotlin +val catalog = CultNetSchemaCatalog() +catalog.upsert( + defineCultNetSchemaDescriptor( + schemaId = "kotlin.note.v1", + kind = "document_payload", + documentType = "kotlin.note", + title = "Kotlin Note", + schemaJson = """{"type":"object","properties":{"body":{"type":"string"}}}""", + ), +) + +val response = catalog.createResponse( + cultNetSchemaCatalogRequest( + messageId = "schema-catalog", + includeSchemaJson = true, + kinds = listOf("document_payload"), + ), +) +``` + +`CultNetSchemaCatalog.applyResponse(...)` imports +`cultnet.schema_catalog_response.v0` descriptors from other runtimes and keeps +their content hashes, wire contracts, schema ids, and optional schema JSON. + ## RUDP Happy Path Kotlin exposes factory helpers around the shared RUDP transport so callers can diff --git a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt index 22bf97d1..4e927c2e 100644 --- a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt +++ b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt @@ -17,6 +17,7 @@ import java.net.URI import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.security.SecureRandom +import java.security.MessageDigest import java.time.Instant import java.util.ArrayDeque import java.util.Base64 @@ -365,6 +366,118 @@ data class CultNetRawDocumentRecord( } } +data class CultNetSchemaDescriptor( + val schemaId: String, + val kind: String, + val schemaVersion: String? = null, + val documentType: String? = null, + val title: String? = null, + val wireContracts: List = listOf("cultnet.schema.v0"), + val contentHash: String, + val schemaJson: String? = null, +) { + fun toWireMap(includeSchemaJson: Boolean = schemaJson != null): Map { + val wire = linkedMapOf( + "schemaId" to schemaId, + "kind" to kind, + "wireContracts" to wireContracts, + "contentHash" to contentHash, + ) + if (!schemaVersion.isNullOrBlank()) wire["schemaVersion"] = schemaVersion + if (!documentType.isNullOrBlank()) wire["documentType"] = documentType + if (!title.isNullOrBlank()) wire["title"] = title + if (includeSchemaJson && schemaJson != null) wire["schemaJson"] = schemaJson + return wire + } +} + +class CultNetSchemaCatalog { + private val descriptorsBySchemaId = linkedMapOf() + private val subscribers = mutableListOf<(CultNetSchemaDescriptor) -> Unit>() + + val schemas: List + get() = descriptorsBySchemaId.toSortedMap().values.toList() + + fun watch(callback: (CultNetSchemaDescriptor) -> Unit): () -> Unit { + subscribers.add(callback) + return { subscribers.remove(callback) } + } + + fun upsert(descriptor: CultNetSchemaDescriptor): CultNetSchemaDescriptor { + requireNonBlank(descriptor.schemaId, "schema.schemaId") + requireNonBlank(descriptor.kind, "schema.kind") + if (descriptor.wireContracts.isEmpty()) throw IOException("schema.wireContracts must not be empty") + descriptorsBySchemaId[descriptor.schemaId] = descriptor + subscribers.toList().forEach { it(descriptor) } + return descriptor + } + + fun get(schemaId: String): CultNetSchemaDescriptor? { + requireNonBlank(schemaId, "schemaId") + return descriptorsBySchemaId[schemaId] + } + + fun list( + schemaIds: List = emptyList(), + kinds: List = emptyList(), + includeSchemaJson: Boolean = false, + ): List { + val requestedIds = schemaIds.toSet() + val requestedKinds = kinds.toSet() + return schemas.filter { descriptor -> + (requestedIds.isEmpty() || descriptor.schemaId in requestedIds) && + (requestedKinds.isEmpty() || descriptor.kind in requestedKinds) + }.map { descriptor -> + if (includeSchemaJson) descriptor else descriptor.copy(schemaJson = null) + } + } + + fun createResponse(request: CultNetMessage): CultNetMessage { + require(request.schemaVersion == "cultnet.schema_catalog_request.v0") { + "Expected cultnet.schema_catalog_request.v0, received ${request.schemaVersion}" + } + val includeSchemaJson = request.body["includeSchemaJson"] as? Boolean ?: false + return cultNetSchemaCatalogResponse( + messageId = request.body["messageId"] as? String ?: "", + schemas = list( + schemaIds = stringList(request.body["schemaIds"]), + kinds = stringList(request.body["kinds"]), + includeSchemaJson = includeSchemaJson, + ), + includeSchemaJson = includeSchemaJson, + ) + } + + fun applyResponse(response: CultNetMessage): List { + require(response.schemaVersion == "cultnet.schema_catalog_response.v0") { + "Expected cultnet.schema_catalog_response.v0, received ${response.schemaVersion}" + } + val applied = mapList(response.body["schemas"]).map { schemaDescriptorFromWire(it) } + applied.forEach { upsert(it) } + return applied + } +} + +fun defineCultNetSchemaDescriptor( + schemaId: String, + kind: String, + schemaVersion: String? = null, + documentType: String? = null, + title: String? = null, + wireContracts: List = listOf("cultnet.schema.v0"), + schemaJson: String? = null, + contentHash: String? = null, +): CultNetSchemaDescriptor = CultNetSchemaDescriptor( + schemaId = schemaId, + kind = kind, + schemaVersion = schemaVersion, + documentType = documentType, + title = title, + wireContracts = wireContracts, + contentHash = contentHash ?: sha256Hex(schemaJson ?: schemaId), + schemaJson = schemaJson, +) + data class CultMeshVerseCompatibility( val transportVersion: String, val rulesHash: String, @@ -585,6 +698,18 @@ fun cultNetSchemaCatalogRequest( ), ) +fun cultNetSchemaCatalogResponse( + messageId: String, + schemas: List, + includeSchemaJson: Boolean = true, +): CultNetMessage = CultNetMessage( + "cultnet.schema_catalog_response.v0", + linkedMapOf( + "messageId" to messageId, + "schemas" to schemas.map { it.toWireMap(includeSchemaJson) }, + ), +) + fun cultNetDocumentPutRaw( messageId: String, document: CultNetRawDocumentRecord, @@ -824,6 +949,17 @@ fun rawDocumentRecordFromWire(wire: Map): CultNetRawDocumentRecord tags = stringList(wire["tags"]), ) +fun schemaDescriptorFromWire(wire: Map): CultNetSchemaDescriptor = CultNetSchemaDescriptor( + schemaId = requireWireString(wire, "schemaId"), + kind = requireWireString(wire, "kind"), + schemaVersion = wire["schemaVersion"] as? String, + documentType = wire["documentType"] as? String, + title = wire["title"] as? String, + wireContracts = stringList(wire["wireContracts"]), + contentHash = requireWireString(wire, "contentHash"), + schemaJson = wire["schemaJson"] as? String, +) + private fun requireNonBlank(value: String, fieldName: String) { if (value.isBlank()) throw IOException("$fieldName must not be blank") } @@ -859,6 +995,11 @@ private fun mapValue(value: Any?): Map { return map } +private fun sha256Hex(value: String): String { + val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray(StandardCharsets.UTF_8)) + return digest.joinToString("") { "%02x".format(it.toInt() and 0xff) } +} + fun CultNetTransportProfile.toWireMap(): Map = linkedMapOf( "schemaVersion" to schemaVersion, "runtimeId" to runtimeId, @@ -1551,6 +1692,7 @@ fun main(args: Array) { cultCacheErgonomicsCoverTypedDocumentsAndGlobals() cultCacheRawSnapshotsRoundTripThroughCultNetMessages() cultNetSchemaMessagesUseMessagePackMaps() + cultNetSchemaCatalogsRoundTripDescriptors() cultMeshCatalogsRoundTripDiscoveryMessages() rudpPacketCodecUsesDeterministicReliableOrderedFixture() rudpSessionPingsAndDetectsReceiveTimeout() @@ -1697,6 +1839,60 @@ private fun cultNetSchemaMessagesUseMessagePackMaps() { check((document["payload"] as ByteArray).contentEquals(payload)) } +private fun cultNetSchemaCatalogsRoundTripDescriptors() { + val catalog = CultNetSchemaCatalog() + var watched: CultNetSchemaDescriptor? = null + val unsubscribe = catalog.watch { watched = it } + val wireSchemaJson = """{"type":"object","properties":{"schemaVersion":{"const":"kotlin.note.v1"}}}""" + val wireDescriptor = defineCultNetSchemaDescriptor( + schemaId = "kotlin.note.v1", + kind = "wire_message", + schemaVersion = "kotlin.note.v1", + title = "Kotlin Note", + wireContracts = listOf("cultnet.schema.v0"), + schemaJson = wireSchemaJson, + ) + val documentDescriptor = defineCultNetSchemaDescriptor( + schemaId = "kotlin.document.v1", + kind = "document_payload", + documentType = "kotlin.document", + title = "Kotlin Document", + wireContracts = listOf("cultnet.schema.v0"), + schemaJson = """{"type":"object","properties":{"body":{"type":"string"}}}""", + ) + catalog.upsert(wireDescriptor) + catalog.upsert(documentDescriptor) + unsubscribe() + check(watched?.schemaId == "kotlin.document.v1") + check(catalog.get("kotlin.note.v1")?.contentHash == sha256Hex(wireSchemaJson)) + + val withoutJson = catalog.createResponse( + cultNetSchemaCatalogRequest( + messageId = "schema-without-json", + includeSchemaJson = false, + kinds = listOf("wire_message"), + ), + ) + val parsedWithoutJson = parseCultNetMessage(withoutJson.toBytes()) + val schemasWithoutJson = mapList(parsedWithoutJson.body["schemas"]) + check(schemasWithoutJson.single()["schemaId"] == "kotlin.note.v1") + check(!schemasWithoutJson.single().containsKey("schemaJson")) + + val withJson = catalog.createResponse( + cultNetSchemaCatalogRequest( + messageId = "schema-with-json", + includeSchemaJson = true, + schemaIds = listOf("kotlin.document.v1"), + ), + ) + val parsedWithJson = parseCultNetMessage(withJson.toBytes()) + val appliedCatalog = CultNetSchemaCatalog() + val applied = appliedCatalog.applyResponse(parsedWithJson) + check(applied.single().schemaId == "kotlin.document.v1") + check(applied.single().schemaJson?.contains("body") == true) + check(appliedCatalog.get("kotlin.document.v1")?.kind == "document_payload") +} + private fun cultMeshCatalogsRoundTripDiscoveryMessages() { val sourceVerse = CultMeshVerseDescriptor( verseId = "public",