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/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..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,9 +38,17 @@ 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) -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 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..ffd9fd672 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/Denormalization.kt @@ -0,0 +1,59 @@ +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.Optic + +/** + * 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> + + /** Whether a change to the referenced model must update the models that reference it. */ + public val watchesReferencedModel: Boolean get() = calculations.any { it.dependencies.isNotEmpty() } + + /** + * A [calculation] that reruns when any of its [dependencies] change. + * + * With no dependencies, it runs only when the reference is set. + */ + public class Calculation( + public val dependencies: Set>, + public val calculation: suspend context(ServerRuntime) (Input) -> Modification, + ) { + 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 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: Optic, + override val info: ModelInfo<*, Referenced, RID>, + 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> + ) : 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 new file mode 100644 index 000000000..eabbcc4a2 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.ext.kt @@ -0,0 +1,68 @@ +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> Optic.denormalizes( + info: ModelInfo<*, Ref, RID>, + build: DenormalizationBuilder.RequiredRefBuilder.(Lens) -> Unit, +): Unit = + builder.addRequiredRef(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.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.watch(ref: Lens) { + requireMarkedDenormalized(this) + builder.registerDenormalization(setOf(ref)) { reference -> + this.mapModification( + Modification.Assign(ref.get(reference)) + ) + } +} + +/** 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.snapshot(ref: Lens) { + requireMarkedDenormalized(this) + requireSourceOfTruth(ref) + builder.registerDenormalization(emptySet()) { reference -> + this.mapModification( + Modification.Assign(ref.get(reference)) + ) + } +} + +/** 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.watch(ref: Optic) { + requireMarkedDenormalized(this) + builder.registerDenormalization(setOf(ref)) { reference -> + this.mapModification( + Modification.Assign(reference?.let(ref::get)) + ) + } +} + +/** 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.snapshot(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 new file mode 100644 index 000000000..b4e8a191d --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationBuilder.kt @@ -0,0 +1,212 @@ +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 [modelInfoWithDeno]. + */ +@DenormalizationBuilder.DenormalizationDsl +public class DenormalizationBuilder { + /** + * DSL marker to prevent scope confusion in nested denormalization builder lambdas. + */ + @DslMarker + public annotation class DenormalizationDsl + + + /** + * 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 + * custom calculations. + */ + @DenormalizationDsl + public class RequiredRefBuilder, RID : Comparable>( + public val reference: Optic, + public val info: ModelInfo<*, Referenced, RID>, + ) { + private val list = + ArrayList>() + + /** + * Registers a [calculation] that reruns when any of the [dependencies] change. + * + * Prefer [watch] or [snapshot], which also build the modification for you. + */ + @PublishedApi + internal fun registerDenormalization( + dependencies: Set>, + calculation: suspend context(ServerRuntime) (Referenced) -> Modification, + ) { + dependencies.forEach(::requireSourceOfTruth) + list.add(Denormalization.Calculation(dependencies, calculation)) + } + + /** + * Runs [calculation] when the reference is set and again whenever any of the [dependencies] change on the + * referenced model. + * + * [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. + * + * ```kotlin + * material.collection.denormalizes(MaterialCollection.info) { collection -> + * watch(collection.reviewCycle) { + * val cycle = ReviewCycle.info.table().getOrBadRequest(it.reviewCycle) + * material.reviewCycleEndAt assign cycle.timeframe.endDate + * } + * } + * ``` + */ + 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) + + /** + * Runs [calculation] whenever the reference is set, on create, replace, or a modification that changes it. + * + * Unlike [watch], later changes to the referenced model are not copied, so the fields keep the values from + * when the reference was set. + * + * ```kotlin + * material.collection.denormalizes(MaterialCollection.info) { + * snapshot { material.collectionNameWhenAdded assign it.name } + * } + * ``` + */ + public inline fun snapshot( + 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) + } + + /** + * The receiver of [denormalizes] for a reference that may be `null`. + * + * Works like [RequiredRefBuilder], except that calculations receive `null` while the reference is unset. + */ + @DenormalizationDsl + public class OptionalRefBuilder, RID : Comparable>( + public val reference: Optic, + public val info: ModelInfo<*, Referenced, RID>, + ) { + private val list: ArrayList> = + ArrayList() + + /** + * Registers a [calculation] that reruns when any of the [dependencies] change. + * + * Prefer [watch] or [snapshot], which also build the modification for you. + */ + @PublishedApi + internal fun registerDenormalization( + dependencies: Set>, + calculation: suspend context(ServerRuntime) (Referenced?) -> Modification, + ) { + dependencies.forEach(::requireSourceOfTruth) + list.add(Denormalization.Calculation(dependencies, calculation)) + } + + /** + * Runs [calculation] when the reference is set and again whenever any of the [dependencies] change on the + * referenced model. + * + * [calculation] receives `null` while the reference is unset. See [RequiredRefBuilder.watch]. + */ + 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) + + /** + * Runs [calculation] whenever the reference is set, on create, replace, or a modification that changes it. + * + * [calculation] receives `null` while the reference is unset. See [RequiredRefBuilder.snapshot]. + */ + public inline fun snapshot( + 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. + */ + @PublishedApi + internal inline fun , RID : Comparable> addRequiredRef( + reference: Optic, + info: ModelInfo<*, Ref, RID>, + build: RequiredRefBuilder.(Lens) -> 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. + */ + @PublishedApi + internal inline fun , RID : Comparable> addOptionalRef( + reference: Optic, + info: ModelInfo<*, Ref, RID>, + build: OptionalRefBuilder.(Optic) -> Unit, + ) { + denormalizations.add( + OptionalRefBuilder(reference, info) + .apply { build(IdentityLens(info.serializer)) } + .build() + ) + } +} + +// 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. +// - 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/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/ModelInfoWithDeno.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt new file mode 100644 index 000000000..63f335a22 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/ModelInfoWithDeno.kt @@ -0,0 +1,277 @@ +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.vet +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 { + 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 +} + +/** + * Creates a [ModelInfo] like [modelInfo] whose table also copies data from the models it references. + * + * 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 `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 watch b.c } + * a.c.denormalizes(C.info) { c -> a.cName watch c.name } + * ``` + * + * 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. + * + * Example: + * ```kotlin + * val announcementInfo = Server.database.modelInfoWithDeno( + * auth = UserAuth.require(), + * tableName = "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 watch course.providerName + * + * // Copied when announcement.course is set; later changes to the course are not copied + * announcement.courseTitle snapshot course.title + * } + * } + * ``` + */ +context(builder: ServerBuilder) +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, + ) + +/** 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 fun baseTableWithDenormalizations(): Table = baseTable().applyDenormalizations(built.value) + } + + 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) continue + when (d) { + is Denormalization.RequiredRef -> d.listenForDenormalizations { modelInfo.baseTableWithDenormalizations() } + is Denormalization.OptionalRef -> 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.RequiredRef.listenForDenormalizations( + table: context(ServerRuntime) () -> Table, +) { + info.registerChangeListener { changes -> + for ((old, new) in changes.changes) { + if (old == null || new == null) continue + val mod = updateDenormalizations(old, new) + if (!mod.isNothing) table().updateManyIgnoringResult(reference.mapCondition(Condition.Equal(old._id)), mod) + } + } +} + +private fun , RID : Comparable> Denormalization.OptionalRef.listenForDenormalizations( + table: context(ServerRuntime) () -> Table, +) { + 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)) + ) + } + } +} + +/** + * 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 id = deno.reference.get(model) ?: return@interceptCreate model + deno.setDenormalizations(deno.info.table().getOrBadRequest(id)).invoke(model) + } + .interceptReplace { model -> + val id = deno.reference.get(model) ?: return@interceptReplace model + deno.setDenormalizations(deno.info.table().getOrBadRequest(id)).invoke(model) + } + .interceptModification { incomingMod -> + var newReference: RID? = null + 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)))) + } + +/** + * 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.setDenormalizations(reference).invoke(model) + } + .interceptReplace { model -> + val reference = deno.reference.get(model)?.let { deno.info.table().getOrBadRequest(it) } + deno.setDenormalizations(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.setDenormalizations(source)) + ) + } + 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/helpers.kt b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt new file mode 100644 index 000000000..7c774a1e6 --- /dev/null +++ b/typed/src/main/kotlin/com/lightningkite/lightningserver/typed/denormalize/helpers.kt @@ -0,0 +1,25 @@ +package com.lightningkite.lightningserver.typed.denormalize + +import com.lightningkite.services.data.Denormalized +import com.lightningkite.services.database.optics.Optic + +/** 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 watch b.c }` then `a.c.denormalizes(C.info) { c -> a.cName watch c.name }`." + ) +} + +/** 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." + } +} + +// TODO: Api Recommendations +// Claude: +// - 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 new file mode 100644 index 000000000..a8ef99e3b --- /dev/null +++ b/typed/src/test/kotlin/com/lightningkite/lightningserver/typed/denormalize/DenormalizationTest.kt @@ -0,0 +1,429 @@ +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 +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.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 +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 + +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.modelInfoWithDeno?, DenoCity, Uuid>( + auth = noAuth, + tableName = "DenoCity", + permissions = { ModelPermissions.allowAll() }, + ) { city -> + city.country.denormalizes(countryInfo) { country -> + city.countryName watch country.name + city.countryNameWhenAssigned snapshot country.name + } + } + + val personInfo = database.modelInfoWithDeno?, DenoPerson, Uuid>( + auth = noAuth, + tableName = "DenoPerson", + permissions = { + ModelPermissions.allowAll().withAdditionalUpdateRestrictions { person -> + person.country.cannotBeModified() + person.countryName.cannotBeModified() + person.favoriteCityName.cannotBeModified() + } + }, + ) { person -> + person.city.denormalizes(cityInfo) { city -> + person.country watch city.country + } + person.country.denormalizes(countryInfo) { country -> + person.countryName watch country.name + } + 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 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) + } + + object MisconfiguredServer : ServerBuilder() { + val database = setting("database", Database.Settings()) + + val readsACopy = database.modelInfoWithDeno?, DenoPerson, Uuid>( + auth = noAuth, + tableName = "ReadsACopyPerson", + permissions = { ModelPermissions.allowAll() }, + ) { person -> + person.city.denormalizes(DenoServer.cityInfo) { city -> + person.countryName watch city.countryName + } + } + + val writesAnUnmarkedField = database.modelInfoWithDeno?, DenoCity, Uuid>( + auth = noAuth, + tableName = "UnmarkedCity", + permissions = { ModelPermissions.allowAll() }, + ) { city -> + city.country.denormalizes(DenoServer.countryInfo) { country -> + city.name watch 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.countryNameWhenAssigned) + assertEquals("France", personInfo.table().get(person._id)!!.countryName) + } + } + + @Test + 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 { + 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.countryNameWhenAssigned) + } + } + + @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 { + 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 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 } + 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().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 }) + } + + 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(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 +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 countryNameWhenAssigned: 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, + val job: DenoJob? = null, +) : HasId + +@Queryable +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 = "", +)