From f59a124ff7a9d2ac0a192076f0235aa9254b2e14 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Tue, 3 Nov 2026 12:38:52 -0700 Subject: [PATCH 1/9] LazyInstanceTable added to library (finally) --- .../typed/LazyInstanceTable.kt | 229 ++++++++++++++++++ .../lightningserver/typed/ModelInfo.kt | 70 ++---- .../lightningserver/typed/Table.ext.kt | 4 +- 3 files changed, 253 insertions(+), 50 deletions(-) create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/LazyInstanceTable.kt diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/LazyInstanceTable.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/LazyInstanceTable.kt new file mode 100644 index 000000000..da2f46d47 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/LazyInstanceTable.kt @@ -0,0 +1,229 @@ +package com.lightningkite.lightningserver.typed + +import com.lightningkite.lightningserver.definition.Runtime +import com.lightningkite.lightningserver.definition.RuntimeDeferred +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.runtime.Engine +import com.lightningkite.services.database.* +import com.lightningkite.services.database.optics.* +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +private class LazyInstanceTable, ID : Comparable>( + override val wraps: Table, + val includeMassUpdates: Boolean = true, + private val interceptor: suspend (instance: RuntimeDeferred, mod: Modification) -> Modification, +) : Table by wraps { + // used only for non-local control flow + @Suppress("ObjectInheritsException") + private object InstanceNotFound : Throwable() { + private fun readResolve(): Any = InstanceNotFound + override fun fillInStackTrace(): Throwable = this + } + + private class LazyInstance(private val wraps: RuntimeDeferred) : RuntimeDeferred { + @Volatile + private var cached: T? = null + private val mutex = Mutex() + + context(server: Engine) + override suspend fun await(): T = + cached ?: mutex.withLock { + cached?.let { return@withLock it } + val n = wraps.await() + cached = n + n + } + + fun cached(): T? = cached + } + + private val wrapsPermissions = generateSequence(wraps) { it.wraps }.any { it is ModelPermissionsTable } + private val idField = serializer._id() + + private fun Condition.onInstance(instance: Model): Condition { + val idEqual = Condition.OnField(idField, Condition.Equal(instance._id)) + return if (wrapsPermissions) Condition.And(this, idEqual) // maintain full condition for permissions + else idEqual + } + + private fun Condition.onInstance(instance: LazyInstance): Condition = + instance.cached()?.let { // instance retrieved, make sure we only modify the same instance retrieved + onInstance(it) + } ?: this + + + override suspend fun insert(models: Iterable): List = + wraps.insert(models.map { // no need to catch + interceptor(Runtime.Constant(it), Modification.Assign(it))(it) + }) + + override suspend fun replaceOne( + condition: Condition, + model: Model, + orderBy: List>, + ): EntryChange = try { + val instance = LazyInstance { + wraps.findOne(condition, orderBy) ?: throw InstanceNotFound + } + val mod = interceptor(instance, Modification.Assign(model)) + + wraps.replaceOne(condition.onInstance(instance), mod(model), orderBy) + } catch (_: InstanceNotFound) { + EntryChange(null, null) + } + + override suspend fun replaceOneIgnoringResult( + condition: Condition, + model: Model, + orderBy: List>, + ): Boolean = try { + val instance = LazyInstance { + wraps.findOne(condition, orderBy) ?: throw InstanceNotFound + } + val mod = interceptor(instance, Modification.Assign(model)) + + wraps.replaceOneIgnoringResult(condition.onInstance(instance), mod(model), orderBy) + } catch (_: InstanceNotFound) { + false + } + + override suspend fun upsertOne( + condition: Condition, + modification: Modification, + model: Model, + ): EntryChange { + var inserting = false + // I'm not throwing an InstanceNotFound here because I still want to use the intercepted mod when inserting without having to recalculate + val instance = LazyInstance { wraps.findOne(condition) ?: model.also { inserting = true } } + val mod = interceptor(instance, modification) // Does this need to check Mod.Assign(model) separately? + + return if (inserting) EntryChange(null, wraps.insertOne(mod(model))) + else wraps.upsertOne(condition.onInstance(instance), mod, mod(model)) + } + + override suspend fun upsertOneIgnoringResult( + condition: Condition, + modification: Modification, + model: Model, + ): Boolean { + var inserting = false + val instance = LazyInstance { wraps.findOne(condition) ?: model.also { inserting = true } } + val mod = interceptor(instance, modification) + + return if (inserting) { + wraps.insertOne(mod(model)) + false + } else wraps.upsertOneIgnoringResult(condition.onInstance(instance), mod, mod(model)) + } + + override suspend fun updateOne( + condition: Condition, + modification: Modification, + orderBy: List>, + ): EntryChange = try { + val instance = LazyInstance { wraps.findOne(condition, orderBy) ?: throw InstanceNotFound } + val mod = interceptor(instance, modification) + + wraps.updateOne(condition.onInstance(instance), mod, orderBy) + } catch (_: InstanceNotFound) { + EntryChange(null, null) + } + + override suspend fun updateOneIgnoringResult( + condition: Condition, + modification: Modification, + orderBy: List>, + ): Boolean = try { + val instance = LazyInstance { wraps.findOne(condition, orderBy) ?: throw InstanceNotFound } + val mod = interceptor(instance, modification) + + wraps.updateOneIgnoringResult(condition.onInstance(instance), mod, orderBy) + } catch (_: InstanceNotFound) { + false + } + + override suspend fun updateMany( + condition: Condition, + modification: Modification, + ): CollectionChanges { + if (!includeMassUpdates) return wraps.updateMany(condition, modification) + + return try { + val models = LazyInstance { wraps.find(condition).toList() } + val first = LazyInstance { models.await().firstOrNull() ?: throw InstanceNotFound } + + val updatedModForFirst = interceptor(first, modification) + + models.cached() + ?.let { instances -> // retrieved instances + if (instances.isEmpty()) return CollectionChanges() + + CollectionChanges( + buildList(instances.size) { + add( + wraps.updateOne(condition.onInstance(first), updatedModForFirst) + ) + for (model in instances.drop(1)) add( + wraps.updateOne(condition.onInstance(model), interceptor(Runtime.Constant(model), modification)) + ) + } + ) + } + ?: wraps.updateMany(condition, updatedModForFirst) + } catch (_: InstanceNotFound) { + CollectionChanges() + } + } + + override suspend fun updateManyIgnoringResult( + condition: Condition, + modification: Modification, + ): Int { + if (!includeMassUpdates) return wraps.updateManyIgnoringResult(condition, modification) + + return try { + val models = LazyInstance { wraps.find(condition).toList() } + val first = LazyInstance { models.await().firstOrNull() ?: throw InstanceNotFound } + + val updatedModForFirst = interceptor(first, modification) + + models.cached() + ?.let { cached -> // retrieved instances + if (cached.isEmpty()) return 0 + var count = 0 + + if (wraps.updateOneIgnoringResult(condition.onInstance(first), updatedModForFirst)) count++ + + count += cached.drop(1).count { model -> + wraps.updateOneIgnoringResult( + condition.onInstance(model), + interceptor(Runtime.Constant(model), modification) + ) + } + + count + } + ?: wraps.updateManyIgnoringResult(condition, updatedModForFirst) + + } catch (_: InstanceNotFound) { + 0 + } + } +} + +/** + * Similar to [interceptChangePerInstance], but the provided instance of the model is lazy and will only be fetched from the database when requested. + * This makes it much more efficient, as you get to choose when expensive fetched data is needed. + * + * Intercepts all changes sent to the database, including inserting, replacing, upserting, and updating. Deletions are not intercepted. + * + * **Warning**: Operations that fetch the lazy `instance` are not atomic, as we must retrieve the data before we can calculate the change. + * + * @param includeMassUpdates If `false` then [updateMany] and [updateManyIgnoringResult] will both be ignored by the interceptor. + */ +public fun , ID : Comparable> Table.interceptChangeWithLazyInstance( + includeMassUpdates: Boolean = true, + interceptor: suspend (instance: RuntimeDeferred, mod: Modification) -> Modification, +): Table = LazyInstanceTable(this, includeMassUpdates, interceptor) \ No newline at end of file diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/ModelInfo.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/ModelInfo.kt index 9e099cdea..4b23172fe 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/ModelInfo.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/ModelInfo.kt @@ -7,6 +7,7 @@ import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.runtime.ServerRuntime import com.lightningkite.services.database.* import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializer public interface ModelInfo?, T : HasId, ID : Comparable> { public val serializer: KSerializer @@ -24,7 +25,7 @@ public interface ModelInfo?, T : HasId, ID : Comparable) -> Unit) @@ -53,11 +54,13 @@ public interface ModelInfo?, T : HasId, ID : Comparable): Table + context(server: ServerRuntime) public suspend fun permissions(auth: AuthAccess): ModelPermissions context(server: ServerRuntime) public suspend fun defaultItem(auth: Authentication?): T = serializer.default() + context(server: ServerRuntime) public fun exampleItem(): T? = null } @@ -67,55 +70,26 @@ public inline fun ?, reified T : HasId, reified ID : auth: AuthRequirement, tableName: String, subscope: Subscope? = Subscope(tableName.lowercase()), - crossinline signals: context(ServerRuntime) (Table) -> Table = { it }, - crossinline log: context(ServerRuntime) AuthAccess?.(Table) -> Table = { it }, - crossinline systemAccess: context(ServerRuntime) (Table) -> Table = { it }, + noinline signals: context(ServerRuntime) (Table) -> Table = { it }, + noinline log: context(ServerRuntime) AuthAccess?.(Table) -> Table = { it }, + noinline systemAccess: context(ServerRuntime) (Table) -> Table = { it }, noinline postPermissionsForUser: suspend context(ServerRuntime) AuthAccess.(Table) -> Table = { it }, - crossinline permissions: suspend context(ServerRuntime) AuthAccess.() -> ModelPermissions, + noinline permissions: suspend context(ServerRuntime) AuthAccess.() -> ModelPermissions, noinline prePermissionsForUser: suspend context(ServerRuntime) AuthAccess.(Table) -> Table = { it }, -): ModelInfo = object : ModelInfo { - override val serializer: KSerializer = serializerOrContextual() - override val idSerializer: KSerializer = serializerOrContextual() - - override val auth: AuthRequirement = subscope?.let { auth.subscope(it) } ?: auth - - // registerTable defines the table, registers it, and creates its (once-per-deploy) prepare task. - override val registration: DatabaseTableRegistration = this@modelInfo.registerTable(tableName, serializer) - - @UnauditedDatabaseAccess - context(server: ServerRuntime) - override fun dangerouslyDirectTable(): Table = registration() - - context(server: ServerRuntime) - override fun baseTable(): Table = log(null, registration()) - - override val tableName: String get() = tableName - - val changeListeners = ArrayList) -> Unit>() - override fun registerChangeListener(action: suspend context(ServerRuntime) (CollectionChanges) -> Unit) { - changeListeners += action - } - - context(server: ServerRuntime) - override suspend fun permissions(auth: AuthAccess): ModelPermissions = permissions(auth) - - // Built on the undecorated table on purpose: table() and table(auth) apply `log` themselves, and - // going through baseTable() here would decorate twice and record every query in duplicate. - @OptIn(UnauditedDatabaseAccess::class) - context(server: ServerRuntime) - fun collectionWithSignals() = - signals(dangerouslyDirectTable().withServerRuntimeChangeListeners(changeListeners)) - - context(server: ServerRuntime) - override suspend fun table(auth: AuthAccess): Table = collectionWithSignals() - .let { log(auth, it) } - .let { postPermissionsForUser(auth, it) } - .withPermissions(permissions(auth)) - .let { prePermissionsForUser(auth, it) } - - context(server: ServerRuntime) - override fun table(): Table = systemAccess(log(null, collectionWithSignals())) -} +): ModelInfo = + explicitModelInfo( + auth = auth, + serializer = serializerOrContextual(), + idSerializer = serializerOrContextual(), + tableName = tableName, + subscope = subscope, + signals = signals, + log = log, + systemAccess = systemAccess, + postPermissionsForUser = postPermissionsForUser, + permissions = permissions, + prePermissionsForUser = prePermissionsForUser + ) context(builder: ServerBuilder) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt index 6fcfb6eae..904f62a60 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt @@ -39,8 +39,8 @@ public suspend fun , ID : Comparable> Table.getOrFo } -public context(server: ServerRuntime) -fun , ID : Comparable> Table.withServerRuntimeChangeListeners( +context(server: ServerRuntime) +public fun , ID : Comparable> Table.withServerRuntimeChangeListeners( changeListeners: List) -> Unit>, ): Table = object : Table by this@withServerRuntimeChangeListeners { override val wraps = this@withServerRuntimeChangeListeners From a60bf7fd494ac85289c14db0ebb336c5899eb364 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Tue, 3 Nov 2026 16:06:56 -0700 Subject: [PATCH 2/9] finally imported denormalization system from other projects --- .../lightningserver/typed/Table.ext.kt | 8 + .../typed/denormalize/Denormalization.kt | 111 ++++++++ .../denormalize/DenormalizationBuilder.ext.kt | 58 ++++ .../denormalize/DenormalizationBuilder.kt | 258 ++++++++++++++++++ .../typed/denormalize/ModelInfoWithDeno.kt | 225 +++++++++++++++ .../typed/denormalize/RefreshDenoEndpoints.kt | 107 ++++++++ .../typed/denormalize/helpers.kt | 38 +++ 7 files changed, 805 insertions(+) create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt index 904f62a60..011575cb2 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/Table.ext.kt @@ -38,6 +38,14 @@ public suspend fun , ID : Comparable> Table.getOrFo ?: throw ForbiddenException(message) } +/** + * Retrieves the [Model] with [id], or throws an [IllegalStateException] with the provided [message] if not found. + * */ +public suspend fun , ID : Comparable> Table.getOrThrow( + id: ID, + message: String = "${serializer.descriptor.serialName.substringAfterLast('.')} $id not recognized", +): Model = + get(id) ?: throw IllegalStateException(message) context(server: ServerRuntime) public fun , ID : Comparable> Table.withServerRuntimeChangeListeners( diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt new file mode 100644 index 000000000..284e2a285 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt @@ -0,0 +1,111 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.services.database.HasId +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.optics.Lens +import com.lightningkite.services.database.optics.Optic + +/** + * Internal representation of a denormalization rule. + * Contains the logic to copy data from a referenced model into the referencing model. + */ +public sealed interface Denormalization, RID : Comparable> { + public val info: ModelInfo<*, Referenced, RID> + public val listenForChanges: Boolean + + /** + * Internal data class pairing a set of field dependencies with their calculation function. + * Used to track which fields trigger denormalization updates. + * + * An empty set of dependencies means the calculation runs on create/replace/modify but does NOT + * register change listeners on the referenced model. Non-empty dependencies trigger both immediate + * denormalization and change listener registration. + */ + public data class Calculation( + val dependencies: Set>, + val calculation: T, + ) + + /** + * Denormalization rule for non-nullable (required) references. + */ + public data class RequiredRef, RID : Comparable>( + val reference: Lens, + override val info: ModelInfo<*, Referenced, RID>, + val calculations: List Modification>>, + ) : Denormalization { + context(_: ServerRuntime) + public suspend fun denormalize(old: Referenced, new: Referenced): Modification = + Modification.Chain( + calculations + .filter { calc -> + calc.dependencies.any { it.get(old) != it.get(new) } + } + .map { it.calculation(new) } + ) + + context(_: ServerRuntime) + public suspend fun denormalize(ref: Referenced): Modification = + Modification.Chain( + calculations.map { it.calculation(ref) } + ) + + override val listenForChanges: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } + } + + /** + * Denormalization rule for nullable (optional) references. + */ + public data class OptionalRef, RID : Comparable>( + val reference: Optic, + override val info: ModelInfo<*, Referenced, RID>, + val calculations: List Modification>>, + ) : Denormalization { + context(_: ServerRuntime) + public suspend fun denormalize(old: Referenced, new: Referenced?): Modification = + Modification.Chain( + calculations + .filter { calc -> + calc.dependencies.any { it.get(old) != new?.let(it::get) } + } + .map { it.calculation(new) } + ) + + context(_: ServerRuntime) + public suspend fun denormalize(ref: Referenced?): Modification = + Modification.Chain( + calculations.map { it.calculation(ref) } + ) + + override val listenForChanges: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } + } + +// data class Chained< +// M : Any, R1 : HasId, R1_ID : Comparable, +// R2 : HasId, R2_ID : Comparable +// >( +// val first: Denormalization, +// val second: Denormalization +// ) : Denormalization { +// override val info: ModelInfo<*, R2, R2_ID> get() = second.info +// override val listenForChanges: Boolean get() = first.listenForChanges || second.listenForChanges +// +// context(_: ServerRuntime) +// suspend fun denormalize(old: R2, new: R2?): Modification { +// when (second) { +// is Chained -> TODO() +// is OptionalRef<*, *, *> -> TODO() +// is RequiredRef<*, *, *> -> TODO() +// } +// } +// +// context(_: ServerRuntime) +// suspend fun denormalize(ref: Referenced?): Modification = +// Modification.Chain( +// calculations.map { it.calculation(ref) } +// ) +// } +} + diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt new file mode 100644 index 000000000..c582f53a7 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt @@ -0,0 +1,58 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.services.database.HasId +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.optics.Lens +import com.lightningkite.services.database.optics.Optic + +context(builder: DenormalizationBuilder) +public inline fun , RID : Comparable> Lens.denormalizes( + info: ModelInfo<*, Ref, RID>, + build: DenormalizationBuilder.RequiredRefBuilder.(Optic) -> Unit, +): Unit = + builder.required(this, info, build) + +@JvmName("denormalizesNullable") +context(builder: DenormalizationBuilder) +public inline fun , RID : Comparable> Optic.denormalizes( + info: ModelInfo<*, Ref, RID>, + build: DenormalizationBuilder.OptionalRefBuilder.(Optic) -> Unit, +): Unit = + builder.optional(this, info, build) + +context(builder: DenormalizationBuilder.RequiredRefBuilder) +public infix fun , RID : Comparable, T> Optic.bind(ref: Lens) { + builder.registerDenormalization(setOf(ref)) { reference -> + this.mapModification( + Modification.Assign(ref.get(reference)) + ) + } +} + +context(builder: DenormalizationBuilder.RequiredRefBuilder) +public infix fun , RID : Comparable, T> Optic.set(ref: Lens) { + builder.registerDenormalization(emptySet()) { reference -> + this.mapModification( + Modification.Assign(ref.get(reference)) + ) + } +} + +context(builder: DenormalizationBuilder.OptionalRefBuilder) +public infix fun , RID : Comparable, T> Optic.bind(ref: Optic) { + builder.registerDenormalization(setOf(ref)) { reference -> + this.mapModification( + Modification.Assign(reference?.let(ref::get)) + ) + } +} + +context(builder: DenormalizationBuilder.OptionalRefBuilder) +public infix fun , RID : Comparable, T> Optic.set(ref: Optic) { + builder.registerDenormalization(emptySet()) { reference -> + this.mapModification( + Modification.Assign(reference?.let(ref::get)) + ) + } +} diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt new file mode 100644 index 000000000..63fa897d3 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -0,0 +1,258 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.services.database.HasId +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.ModificationBuilder +import com.lightningkite.services.database.optics.IdentityLens +import com.lightningkite.services.database.optics.Lens +import com.lightningkite.services.database.optics.Optic + + +/** + * Internal builder for defining denormalization rules on a model. + * Used as the receiver in the `denormalizations` lambda of [withDenormalizations]. + */ +@DenormalizationBuilder.DenormalizationDsl +public class DenormalizationBuilder { + /** + * DSL marker to prevent scope confusion in nested denormalization builder lambdas. + */ + @DslMarker + public annotation class DenormalizationDsl + + + /** + * Builder context for defining denormalization rules for a required (non-nullable) reference. + * This is the receiver of the lambda passed to [denormalizes] for non-nullable references. + * + * Common methods: + * - [bind] - Simple field copy that watches for changes in the source field + * - [set] - Simple field copy WITHOUT watching for changes (lighter weight) + * - [watch] - Watch specific dependencies and perform calculations when they change + * - [once] - Perform calculations without watching for changes in the referenced model + */ + @DenormalizationDsl + public class RequiredRefBuilder, RID : Comparable>( + public val reference: Lens, + public val info: ModelInfo<*, Referenced, RID>, + ) { + private val list = + ArrayList Modification>>() + + /** + * Low-level method to register a dependency-based calculation. + * Use [watch], [bind], [set], or [once] instead for most use cases. + */ + public fun registerDenormalization( + dependencies: Set>, + calculation: suspend context(ServerRuntime) (Referenced) -> Modification, + ) { + list.add(Denormalization.Calculation(dependencies, calculation)) + } + + /** + * Watch specific fields on the referenced model and perform calculations when they change. + * + * Use this when you need to: + * - Perform calculations based on the referenced data + * - Watch multiple dependencies for the same calculation + * - Fetch additional data from other tables + * + * Example: + * ```kotlin + * material.collection.denormalizes(MaterialCollection.info) { collection -> + * // Only update when the submitted field changes + * watch(collection.submitted) { + * material.submittedAt assign it.submitted?.timestamp + * } + * + * // Fetch additional data when reviewCycle changes + * watch(collection.reviewCycle) { + * val cycle = ReviewCycle.info.table().getOrBadRequest(it.reviewCycle) + * material.reviewCycleEndAt assign cycle.timeframe.endDate + * } + * } + * ``` + * + * @param dependencies One or more fields to watch on the referenced model + * @param calculation Lambda to create a denormalization modification based on the referenced model + */ + public inline fun watch( + dependencies: Set>, + crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced) -> Unit, + ) { + registerDenormalization(dependencies) { + ModificationBuilder().apply { calculation(it) }.build() + } + } + + public inline fun watch( + dependency: Optic, + crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced) -> Unit + ): Unit = watch(setOf(dependency), calculation) + + /** + * Denormalize data from the referenced model without watching for changes in the referenced model. + * + * Unlike [watch], once calculations run whenever the reference is set (create, replace, modify) + * but do NOT listen for changes in the referenced model itself. This means the denormalized data + * will only update when you change which model you're referencing, not when that referenced model changes. + * + * **When it runs:** + * - On create: Yes + * - On replace: Yes + * - On modify (when reference changes): Yes + * - When referenced model changes: **No** (this is the key difference from watch) + * + * Use this when you want to: + * - Copy data from a reference without the overhead of change listeners + * - Denormalize fields that don't need to stay in sync with the source + * - Reduce database load by avoiding reactive updates + * + * **Note:** The name "once" is somewhat misleading - it actually runs on create, replace, and modify. + * The key distinction is that it doesn't watch for changes in the referenced model. + * + * Example: + * ```kotlin + * material.collection.denormalizes(MaterialCollection.info) { collection -> + * // Updates whenever material.collection reference changes, but not when + * // the MaterialCollection itself is modified + * once { + * material.collectionName assign it.name + * } + * + * // For comparison: this DOES update when the MaterialCollection.status changes + * watch(collection.status) { + * material.currentStatus assign it.status + * } + * } + * ``` + * + * @param calculation Lambda to create a denormalization modification based on the referenced model + */ + public inline fun once( + crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced) -> Unit, + ) { + registerDenormalization(emptySet()) { + ModificationBuilder().apply { calculation(it) }.build() + } + } + + public fun build(): Denormalization.RequiredRef = Denormalization.RequiredRef(reference, info, list) + } + + /** + * Builder context for defining denormalization rules for an optional (nullable) reference. + * This is the receiver of the lambda passed to [denormalizes] for nullable references. + * + * Similar to [RequiredRefBuilder], but lambdas receive `Referenced?` (nullable) instead of `Referenced`. + * + * Common methods: + * - [bind] - Simple field copy that watches for changes + * - [set] - Simple field copy WITHOUT watching for changes + * - [watch] - Watch specific dependencies with nullable reference + * - [once] - Perform calculations without watching for changes + */ + @DenormalizationDsl + public class OptionalRefBuilder, RID : Comparable>( + public val reference: Optic, + public val info: ModelInfo<*, Referenced, RID>, + ) { + private val list: ArrayList Modification>> = + ArrayList() + + /** + * Low-level method to register a dependency-based calculation. + * Use [watch], [bind], [set], or [once] instead for most use cases. + */ + public fun registerDenormalization( + dependencies: Set>, + calculation: suspend context(ServerRuntime) (Referenced?) -> Modification, + ) { + list.add(Denormalization.Calculation(dependencies, calculation)) + } + + /** + * Watch specific fields on the referenced model and perform calculations when they change. + * Same as [RequiredRefBuilder.watch] but receives `Referenced?` (nullable) instead of `Referenced`. + * + * @param dependencies One or more fields to watch on the referenced model + * @param calculation Lambda to create a denormalization modification based on the referenced model + */ + public inline fun watch( + dependencies: Set>, + crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced?) -> Unit, + ) { + registerDenormalization(dependencies) { + ModificationBuilder().apply { calculation(it) }.build() + } + } + + public inline fun watch( + dependency: Optic, + crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced?) -> Unit + ): Unit = watch(setOf(dependency), calculation) + + /** + * Denormalize data from an optional referenced model without watching for changes in the referenced model. + * + * Same as [RequiredRefBuilder.once] but for nullable references. The calculation receives `Referenced?` + * which will be null if the reference is null. + * + * **When it runs:** + * - On create: Yes + * - On replace: Yes + * - On modify (when reference changes): Yes + * - When referenced model changes: **No** (this is the key difference from watch) + * + * @param calculation Lambda to create a denormalization modification. Receives `Referenced?` (nullable). + * @see RequiredRefBuilder.once for detailed documentation + */ + public inline fun once( + crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced?) -> Unit, + ) { + registerDenormalization(emptySet()) { + ModificationBuilder().apply { calculation(it) }.build() + } + } + + public fun build(): Denormalization.OptionalRef = Denormalization.OptionalRef(reference, info, list) + } + + @PublishedApi + internal val denormalizations: ArrayList> = ArrayList() + + /** + * Register a required (non-nullable) reference denormalization. + * Called by the [denormalizes] extension function. + */ + public inline fun , RID : Comparable> required( + reference: Lens, + info: ModelInfo<*, Ref, RID>, + build: RequiredRefBuilder.(Optic) -> Unit, + ) { + denormalizations.add( + RequiredRefBuilder(reference, info) + .apply { build(IdentityLens(info.serializer)) } + .build() + ) + } + + /** + * Register an optional (nullable) reference denormalization. + * Called by the [denormalizes] extension function for nullable references. + */ + public inline fun , RID : Comparable> optional( + reference: Optic, + info: ModelInfo<*, Ref, RID>, + build: OptionalRefBuilder.(Optic) -> Unit, + ) { + denormalizations.add( + OptionalRefBuilder(reference, info) + .apply { build(IdentityLens(info.serializer)) } + .build() + ) + } +} diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt new file mode 100644 index 000000000..8b7096857 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -0,0 +1,225 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.definition.StartupTask +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.typed.AuthAccess +import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.services.database.HasId +import com.lightningkite.services.database.Table +import com.lightningkite.services.database.optics.IdentityLens +import com.lightningkite.services.database.optics.Lens +import com.lightningkite.lightningserver.definition.Runtime +import com.lightningkite.lightningserver.typed.getOrBadRequest +import com.lightningkite.services.database.Condition +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.interceptCreate +import com.lightningkite.services.database.interceptModification +import com.lightningkite.services.database.interceptReplace +import com.lightningkite.services.database.vet + +public interface ModelInfoWithDeno?, T : HasId, ID : Comparable> : ModelInfo { + public val denormalizations: List> +} + +/** + * Adds denormalization support to a [ModelInfo] + * + * This is the primary entry point for defining models that denormalize data from referenced models. + * Use this instead of the standard `modelInfo()` when you need to copy data from referenced models + * to avoid expensive joins or enable efficient permission checks. + * + * **How denormalization works:** + * - On create/replace: Fetches referenced models and copies specified fields + * - On modify: Detects reference changes and updates denormalized fields + * - On referenced model change: Automatically updates all referencing models (if listenForChanges = true) + * + * Example: + * ```kotlin + * object AnnouncementEndpoints : ServerBuilder() { + * private val info = Server.database.modelInfoWithDeno( + * auth = UserAuth.require(), + * permissions = { permissions(auth) }, + * denormalizations = { announcement -> + * announcement.course.denormalizes(Course.info) { + * // Watch for changes - updates when Course.submitter.courseProvider changes + * announcement.courseProvider assign it.submitter.courseProvider + * + * // No change watching - only updates when announcement.course reference changes + * announcement.courseTitle assignOnce it.title + * } + * } + * ) + * } + * ``` + * + * **Important:** Remember to mark denormalized fields as `cannotBeModified()` in your update restrictions: + * ```kotlin + * updateRestrictions = blacklistRestrictions { + * it.courseProvider.cannotBeModified() // denormalized field + * } + * ``` + */ +context(builder: ServerBuilder) +public fun ?, T : HasId, ID : Comparable> ModelInfo.withDenormalizations( + denormalizations: DenormalizationBuilder.(Lens) -> Unit, +): ModelInfoWithDeno = + object : ModelInfoWithDeno, ModelInfo by this@withDenormalizations { + override val denormalizations by lazy { // lazy so that we don't run into initialization order issues when declaring modelInfo + DenormalizationBuilder().apply { denormalizations(IdentityLens(serializer)) }.denormalizations + } + + context(server: ServerRuntime) + private fun wrapWithDeno(table: Table): Table = + this.denormalizations.fold(table) { t, deno -> t.denormalize(deno) } + + private val wraps = this@withDenormalizations + + context(server: ServerRuntime) + override suspend fun table(auth: AuthAccess): Table = wrapWithDeno(wraps.table(auth)) + + context(server: ServerRuntime) + override fun table(): Table = wrapWithDeno(wraps.table()) + + init { + val modelInfo = this + with(builder) { + builder.path.path("$tableName-deno") bind StartupTask { + modelInfo.denormalizations + .filter { it.listenForChanges } + .takeUnless { it.isEmpty() } + ?.let { deno -> + val table = Runtime { baseTable() } + for (d in deno) d.listenForDenormalizations(table) + } + } + } + } + } + + +context(runtime: ServerRuntime) +private fun , RID : Comparable> Table.denormalize( + calculation: Denormalization, +): Table = when (calculation) { + is Denormalization.RequiredRef -> denormalizeImpl(calculation) + is Denormalization.OptionalRef -> denormalizeNullableImpl(calculation) +} + +private fun , RID : Comparable> Denormalization.listenForDenormalizations( + table: Runtime>, +) { + when (this) { + is Denormalization.RequiredRef -> info.registerChangeListener { changes -> + for ((old, new) in changes.changes) { + if (old == null || new == null) continue + + val mod = denormalize(old, new) + if (mod.isNothing) continue + + table().updateManyIgnoringResult( + reference.mapCondition(Condition.Equal(old._id)), + mod + ) + } + } + + is Denormalization.OptionalRef -> info.registerChangeListener { changes -> + for ((old, new) in changes.changes) { + if (old == null) continue + + val mod = denormalize(old, new) + val removeRef = + if (new == null) reference.mapModification( // model is deleted, remove reference + Modification.Assign(null) + ) + else null + + if (!mod.isNothing || removeRef != null) table().updateManyIgnoringResult( + reference.mapCondition( + Condition.Equal(new?._id ?: old._id) + ), + Modification.Chain( + listOfNotNull(removeRef, mod) + ) + ) + } + } + } +} + +/** + * Internal implementation that adds denormalization interceptors for required references. + * Intercepts create, replace, and modification operations to automatically denormalize data. + */ +context(_: ServerRuntime) +private fun , RID : Comparable> Table.denormalizeImpl( + deno: Denormalization.RequiredRef, +): Table = this + .interceptCreate { model -> + val reference = deno.info.table().getOrBadRequest(deno.reference.get(model)) + deno.denormalize(reference).invoke(model) + } + .interceptReplace { model -> + val reference = deno.info.table().getOrBadRequest(deno.reference.get(model)) + deno.denormalize(reference).invoke(model) + } + .interceptModification { incomingMod -> + var updatedMod = incomingMod + var newReference: RID? = null + incomingMod.vet(deno.reference) { + when (it) { + is Modification.Assign -> { + newReference = it.value + } + + else -> {} + } + } + if (newReference != null) { + val source = deno.info.table().getOrBadRequest(newReference) + updatedMod = Modification.Chain( + listOf(incomingMod, deno.denormalize(source)) + ) + } + updatedMod + } + +/** + * Internal implementation that adds denormalization interceptors for optional references. + * Intercepts create, replace, and modification operations to automatically denormalize data. + */ +context(_: ServerRuntime) +private fun , RID : Comparable> Table.denormalizeNullableImpl( + deno: Denormalization.OptionalRef, +): Table = this + .interceptCreate { model -> + val reference = deno.reference.get(model)?.let { deno.info.table().getOrBadRequest(it) } + deno.denormalize(reference).invoke(model) + } + .interceptReplace { model -> + val reference = deno.reference.get(model)?.let { deno.info.table().getOrBadRequest(it) } + deno.denormalize(reference).invoke(model) + } + .interceptModification { incomingMod -> + var updatedMod = incomingMod + var changed = false + var newReference: RID? = null + incomingMod.vet(deno.reference) { + when (it) { + is Modification.Assign -> { + changed = true + newReference = it.value + } + + else -> {} + } + } + if (changed) { + val source = newReference?.let { deno.info.table().getOrBadRequest(it) } + updatedMod = Modification.Chain( + listOf(incomingMod, deno.denormalize(source)) + ) + } + updatedMod + } diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt new file mode 100644 index 000000000..31b86f20f --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt @@ -0,0 +1,107 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.http.post +import com.lightningkite.lightningserver.pathing.PathSpec +import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.pathing.PathSpec1 +import com.lightningkite.lightningserver.pathing.arg1 +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.typed.ApiHttpHandler +import com.lightningkite.lightningserver.typed.explicitApiHttpHandler +import com.lightningkite.lightningserver.typed.getOrNotFound +import com.lightningkite.lightningserver.typed.getOrThrow +import com.lightningkite.services.database.Condition +import com.lightningkite.services.database.HasId +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database._id +import com.lightningkite.services.database.all +import com.lightningkite.services.database.updateOneByIdIgnoringResult +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer + + +/** Caps how many ids [RefreshDenoEndpoints.refreshAllDenormalizations] puts in a single update query. */ +private const val UPDATE_BATCH = 1000 + +public class RefreshDenoEndpoints?, T : HasId, ID : Comparable>( + private val info: ModelInfoWithDeno +) : ServerBuilder() { + context(_: ServerRuntime) + private suspend fun , RID : Comparable> Denormalization.modification( + model: T + ): Modification = when (val deno = this) { + is Denormalization.OptionalRef -> { + val ref = deno.reference.get(model) + val referenced = ref?.let { deno.info.table().getOrThrow(it) } + val mod = deno.denormalize(referenced) + + if (mod(model) == model) Modification.Nothing() + else mod + } + + is Denormalization.RequiredRef -> { + val referenced = deno.info.table().getOrThrow( + deno.reference.get(model) ?: throw IllegalStateException("Could not get ref ${deno.reference} for ${info.tableName} $model") + ) + val mod = deno.denormalize(referenced) + + if (mod(model) == model) Modification.Nothing() + else mod + } + } + + public val refreshDetail: ApiHttpHandler, HasId<*>, Unit, Modification> = + path.arg(PathSpec.Segment.Wildcard("id", info.idSerializer)).post bind explicitApiHttpHandler( + summary = "Refresh Denormalizations", + description = "Refreshes the denormalized ", + inputType = Unit.serializer(), + outputType = Modification.serializer(info.serializer), + auth = AuthRequirement.IsAdmin, + implementation = { + val model = info.table().getOrNotFound(request.arg1) + val mod = Modification.Chain(info.denormalizations.map { it.modification(model) }) + if (!mod.isNothing) info.baseTable().updateOneByIdIgnoringResult(model._id, mod) + mod + } + ) + + context(_: ServerRuntime) + public suspend fun refreshAllDenormalizations(): Map> { + // todo: should re-use reference ids where possible and parallelize + // Streamed rather than materialized: the rows themselves are discarded as we go and only the + // modifications that are actually needed are retained (those are the return value anyway). + // The write pass runs after the read finishes so updates never race the cursor feeding them. + val mods = LinkedHashMap>() + info.table().all().collect { model -> + val mod = Modification.Chain(info.denormalizations.map { it.modification(model) }) + if (!mod.isNothing) mods[model._id] = mod + } + + // Rows needing the identical modification go out in one write, so the change notifications + // this produces scale with the number of distinct changes rather than the number of rows. + val table = info.baseTable() + for ((mod, ids) in mods.entries.groupBy({ it.value }, { it.key })) { + for (idBatch in ids.chunked(UPDATE_BATCH)) { + table.updateManyIgnoringResult( + Condition.OnField(info.serializer._id(), Condition.Inside(idBatch)), + mod + ) + } + } + + return mods.mapKeys { it.key.toString() } + } + + public val refreshAll: ApiHttpHandler, Unit, Map>> = + path.path("refresh-all").post bind explicitApiHttpHandler( + summary = "Refresh Denormalizations", + inputType = Unit.serializer(), + outputType = MapSerializer(String.serializer(), Modification.serializer(info.serializer)), + auth = AuthRequirement.IsAdmin, + implementation = { + refreshAllDenormalizations() + } + ) +} diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt new file mode 100644 index 000000000..c0b19f24b --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt @@ -0,0 +1,38 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.services.Untested +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.optics.Field +import com.lightningkite.services.database.optics.Optic + +// TODO: Tests needed +@Untested +internal fun Modification.vet(path: Optic, onModification: (Modification) -> Unit) = + @Suppress("UNCHECKED_CAST") + vet(path.fields as List>, onModification as (Modification<*>) -> Unit) + +private fun Modification<*>.vet(path: List>, onModification: (Modification<*>) -> Unit) { + when (this) { + is Modification.Assign -> { + var value = this.value + for (key in path) { + value = key.get(value) + } + onModification(Modification.Assign(value)) + } + + is Modification.Chain -> modifications.forEach { it.vet(path, onModification) } + + is Modification.OnField<*, *> -> + if (this.key == path.firstOrNull()) { + if (path.size == 1) onModification(this.modification) + else this.modification.vet( + path.subList(1, path.size), + onModification + ) + } + + is Modification.IfNotNull -> this.modification.vet(path, onModification) + else -> {} + } +} From efd0f2a0e0f08e04b9edb057d6c9e96363ee5c61 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Tue, 3 Nov 2026 17:44:24 -0700 Subject: [PATCH 3/9] Added checks for denormalizing based on denormalized fields, added tests for vet --- .../typed/denormalize/Denormalization.kt | 26 -- .../denormalize/DenormalizationBuilder.ext.kt | 8 +- .../denormalize/DenormalizationBuilder.kt | 4 +- .../typed/denormalize/ModelInfoWithDeno.kt | 143 +++++---- .../typed/denormalize/RefreshDenoEndpoints.kt | 10 +- .../typed/denormalize/helpers.kt | 92 ++++-- .../typed/denormalize/DenormalizationTest.kt | 292 ++++++++++++++++++ .../typed/denormalize/VetTest.kt | 125 ++++++++ 8 files changed, 578 insertions(+), 122 deletions(-) create mode 100644 typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt create mode 100644 typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt index 284e2a285..b1a2d9e0d 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt @@ -81,31 +81,5 @@ public sealed interface Denormalization, RI override val listenForChanges: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } } - -// data class Chained< -// M : Any, R1 : HasId, R1_ID : Comparable, -// R2 : HasId, R2_ID : Comparable -// >( -// val first: Denormalization, -// val second: Denormalization -// ) : Denormalization { -// override val info: ModelInfo<*, R2, R2_ID> get() = second.info -// override val listenForChanges: Boolean get() = first.listenForChanges || second.listenForChanges -// -// context(_: ServerRuntime) -// suspend fun denormalize(old: R2, new: R2?): Modification { -// when (second) { -// is Chained -> TODO() -// is OptionalRef<*, *, *> -> TODO() -// is RequiredRef<*, *, *> -> TODO() -// } -// } -// -// context(_: ServerRuntime) -// suspend fun denormalize(ref: Referenced?): Modification = -// Modification.Chain( -// calculations.map { it.calculation(ref) } -// ) -// } } diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt index c582f53a7..25b4025b7 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt @@ -9,7 +9,7 @@ import com.lightningkite.services.database.optics.Optic context(builder: DenormalizationBuilder) public inline fun , RID : Comparable> Lens.denormalizes( info: ModelInfo<*, Ref, RID>, - build: DenormalizationBuilder.RequiredRefBuilder.(Optic) -> Unit, + build: DenormalizationBuilder.RequiredRefBuilder.(Lens) -> Unit, ): Unit = builder.required(this, info, build) @@ -23,6 +23,7 @@ public inline fun , RID : Comparable> Optic) public infix fun , RID : Comparable, T> Optic.bind(ref: Lens) { + requireMarkedDenormalized(this) builder.registerDenormalization(setOf(ref)) { reference -> this.mapModification( Modification.Assign(ref.get(reference)) @@ -32,6 +33,8 @@ public infix fun , RID : Comparable, T> Optic context(builder: DenormalizationBuilder.RequiredRefBuilder) public infix fun , RID : Comparable, T> Optic.set(ref: Lens) { + requireMarkedDenormalized(this) + requireSourceOfTruth(ref) builder.registerDenormalization(emptySet()) { reference -> this.mapModification( Modification.Assign(ref.get(reference)) @@ -41,6 +44,7 @@ public infix fun , RID : Comparable, T> Optic context(builder: DenormalizationBuilder.OptionalRefBuilder) public infix fun , RID : Comparable, T> Optic.bind(ref: Optic) { + requireMarkedDenormalized(this) builder.registerDenormalization(setOf(ref)) { reference -> this.mapModification( Modification.Assign(reference?.let(ref::get)) @@ -50,6 +54,8 @@ public infix fun , RID : Comparable, T> Optic context(builder: DenormalizationBuilder.OptionalRefBuilder) public infix fun , RID : Comparable, T> Optic.set(ref: Optic) { + requireMarkedDenormalized(this) + requireSourceOfTruth(ref) builder.registerDenormalization(emptySet()) { reference -> this.mapModification( Modification.Assign(reference?.let(ref::get)) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt index 63fa897d3..8211a8046 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -49,6 +49,7 @@ public class DenormalizationBuilder { dependencies: Set>, calculation: suspend context(ServerRuntime) (Referenced) -> Modification, ) { + dependencies.forEach(::requireSourceOfTruth) list.add(Denormalization.Calculation(dependencies, calculation)) } @@ -171,6 +172,7 @@ public class DenormalizationBuilder { dependencies: Set>, calculation: suspend context(ServerRuntime) (Referenced?) -> Modification, ) { + dependencies.forEach(::requireSourceOfTruth) list.add(Denormalization.Calculation(dependencies, calculation)) } @@ -231,7 +233,7 @@ public class DenormalizationBuilder { public inline fun , RID : Comparable> required( reference: Lens, info: ModelInfo<*, Ref, RID>, - build: RequiredRefBuilder.(Optic) -> Unit, + build: RequiredRefBuilder.(Lens) -> Unit, ) { denormalizations.add( RequiredRefBuilder(reference, info) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt index 8b7096857..e04de89a8 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -9,17 +9,25 @@ import com.lightningkite.services.database.HasId import com.lightningkite.services.database.Table import com.lightningkite.services.database.optics.IdentityLens import com.lightningkite.services.database.optics.Lens -import com.lightningkite.lightningserver.definition.Runtime import com.lightningkite.lightningserver.typed.getOrBadRequest import com.lightningkite.services.database.Condition import com.lightningkite.services.database.Modification import com.lightningkite.services.database.interceptCreate import com.lightningkite.services.database.interceptModification import com.lightningkite.services.database.interceptReplace -import com.lightningkite.services.database.vet +import java.util.concurrent.atomic.AtomicBoolean public interface ModelInfoWithDeno?, T : HasId, ID : Comparable> : ModelInfo { public val denormalizations: List> + + /** + * Returns [baseTable] with this model's [denormalizations] applied, so a write that changes a reference also + * recalculates the fields denormalized from it. + * + * Like [baseTable], writes through this table skip permissions and signals. + */ + context(server: ServerRuntime) + public fun baseTableWithDenormalizations(): Table } /** @@ -34,22 +42,30 @@ public interface ModelInfoWithDeno?, T : HasId, ID : Compara * - On modify: Detects reference changes and updates denormalized fields * - On referenced model change: Automatically updates all referencing models (if listenForChanges = true) * + * Denormalizations read from the source of truth only. Reading a field the referenced model marks `@Denormalized` + * throws when the denormalizations are built. To reach a model two references away, denormalize the intermediate + * reference onto this model and denormalize from that: + * ```kotlin + * a.b.denormalizes(B.info) { b -> a.c bind b.c } + * a.c.denormalizes(C.info) { c -> a.cName bind c.name } + * ``` + * + * Fields written by `bind` or `set` must be marked `@Denormalized`. + * * Example: * ```kotlin - * object AnnouncementEndpoints : ServerBuilder() { - * private val info = Server.database.modelInfoWithDeno( - * auth = UserAuth.require(), - * permissions = { permissions(auth) }, - * denormalizations = { announcement -> - * announcement.course.denormalizes(Course.info) { - * // Watch for changes - updates when Course.submitter.courseProvider changes - * announcement.courseProvider assign it.submitter.courseProvider + * val announcementInfo = Server.database.modelInfo( + * auth = UserAuth.require(), + * tableName = "Announcement", + * permissions = { permissions(auth) }, + * ).withDenormalizations { announcement -> + * announcement.course.denormalizes(CourseEndpoints.info) { course -> + * // Kept in sync: updates whenever Course.providerName changes + * announcement.courseProvider bind course.providerName * - * // No change watching - only updates when announcement.course reference changes - * announcement.courseTitle assignOnce it.title - * } - * } - * ) + * // Not watched: only updates when announcement.course changes + * announcement.courseTitle set course.title + * } * } * ``` * @@ -65,16 +81,27 @@ public fun ?, T : HasId, ID : Comparable> ModelInfo.(Lens) -> Unit, ): ModelInfoWithDeno = object : ModelInfoWithDeno, ModelInfo by this@withDenormalizations { - override val denormalizations by lazy { // lazy so that we don't run into initialization order issues when declaring modelInfo + override val denormalizations: List> by lazy { // lazy so that we don't run into initialization order issues when declaring modelInfo DenormalizationBuilder().apply { denormalizations(IdentityLens(serializer)) }.denormalizations } context(server: ServerRuntime) private fun wrapWithDeno(table: Table): Table = - this.denormalizations.fold(table) { t, deno -> t.denormalize(deno) } + // Claude: foldRight so the first declared denormalization intercepts first; later ones read the references it sets. + this.denormalizations.foldRight(table) { deno, t -> + when (deno) { + is Denormalization.RequiredRef -> t.denormalizeImpl(deno) + is Denormalization.OptionalRef -> t.denormalizeNullableImpl(deno) + } + } private val wraps = this@withDenormalizations + context(server: ServerRuntime) + override fun baseTableWithDenormalizations(): Table = wrapWithDeno(baseTable()) + + private val listening = AtomicBoolean(false) + context(server: ServerRuntime) override suspend fun table(auth: AuthAccess): Table = wrapWithDeno(wraps.table(auth)) @@ -85,65 +112,53 @@ public fun ?, T : HasId, ID : Comparable> ModelInfo - val table = Runtime { baseTable() } - for (d in deno) d.listenForDenormalizations(table) - } + // Claude: listeners live on the ModelInfo, which can outlive the engine, so a second engine in the same process (as in tests) must not add them again. + if (!listening.compareAndSet(false, true)) return@StartupTask + for (d in modelInfo.denormalizations) { + if (d.listenForChanges) d.listenForDenormalizations { modelInfo.baseTableWithDenormalizations() } + } } } } } -context(runtime: ServerRuntime) -private fun , RID : Comparable> Table.denormalize( - calculation: Denormalization, -): Table = when (calculation) { - is Denormalization.RequiredRef -> denormalizeImpl(calculation) - is Denormalization.OptionalRef -> denormalizeNullableImpl(calculation) +private fun , RID : Comparable> Denormalization.listenForDenormalizations( + table: context(ServerRuntime) () -> Table, +) { + info.registerChangeListener { changes -> + for ((old, new) in changes.changes) { + if (old != null) updateReferencing(table(), old, new) + } + } } -private fun , RID : Comparable> Denormalization.listenForDenormalizations( - table: Runtime>, +context(_: ServerRuntime) +private suspend fun , RID : Comparable> Denormalization.updateReferencing( + table: Table, + old: Ref, + new: Ref?, ) { when (this) { - is Denormalization.RequiredRef -> info.registerChangeListener { changes -> - for ((old, new) in changes.changes) { - if (old == null || new == null) continue - - val mod = denormalize(old, new) - if (mod.isNothing) continue - - table().updateManyIgnoringResult( - reference.mapCondition(Condition.Equal(old._id)), - mod - ) - } + is Denormalization.RequiredRef -> { + if (new == null) return + val mod = denormalize(old, new) + if (mod.isNothing) return + table.updateManyIgnoringResult(reference.mapCondition(Condition.Equal(old._id)), mod) } - is Denormalization.OptionalRef -> info.registerChangeListener { changes -> - for ((old, new) in changes.changes) { - if (old == null) continue - - val mod = denormalize(old, new) - val removeRef = - if (new == null) reference.mapModification( // model is deleted, remove reference - Modification.Assign(null) - ) - else null - - if (!mod.isNothing || removeRef != null) table().updateManyIgnoringResult( - reference.mapCondition( - Condition.Equal(new?._id ?: old._id) - ), - Modification.Chain( - listOfNotNull(removeRef, mod) - ) + is Denormalization.OptionalRef -> { + val mod = denormalize(old, new) + val removeRef = + if (new == null) reference.mapModification( // model is deleted, remove reference + Modification.Assign(null) ) - } + else null + + if (!mod.isNothing || removeRef != null) table.updateManyIgnoringResult( + reference.mapCondition(Condition.Equal(old._id)), + Modification.Chain(listOfNotNull(removeRef, mod)) + ) } } } @@ -205,7 +220,7 @@ private fun , RID : Comparable> Table< var updatedMod = incomingMod var changed = false var newReference: RID? = null - incomingMod.vet(deno.reference) { + incomingMod.vetNullable(deno.reference) { when (it) { is Modification.Assign -> { changed = true diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt index 31b86f20f..2a5acb78a 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt @@ -42,9 +42,7 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab } is Denormalization.RequiredRef -> { - val referenced = deno.info.table().getOrThrow( - deno.reference.get(model) ?: throw IllegalStateException("Could not get ref ${deno.reference} for ${info.tableName} $model") - ) + val referenced = deno.info.table().getOrThrow(deno.reference.get(model)) val mod = deno.denormalize(referenced) if (mod(model) == model) Modification.Nothing() @@ -55,14 +53,14 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab public val refreshDetail: ApiHttpHandler, HasId<*>, Unit, Modification> = path.arg(PathSpec.Segment.Wildcard("id", info.idSerializer)).post bind explicitApiHttpHandler( summary = "Refresh Denormalizations", - description = "Refreshes the denormalized ", + description = "Recalculates every denormalized field on this ${info.tableName} from its references and returns the modification applied.", inputType = Unit.serializer(), outputType = Modification.serializer(info.serializer), auth = AuthRequirement.IsAdmin, implementation = { val model = info.table().getOrNotFound(request.arg1) val mod = Modification.Chain(info.denormalizations.map { it.modification(model) }) - if (!mod.isNothing) info.baseTable().updateOneByIdIgnoringResult(model._id, mod) + if (!mod.isNothing) info.baseTableWithDenormalizations().updateOneByIdIgnoringResult(model._id, mod) mod } ) @@ -81,7 +79,7 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab // Rows needing the identical modification go out in one write, so the change notifications // this produces scale with the number of distinct changes rather than the number of rows. - val table = info.baseTable() + val table = info.baseTableWithDenormalizations() for ((mod, ids) in mods.entries.groupBy({ it.value }, { it.key })) { for (idBatch in ids.chunked(UPDATE_BATCH)) { table.updateManyIgnoringResult( diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt index c0b19f24b..2d8e4911d 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt @@ -1,38 +1,82 @@ package com.lightningkite.lightningserver.typed.denormalize -import com.lightningkite.services.Untested +import com.lightningkite.services.data.Denormalized import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.optics.ComposedOptic import com.lightningkite.services.database.optics.Field +import com.lightningkite.services.database.optics.IdentityLens +import com.lightningkite.services.database.optics.Lens +import com.lightningkite.services.database.optics.NotNullOptic import com.lightningkite.services.database.optics.Optic -// TODO: Tests needed -@Untested -internal fun Modification.vet(path: Optic, onModification: (Modification) -> Unit) = +/** + * Calls [onModification] with each part of this modification that affects the target of [path]. + * + * An assignment to a value containing the target is reported as an assignment to the target. The parts of a + * [Modification.Chain] are reported separately, in order, and parts that don't affect the target are not reported. + * + * @throws IllegalArgumentException if [path] passes through a field shared by the variants of a sealed type. + */ +public fun Modification.vet(path: Lens, onModification: (Modification) -> Unit): Unit = @Suppress("UNCHECKED_CAST") - vet(path.fields as List>, onModification as (Modification<*>) -> Unit) - -private fun Modification<*>.vet(path: List>, onModification: (Modification<*>) -> Unit) { - when (this) { - is Modification.Assign -> { - var value = this.value - for (key in path) { - value = key.get(value) + vetAny(path, onModification as (Modification<*>) -> Unit) + +/** + * Calls [onModification] with each part of this modification that affects the target of [path]. + * + * An assignment to a value containing the target is reported as an assignment to the target, or as an assignment of + * `null` if a nullable value on the way to the target is `null`. The parts of a [Modification.Chain] are reported + * separately, in order, and parts that don't affect the target are not reported. + * + * @throws IllegalArgumentException if [path] passes through collection elements or a sealed type. + */ +public fun Modification.vetNullable(path: Optic, onModification: (Modification) -> Unit): Unit = + @Suppress("UNCHECKED_CAST") + vetAny(path, onModification as (Modification<*>) -> Unit) + +private fun Modification<*>.vetAny(path: Optic<*, *>, onModification: (Modification<*>) -> Unit) { + if (this is Modification.Chain) return modifications.forEach { it.vetAny(path, onModification) } + when (path) { + is IdentityLens<*> -> onModification(this) + is ComposedOptic<*, *, *> -> vetAny(path.outer) { it.vetAny(path.inner, onModification) } + is Field<*, *> -> when (this) { + is Modification.Assign -> { + @Suppress("UNCHECKED_CAST") + onModification(Modification.Assign(value?.let { (path as Field).get(it) })) } - onModification(Modification.Assign(value)) + is Modification.OnField<*, *> -> if (key == path) modification.forEachPart(onModification) + else -> {} } - is Modification.Chain -> modifications.forEach { it.vet(path, onModification) } - - is Modification.OnField<*, *> -> - if (this.key == path.firstOrNull()) { - if (path.size == 1) onModification(this.modification) - else this.modification.vet( - path.subList(1, path.size), - onModification - ) + is NotNullOptic<*, *> -> vetAny(path.wraps) { + when (it) { + is Modification.Assign -> onModification(it) + is Modification.IfNotNull -> it.modification.forEachPart(onModification) + else -> {} } + } + + else -> throw IllegalArgumentException("vet does not support the step $path") + } +} + +private fun Modification<*>.forEachPart(action: (Modification<*>) -> Unit) { + if (this is Modification.Chain) modifications.forEach { it.forEachPart(action) } else action(this) +} + +/** Throws an [IllegalArgumentException] if [source] passes through a field marked [Denormalized]. */ +internal fun requireSourceOfTruth(source: Optic<*, *>) { + val copied = source.fields.firstOrNull { field -> field.annotations.any { it is Denormalized } } ?: return + throw IllegalArgumentException( + "A denormalization reads $source, but '${copied.name}' is itself @Denormalized. " + + "Denormalize the reference '${copied.name}' comes from onto this model and read the value from its source " + + "instead, e.g. `a.b.denormalizes(B.info) { b -> a.c bind b.c }` then `a.c.denormalizes(C.info) { c -> a.cName bind c.name }`." + ) +} - is Modification.IfNotNull -> this.modification.vet(path, onModification) - else -> {} +/** Throws an [IllegalArgumentException] unless the last field of [target] is marked [Denormalized]. */ +internal fun requireMarkedDenormalized(target: Optic<*, *>) { + require(target.fields.lastOrNull()?.annotations.orEmpty().any { it is Denormalized }) { + "$target is written by a denormalization, so it must be marked @Denormalized." } } diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt new file mode 100644 index 000000000..9304af322 --- /dev/null +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -0,0 +1,292 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.BadRequestException +import com.lightningkite.lightningserver.auth.noAuth +import com.lightningkite.lightningserver.definition.GeneralServerSettings +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.definition.generalSettings +import com.lightningkite.lightningserver.runtime.test.TestRunner +import com.lightningkite.lightningserver.runtime.test.execute +import com.lightningkite.lightningserver.runtime.test.executeStartupTasks +import com.lightningkite.lightningserver.runtime.test.testBlocking +import com.lightningkite.lightningserver.serialization.registerBasicMediaTypeCoders +import com.lightningkite.lightningserver.settings.set +import com.lightningkite.lightningserver.settings.setStatic +import com.lightningkite.lightningserver.typed.modelInfo +import com.lightningkite.services.data.Denormalized +import com.lightningkite.services.data.Queryable +import com.lightningkite.services.database.* +import kotlinx.coroutines.flow.toList +import kotlin.test.* +import kotlin.uuid.Uuid + +class DenormalizationTest { + + object DenoServer : ServerBuilder() { + init { registerBasicMediaTypeCoders() } + + val database = setting("database", Database.Settings()) + + val countryInfo = database.modelInfo?, DenoCountry, Uuid>( + auth = noAuth, + tableName = "DenoCountry", + permissions = { ModelPermissions.allowAll() }, + ) + + val cityInfo = database.modelInfo?, DenoCity, Uuid>( + auth = noAuth, + tableName = "DenoCity", + permissions = { ModelPermissions.allowAll() }, + ).withDenormalizations { city -> + city.country.denormalizes(countryInfo) { country -> + city.countryName bind country.name + city.countryNameAtCreation set country.name + } + } + + val personInfo = database.modelInfo?, DenoPerson, Uuid>( + auth = noAuth, + tableName = "DenoPerson", + permissions = { ModelPermissions.allowAll() }, + ).withDenormalizations { person -> + person.city.denormalizes(cityInfo) { city -> + person.country bind city.country + } + person.country.denormalizes(countryInfo) { country -> + person.countryName bind country.name + } + person.favoriteCity.denormalizes(cityInfo) { city -> + person.favoriteCityName bind city.name + } + } + + val personRefresh = path.path("person-deno") include RefreshDenoEndpoints(personInfo) + } + + object MisconfiguredServer : ServerBuilder() { + val database = setting("database", Database.Settings()) + + val readsACopy = database.modelInfo?, DenoPerson, Uuid>( + auth = noAuth, + tableName = "ReadsACopyPerson", + permissions = { ModelPermissions.allowAll() }, + ).withDenormalizations { person -> + person.city.denormalizes(DenoServer.cityInfo) { city -> + person.countryName bind city.countryName + } + } + + val writesAnUnmarkedField = database.modelInfo?, DenoCity, Uuid>( + auth = noAuth, + tableName = "UnmarkedCity", + permissions = { ModelPermissions.allowAll() }, + ).withDenormalizations { city -> + city.country.denormalizes(DenoServer.countryInfo) { country -> + city.name bind country.name + } + } + } + + private fun denoTest(action: suspend context(TestRunner) DenoServer.() -> Unit) = + DenoServer.testBlocking(settings = { + generalSettings set GeneralServerSettings() + database set Database.Settings() + }) { + executeStartupTasks() + action() + } + + @Test + fun create_copies_referenced_fields() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val person = DenoPerson(city = paris._id) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + personInfo.table().insertOne(person) + } + + execute { + val storedCity = cityInfo.table().get(paris._id)!! + assertEquals("France", storedCity.countryName) + assertEquals("France", storedCity.countryNameAtCreation) + assertEquals("France", personInfo.table().get(person._id)!!.countryName) + } + } + + @Test + fun bind_follows_the_referenced_model_and_set_does_not() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + countryInfo.table().updateOneById(france._id, Modification { it.name assign "République française" }) + } + + execute { + val storedCity = cityInfo.table().get(paris._id)!! + assertEquals("République française", storedCity.countryName) + assertEquals("France", storedCity.countryNameAtCreation) + } + } + + /** Person.countryName comes from Country.name through Person.country, which is denormalized from City.country. */ + @Test + fun stored_intermediate_reference_follows_the_source() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val person = DenoPerson(city = paris._id) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + personInfo.table().insertOne(person) + countryInfo.table().updateOneById(france._id, Modification { it.name assign "République française" }) + } + + execute { + assertEquals("République française", personInfo.table().get(person._id)!!.countryName) + } + } + + @Test + fun moving_the_intermediate_reference_recalculates_downstream_fields() = denoTest { + val france = DenoCountry(name = "France") + val spain = DenoCountry(name = "Spain") + val border = DenoCity(country = france._id, name = "Hendaye") + val person = DenoPerson(city = border._id) + execute { + countryInfo.table().insertMany(listOf(france, spain)) + cityInfo.table().insertOne(border) + personInfo.table().insertOne(person) + cityInfo.table().updateOneById(border._id, Modification { it.country assign spain._id }) + } + + execute { + val stored = personInfo.table().get(person._id)!! + assertEquals(spain._id, stored.country) + assertEquals("Spain", stored.countryName) + } + } + + @Test + fun reading_a_denormalized_field_fails_when_built() { + val error = assertFailsWith { MisconfiguredServer.readsACopy.denormalizations } + assertContains(error.message!!, "'countryName' is itself @Denormalized") + } + + @Test + fun reading_a_denormalized_field_fails_when_run() { + val error = assertFailsWith { + MisconfiguredServer.testBlocking({ + database set Database.Settings() + }) { + execute { + readsACopy.table().all().toList() + } + } + } + assertContains(error.message!!, "'countryName' is itself @Denormalized") + } + + @Test + fun writing_an_unmarked_field_fails_when_built() { + val error = assertFailsWith { MisconfiguredServer.writesAnUnmarkedField.denormalizations } + assertContains(error.message!!, "must be marked @Denormalized") + } + + @Test + fun changing_the_reference_recalculates() = denoTest { + val france = DenoCountry(name = "France") + val spain = DenoCountry(name = "Spain") + val paris = DenoCity(country = france._id, name = "Paris") + val madrid = DenoCity(country = spain._id, name = "Madrid") + val person = DenoPerson(city = paris._id) + execute { + countryInfo.table().insertMany(listOf(france, spain)) + cityInfo.table().insertMany(listOf(paris, madrid)) + personInfo.table().insertOne(person) + personInfo.table().updateOneById(person._id, Modification { it.city assign madrid._id }) + } + + execute { + assertEquals("Spain", personInfo.table().get(person._id)!!.countryName) + } + } + + @Test + fun missing_reference_is_rejected() = denoTest { + assertFailsWith { + execute { cityInfo.table().insertOne(DenoCity(country = Uuid.random(), name = "Atlantis")) } + } + } + + @Test + fun optional_reference_follows_the_referenced_model_and_clears_on_delete() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val home = DenoCity(country = france._id, name = "Lyon") + val person = DenoPerson(city = home._id) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertMany(listOf(paris, home)) + personInfo.table().insertOne(person) + assertNull(personInfo.table().get(person._id)!!.favoriteCityName) + + personInfo.table().updateOneById(person._id, Modification { it.favoriteCity assign paris._id }) + assertEquals("Paris", personInfo.table().get(person._id)!!.favoriteCityName) + + cityInfo.table().updateOneById(paris._id, Modification { it.name assign "Paname" }) + assertEquals("Paname", personInfo.table().get(person._id)!!.favoriteCityName) + + cityInfo.table().deleteOneById(paris._id) + val stored = personInfo.table().get(person._id)!! + assertNull(stored.favoriteCity) + assertNull(stored.favoriteCityName) + } + } + + @Test + fun refresh_repairs_stale_values() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val person = DenoPerson(city = paris._id) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + personInfo.table().insertOne(person) + personInfo.baseTable().updateOneById(person._id, Modification { it.countryName assign "stale" }) + + val applied = personRefresh.refreshAllDenormalizations() + + assertEquals(setOf(person._id.toString()), applied.keys) + assertEquals("France", personInfo.table().get(person._id)!!.countryName) + } + } +} + +@Queryable +data class DenoCountry( + override val _id: Uuid = Uuid.random(), + val name: String = "", +) : HasId + +@Queryable +data class DenoCity( + override val _id: Uuid = Uuid.random(), + val country: Uuid, + val name: String = "", + @Denormalized val countryName: String = "", + @Denormalized val countryNameAtCreation: String = "", +) : HasId + +@Queryable +data class DenoPerson( + override val _id: Uuid = Uuid.random(), + val city: Uuid, + @Denormalized val country: Uuid = Uuid.NIL, + @Denormalized val countryName: String = "", + val favoriteCity: Uuid? = null, + @Denormalized val favoriteCityName: String? = null, +) : HasId diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt new file mode 100644 index 000000000..0d90d29f1 --- /dev/null +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt @@ -0,0 +1,125 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.services.data.Queryable +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.optics.IdentityLens +import com.lightningkite.services.database.optics.Lens +import com.lightningkite.services.database.optics.Optic +import com.lightningkite.services.database.optics.elements +import com.lightningkite.services.database.optics.notNull +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class VetTest { + private fun Modification.vetted(path: Lens): List> = + buildList { vet(path) { add(it) } } + + private fun Modification.vettedNullable(path: Optic): List> = + buildList { vetNullable(path) { add(it) } } + + @Test + fun assign_on_the_path_is_reported() { + val mod = Modification { it.name assign "new" } + assertEquals(listOf(Modification.Assign("new")), mod.vetted(VetRoot.name)) + } + + @Test + fun other_modifications_on_the_path_are_reported_as_is() { + val mod = Modification { it.inner.value += 2 } + assertEquals(listOf(Modification.Increment(2)), mod.vetted(VetRoot.inner.value)) + } + + @Test + fun modifications_on_other_fields_are_ignored() { + val mod = Modification { + it.name assign "new" + it.inner.label assign "other" + } + assertEquals(emptyList>(), mod.vetted(VetRoot.inner.value)) + } + + @Test + fun nested_assign_on_the_path_is_reported() { + val mod = Modification { it.inner.value assign 3 } + assertEquals(listOf(Modification.Assign(3)), mod.vetted(VetRoot.inner.value)) + } + + @Test + fun assign_on_a_parent_reports_the_value_at_the_path() { + val mod = Modification { it.inner assign VetInner(value = 7, label = "seven") } + assertEquals(listOf(Modification.Assign(7)), mod.vetted(VetRoot.inner.value)) + } + + @Test + fun assign_on_the_whole_model_reports_the_value_at_the_path() { + val mod: Modification = Modification.Assign(VetRoot(name = "replaced", inner = VetInner(value = 4))) + assertEquals(listOf(Modification.Assign(4)), mod.vetted(VetRoot.inner.value)) + } + + @Test + fun every_modification_in_a_chain_is_reported_in_order() { + val mod = Modification { + it.inner.value assign 1 + it.name assign "between" + it.inner.value += 5 + } + assertEquals( + listOf(Modification.Assign(1), Modification.Increment(5)), + mod.vetted(VetRoot.inner.value), + ) + } + + @Test + fun modifications_through_a_nullable_field_are_reported() { + val mod = Modification { it.maybe.notNull.value assign 9 } + assertEquals(listOf(Modification.Assign(9)), mod.vettedNullable(VetRoot.maybe.notNull.value)) + } + + @Test + fun other_modifications_through_a_nullable_field_are_reported_as_is() { + val mod = Modification { it.maybe.notNull.value += 2 } + assertEquals>(listOf(Modification.Increment(2)), mod.vettedNullable(VetRoot.maybe.notNull.value)) + } + + @Test + fun assign_on_a_nullable_parent_reports_the_value_at_the_path() { + val mod = Modification { it.maybe assign VetInner(value = 6) } + assertEquals(listOf(Modification.Assign(6)), mod.vettedNullable(VetRoot.maybe.notNull.value)) + } + + @Test + fun assigning_null_to_a_nullable_parent_reports_null() { + val mod = Modification { it.maybe assign null } + assertEquals(listOf(Modification.Assign(null)), mod.vettedNullable(VetRoot.maybe.notNull.value)) + } + + @Test + fun an_identity_path_reports_every_part() { + val mod = Modification { + it.name assign "new" + it.inner.value += 1 + } + assertEquals((mod as Modification.Chain).modifications, mod.vetted(IdentityLens(VetRoot.serializer()))) + } + + @Test + fun collection_elements_are_rejected() { + val mod = Modification { it.tags assign listOf("a") } + assertFailsWith { mod.vettedNullable(VetRoot.tags.elements) } + } +} + +@Queryable +data class VetRoot( + val name: String = "", + val inner: VetInner = VetInner(), + val maybe: VetInner? = null, + val tags: List = listOf(), +) + +@Queryable +data class VetInner( + val value: Int = 0, + val label: String = "", +) From b4e84990f89e44e9e41a47256f72be6581428dff Mon Sep 17 00:00:00 2001 From: iHoonter Date: Wed, 4 Nov 2026 10:01:32 -0700 Subject: [PATCH 4/9] Simplified Denormalization and made ModelInfoWithDeno it's own entire constructor --- .../typed/denormalize/Denormalization.kt | 86 ++++----- .../denormalize/DenormalizationBuilder.ext.kt | 5 + .../denormalize/DenormalizationBuilder.kt | 9 +- .../typed/denormalize/ModelInfoWithDeno.kt | 172 ++++++++++++------ .../typed/denormalize/RefreshDenoEndpoints.kt | 7 + .../typed/denormalize/helpers.kt | 7 + .../typed/denormalize/DenormalizationTest.kt | 67 +++++-- 7 files changed, 233 insertions(+), 120 deletions(-) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt index b1a2d9e0d..70c763751 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt @@ -7,79 +7,63 @@ import com.lightningkite.services.database.Modification import com.lightningkite.services.database.optics.Lens import com.lightningkite.services.database.optics.Optic -/** - * Internal representation of a denormalization rule. - * Contains the logic to copy data from a referenced model into the referencing model. - */ +/** A denormalization declared with `denormalizes` on a model created by [modelInfoWithDeno]. */ public sealed interface Denormalization, RID : Comparable> { public val info: ModelInfo<*, Referenced, RID> - public val listenForChanges: Boolean + public val calculations: List> + + /** Whether a change to the referenced model must update the models that reference it. */ + public val watchesReferencedModel: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } /** - * Internal data class pairing a set of field dependencies with their calculation function. - * Used to track which fields trigger denormalization updates. + * A [calculation] that reruns when any of its [dependencies] change. * - * An empty set of dependencies means the calculation runs on create/replace/modify but does NOT - * register change listeners on the referenced model. Non-empty dependencies trigger both immediate - * denormalization and change listener registration. + * With no dependencies, it runs only when the reference is set. */ - public data class Calculation( - val dependencies: Set>, - val calculation: T, - ) + public class Calculation( + public val dependencies: Set>, + public val calculation: T, + ) { + /** Returns `true` if any of the [dependencies] differ between [old] and [new]. */ + public fun changedBetween(old: Ref, new: Ref?): Boolean = + dependencies.any { it.get(old) != new?.let(it::get) } + } - /** - * Denormalization rule for non-nullable (required) references. - */ - public data class RequiredRef, RID : Comparable>( - val reference: Lens, + /** A denormalization through a reference that is always set. */ + public class RequiredRef, RID : Comparable>( + public val reference: Lens, override val info: ModelInfo<*, Referenced, RID>, - val calculations: List Modification>>, + override val calculations: List Modification>>, ) : Denormalization { + /** Returns the modification that updates a referencing model after the referenced model changed from [old] to [new]. */ context(_: ServerRuntime) public suspend fun denormalize(old: Referenced, new: Referenced): Modification = - Modification.Chain( - calculations - .filter { calc -> - calc.dependencies.any { it.get(old) != it.get(new) } - } - .map { it.calculation(new) } - ) + Modification.Chain(calculations.filter { it.changedBetween(old, new) }.map { it.calculation(new) }) + /** Returns the modification that fills in every denormalized field from [ref]. */ context(_: ServerRuntime) public suspend fun denormalize(ref: Referenced): Modification = - Modification.Chain( - calculations.map { it.calculation(ref) } - ) - - override val listenForChanges: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } + Modification.Chain(calculations.map { it.calculation(ref) }) } - /** - * Denormalization rule for nullable (optional) references. - */ - public data class OptionalRef, RID : Comparable>( - val reference: Optic, + /** A denormalization through a reference that may be `null`. */ + public class OptionalRef, RID : Comparable>( + public val reference: Optic, override val info: ModelInfo<*, Referenced, RID>, - val calculations: List Modification>>, + override val calculations: List Modification>>, ) : Denormalization { + /** + * Returns the modification that updates a referencing model after the referenced model changed from [old] to [new]. + * + * [new] is `null` when the referenced model was deleted. + */ context(_: ServerRuntime) public suspend fun denormalize(old: Referenced, new: Referenced?): Modification = - Modification.Chain( - calculations - .filter { calc -> - calc.dependencies.any { it.get(old) != new?.let(it::get) } - } - .map { it.calculation(new) } - ) + Modification.Chain(calculations.filter { it.changedBetween(old, new) }.map { it.calculation(new) }) + /** Returns the modification that fills in every denormalized field from [ref], which is `null` when the reference is unset. */ context(_: ServerRuntime) public suspend fun denormalize(ref: Referenced?): Modification = - Modification.Chain( - calculations.map { it.calculation(ref) } - ) - - override val listenForChanges: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } + Modification.Chain(calculations.map { it.calculation(ref) }) } } - diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt index 25b4025b7..7dbbdc859 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt @@ -62,3 +62,8 @@ public infix fun , RID : Comparable, T> Optic ) } } + +// TODO: Api Recommendations +// Claude: +// - The denormalizes extensions duplicate DenormalizationBuilder.required/optional; keep one public way in. +// - Rename `set` along with `once` (see DenormalizationBuilder.kt). diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt index 8211a8046..004b4a28d 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -12,7 +12,7 @@ import com.lightningkite.services.database.optics.Optic /** * Internal builder for defining denormalization rules on a model. - * Used as the receiver in the `denormalizations` lambda of [withDenormalizations]. + * Used as the receiver in the `denormalizations` lambda of [modelInfoWithDeno]. */ @DenormalizationBuilder.DenormalizationDsl public class DenormalizationBuilder { @@ -258,3 +258,10 @@ public class DenormalizationBuilder { ) } } + +// TODO: Api Recommendations +// Claude: +// - Shrink the public surface before release: registerDenormalization, required/optional, build(), and the builders' reference/info can be @PublishedApi internal or internal. +// - Two ideas, four verbs: bind/watch keep a field in sync, set/once copy it when the reference is set. Neither `set` (reads like assignment, clashes with Optic.set) nor `once` (its own doc calls it misleading) says "not kept in sync". Consider one name, e.g. `snapshot`, for both copy forms. +// - Doc examples should make the difference between the path parameter (`{ collection -> ... }`) and the referenced value (`it`) obvious. +// - requireSourceOfTruth only sees declared dependencies; a watch/once body can still read a @Denormalized field unnoticed. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt index e04de89a8..977426c6f 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -1,20 +1,29 @@ package com.lightningkite.lightningserver.typed.denormalize +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.auth.Subscope +import com.lightningkite.lightningserver.definition.Runtime import com.lightningkite.lightningserver.definition.StartupTask import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.runtime.ServerRuntime import com.lightningkite.lightningserver.typed.AuthAccess +import com.lightningkite.lightningserver.serialization.serializerOrContextual import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.lightningserver.typed.explicitModelInfo +import com.lightningkite.lightningserver.typed.modelInfo import com.lightningkite.services.database.HasId import com.lightningkite.services.database.Table import com.lightningkite.services.database.optics.IdentityLens import com.lightningkite.services.database.optics.Lens import com.lightningkite.lightningserver.typed.getOrBadRequest import com.lightningkite.services.database.Condition +import com.lightningkite.services.database.Database +import com.lightningkite.services.database.ModelPermissions import com.lightningkite.services.database.Modification import com.lightningkite.services.database.interceptCreate import com.lightningkite.services.database.interceptModification import com.lightningkite.services.database.interceptReplace +import kotlinx.serialization.KSerializer import java.util.concurrent.atomic.AtomicBoolean public interface ModelInfoWithDeno?, T : HasId, ID : Comparable> : ModelInfo { @@ -31,16 +40,12 @@ public interface ModelInfoWithDeno?, T : HasId, ID : Compara } /** - * Adds denormalization support to a [ModelInfo] + * Creates a [ModelInfo] like [modelInfo] whose table also copies data from the models it references. * - * This is the primary entry point for defining models that denormalize data from referenced models. - * Use this instead of the standard `modelInfo()` when you need to copy data from referenced models - * to avoid expensive joins or enable efficient permission checks. - * - * **How denormalization works:** - * - On create/replace: Fetches referenced models and copies specified fields - * - On modify: Detects reference changes and updates denormalized fields - * - On referenced model change: Automatically updates all referencing models (if listenForChanges = true) + * Each denormalization is declared on a reference field with `denormalizes`: + * - On create and replace, it fetches the referenced model and fills in the denormalized fields. + * - On a modification that changes the reference, it recalculates them. + * - With `bind` or `watch`, a change to the referenced model updates every model that references it. * * Denormalizations read from the source of truth only. Reading a field the referenced model marks `@Denormalized` * throws when the denormalizations are built. To reach a model two references away, denormalize the intermediate @@ -50,15 +55,22 @@ public interface ModelInfoWithDeno?, T : HasId, ID : Compara * a.c.denormalizes(C.info) { c -> a.cName bind c.name } * ``` * - * Fields written by `bind` or `set` must be marked `@Denormalized`. + * Fields written by `bind` or `set` must be marked `@Denormalized`. Mark them `cannotBeModified()` in the update + * restrictions too, so callers can't write them; the denormalizations still can. The caller chooses the reference, + * so a denormalized field shows the referenced model's value to anyone who can read this model. * * Example: * ```kotlin - * val announcementInfo = Server.database.modelInfo( + * val announcementInfo = Server.database.modelInfoWithDeno( * auth = UserAuth.require(), * tableName = "Announcement", - * permissions = { permissions(auth) }, - * ).withDenormalizations { announcement -> + * permissions = { + * permissions(auth).withAdditionalUpdateRestrictions { + * it.courseProvider.cannotBeModified() + * it.courseTitle.cannotBeModified() + * } + * }, + * ) { announcement -> * announcement.course.denormalizes(CourseEndpoints.info) { course -> * // Kept in sync: updates whenever Course.providerName changes * announcement.courseProvider bind course.providerName @@ -68,60 +80,96 @@ public interface ModelInfoWithDeno?, T : HasId, ID : Compara * } * } * ``` - * - * **Important:** Remember to mark denormalized fields as `cannotBeModified()` in your update restrictions: - * ```kotlin - * updateRestrictions = blacklistRestrictions { - * it.courseProvider.cannotBeModified() // denormalized field - * } - * ``` */ context(builder: ServerBuilder) -public fun ?, T : HasId, ID : Comparable> ModelInfo.withDenormalizations( - denormalizations: DenormalizationBuilder.(Lens) -> Unit, -): ModelInfoWithDeno = - object : ModelInfoWithDeno, ModelInfo by this@withDenormalizations { - override val denormalizations: List> by lazy { // lazy so that we don't run into initialization order issues when declaring modelInfo - DenormalizationBuilder().apply { denormalizations(IdentityLens(serializer)) }.denormalizations - } - - context(server: ServerRuntime) - private fun wrapWithDeno(table: Table): Table = - // Claude: foldRight so the first declared denormalization intercepts first; later ones read the references it sets. - this.denormalizations.foldRight(table) { deno, t -> - when (deno) { - is Denormalization.RequiredRef -> t.denormalizeImpl(deno) - is Denormalization.OptionalRef -> t.denormalizeNullableImpl(deno) - } - } - - private val wraps = this@withDenormalizations +public inline fun ?, reified T : HasId, reified ID : Comparable> Runtime.modelInfoWithDeno( + auth: AuthRequirement, + tableName: String, + subscope: Subscope? = Subscope(tableName.lowercase()), + noinline signals: context(ServerRuntime) (Table) -> Table = { it }, + noinline log: context(ServerRuntime) AuthAccess?.(Table) -> Table = { it }, + noinline systemAccess: context(ServerRuntime) (Table) -> Table = { it }, + noinline postPermissionsForUser: suspend context(ServerRuntime) AuthAccess.(Table) -> Table = { it }, + noinline permissions: suspend context(ServerRuntime) AuthAccess.() -> ModelPermissions, + noinline prePermissionsForUser: suspend context(ServerRuntime) AuthAccess.(Table) -> Table = { it }, + noinline denormalizations: DenormalizationBuilder.(Lens) -> Unit, +): ModelInfoWithDeno = + explicitModelInfoWithDeno( + auth = auth, + serializer = serializerOrContextual(), + idSerializer = serializerOrContextual(), + tableName = tableName, + subscope = subscope, + signals = signals, + log = log, + systemAccess = systemAccess, + postPermissionsForUser = postPermissionsForUser, + permissions = permissions, + prePermissionsForUser = prePermissionsForUser, + denormalizations = denormalizations, + ) - context(server: ServerRuntime) - override fun baseTableWithDenormalizations(): Table = wrapWithDeno(baseTable()) - - private val listening = AtomicBoolean(false) +/** Creates a [ModelInfoWithDeno] like [modelInfoWithDeno], using the given [serializer] and [idSerializer]. */ +context(builder: ServerBuilder) +public fun ?, T : HasId, ID : Comparable> Runtime.explicitModelInfoWithDeno( + auth: AuthRequirement, + serializer: KSerializer, + idSerializer: KSerializer, + tableName: String, + subscope: Subscope? = Subscope(tableName.lowercase()), + signals: context(ServerRuntime) (Table) -> Table = { it }, + log: context(ServerRuntime) AuthAccess?.(Table) -> Table = { it }, + systemAccess: context(ServerRuntime) (Table) -> Table = { it }, + postPermissionsForUser: suspend context(ServerRuntime) AuthAccess.(Table) -> Table = { it }, + permissions: suspend context(ServerRuntime) AuthAccess.() -> ModelPermissions, + prePermissionsForUser: suspend context(ServerRuntime) AuthAccess.(Table) -> Table = { it }, + denormalizations: DenormalizationBuilder.(Lens) -> Unit, +): ModelInfoWithDeno { + // Claude: lazy so that models can reference each other's ModelInfo regardless of declaration order. + val built = lazy { DenormalizationBuilder().apply { denormalizations(IdentityLens(serializer)) }.denormalizations } + val info = explicitModelInfo( + auth = auth, + serializer = serializer, + idSerializer = idSerializer, + tableName = tableName, + subscope = subscope, + // Claude: the signals slot is inside permissions, so they judge only the caller's modification, and outside the change listeners, so those see the denormalized fields. + signals = { table -> signals(table).applyDenormalizations(built.value) }, + log = log, + systemAccess = systemAccess, + postPermissionsForUser = postPermissionsForUser, + permissions = permissions, + prePermissionsForUser = prePermissionsForUser, + ) + val modelInfo = object : ModelInfoWithDeno, ModelInfo by info { + override val denormalizations: List> by built context(server: ServerRuntime) - override suspend fun table(auth: AuthAccess): Table = wrapWithDeno(wraps.table(auth)) + override fun baseTableWithDenormalizations(): Table = baseTable().applyDenormalizations(built.value) + } - context(server: ServerRuntime) - override fun table(): Table = wrapWithDeno(wraps.table()) - - init { - val modelInfo = this - with(builder) { - builder.path.path("$tableName-deno") bind StartupTask { - // Claude: listeners live on the ModelInfo, which can outlive the engine, so a second engine in the same process (as in tests) must not add them again. - if (!listening.compareAndSet(false, true)) return@StartupTask - for (d in modelInfo.denormalizations) { - if (d.listenForChanges) d.listenForDenormalizations { modelInfo.baseTableWithDenormalizations() } - } - } + val listening = AtomicBoolean(false) + with(builder) { + path.path("$tableName-deno") bind StartupTask { + // Claude: listeners live on the ModelInfo, which can outlive the engine, so a second engine in the same process (as in tests) must not add them again. + if (!listening.compareAndSet(false, true)) return@StartupTask + for (d in modelInfo.denormalizations) { + if (d.watchesReferencedModel) d.listenForDenormalizations { modelInfo.baseTableWithDenormalizations() } } } } + return modelInfo +} +context(_: ServerRuntime) +private fun Table.applyDenormalizations(denormalizations: List>): Table = + // Claude: foldRight so the first declared denormalization intercepts first; later ones read the references it sets. + denormalizations.foldRight(this) { deno, table -> + when (deno) { + is Denormalization.RequiredRef -> table.denormalizeImpl(deno) + is Denormalization.OptionalRef -> table.denormalizeNullableImpl(deno) + } + } private fun , RID : Comparable> Denormalization.listenForDenormalizations( table: context(ServerRuntime) () -> Table, @@ -238,3 +286,13 @@ private fun , RID : Comparable> Table< } updatedMod } + +// TODO: Api Recommendations +// Claude: +// - Deleting a row that a required reference points to leaves the referencing rows pointing at nothing with stale values. Pick an explicit policy: block, cascade, or document. +// - Listener updates run inside the request that changed the referenced row. Dispatch them as a Task so a popular row's change doesn't slow or partially fail that request, and so they can retry. +// - Nothing ensures reference fields are indexed; every listener write is updateMany(reference == id). Declare the index, or check for one at startup. +// - insertMany fetches the referenced row once per row per denormalization; fetch each distinct id once. +// - Document that writes skipping ModelInfo.table() (baseTable(), migrations, other services) never propagate, and that a row created while its reference is changing can keep the old value; refresh is the repair for both. +// - Names: spell out "Deno" (ModelInfoWithDeno, modelInfoWithDeno, the "$tableName-deno" startup path), e.g. DenormalizedModelInfo. +// - Once polished, consider merging into modelInfo as a denormalizations parameter with denormalizations on ModelInfo, removing ModelInfoWithDeno. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt index 2a5acb78a..a1fa92df0 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt @@ -103,3 +103,10 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab } ) } + +// TODO: Api Recommendations +// Claude: +// - Refresh runs every calculation, so it overwrites set/once values with the referenced model's current values. Skip calculations with no dependencies. +// - refreshAll fetches the referenced row once per row per denormalization; fetch each distinct id once. +// - refreshAll is a single HTTP request over the whole table, so it will time out on large tables, and one missing required reference aborts the run (getOrThrow). Run it as a Task that skips and reports bad rows. +// - Rename to spell out "Deno", e.g. DenormalizationRefreshEndpoints. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt index 2d8e4911d..53c00749d 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt @@ -80,3 +80,10 @@ internal fun requireMarkedDenormalized(target: Optic<*, *>) { "$target is written by a denormalization, so it must be marked @Denormalized." } } + +// TODO: Api Recommendations +// Claude: +// - vetNullable is a placeholder name; settle it before vet/vetNullable go public in service-abstractions. +// - When moving vet/vetNullable to service-abstractions, deprecate the list-based vet(fieldChain: List), which has the same fields-walking bugs and the null-parent crash. vet(field: Field) behaves the same as vet(Lens) and could be deprecated too. +// - Rejecting asType and SealedSharedFieldLens steps in vetAny is untested; it needs a sealed @Queryable model. +// - requireSourceOfTruth and requireMarkedDenormalized scan path.fields, so they can't see through a SealedSharedFieldLens. diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt index 9304af322..33c2347fa 100644 --- a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -1,6 +1,7 @@ package com.lightningkite.lightningserver.typed.denormalize import com.lightningkite.lightningserver.BadRequestException +import com.lightningkite.lightningserver.NotFoundException import com.lightningkite.lightningserver.auth.noAuth import com.lightningkite.lightningserver.definition.GeneralServerSettings import com.lightningkite.lightningserver.definition.builder.ServerBuilder @@ -12,7 +13,9 @@ import com.lightningkite.lightningserver.runtime.test.testBlocking import com.lightningkite.lightningserver.serialization.registerBasicMediaTypeCoders import com.lightningkite.lightningserver.settings.set import com.lightningkite.lightningserver.settings.setStatic +import com.lightningkite.lightningserver.typed.ModelRestEndpoints import com.lightningkite.lightningserver.typed.modelInfo +import com.lightningkite.lightningserver.typed.test import com.lightningkite.services.data.Denormalized import com.lightningkite.services.data.Queryable import com.lightningkite.services.database.* @@ -33,22 +36,28 @@ class DenormalizationTest { permissions = { ModelPermissions.allowAll() }, ) - val cityInfo = database.modelInfo?, DenoCity, Uuid>( + val cityInfo = database.modelInfoWithDeno?, DenoCity, Uuid>( auth = noAuth, tableName = "DenoCity", permissions = { ModelPermissions.allowAll() }, - ).withDenormalizations { city -> + ) { city -> city.country.denormalizes(countryInfo) { country -> city.countryName bind country.name city.countryNameAtCreation set country.name } } - val personInfo = database.modelInfo?, DenoPerson, Uuid>( + val personInfo = database.modelInfoWithDeno?, DenoPerson, Uuid>( auth = noAuth, tableName = "DenoPerson", - permissions = { ModelPermissions.allowAll() }, - ).withDenormalizations { person -> + permissions = { + ModelPermissions.allowAll().withAdditionalUpdateRestrictions { person -> + person.country.cannotBeModified() + person.countryName.cannotBeModified() + person.favoriteCityName.cannotBeModified() + } + }, + ) { person -> person.city.denormalizes(cityInfo) { city -> person.country bind city.country } @@ -61,26 +70,27 @@ class DenormalizationTest { } val personRefresh = path.path("person-deno") include RefreshDenoEndpoints(personInfo) + val personRest = path.path("people") include ModelRestEndpoints(personInfo) } object MisconfiguredServer : ServerBuilder() { val database = setting("database", Database.Settings()) - val readsACopy = database.modelInfo?, DenoPerson, Uuid>( + val readsACopy = database.modelInfoWithDeno?, DenoPerson, Uuid>( auth = noAuth, tableName = "ReadsACopyPerson", permissions = { ModelPermissions.allowAll() }, - ).withDenormalizations { person -> + ) { person -> person.city.denormalizes(DenoServer.cityInfo) { city -> person.countryName bind city.countryName } } - val writesAnUnmarkedField = database.modelInfo?, DenoCity, Uuid>( + val writesAnUnmarkedField = database.modelInfoWithDeno?, DenoCity, Uuid>( auth = noAuth, tableName = "UnmarkedCity", permissions = { ModelPermissions.allowAll() }, - ).withDenormalizations { city -> + ) { city -> city.country.denormalizes(DenoServer.countryInfo) { country -> city.name bind country.name } @@ -170,6 +180,41 @@ class DenormalizationTest { } } + @Test + fun client_reference_change_updates_restricted_denormalized_fields() = denoTest { + val france = DenoCountry(name = "France") + val spain = DenoCountry(name = "Spain") + val paris = DenoCity(country = france._id, name = "Paris") + val madrid = DenoCity(country = spain._id, name = "Madrid") + val person = DenoPerson(city = paris._id) + execute { + countryInfo.table().insertMany(listOf(france, spain)) + cityInfo.table().insertMany(listOf(paris, madrid)) + personInfo.table().insertOne(person) + } + + val updated = personRest.modify.test(person._id, null, Modification { it.city assign madrid._id }) + + assertEquals("Spain", updated.countryName) + } + + @Test + fun clients_cannot_write_restricted_denormalized_fields() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val person = DenoPerson(city = paris._id) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + personInfo.table().insertOne(person) + } + + assertFailsWith { + personRest.modify.test(person._id, null, Modification { it.countryName assign "forged" }) + } + execute { assertEquals("France", personInfo.table().get(person._id)!!.countryName) } + } + @Test fun reading_a_denormalized_field_fails_when_built() { val error = assertFailsWith { MisconfiguredServer.readsACopy.denormalizations } @@ -204,8 +249,8 @@ class DenormalizationTest { val madrid = DenoCity(country = spain._id, name = "Madrid") val person = DenoPerson(city = paris._id) execute { - countryInfo.table().insertMany(listOf(france, spain)) - cityInfo.table().insertMany(listOf(paris, madrid)) + countryInfo.table().insert(listOf(france, spain)) + cityInfo.table().insert(listOf(paris, madrid)) personInfo.table().insertOne(person) personInfo.table().updateOneById(person._id, Modification { it.city assign madrid._id }) } From 3822927c69bc94f08431a880f4ad9989c9ad9ecc Mon Sep 17 00:00:00 2001 From: iHoonter Date: Wed, 4 Nov 2026 11:39:41 -0700 Subject: [PATCH 5/9] More Denormalization simplifications --- .../typed/denormalize/Denormalization.kt | 57 +++++++----------- .../denormalize/DenormalizationBuilder.kt | 6 +- .../typed/denormalize/ModelInfoWithDeno.kt | 60 ++++++++----------- .../typed/denormalize/RefreshDenoEndpoints.kt | 33 +++++----- 4 files changed, 66 insertions(+), 90 deletions(-) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt index 70c763751..fb27025cb 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt @@ -7,10 +7,14 @@ import com.lightningkite.services.database.Modification import com.lightningkite.services.database.optics.Lens import com.lightningkite.services.database.optics.Optic -/** A denormalization declared with `denormalizes` on a model created by [modelInfoWithDeno]. */ -public sealed interface Denormalization, RID : Comparable> { +/** + * A denormalization declared with `denormalizes` on a model created by [modelInfoWithDeno]. + * + * [Input] is what the calculations receive: [Referenced] for a [RequiredRef], or `Referenced?` for an [OptionalRef]. + */ +public sealed interface Denormalization, RID : Comparable, Input : Referenced?> { public val info: ModelInfo<*, Referenced, RID> - public val calculations: List> + public val calculations: List> /** Whether a change to the referenced model must update the models that reference it. */ public val watchesReferencedModel: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } @@ -20,50 +24,33 @@ public sealed interface Denormalization, RI * * With no dependencies, it runs only when the reference is set. */ - public class Calculation( + public class Calculation( public val dependencies: Set>, - public val calculation: T, + public val calculation: suspend context(ServerRuntime) (Input) -> Modification, ) { - /** Returns `true` if any of the [dependencies] differ between [old] and [new]. */ - public fun changedBetween(old: Ref, new: Ref?): Boolean = + public fun dependenciesChanged(old: Ref, new: Input): Boolean = dependencies.any { it.get(old) != new?.let(it::get) } } + context(_: ServerRuntime) + public suspend fun updateDenormalizations(old: Referenced, new: Input): Modification = + Modification.Chain(calculations.filter { it.dependenciesChanged(old, new) }.map { it.calculation(new) }) + + context(_: ServerRuntime) + public suspend fun setDenormalizations(ref: Input): Modification = + Modification.Chain(calculations.map { it.calculation(ref) }) + /** A denormalization through a reference that is always set. */ public class RequiredRef, RID : Comparable>( public val reference: Lens, override val info: ModelInfo<*, Referenced, RID>, - override val calculations: List Modification>>, - ) : Denormalization { - /** Returns the modification that updates a referencing model after the referenced model changed from [old] to [new]. */ - context(_: ServerRuntime) - public suspend fun denormalize(old: Referenced, new: Referenced): Modification = - Modification.Chain(calculations.filter { it.changedBetween(old, new) }.map { it.calculation(new) }) - - /** Returns the modification that fills in every denormalized field from [ref]. */ - context(_: ServerRuntime) - public suspend fun denormalize(ref: Referenced): Modification = - Modification.Chain(calculations.map { it.calculation(ref) }) - } + override val calculations: List> + ) : Denormalization /** A denormalization through a reference that may be `null`. */ public class OptionalRef, RID : Comparable>( public val reference: Optic, override val info: ModelInfo<*, Referenced, RID>, - override val calculations: List Modification>>, - ) : Denormalization { - /** - * Returns the modification that updates a referencing model after the referenced model changed from [old] to [new]. - * - * [new] is `null` when the referenced model was deleted. - */ - context(_: ServerRuntime) - public suspend fun denormalize(old: Referenced, new: Referenced?): Modification = - Modification.Chain(calculations.filter { it.changedBetween(old, new) }.map { it.calculation(new) }) - - /** Returns the modification that fills in every denormalized field from [ref], which is `null` when the reference is unset. */ - context(_: ServerRuntime) - public suspend fun denormalize(ref: Referenced?): Modification = - Modification.Chain(calculations.map { it.calculation(ref) }) - } + override val calculations: List> + ) : Denormalization } diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt index 004b4a28d..b2eee6176 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -39,7 +39,7 @@ public class DenormalizationBuilder { public val info: ModelInfo<*, Referenced, RID>, ) { private val list = - ArrayList Modification>>() + ArrayList>() /** * Low-level method to register a dependency-based calculation. @@ -161,7 +161,7 @@ public class DenormalizationBuilder { public val reference: Optic, public val info: ModelInfo<*, Referenced, RID>, ) { - private val list: ArrayList Modification>> = + private val list: ArrayList> = ArrayList() /** @@ -224,7 +224,7 @@ public class DenormalizationBuilder { } @PublishedApi - internal val denormalizations: ArrayList> = ArrayList() + internal val denormalizations: ArrayList> = ArrayList() /** * Register a required (non-nullable) reference denormalization. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt index 977426c6f..2e11326b9 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -27,7 +27,7 @@ import kotlinx.serialization.KSerializer import java.util.concurrent.atomic.AtomicBoolean public interface ModelInfoWithDeno?, T : HasId, ID : Comparable> : ModelInfo { - public val denormalizations: List> + public val denormalizations: List> /** * Returns [baseTable] with this model's [denormalizations] applied, so a write that changes a reference also @@ -142,7 +142,7 @@ public fun ?, T : HasId, ID : Comparable> Runtime, ModelInfo by info { - override val denormalizations: List> by built + override val denormalizations: List> by built context(server: ServerRuntime) override fun baseTableWithDenormalizations(): Table = baseTable().applyDenormalizations(built.value) @@ -154,7 +154,11 @@ public fun ?, T : HasId, ID : Comparable> Runtime -> d.listenForDenormalizations { modelInfo.baseTableWithDenormalizations() } + is Denormalization.OptionalRef -> d.listenForDenormalizations { modelInfo.baseTableWithDenormalizations() } + } } } } @@ -162,7 +166,7 @@ public fun ?, T : HasId, ID : Comparable> Runtime Table.applyDenormalizations(denormalizations: List>): Table = +private fun Table.applyDenormalizations(denormalizations: List>): Table = // Claude: foldRight so the first declared denormalization intercepts first; later ones read the references it sets. denormalizations.foldRight(this) { deno, table -> when (deno) { @@ -171,39 +175,27 @@ private fun Table.applyDenormalizations(denormalizations: List, RID : Comparable> Denormalization.listenForDenormalizations( +private fun , RID : Comparable> Denormalization.RequiredRef.listenForDenormalizations( table: context(ServerRuntime) () -> Table, ) { info.registerChangeListener { changes -> for ((old, new) in changes.changes) { - if (old != null) updateReferencing(table(), old, new) + if (old == null || new == null) continue + val mod = updateDenormalizations(old, new) + if (!mod.isNothing) table().updateManyIgnoringResult(reference.mapCondition(Condition.Equal(old._id)), mod) } } } -context(_: ServerRuntime) -private suspend fun , RID : Comparable> Denormalization.updateReferencing( - table: Table, - old: Ref, - new: Ref?, +private fun , RID : Comparable> Denormalization.OptionalRef.listenForDenormalizations( + table: context(ServerRuntime) () -> Table, ) { - when (this) { - is Denormalization.RequiredRef -> { - if (new == null) return - val mod = denormalize(old, new) - if (mod.isNothing) return - table.updateManyIgnoringResult(reference.mapCondition(Condition.Equal(old._id)), mod) - } - - is Denormalization.OptionalRef -> { - val mod = denormalize(old, new) - val removeRef = - if (new == null) reference.mapModification( // model is deleted, remove reference - Modification.Assign(null) - ) - else null - - if (!mod.isNothing || removeRef != null) table.updateManyIgnoringResult( + info.registerChangeListener { changes -> + for ((old, new) in changes.changes) { + if (old == null) continue + val mod = updateDenormalizations(old, new) + val removeRef = if (new == null) reference.mapModification(Modification.Assign(null)) else null + if (!mod.isNothing || removeRef != null) table().updateManyIgnoringResult( reference.mapCondition(Condition.Equal(old._id)), Modification.Chain(listOfNotNull(removeRef, mod)) ) @@ -221,11 +213,11 @@ private fun , RID : Comparable> Table< ): Table = this .interceptCreate { model -> val reference = deno.info.table().getOrBadRequest(deno.reference.get(model)) - deno.denormalize(reference).invoke(model) + deno.setDenormalizations(reference).invoke(model) } .interceptReplace { model -> val reference = deno.info.table().getOrBadRequest(deno.reference.get(model)) - deno.denormalize(reference).invoke(model) + deno.setDenormalizations(reference).invoke(model) } .interceptModification { incomingMod -> var updatedMod = incomingMod @@ -242,7 +234,7 @@ private fun , RID : Comparable> Table< if (newReference != null) { val source = deno.info.table().getOrBadRequest(newReference) updatedMod = Modification.Chain( - listOf(incomingMod, deno.denormalize(source)) + listOf(incomingMod, deno.setDenormalizations(source)) ) } updatedMod @@ -258,11 +250,11 @@ private fun , RID : Comparable> Table< ): Table = this .interceptCreate { model -> val reference = deno.reference.get(model)?.let { deno.info.table().getOrBadRequest(it) } - deno.denormalize(reference).invoke(model) + deno.setDenormalizations(reference).invoke(model) } .interceptReplace { model -> val reference = deno.reference.get(model)?.let { deno.info.table().getOrBadRequest(it) } - deno.denormalize(reference).invoke(model) + deno.setDenormalizations(reference).invoke(model) } .interceptModification { incomingMod -> var updatedMod = incomingMod @@ -281,7 +273,7 @@ private fun , RID : Comparable> Table< if (changed) { val source = newReference?.let { deno.info.table().getOrBadRequest(it) } updatedMod = Modification.Chain( - listOf(incomingMod, deno.denormalize(source)) + listOf(incomingMod, deno.setDenormalizations(source)) ) } updatedMod diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt index a1fa92df0..068735316 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt @@ -29,26 +29,23 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab private val info: ModelInfoWithDeno ) : ServerBuilder() { context(_: ServerRuntime) - private suspend fun , RID : Comparable> Denormalization.modification( + private suspend fun , RID : Comparable> Denormalization.RequiredRef.modification( model: T - ): Modification = when (val deno = this) { - is Denormalization.OptionalRef -> { - val ref = deno.reference.get(model) - val referenced = ref?.let { deno.info.table().getOrThrow(it) } - val mod = deno.denormalize(referenced) + ): Modification = setDenormalizations(info.table().getOrThrow(reference.get(model))) - if (mod(model) == model) Modification.Nothing() - else mod - } - - is Denormalization.RequiredRef -> { - val referenced = deno.info.table().getOrThrow(deno.reference.get(model)) - val mod = deno.denormalize(referenced) + context(_: ServerRuntime) + private suspend fun , RID : Comparable> Denormalization.OptionalRef.modification( + model: T + ): Modification = setDenormalizations(reference.get(model)?.let { info.table().getOrThrow(it) }) - if (mod(model) == model) Modification.Nothing() - else mod + context(_: ServerRuntime) + private suspend fun refresh(model: T): Modification = Modification.Chain(info.denormalizations.map { deno -> + val mod = when (deno) { + is Denormalization.RequiredRef -> deno.modification(model) + is Denormalization.OptionalRef -> deno.modification(model) } - } + if (mod(model) == model) Modification.Nothing() else mod + }) public val refreshDetail: ApiHttpHandler, HasId<*>, Unit, Modification> = path.arg(PathSpec.Segment.Wildcard("id", info.idSerializer)).post bind explicitApiHttpHandler( @@ -59,7 +56,7 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab auth = AuthRequirement.IsAdmin, implementation = { val model = info.table().getOrNotFound(request.arg1) - val mod = Modification.Chain(info.denormalizations.map { it.modification(model) }) + val mod = refresh(model) if (!mod.isNothing) info.baseTableWithDenormalizations().updateOneByIdIgnoringResult(model._id, mod) mod } @@ -73,7 +70,7 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab // The write pass runs after the read finishes so updates never race the cursor feeding them. val mods = LinkedHashMap>() info.table().all().collect { model -> - val mod = Modification.Chain(info.denormalizations.map { it.modification(model) }) + val mod = refresh(model) if (!mod.isNothing) mods[model._id] = mod } From ad268f7e4b2d0d3ddbe3789a67f3087ab887eea6 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Wed, 4 Nov 2026 12:16:47 -0700 Subject: [PATCH 6/9] reduced denormalization public api --- .../denormalize/DenormalizationBuilder.ext.kt | 21 ++- .../denormalize/DenormalizationBuilder.kt | 129 +++++------------- .../typed/denormalize/ModelInfoWithDeno.kt | 14 +- .../typed/denormalize/RefreshDenoEndpoints.kt | 2 +- .../typed/denormalize/helpers.kt | 2 +- .../typed/denormalize/DenormalizationTest.kt | 22 +-- 6 files changed, 67 insertions(+), 123 deletions(-) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt index 7dbbdc859..1de808929 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt @@ -11,7 +11,7 @@ public inline fun , RID : Comparable> Lens, build: DenormalizationBuilder.RequiredRefBuilder.(Lens) -> Unit, ): Unit = - builder.required(this, info, build) + builder.addRequiredRef(this, info, build) @JvmName("denormalizesNullable") context(builder: DenormalizationBuilder) @@ -19,10 +19,11 @@ public inline fun , RID : Comparable> Optic, build: DenormalizationBuilder.OptionalRefBuilder.(Optic) -> Unit, ): Unit = - builder.optional(this, info, build) + builder.addOptionalRef(this, info, build) +/** Keeps this field equal to [ref] on the referenced model, updating it whenever [ref] changes. */ context(builder: DenormalizationBuilder.RequiredRefBuilder) -public infix fun , RID : Comparable, T> Optic.bind(ref: Lens) { +public infix fun , RID : Comparable, T> Optic.watch(ref: Lens) { requireMarkedDenormalized(this) builder.registerDenormalization(setOf(ref)) { reference -> this.mapModification( @@ -31,8 +32,9 @@ public infix fun , RID : Comparable, T> Optic } } +/** Copies [ref] from the referenced model into this field whenever the reference is set, without following later changes to [ref]. */ context(builder: DenormalizationBuilder.RequiredRefBuilder) -public infix fun , RID : Comparable, T> Optic.set(ref: Lens) { +public infix fun , RID : Comparable, T> Optic.snapshot(ref: Lens) { requireMarkedDenormalized(this) requireSourceOfTruth(ref) builder.registerDenormalization(emptySet()) { reference -> @@ -42,8 +44,9 @@ public infix fun , RID : Comparable, T> Optic } } +/** Keeps this field equal to [ref] on the referenced model, updating it whenever [ref] changes. It is `null` while the reference is unset. */ context(builder: DenormalizationBuilder.OptionalRefBuilder) -public infix fun , RID : Comparable, T> Optic.bind(ref: Optic) { +public infix fun , RID : Comparable, T> Optic.watch(ref: Optic) { requireMarkedDenormalized(this) builder.registerDenormalization(setOf(ref)) { reference -> this.mapModification( @@ -52,8 +55,9 @@ public infix fun , RID : Comparable, T> Optic } } +/** Copies [ref] from the referenced model into this field whenever the reference is set, without following later changes to [ref]. It is `null` while the reference is unset. */ context(builder: DenormalizationBuilder.OptionalRefBuilder) -public infix fun , RID : Comparable, T> Optic.set(ref: Optic) { +public infix fun , RID : Comparable, T> Optic.snapshot(ref: Optic) { requireMarkedDenormalized(this) requireSourceOfTruth(ref) builder.registerDenormalization(emptySet()) { reference -> @@ -62,8 +66,3 @@ public infix fun , RID : Comparable, T> Optic ) } } - -// TODO: Api Recommendations -// Claude: -// - The denormalizes extensions duplicate DenormalizationBuilder.required/optional; keep one public way in. -// - Rename `set` along with `once` (see DenormalizationBuilder.kt). diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt index b2eee6176..7ccee034d 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -24,14 +24,11 @@ public class DenormalizationBuilder { /** - * Builder context for defining denormalization rules for a required (non-nullable) reference. - * This is the receiver of the lambda passed to [denormalizes] for non-nullable references. + * The receiver of [denormalizes] for a reference that is always set. * - * Common methods: - * - [bind] - Simple field copy that watches for changes in the source field - * - [set] - Simple field copy WITHOUT watching for changes (lighter weight) - * - [watch] - Watch specific dependencies and perform calculations when they change - * - [once] - Perform calculations without watching for changes in the referenced model + * [watch] keeps fields in sync with the referenced model. [snapshot] copies them when the reference is set and + * ignores later changes to the referenced model. Both have an infix form for a single field and a block form for + * custom calculations. */ @DenormalizationDsl public class RequiredRefBuilder, RID : Comparable>( @@ -42,10 +39,12 @@ public class DenormalizationBuilder { ArrayList>() /** - * Low-level method to register a dependency-based calculation. - * Use [watch], [bind], [set], or [once] instead for most use cases. + * Registers a [calculation] that reruns when any of the [dependencies] change. + * + * Prefer [watch] or [snapshot], which also build the modification for you. */ - public fun registerDenormalization( + @PublishedApi + internal fun registerDenormalization( dependencies: Set>, calculation: suspend context(ServerRuntime) (Referenced) -> Modification, ) { @@ -54,31 +53,20 @@ public class DenormalizationBuilder { } /** - * Watch specific fields on the referenced model and perform calculations when they change. + * Runs [calculation] when the reference is set and again whenever any of the [dependencies] change on the + * referenced model. * - * Use this when you need to: - * - Perform calculations based on the referenced data - * - Watch multiple dependencies for the same calculation - * - Fetch additional data from other tables + * [calculation] receives the referenced model and writes the denormalized fields. In the example, `collection` + * is a path into the referenced model, used to name dependencies, and `it` is the referenced model itself. * - * Example: * ```kotlin * material.collection.denormalizes(MaterialCollection.info) { collection -> - * // Only update when the submitted field changes - * watch(collection.submitted) { - * material.submittedAt assign it.submitted?.timestamp - * } - * - * // Fetch additional data when reviewCycle changes * watch(collection.reviewCycle) { * val cycle = ReviewCycle.info.table().getOrBadRequest(it.reviewCycle) * material.reviewCycleEndAt assign cycle.timeframe.endDate * } * } * ``` - * - * @param dependencies One or more fields to watch on the referenced model - * @param calculation Lambda to create a denormalization modification based on the referenced model */ public inline fun watch( dependencies: Set>, @@ -95,45 +83,18 @@ public class DenormalizationBuilder { ): Unit = watch(setOf(dependency), calculation) /** - * Denormalize data from the referenced model without watching for changes in the referenced model. - * - * Unlike [watch], once calculations run whenever the reference is set (create, replace, modify) - * but do NOT listen for changes in the referenced model itself. This means the denormalized data - * will only update when you change which model you're referencing, not when that referenced model changes. + * Runs [calculation] whenever the reference is set, on create, replace, or a modification that changes it. * - * **When it runs:** - * - On create: Yes - * - On replace: Yes - * - On modify (when reference changes): Yes - * - When referenced model changes: **No** (this is the key difference from watch) + * Unlike [watch], later changes to the referenced model are not copied, so the fields keep the values from + * when the reference was set. * - * Use this when you want to: - * - Copy data from a reference without the overhead of change listeners - * - Denormalize fields that don't need to stay in sync with the source - * - Reduce database load by avoiding reactive updates - * - * **Note:** The name "once" is somewhat misleading - it actually runs on create, replace, and modify. - * The key distinction is that it doesn't watch for changes in the referenced model. - * - * Example: * ```kotlin - * material.collection.denormalizes(MaterialCollection.info) { collection -> - * // Updates whenever material.collection reference changes, but not when - * // the MaterialCollection itself is modified - * once { - * material.collectionName assign it.name - * } - * - * // For comparison: this DOES update when the MaterialCollection.status changes - * watch(collection.status) { - * material.currentStatus assign it.status - * } + * material.collection.denormalizes(MaterialCollection.info) { + * snapshot { material.collectionNameWhenAdded assign it.name } * } * ``` - * - * @param calculation Lambda to create a denormalization modification based on the referenced model */ - public inline fun once( + public inline fun snapshot( crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced) -> Unit, ) { registerDenormalization(emptySet()) { @@ -145,16 +106,9 @@ public class DenormalizationBuilder { } /** - * Builder context for defining denormalization rules for an optional (nullable) reference. - * This is the receiver of the lambda passed to [denormalizes] for nullable references. + * The receiver of [denormalizes] for a reference that may be `null`. * - * Similar to [RequiredRefBuilder], but lambdas receive `Referenced?` (nullable) instead of `Referenced`. - * - * Common methods: - * - [bind] - Simple field copy that watches for changes - * - [set] - Simple field copy WITHOUT watching for changes - * - [watch] - Watch specific dependencies with nullable reference - * - [once] - Perform calculations without watching for changes + * Works like [RequiredRefBuilder], except that calculations receive `null` while the reference is unset. */ @DenormalizationDsl public class OptionalRefBuilder, RID : Comparable>( @@ -165,10 +119,12 @@ public class DenormalizationBuilder { ArrayList() /** - * Low-level method to register a dependency-based calculation. - * Use [watch], [bind], [set], or [once] instead for most use cases. + * Registers a [calculation] that reruns when any of the [dependencies] change. + * + * Prefer [watch] or [snapshot], which also build the modification for you. */ - public fun registerDenormalization( + @PublishedApi + internal fun registerDenormalization( dependencies: Set>, calculation: suspend context(ServerRuntime) (Referenced?) -> Modification, ) { @@ -177,11 +133,10 @@ public class DenormalizationBuilder { } /** - * Watch specific fields on the referenced model and perform calculations when they change. - * Same as [RequiredRefBuilder.watch] but receives `Referenced?` (nullable) instead of `Referenced`. + * Runs [calculation] when the reference is set and again whenever any of the [dependencies] change on the + * referenced model. * - * @param dependencies One or more fields to watch on the referenced model - * @param calculation Lambda to create a denormalization modification based on the referenced model + * [calculation] receives `null` while the reference is unset. See [RequiredRefBuilder.watch]. */ public inline fun watch( dependencies: Set>, @@ -198,21 +153,11 @@ public class DenormalizationBuilder { ): Unit = watch(setOf(dependency), calculation) /** - * Denormalize data from an optional referenced model without watching for changes in the referenced model. + * Runs [calculation] whenever the reference is set, on create, replace, or a modification that changes it. * - * Same as [RequiredRefBuilder.once] but for nullable references. The calculation receives `Referenced?` - * which will be null if the reference is null. - * - * **When it runs:** - * - On create: Yes - * - On replace: Yes - * - On modify (when reference changes): Yes - * - When referenced model changes: **No** (this is the key difference from watch) - * - * @param calculation Lambda to create a denormalization modification. Receives `Referenced?` (nullable). - * @see RequiredRefBuilder.once for detailed documentation + * [calculation] receives `null` while the reference is unset. See [RequiredRefBuilder.snapshot]. */ - public inline fun once( + public inline fun snapshot( crossinline calculation: suspend context(ServerRuntime) ModificationBuilder.(Referenced?) -> Unit, ) { registerDenormalization(emptySet()) { @@ -230,7 +175,8 @@ public class DenormalizationBuilder { * Register a required (non-nullable) reference denormalization. * Called by the [denormalizes] extension function. */ - public inline fun , RID : Comparable> required( + @PublishedApi + internal inline fun , RID : Comparable> addRequiredRef( reference: Lens, info: ModelInfo<*, Ref, RID>, build: RequiredRefBuilder.(Lens) -> Unit, @@ -246,7 +192,8 @@ public class DenormalizationBuilder { * Register an optional (nullable) reference denormalization. * Called by the [denormalizes] extension function for nullable references. */ - public inline fun , RID : Comparable> optional( + @PublishedApi + internal inline fun , RID : Comparable> addOptionalRef( reference: Optic, info: ModelInfo<*, Ref, RID>, build: OptionalRefBuilder.(Optic) -> Unit, @@ -262,6 +209,4 @@ public class DenormalizationBuilder { // TODO: Api Recommendations // Claude: // - Shrink the public surface before release: registerDenormalization, required/optional, build(), and the builders' reference/info can be @PublishedApi internal or internal. -// - Two ideas, four verbs: bind/watch keep a field in sync, set/once copy it when the reference is set. Neither `set` (reads like assignment, clashes with Optic.set) nor `once` (its own doc calls it misleading) says "not kept in sync". Consider one name, e.g. `snapshot`, for both copy forms. -// - Doc examples should make the difference between the path parameter (`{ collection -> ... }`) and the referenced value (`it`) obvious. -// - requireSourceOfTruth only sees declared dependencies; a watch/once body can still read a @Denormalized field unnoticed. +// - requireSourceOfTruth only sees declared dependencies; a watch/snapshot body can still read a @Denormalized field unnoticed. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt index 2e11326b9..1e1d4e581 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -45,17 +45,17 @@ public interface ModelInfoWithDeno?, T : HasId, ID : Compara * Each denormalization is declared on a reference field with `denormalizes`: * - On create and replace, it fetches the referenced model and fills in the denormalized fields. * - On a modification that changes the reference, it recalculates them. - * - With `bind` or `watch`, a change to the referenced model updates every model that references it. + * - With `watch`, a change to the referenced model updates every model that references it. With `snapshot`, it doesn't. * * Denormalizations read from the source of truth only. Reading a field the referenced model marks `@Denormalized` * throws when the denormalizations are built. To reach a model two references away, denormalize the intermediate * reference onto this model and denormalize from that: * ```kotlin - * a.b.denormalizes(B.info) { b -> a.c bind b.c } - * a.c.denormalizes(C.info) { c -> a.cName bind c.name } + * a.b.denormalizes(B.info) { b -> a.c watch b.c } + * a.c.denormalizes(C.info) { c -> a.cName watch c.name } * ``` * - * Fields written by `bind` or `set` must be marked `@Denormalized`. Mark them `cannotBeModified()` in the update + * Fields written by the infix `watch` or `snapshot` must be marked `@Denormalized`. Mark them `cannotBeModified()` in the update * restrictions too, so callers can't write them; the denormalizations still can. The caller chooses the reference, * so a denormalized field shows the referenced model's value to anyone who can read this model. * @@ -73,10 +73,10 @@ public interface ModelInfoWithDeno?, T : HasId, ID : Compara * ) { announcement -> * announcement.course.denormalizes(CourseEndpoints.info) { course -> * // Kept in sync: updates whenever Course.providerName changes - * announcement.courseProvider bind course.providerName + * announcement.courseProvider watch course.providerName * - * // Not watched: only updates when announcement.course changes - * announcement.courseTitle set course.title + * // Copied when announcement.course is set; later changes to the course are not copied + * announcement.courseTitle snapshot course.title * } * } * ``` diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt index 068735316..c10c2b3b5 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt @@ -103,7 +103,7 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab // TODO: Api Recommendations // Claude: -// - Refresh runs every calculation, so it overwrites set/once values with the referenced model's current values. Skip calculations with no dependencies. +// - Refresh runs every calculation, so it overwrites snapshot values with the referenced model's current values. Skip calculations with no dependencies. // - refreshAll fetches the referenced row once per row per denormalization; fetch each distinct id once. // - refreshAll is a single HTTP request over the whole table, so it will time out on large tables, and one missing required reference aborts the run (getOrThrow). Run it as a Task that skips and reports bad rows. // - Rename to spell out "Deno", e.g. DenormalizationRefreshEndpoints. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt index 53c00749d..d73781b8c 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt @@ -70,7 +70,7 @@ internal fun requireSourceOfTruth(source: Optic<*, *>) { throw IllegalArgumentException( "A denormalization reads $source, but '${copied.name}' is itself @Denormalized. " + "Denormalize the reference '${copied.name}' comes from onto this model and read the value from its source " + - "instead, e.g. `a.b.denormalizes(B.info) { b -> a.c bind b.c }` then `a.c.denormalizes(C.info) { c -> a.cName bind c.name }`." + "instead, e.g. `a.b.denormalizes(B.info) { b -> a.c watch b.c }` then `a.c.denormalizes(C.info) { c -> a.cName watch c.name }`." ) } diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt index 33c2347fa..f5819c90d 100644 --- a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -42,8 +42,8 @@ class DenormalizationTest { permissions = { ModelPermissions.allowAll() }, ) { city -> city.country.denormalizes(countryInfo) { country -> - city.countryName bind country.name - city.countryNameAtCreation set country.name + city.countryName watch country.name + city.countryNameWhenAssigned snapshot country.name } } @@ -59,13 +59,13 @@ class DenormalizationTest { }, ) { person -> person.city.denormalizes(cityInfo) { city -> - person.country bind city.country + person.country watch city.country } person.country.denormalizes(countryInfo) { country -> - person.countryName bind country.name + person.countryName watch country.name } person.favoriteCity.denormalizes(cityInfo) { city -> - person.favoriteCityName bind city.name + person.favoriteCityName watch city.name } } @@ -82,7 +82,7 @@ class DenormalizationTest { permissions = { ModelPermissions.allowAll() }, ) { person -> person.city.denormalizes(DenoServer.cityInfo) { city -> - person.countryName bind city.countryName + person.countryName watch city.countryName } } @@ -92,7 +92,7 @@ class DenormalizationTest { permissions = { ModelPermissions.allowAll() }, ) { city -> city.country.denormalizes(DenoServer.countryInfo) { country -> - city.name bind country.name + city.name watch country.name } } } @@ -120,13 +120,13 @@ class DenormalizationTest { execute { val storedCity = cityInfo.table().get(paris._id)!! assertEquals("France", storedCity.countryName) - assertEquals("France", storedCity.countryNameAtCreation) + assertEquals("France", storedCity.countryNameWhenAssigned) assertEquals("France", personInfo.table().get(person._id)!!.countryName) } } @Test - fun bind_follows_the_referenced_model_and_set_does_not() = denoTest { + fun watch_follows_the_referenced_model_and_snapshot_does_not() = denoTest { val france = DenoCountry(name = "France") val paris = DenoCity(country = france._id, name = "Paris") execute { @@ -138,7 +138,7 @@ class DenormalizationTest { execute { val storedCity = cityInfo.table().get(paris._id)!! assertEquals("République française", storedCity.countryName) - assertEquals("France", storedCity.countryNameAtCreation) + assertEquals("France", storedCity.countryNameWhenAssigned) } } @@ -323,7 +323,7 @@ data class DenoCity( val country: Uuid, val name: String = "", @Denormalized val countryName: String = "", - @Denormalized val countryNameAtCreation: String = "", + @Denormalized val countryNameWhenAssigned: String = "", ) : HasId @Queryable From 775c8db19afc3b9b10855e92fab566bf04206cda Mon Sep 17 00:00:00 2001 From: iHoonter Date: Wed, 4 Nov 2026 12:34:46 -0700 Subject: [PATCH 7/9] Added Optic support to denormalizations --- .../typed/denormalize/Denormalization.kt | 9 +++-- .../denormalize/DenormalizationBuilder.ext.kt | 2 +- .../denormalize/DenormalizationBuilder.kt | 6 ++-- .../typed/denormalize/ModelInfoWithDeno.kt | 28 ++++----------- .../typed/denormalize/RefreshDenoEndpoints.kt | 2 +- .../typed/denormalize/DenormalizationTest.kt | 36 +++++++++++++++++++ 6 files changed, 54 insertions(+), 29 deletions(-) diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt index fb27025cb..ffd9fd672 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt @@ -4,7 +4,6 @@ import com.lightningkite.lightningserver.runtime.ServerRuntime import com.lightningkite.lightningserver.typed.ModelInfo import com.lightningkite.services.database.HasId import com.lightningkite.services.database.Modification -import com.lightningkite.services.database.optics.Lens import com.lightningkite.services.database.optics.Optic /** @@ -40,9 +39,13 @@ public sealed interface Denormalization, RI public suspend fun setDenormalizations(ref: Input): Modification = Modification.Chain(calculations.map { it.calculation(ref) }) - /** A denormalization through a reference that is always set. */ + /** + * A denormalization through a non-null reference. + * + * Where [reference] doesn't reach a value, for example under a `null` parent, the denormalization does nothing. + */ public class RequiredRef, RID : Comparable>( - public val reference: Lens, + public val reference: Optic, override val info: ModelInfo<*, Referenced, RID>, override val calculations: List> ) : Denormalization diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt index 1de808929..eabbcc4a2 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt @@ -7,7 +7,7 @@ import com.lightningkite.services.database.optics.Lens import com.lightningkite.services.database.optics.Optic context(builder: DenormalizationBuilder) -public inline fun , RID : Comparable> Lens.denormalizes( +public inline fun , RID : Comparable> Optic.denormalizes( info: ModelInfo<*, Ref, RID>, build: DenormalizationBuilder.RequiredRefBuilder.(Lens) -> Unit, ): Unit = diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt index 7ccee034d..b4e8a191d 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -24,7 +24,7 @@ public class DenormalizationBuilder { /** - * The receiver of [denormalizes] for a reference that is always set. + * The receiver of [denormalizes] for a non-null reference. * * [watch] keeps fields in sync with the referenced model. [snapshot] copies them when the reference is set and * ignores later changes to the referenced model. Both have an infix form for a single field and a block form for @@ -32,7 +32,7 @@ public class DenormalizationBuilder { */ @DenormalizationDsl public class RequiredRefBuilder, RID : Comparable>( - public val reference: Lens, + public val reference: Optic, public val info: ModelInfo<*, Referenced, RID>, ) { private val list = @@ -177,7 +177,7 @@ public class DenormalizationBuilder { */ @PublishedApi internal inline fun , RID : Comparable> addRequiredRef( - reference: Lens, + reference: Optic, info: ModelInfo<*, Ref, RID>, build: RequiredRefBuilder.(Lens) -> Unit, ) { diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt index 1e1d4e581..2e027c41f 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -212,32 +212,18 @@ private fun , RID : Comparable> Table< deno: Denormalization.RequiredRef, ): Table = this .interceptCreate { model -> - val reference = deno.info.table().getOrBadRequest(deno.reference.get(model)) - deno.setDenormalizations(reference).invoke(model) + val id = deno.reference.get(model) ?: return@interceptCreate model + deno.setDenormalizations(deno.info.table().getOrBadRequest(id)).invoke(model) } .interceptReplace { model -> - val reference = deno.info.table().getOrBadRequest(deno.reference.get(model)) - deno.setDenormalizations(reference).invoke(model) + val id = deno.reference.get(model) ?: return@interceptReplace model + deno.setDenormalizations(deno.info.table().getOrBadRequest(id)).invoke(model) } .interceptModification { incomingMod -> - var updatedMod = incomingMod var newReference: RID? = null - incomingMod.vet(deno.reference) { - when (it) { - is Modification.Assign -> { - newReference = it.value - } - - else -> {} - } - } - if (newReference != null) { - val source = deno.info.table().getOrBadRequest(newReference) - updatedMod = Modification.Chain( - listOf(incomingMod, deno.setDenormalizations(source)) - ) - } - updatedMod + incomingMod.vetNullable(deno.reference) { if (it is Modification.Assign) newReference = it.value } + val id = newReference ?: return@interceptModification incomingMod + Modification.Chain(listOf(incomingMod, deno.setDenormalizations(deno.info.table().getOrBadRequest(id)))) } /** diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt index c10c2b3b5..62703812e 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt @@ -31,7 +31,7 @@ public class RefreshDenoEndpoints?, T : HasId, ID : Comparab context(_: ServerRuntime) private suspend fun , RID : Comparable> Denormalization.RequiredRef.modification( model: T - ): Modification = setDenormalizations(info.table().getOrThrow(reference.get(model))) + ): Modification = reference.get(model)?.let { setDenormalizations(info.table().getOrThrow(it)) } ?: Modification.Nothing() context(_: ServerRuntime) private suspend fun , RID : Comparable> Denormalization.OptionalRef.modification( diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt index f5819c90d..7b9eb9f82 100644 --- a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -19,6 +19,7 @@ import com.lightningkite.lightningserver.typed.test import com.lightningkite.services.data.Denormalized import com.lightningkite.services.data.Queryable import com.lightningkite.services.database.* +import com.lightningkite.services.database.optics.notNull import kotlinx.coroutines.flow.toList import kotlin.test.* import kotlin.uuid.Uuid @@ -67,6 +68,9 @@ class DenormalizationTest { person.favoriteCity.denormalizes(cityInfo) { city -> person.favoriteCityName watch city.name } + person.job.notNull.city.denormalizes(cityInfo) { city -> + person.job.notNull.cityName watch city.name + } } val personRefresh = path.path("person-deno") include RefreshDenoEndpoints(personInfo) @@ -142,6 +146,31 @@ class DenormalizationTest { } } + @Test + fun reference_under_a_nullable_parent_is_followed_when_present() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val lyon = DenoCity(country = france._id, name = "Lyon") + val unemployed = DenoPerson(city = paris._id) + val employed = DenoPerson(city = paris._id, job = DenoJob(city = paris._id)) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insert(listOf(paris, lyon)) + personInfo.table().insert(listOf(unemployed, employed)) + } + + execute { + assertEquals(null, personInfo.table().get(unemployed._id)!!.job) + assertEquals("Paris", personInfo.table().get(employed._id)!!.job?.cityName) + + personInfo.table().updateOneById(unemployed._id, Modification { it.job assign DenoJob(city = lyon._id) }) + assertEquals("Lyon", personInfo.table().get(unemployed._id)!!.job?.cityName) + + cityInfo.table().updateOneById(paris._id, Modification { it.name assign "Paname" }) + assertEquals("Paname", personInfo.table().get(employed._id)!!.job?.cityName) + } + } + /** Person.countryName comes from Country.name through Person.country, which is denormalized from City.country. */ @Test fun stored_intermediate_reference_follows_the_source() = denoTest { @@ -334,4 +363,11 @@ data class DenoPerson( @Denormalized val countryName: String = "", val favoriteCity: Uuid? = null, @Denormalized val favoriteCityName: String? = null, + val job: DenoJob? = null, ) : HasId + +@Queryable +data class DenoJob( + val city: Uuid, + @Denormalized val cityName: String = "", +) From 7bf145a453e9c2ab7cf37ec2b7c034567579c0e9 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Wed, 4 Nov 2026 12:49:31 -0700 Subject: [PATCH 8/9] Polished deno refresh endpoints --- .../DenormalizationRefreshEndpoints.kt | 164 ++++++++++++++++++ .../typed/denormalize/RefreshDenoEndpoints.kt | 109 ------------ .../typed/denormalize/DenormalizationTest.kt | 45 ++++- 3 files changed, 207 insertions(+), 111 deletions(-) create mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationRefreshEndpoints.kt delete mode 100644 typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationRefreshEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationRefreshEndpoints.kt new file mode 100644 index 000000000..88efc33d3 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationRefreshEndpoints.kt @@ -0,0 +1,164 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.lightningserver.BadRequestException +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.definition.Task +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.definition.launch +import com.lightningkite.lightningserver.http.post +import com.lightningkite.lightningserver.pathing.PathSpec +import com.lightningkite.lightningserver.pathing.PathSpec0 +import com.lightningkite.lightningserver.pathing.PathSpec1 +import com.lightningkite.lightningserver.pathing.arg1 +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.lightningserver.typed.ApiHttpHandler +import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.lightningserver.typed.explicitApiHttpHandler +import com.lightningkite.lightningserver.typed.getOrBadRequest +import com.lightningkite.lightningserver.typed.getOrNotFound +import com.lightningkite.services.database.Condition +import com.lightningkite.services.database.HasId +import com.lightningkite.services.database.Modification +import com.lightningkite.services.database._id +import com.lightningkite.services.database.all +import com.lightningkite.services.database.updateOneByIdIgnoringResult +import io.github.oshai.kotlinlogging.KotlinLogging +import kotlinx.serialization.builtins.serializer + +private val logger = KotlinLogging.logger("com.lightningkite.lightningserver.typed.denormalize.DenormalizationRefreshEndpoints") + +/** Caps how many ids [DenormalizationRefreshEndpoints.refreshAllDenormalizations] puts in a single update query. */ +private const val UPDATE_BATCH = 1000 + +/** + * Admin endpoints that recalculate the denormalized fields of a model created by [modelInfoWithDeno]. + * + * Use them to repair rows whose denormalized fields went stale, for example after writes through + * [ModelInfo.baseTable] or a migration. The endpoints take `includeSnapshots` as their input: fields written by + * `snapshot` keep their values unless it is `true`. + */ +public class DenormalizationRefreshEndpoints?, T : HasId, ID : Comparable>( + private val info: ModelInfoWithDeno +) : ServerBuilder() { + // Claude: one per refresh, so refreshing many rows fetches each referenced row once. + private class ReferencedRows { + private val rows = HashMap, Any>, Any>() + + context(_: ServerRuntime) + suspend fun , RID : Comparable> get(info: ModelInfo<*, Ref, RID>, id: RID): Ref { + @Suppress("UNCHECKED_CAST") + return rows.getOrPut(info to id) { info.table().getOrBadRequest(id) } as Ref + } + } + + context(_: ServerRuntime) + private suspend fun refreshedFields( + calculations: List>, + ref: Input, + includeSnapshots: Boolean, + ): Modification = Modification.Chain( + calculations.filter { includeSnapshots || it.dependencies.isNotEmpty() }.map { it.calculation(ref) } + ) + + context(_: ServerRuntime) + private suspend fun , RID : Comparable> Denormalization.RequiredRef.refreshedFields( + model: T, + rows: ReferencedRows, + includeSnapshots: Boolean, + ): Modification { + val id = reference.get(model) ?: return Modification.Nothing() + return refreshedFields(calculations, rows.get(this.info, id), includeSnapshots) + } + + context(_: ServerRuntime) + private suspend fun , RID : Comparable> Denormalization.OptionalRef.refreshedFields( + model: T, + rows: ReferencedRows, + includeSnapshots: Boolean, + ): Modification = refreshedFields(calculations, reference.get(model)?.let { rows.get(this.info, it) }, includeSnapshots) + + context(_: ServerRuntime) + private suspend fun refresh(model: T, rows: ReferencedRows, includeSnapshots: Boolean): Modification = Modification.Chain( + info.denormalizations.filter { includeSnapshots || it.watchesReferencedModel }.map { deno -> + val mod = when (deno) { + is Denormalization.RequiredRef -> deno.refreshedFields(model, rows, includeSnapshots) + is Denormalization.OptionalRef -> deno.refreshedFields(model, rows, includeSnapshots) + } + if (mod(model) == model) Modification.Nothing() else mod + } + ) + + public val refreshDetail: ApiHttpHandler, HasId<*>, Boolean, Modification> = + path.arg(PathSpec.Segment.Wildcard("id", info.idSerializer)).post bind explicitApiHttpHandler( + summary = "Refresh Denormalizations", + description = "Recalculates the denormalized fields on this ${info.tableName} from its references and returns the modification applied. The input is includeSnapshots: snapshot fields are kept unless it is true.", + inputType = Boolean.serializer(), + outputType = Modification.serializer(info.serializer), + auth = AuthRequirement.IsAdmin, + implementation = { includeSnapshots: Boolean -> + val model = info.table().getOrNotFound(request.arg1) + val mod = refresh(model, ReferencedRows(), includeSnapshots) + if (!mod.isNothing) info.baseTableWithDenormalizations().updateOneByIdIgnoringResult(model._id, mod) + mod + } + ) + + /** + * Recalculates the denormalized fields on every row and returns the modifications applied, keyed by id. + * + * Fields written by `snapshot` keep their values unless [includeSnapshots] is `true`. Rows that can't be refreshed, such as rows whose reference points at a missing model, are logged and skipped. + */ + context(_: ServerRuntime) + public suspend fun refreshAllDenormalizations(includeSnapshots: Boolean): Map> { + // todo: parallelize + // Streamed rather than materialized: the rows themselves are discarded as we go and only the + // modifications that are actually needed are retained (those are the return value anyway). + // The write pass runs after the read finishes so updates never race the cursor feeding them. + val rows = ReferencedRows() + val mods = LinkedHashMap>() + info.table().all().collect { model -> + val mod = try { + refresh(model, rows, includeSnapshots) + } catch (e: BadRequestException) { + logger.warn { "Skipped refreshing ${info.tableName} ${model._id}: ${e.message}" } + return@collect + } + if (!mod.isNothing) mods[model._id] = mod + } + + // Rows needing the identical modification go out in one write, so the change notifications + // this produces scale with the number of distinct changes rather than the number of rows. + val table = info.baseTableWithDenormalizations() + for ((mod, ids) in mods.entries.groupBy({ it.value }, { it.key })) { + for (idBatch in ids.chunked(UPDATE_BATCH)) { + table.updateManyIgnoringResult( + Condition.OnField(info.serializer._id(), Condition.Inside(idBatch)), + mod + ) + } + } + + return mods.mapKeys { it.key.toString() } + } + + /** Runs [refreshAllDenormalizations] in the background. */ + public val refreshAllTask: Task = path.path("refresh-all-task") bind Task { includeSnapshots: Boolean -> + refreshAllDenormalizations(includeSnapshots) + } + + public val refreshAll: ApiHttpHandler, Boolean, Unit> = + path.path("refresh-all").post bind explicitApiHttpHandler( + summary = "Refresh All Denormalizations", + description = "Starts recalculating the denormalized fields on every ${info.tableName} in the background. The input is includeSnapshots: snapshot fields are kept unless it is true. Rows that can't be refreshed are logged and skipped.", + inputType = Boolean.serializer(), + outputType = Unit.serializer(), + auth = AuthRequirement.IsAdmin, + implementation = { includeSnapshots: Boolean -> + refreshAllTask.launch(includeSnapshots) + } + ) +} + +// TODO: Api Recommendations +// Claude: +// - refreshAll runs as one Task with the default 5 minute timeout; a very large table needs the work split into batches of Tasks. diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt deleted file mode 100644 index 62703812e..000000000 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/RefreshDenoEndpoints.kt +++ /dev/null @@ -1,109 +0,0 @@ -package com.lightningkite.lightningserver.typed.denormalize - -import com.lightningkite.lightningserver.auth.AuthRequirement -import com.lightningkite.lightningserver.definition.builder.ServerBuilder -import com.lightningkite.lightningserver.http.post -import com.lightningkite.lightningserver.pathing.PathSpec -import com.lightningkite.lightningserver.pathing.PathSpec0 -import com.lightningkite.lightningserver.pathing.PathSpec1 -import com.lightningkite.lightningserver.pathing.arg1 -import com.lightningkite.lightningserver.runtime.ServerRuntime -import com.lightningkite.lightningserver.typed.ApiHttpHandler -import com.lightningkite.lightningserver.typed.explicitApiHttpHandler -import com.lightningkite.lightningserver.typed.getOrNotFound -import com.lightningkite.lightningserver.typed.getOrThrow -import com.lightningkite.services.database.Condition -import com.lightningkite.services.database.HasId -import com.lightningkite.services.database.Modification -import com.lightningkite.services.database._id -import com.lightningkite.services.database.all -import com.lightningkite.services.database.updateOneByIdIgnoringResult -import kotlinx.serialization.builtins.MapSerializer -import kotlinx.serialization.builtins.serializer - - -/** Caps how many ids [RefreshDenoEndpoints.refreshAllDenormalizations] puts in a single update query. */ -private const val UPDATE_BATCH = 1000 - -public class RefreshDenoEndpoints?, T : HasId, ID : Comparable>( - private val info: ModelInfoWithDeno -) : ServerBuilder() { - context(_: ServerRuntime) - private suspend fun , RID : Comparable> Denormalization.RequiredRef.modification( - model: T - ): Modification = reference.get(model)?.let { setDenormalizations(info.table().getOrThrow(it)) } ?: Modification.Nothing() - - context(_: ServerRuntime) - private suspend fun , RID : Comparable> Denormalization.OptionalRef.modification( - model: T - ): Modification = setDenormalizations(reference.get(model)?.let { info.table().getOrThrow(it) }) - - context(_: ServerRuntime) - private suspend fun refresh(model: T): Modification = Modification.Chain(info.denormalizations.map { deno -> - val mod = when (deno) { - is Denormalization.RequiredRef -> deno.modification(model) - is Denormalization.OptionalRef -> deno.modification(model) - } - if (mod(model) == model) Modification.Nothing() else mod - }) - - public val refreshDetail: ApiHttpHandler, HasId<*>, Unit, Modification> = - path.arg(PathSpec.Segment.Wildcard("id", info.idSerializer)).post bind explicitApiHttpHandler( - summary = "Refresh Denormalizations", - description = "Recalculates every denormalized field on this ${info.tableName} from its references and returns the modification applied.", - inputType = Unit.serializer(), - outputType = Modification.serializer(info.serializer), - auth = AuthRequirement.IsAdmin, - implementation = { - val model = info.table().getOrNotFound(request.arg1) - val mod = refresh(model) - if (!mod.isNothing) info.baseTableWithDenormalizations().updateOneByIdIgnoringResult(model._id, mod) - mod - } - ) - - context(_: ServerRuntime) - public suspend fun refreshAllDenormalizations(): Map> { - // todo: should re-use reference ids where possible and parallelize - // Streamed rather than materialized: the rows themselves are discarded as we go and only the - // modifications that are actually needed are retained (those are the return value anyway). - // The write pass runs after the read finishes so updates never race the cursor feeding them. - val mods = LinkedHashMap>() - info.table().all().collect { model -> - val mod = refresh(model) - if (!mod.isNothing) mods[model._id] = mod - } - - // Rows needing the identical modification go out in one write, so the change notifications - // this produces scale with the number of distinct changes rather than the number of rows. - val table = info.baseTableWithDenormalizations() - for ((mod, ids) in mods.entries.groupBy({ it.value }, { it.key })) { - for (idBatch in ids.chunked(UPDATE_BATCH)) { - table.updateManyIgnoringResult( - Condition.OnField(info.serializer._id(), Condition.Inside(idBatch)), - mod - ) - } - } - - return mods.mapKeys { it.key.toString() } - } - - public val refreshAll: ApiHttpHandler, Unit, Map>> = - path.path("refresh-all").post bind explicitApiHttpHandler( - summary = "Refresh Denormalizations", - inputType = Unit.serializer(), - outputType = MapSerializer(String.serializer(), Modification.serializer(info.serializer)), - auth = AuthRequirement.IsAdmin, - implementation = { - refreshAllDenormalizations() - } - ) -} - -// TODO: Api Recommendations -// Claude: -// - Refresh runs every calculation, so it overwrites snapshot values with the referenced model's current values. Skip calculations with no dependencies. -// - refreshAll fetches the referenced row once per row per denormalization; fetch each distinct id once. -// - refreshAll is a single HTTP request over the whole table, so it will time out on large tables, and one missing required reference aborts the run (getOrThrow). Run it as a Task that skips and reports bad rows. -// - Rename to spell out "Deno", e.g. DenormalizationRefreshEndpoints. diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt index 7b9eb9f82..517d0420d 100644 --- a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -73,7 +73,8 @@ class DenormalizationTest { } } - val personRefresh = path.path("person-deno") include RefreshDenoEndpoints(personInfo) + val cityRefresh = path.path("city-deno") include DenormalizationRefreshEndpoints(cityInfo) + val personRefresh = path.path("person-deno") include DenormalizationRefreshEndpoints(personInfo) val personRest = path.path("people") include ModelRestEndpoints(personInfo) } @@ -332,12 +333,52 @@ class DenormalizationTest { personInfo.table().insertOne(person) personInfo.baseTable().updateOneById(person._id, Modification { it.countryName assign "stale" }) - val applied = personRefresh.refreshAllDenormalizations() + val applied = personRefresh.refreshAllDenormalizations(includeSnapshots = false) assertEquals(setOf(person._id.toString()), applied.keys) assertEquals("France", personInfo.table().get(person._id)!!.countryName) } } + + @Test + fun refresh_keeps_snapshot_values_unless_asked() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + cityInfo.baseTable().updateOneById(paris._id, Modification { + it.countryName assign "stale" + it.countryNameWhenAssigned assign "Gaul" + }) + + cityRefresh.refreshAllDenormalizations(includeSnapshots = false) + val kept = cityInfo.table().get(paris._id)!! + assertEquals("France", kept.countryName) + assertEquals("Gaul", kept.countryNameWhenAssigned) + + cityRefresh.refreshAllDenormalizations(includeSnapshots = true) + assertEquals("France", cityInfo.table().get(paris._id)!!.countryNameWhenAssigned) + } + } + + @Test + fun refresh_skips_rows_with_missing_references() = denoTest { + val france = DenoCountry(name = "France") + val paris = DenoCity(country = france._id, name = "Paris") + val stale = DenoPerson(city = paris._id, country = france._id, countryName = "stale") + val orphan = DenoPerson(city = Uuid.random(), country = Uuid.random()) + execute { + countryInfo.table().insertOne(france) + cityInfo.table().insertOne(paris) + personInfo.baseTable().insert(listOf(stale, orphan)) + + val applied = personRefresh.refreshAllDenormalizations(includeSnapshots = false) + + assertEquals(setOf(stale._id.toString()), applied.keys) + assertEquals("France", personInfo.table().get(stale._id)!!.countryName) + } + } } @Queryable From e8d0b87cf13b20d53b0dfb6d3f1dac7ff637e7f9 Mon Sep 17 00:00:00 2001 From: iHoonter Date: Wed, 4 Nov 2026 15:02:43 -0700 Subject: [PATCH 9/9] Moved Modification.vet to service abstractions --- gradle/libs.versions.toml | 2 +- .../typed/denormalize/ModelInfoWithDeno.kt | 5 +- .../typed/denormalize/helpers.kt | 64 --------- .../typed/denormalize/DenormalizationTest.kt | 15 +++ .../typed/denormalize/VetTest.kt | 125 ------------------ 5 files changed, 19 insertions(+), 192 deletions(-) delete mode 100644 typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d9a61feca..3f4d7f4a6 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -28,7 +28,7 @@ oneTimePass = "3.0.0" orgCrac = "0.1.3" proguard = "7.10.0" scrimage = "4.6.8" -serviceAbstractions = "1.4.0-prerelease-128-ea909d37" +serviceAbstractions = "1.4.0-prerelease-129-e0cd3f36" vanniktechMavenPublish = "0.37.0" webauthn4jCore = "0.31.10.RELEASE" diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt index 2e027c41f..63f335a22 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -20,6 +20,7 @@ import com.lightningkite.services.database.Condition import com.lightningkite.services.database.Database import com.lightningkite.services.database.ModelPermissions import com.lightningkite.services.database.Modification +import com.lightningkite.services.database.vet import com.lightningkite.services.database.interceptCreate import com.lightningkite.services.database.interceptModification import com.lightningkite.services.database.interceptReplace @@ -221,7 +222,7 @@ private fun , RID : Comparable> Table< } .interceptModification { incomingMod -> var newReference: RID? = null - incomingMod.vetNullable(deno.reference) { if (it is Modification.Assign) newReference = it.value } + incomingMod.vet(deno.reference) { if (it is Modification.Assign) newReference = it.value } val id = newReference ?: return@interceptModification incomingMod Modification.Chain(listOf(incomingMod, deno.setDenormalizations(deno.info.table().getOrBadRequest(id)))) } @@ -246,7 +247,7 @@ private fun , RID : Comparable> Table< var updatedMod = incomingMod var changed = false var newReference: RID? = null - incomingMod.vetNullable(deno.reference) { + incomingMod.vet(deno.reference) { when (it) { is Modification.Assign -> { changed = true diff --git a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt index d73781b8c..7c774a1e6 100644 --- a/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt @@ -1,69 +1,8 @@ package com.lightningkite.lightningserver.typed.denormalize import com.lightningkite.services.data.Denormalized -import com.lightningkite.services.database.Modification -import com.lightningkite.services.database.optics.ComposedOptic -import com.lightningkite.services.database.optics.Field -import com.lightningkite.services.database.optics.IdentityLens -import com.lightningkite.services.database.optics.Lens -import com.lightningkite.services.database.optics.NotNullOptic import com.lightningkite.services.database.optics.Optic -/** - * Calls [onModification] with each part of this modification that affects the target of [path]. - * - * An assignment to a value containing the target is reported as an assignment to the target. The parts of a - * [Modification.Chain] are reported separately, in order, and parts that don't affect the target are not reported. - * - * @throws IllegalArgumentException if [path] passes through a field shared by the variants of a sealed type. - */ -public fun Modification.vet(path: Lens, onModification: (Modification) -> Unit): Unit = - @Suppress("UNCHECKED_CAST") - vetAny(path, onModification as (Modification<*>) -> Unit) - -/** - * Calls [onModification] with each part of this modification that affects the target of [path]. - * - * An assignment to a value containing the target is reported as an assignment to the target, or as an assignment of - * `null` if a nullable value on the way to the target is `null`. The parts of a [Modification.Chain] are reported - * separately, in order, and parts that don't affect the target are not reported. - * - * @throws IllegalArgumentException if [path] passes through collection elements or a sealed type. - */ -public fun Modification.vetNullable(path: Optic, onModification: (Modification) -> Unit): Unit = - @Suppress("UNCHECKED_CAST") - vetAny(path, onModification as (Modification<*>) -> Unit) - -private fun Modification<*>.vetAny(path: Optic<*, *>, onModification: (Modification<*>) -> Unit) { - if (this is Modification.Chain) return modifications.forEach { it.vetAny(path, onModification) } - when (path) { - is IdentityLens<*> -> onModification(this) - is ComposedOptic<*, *, *> -> vetAny(path.outer) { it.vetAny(path.inner, onModification) } - is Field<*, *> -> when (this) { - is Modification.Assign -> { - @Suppress("UNCHECKED_CAST") - onModification(Modification.Assign(value?.let { (path as Field).get(it) })) - } - is Modification.OnField<*, *> -> if (key == path) modification.forEachPart(onModification) - else -> {} - } - - is NotNullOptic<*, *> -> vetAny(path.wraps) { - when (it) { - is Modification.Assign -> onModification(it) - is Modification.IfNotNull -> it.modification.forEachPart(onModification) - else -> {} - } - } - - else -> throw IllegalArgumentException("vet does not support the step $path") - } -} - -private fun Modification<*>.forEachPart(action: (Modification<*>) -> Unit) { - if (this is Modification.Chain) modifications.forEach { it.forEachPart(action) } else action(this) -} - /** Throws an [IllegalArgumentException] if [source] passes through a field marked [Denormalized]. */ internal fun requireSourceOfTruth(source: Optic<*, *>) { val copied = source.fields.firstOrNull { field -> field.annotations.any { it is Denormalized } } ?: return @@ -83,7 +22,4 @@ internal fun requireMarkedDenormalized(target: Optic<*, *>) { // TODO: Api Recommendations // Claude: -// - vetNullable is a placeholder name; settle it before vet/vetNullable go public in service-abstractions. -// - When moving vet/vetNullable to service-abstractions, deprecate the list-based vet(fieldChain: List), which has the same fields-walking bugs and the null-parent crash. vet(field: Field) behaves the same as vet(Lens) and could be deprecated too. -// - Rejecting asType and SealedSharedFieldLens steps in vetAny is untested; it needs a sealed @Queryable model. // - requireSourceOfTruth and requireMarkedDenormalized scan path.fields, so they can't see through a SealedSharedFieldLens. diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt index 517d0420d..a8ef99e3b 100644 --- a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -14,6 +14,7 @@ import com.lightningkite.lightningserver.serialization.registerBasicMediaTypeCod import com.lightningkite.lightningserver.settings.set import com.lightningkite.lightningserver.settings.setStatic import com.lightningkite.lightningserver.typed.ModelRestEndpoints +import com.lightningkite.lightningserver.typed.denormalize.denormalizes import com.lightningkite.lightningserver.typed.modelInfo import com.lightningkite.lightningserver.typed.test import com.lightningkite.services.data.Denormalized @@ -412,3 +413,17 @@ data class DenoJob( val city: Uuid, @Denormalized val cityName: String = "", ) + +@Queryable +data class VetRoot( + val name: String = "", + val inner: VetInner = VetInner(), + val maybe: VetInner? = null, + val tags: List = listOf(), +) + +@Queryable +data class VetInner( + val value: Int = 0, + val label: String = "", +) diff --git a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt deleted file mode 100644 index 0d90d29f1..000000000 --- a/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/VetTest.kt +++ /dev/null @@ -1,125 +0,0 @@ -package com.lightningkite.lightningserver.typed.denormalize - -import com.lightningkite.services.data.Queryable -import com.lightningkite.services.database.Modification -import com.lightningkite.services.database.optics.IdentityLens -import com.lightningkite.services.database.optics.Lens -import com.lightningkite.services.database.optics.Optic -import com.lightningkite.services.database.optics.elements -import com.lightningkite.services.database.optics.notNull -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class VetTest { - private fun Modification.vetted(path: Lens): List> = - buildList { vet(path) { add(it) } } - - private fun Modification.vettedNullable(path: Optic): List> = - buildList { vetNullable(path) { add(it) } } - - @Test - fun assign_on_the_path_is_reported() { - val mod = Modification { it.name assign "new" } - assertEquals(listOf(Modification.Assign("new")), mod.vetted(VetRoot.name)) - } - - @Test - fun other_modifications_on_the_path_are_reported_as_is() { - val mod = Modification { it.inner.value += 2 } - assertEquals(listOf(Modification.Increment(2)), mod.vetted(VetRoot.inner.value)) - } - - @Test - fun modifications_on_other_fields_are_ignored() { - val mod = Modification { - it.name assign "new" - it.inner.label assign "other" - } - assertEquals(emptyList>(), mod.vetted(VetRoot.inner.value)) - } - - @Test - fun nested_assign_on_the_path_is_reported() { - val mod = Modification { it.inner.value assign 3 } - assertEquals(listOf(Modification.Assign(3)), mod.vetted(VetRoot.inner.value)) - } - - @Test - fun assign_on_a_parent_reports_the_value_at_the_path() { - val mod = Modification { it.inner assign VetInner(value = 7, label = "seven") } - assertEquals(listOf(Modification.Assign(7)), mod.vetted(VetRoot.inner.value)) - } - - @Test - fun assign_on_the_whole_model_reports_the_value_at_the_path() { - val mod: Modification = Modification.Assign(VetRoot(name = "replaced", inner = VetInner(value = 4))) - assertEquals(listOf(Modification.Assign(4)), mod.vetted(VetRoot.inner.value)) - } - - @Test - fun every_modification_in_a_chain_is_reported_in_order() { - val mod = Modification { - it.inner.value assign 1 - it.name assign "between" - it.inner.value += 5 - } - assertEquals( - listOf(Modification.Assign(1), Modification.Increment(5)), - mod.vetted(VetRoot.inner.value), - ) - } - - @Test - fun modifications_through_a_nullable_field_are_reported() { - val mod = Modification { it.maybe.notNull.value assign 9 } - assertEquals(listOf(Modification.Assign(9)), mod.vettedNullable(VetRoot.maybe.notNull.value)) - } - - @Test - fun other_modifications_through_a_nullable_field_are_reported_as_is() { - val mod = Modification { it.maybe.notNull.value += 2 } - assertEquals>(listOf(Modification.Increment(2)), mod.vettedNullable(VetRoot.maybe.notNull.value)) - } - - @Test - fun assign_on_a_nullable_parent_reports_the_value_at_the_path() { - val mod = Modification { it.maybe assign VetInner(value = 6) } - assertEquals(listOf(Modification.Assign(6)), mod.vettedNullable(VetRoot.maybe.notNull.value)) - } - - @Test - fun assigning_null_to_a_nullable_parent_reports_null() { - val mod = Modification { it.maybe assign null } - assertEquals(listOf(Modification.Assign(null)), mod.vettedNullable(VetRoot.maybe.notNull.value)) - } - - @Test - fun an_identity_path_reports_every_part() { - val mod = Modification { - it.name assign "new" - it.inner.value += 1 - } - assertEquals((mod as Modification.Chain).modifications, mod.vetted(IdentityLens(VetRoot.serializer()))) - } - - @Test - fun collection_elements_are_rejected() { - val mod = Modification { it.tags assign listOf("a") } - assertFailsWith { mod.vettedNullable(VetRoot.tags.elements) } - } -} - -@Queryable -data class VetRoot( - val name: String = "", - val inner: VetInner = VetInner(), - val maybe: VetInner? = null, - val tags: List = listOf(), -) - -@Queryable -data class VetInner( - val value: Int = 0, - val label: String = "", -)