Skip to content

Commit

Permalink
Fix invariants for expireAfter (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel authored Dec 23, 2024
1 parent b27b8c0 commit 1ff5c87
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import java.util.concurrent.Executor
* If the suspendable computation throws or computes a null value then the
* entry will be automatically removed.
*/
fun <K, V> Caffeine<Any, Any>.asCache(): Cache<K, V> {
fun <K : Any?, V : Any?> Caffeine<in K, in V>.asCache(): Cache<K, V> {
val scope = CoroutineScope(Dispatchers.IO + CoroutineName("Aedile-AsyncLoadingCache-Scope") + SupervisorJob())
return asCache(scope)
}
Expand All @@ -34,7 +34,7 @@ fun <K, V> Caffeine<Any, Any>.asCache(): Cache<K, V> {
* If the suspendable computation throws or computes a null value then the
* entry will be automatically removed.
*/
fun <K, V> Caffeine<Any, Any>.asCache(scope: CoroutineScope): Cache<K, V> {
fun <K : Any?, V : Any?> Caffeine<in K, in V>.asCache(scope: CoroutineScope): Cache<K, V> {
return Cache(scope, true, buildAsync())
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.sksamuel.aedile.core

import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.Expiry
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.delay
import org.checkerframework.checker.index.qual.NonNegative

class AsCacheTest : FunSpec() {
init {
Expand Down Expand Up @@ -110,5 +112,37 @@ class AsCacheTest : FunSpec() {
cache.contains("wibble") shouldBe true
cache.contains("bubble") shouldBe false
}

test("check invariants on expire after") {
val loggerExpiry = object : Expiry<Int, String> {
override fun expireAfterRead(
key: Int?,
value: String?,
currentTime: Long,
currentDuration: @NonNegative Long
): Long {
return 0
}

override fun expireAfterCreate(key: Int?, value: String?, currentTime: Long): Long {
return 0
}

override fun expireAfterUpdate(
key: Int?,
value: String?,
currentTime: Long,
currentDuration: @NonNegative Long
): Long {
return 0
}
}

Caffeine.newBuilder()
.maximumSize(2000)
.initialCapacity(500)
.expireAfter(loggerExpiry)
.asCache<Int, String>()
}
}
}

0 comments on commit 1ff5c87

Please sign in to comment.