Skip to content

Commit

Permalink
Cached Tool with seed (#759)
Browse files Browse the repository at this point in the history
  • Loading branch information
javipacheco authored Jun 11, 2024
1 parent ede4497 commit 9e854cd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,34 @@ import arrow.fx.coroutines.timeInMillis
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days

data class CachedToolKey<K>(val value: K, val seed: String)

data class CachedToolValue<V>(val value: V, val timestamp: Long)

abstract class CachedTool<Input, Output>(
private val cache: Atomic<MutableMap<Input, CachedToolInfo<Output>>>,
private val cache: Atomic<MutableMap<CachedToolKey<Input>, CachedToolValue<Output>>>,
private val seed: String,
private val timeCachePolicy: Duration = 1.days
) : Tool<Input, Output> {

override suspend fun invoke(input: Input): Output {
return cache(input) { onCacheMissed(input) }
return cache(CachedToolKey(input, seed)) { onCacheMissed(input) }
}

abstract suspend fun onCacheMissed(input: Input): Output

private suspend fun cache(input: Input, block: suspend () -> Output): Output {
private suspend fun cache(input: CachedToolKey<Input>, block: suspend () -> Output): Output {
val cachedToolInfo = cache.get().get(input)
if (cachedToolInfo != null) {
val lastTimeInCache = timeInMillis() - timeCachePolicy.inWholeMilliseconds
if (lastTimeInCache > cachedToolInfo.timestamp) {
cache.get().remove(input)
} else {
return cachedToolInfo.response
return cachedToolInfo.value
}
}
val response = block()
cache.get().put(input, CachedToolInfo(response, timeInMillis()))
cache.get().put(input, CachedToolValue(response, timeInMillis()))
return response
}
}

This file was deleted.

0 comments on commit 9e854cd

Please sign in to comment.