Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
Original file line number Diff line number Diff line change
@@ -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<Model : HasId<ID>, ID : Comparable<ID>>(
override val wraps: Table<Model>,
val includeMassUpdates: Boolean = true,
private val interceptor: suspend (instance: RuntimeDeferred<Model>, mod: Modification<Model>) -> Modification<Model>,
) : Table<Model> 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<out T : Any>(private val wraps: RuntimeDeferred<T>) : RuntimeDeferred<T> {
@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<Model>.onInstance(instance: Model): Condition<Model> {
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<Model>.onInstance(instance: LazyInstance<Model>): Condition<Model> =
instance.cached()?.let { // instance retrieved, make sure we only modify the same instance retrieved
onInstance(it)
} ?: this


override suspend fun insert(models: Iterable<Model>): List<Model> =
wraps.insert(models.map { // no need to catch
interceptor(Runtime.Constant(it), Modification.Assign(it))(it)
})

override suspend fun replaceOne(
condition: Condition<Model>,
model: Model,
orderBy: List<SortPart<Model>>,
): EntryChange<Model> = 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: Model,
orderBy: List<SortPart<Model>>,
): 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<Model>,
modification: Modification<Model>,
model: Model,
): EntryChange<Model> {
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<Model>,
modification: Modification<Model>,
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<Model>,
modification: Modification<Model>,
orderBy: List<SortPart<Model>>,
): EntryChange<Model> = 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<Model>,
modification: Modification<Model>,
orderBy: List<SortPart<Model>>,
): 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<Model>,
modification: Modification<Model>,
): CollectionChanges<Model> {
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<Model>,
modification: Modification<Model>,
): 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 <Model : HasId<ID>, ID : Comparable<ID>> Table<Model>.interceptChangeWithLazyInstance(
includeMassUpdates: Boolean = true,
interceptor: suspend (instance: RuntimeDeferred<Model>, mod: Modification<Model>) -> Modification<Model>,
): Table<Model> = LazyInstanceTable(this, includeMassUpdates, interceptor)
Original file line number Diff line number Diff line change
Expand Up @@ -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<SUBJECT : HasId<*>?, T : HasId<ID>, ID : Comparable<ID>> {
public val serializer: KSerializer<T>
Expand All @@ -24,7 +25,7 @@ public interface ModelInfo<SUBJECT : HasId<*>?, T : HasId<ID>, ID : Comparable<I
}

public val tableName: String
get() = serializer.descriptor.serialName.substringBefore('/').substringBefore('<').substringAfterLast('.')
get() = registration.tableDefinition.name

public fun registerChangeListener(action: suspend context(ServerRuntime) (CollectionChanges<T>) -> Unit)

Expand Down Expand Up @@ -53,11 +54,13 @@ public interface ModelInfo<SUBJECT : HasId<*>?, T : HasId<ID>, ID : Comparable<I

context(server: ServerRuntime)
public suspend fun table(auth: AuthAccess<SUBJECT>): Table<T>

context(server: ServerRuntime)
public suspend fun permissions(auth: AuthAccess<SUBJECT>): ModelPermissions<T>

context(server: ServerRuntime)
public suspend fun defaultItem(auth: Authentication<SUBJECT & Any>?): T = serializer.default()

context(server: ServerRuntime)
public fun exampleItem(): T? = null
}
Expand All @@ -67,55 +70,26 @@ public inline fun <reified USER : HasId<*>?, reified T : HasId<ID>, reified ID :
auth: AuthRequirement<USER>,
tableName: String,
subscope: Subscope? = Subscope(tableName.lowercase()),
crossinline signals: context(ServerRuntime) (Table<T>) -> Table<T> = { it },
crossinline log: context(ServerRuntime) AuthAccess<USER>?.(Table<T>) -> Table<T> = { it },
crossinline systemAccess: context(ServerRuntime) (Table<T>) -> Table<T> = { it },
noinline signals: context(ServerRuntime) (Table<T>) -> Table<T> = { it },
noinline log: context(ServerRuntime) AuthAccess<USER>?.(Table<T>) -> Table<T> = { it },
noinline systemAccess: context(ServerRuntime) (Table<T>) -> Table<T> = { it },
noinline postPermissionsForUser: suspend context(ServerRuntime) AuthAccess<USER>.(Table<T>) -> Table<T> = { it },
crossinline permissions: suspend context(ServerRuntime) AuthAccess<USER>.() -> ModelPermissions<T>,
noinline permissions: suspend context(ServerRuntime) AuthAccess<USER>.() -> ModelPermissions<T>,
noinline prePermissionsForUser: suspend context(ServerRuntime) AuthAccess<USER>.(Table<T>) -> Table<T> = { it },
): ModelInfo<USER, T, ID> = object : ModelInfo<USER, T, ID> {
override val serializer: KSerializer<T> = serializerOrContextual<T>()
override val idSerializer: KSerializer<ID> = serializerOrContextual<ID>()

override val auth: AuthRequirement<USER> = subscope?.let { auth.subscope(it) } ?: auth

// registerTable defines the table, registers it, and creates its (once-per-deploy) prepare task.
override val registration: DatabaseTableRegistration<T> = this@modelInfo.registerTable(tableName, serializer)

@UnauditedDatabaseAccess
context(server: ServerRuntime)
override fun dangerouslyDirectTable(): Table<T> = registration()

context(server: ServerRuntime)
override fun baseTable(): Table<T> = log(null, registration())

override val tableName: String get() = tableName

val changeListeners = ArrayList<suspend context(ServerRuntime) (CollectionChanges<T>) -> Unit>()
override fun registerChangeListener(action: suspend context(ServerRuntime) (CollectionChanges<T>) -> Unit) {
changeListeners += action
}

context(server: ServerRuntime)
override suspend fun permissions(auth: AuthAccess<USER>): ModelPermissions<T> = 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<USER>): Table<T> = collectionWithSignals()
.let { log(auth, it) }
.let { postPermissionsForUser(auth, it) }
.withPermissions(permissions(auth))
.let { prePermissionsForUser(auth, it) }

context(server: ServerRuntime)
override fun table(): Table<T> = systemAccess(log(null, collectionWithSignals()))
}
): ModelInfo<USER, T, ID> =
explicitModelInfo(
auth = auth,
serializer = serializerOrContextual<T>(),
idSerializer = serializerOrContextual<ID>(),
tableName = tableName,
subscope = subscope,
signals = signals,
log = log,
systemAccess = systemAccess,
postPermissionsForUser = postPermissionsForUser,
permissions = permissions,
prePermissionsForUser = prePermissionsForUser
)


context(builder: ServerBuilder)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,17 @@ public suspend fun <Model : HasId<ID>, ID : Comparable<ID>> Table<Model>.getOrFo
?: throw ForbiddenException(message)
}

/**
* Retrieves the [Model] with [id], or throws an [IllegalStateException] with the provided [message] if not found.
* */
public suspend fun <Model : HasId<ID>, ID : Comparable<ID>> Table<Model>.getOrThrow(
id: ID,
message: String = "${serializer.descriptor.serialName.substringAfterLast('.')} $id not recognized",
): Model =
get(id) ?: throw IllegalStateException(message)

public context(server: ServerRuntime)
fun <Model : HasId<ID>, ID : Comparable<ID>> Table<Model>.withServerRuntimeChangeListeners(
context(server: ServerRuntime)
public fun <Model : HasId<ID>, ID : Comparable<ID>> Table<Model>.withServerRuntimeChangeListeners(
changeListeners: List<suspend context(ServerRuntime) (CollectionChanges<Model>) -> Unit>,
): Table<Model> = object : Table<Model> by this@withServerRuntimeChangeListeners {
override val wraps = this@withServerRuntimeChangeListeners
Expand Down
Loading
Loading