Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Expiration of Caffeine Cache #562

Merged
merged 2 commits into from
Sep 9, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class CaffeineCache[F[_]: Sync, V](val underlying: CCache[String, Entry[V]])(imp
def doGet(key: String): F[Option[V]] = {
F.delay {
Option(underlying.getIfPresent(key))
}.flatMap(_.filterA(Entry.isExpired[F, V]))
}.flatMap(_.filterA(Entry.isBeforeExpiration[F, V]))
.map(_.map(_.value))
.flatTap { result =>
logCacheHitOrMiss(key, result)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,11 @@ class CaffeineCacheSpec extends AnyFlatSpec with Matchers with BeforeAndAfter wi
newIOCache(underlying).get("non-existent key").map(_ shouldBe None)
}

it should "return None if the given key exists but the value has expired" in ticked { _ =>
it should "return None if the given key exists but the value has expired" in ticked { ticker =>
val ctx = ticker.ctx
val underlying = newCCache
val expiredEntry =
Entry("hello", expiresAt = Some(Instant.now.minusSeconds(1)))
Entry("hello", expiresAt = Some(Instant.ofEpochMilli(ctx.now().toMillis).minusSeconds(1)))
underlying.put("key1", expiredEntry)
newIOCache(underlying).get("key1").map(_ shouldBe None)
}
Expand Down
16 changes: 6 additions & 10 deletions modules/core/src/main/scala/scalacache/Entry.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,13 @@ case class Entry[+A](value: A, expiresAt: Option[Instant])

object Entry {

/** Has the entry expired yet?
*/
def isExpired[F[_], A](entry: Entry[A])(implicit clock: Clock[F], applicative: Applicative[F]): F[Boolean] =
def isBeforeExpiration[F[_], A](entry: Entry[A])(implicit clock: Clock[F], applicative: Applicative[F]): F[Boolean] =
entry.expiresAt
.traverse { expiration =>
val now = clock.monotonic.map(m => Instant.ofEpochMilli(m.toMillis))

now.map(expiration.isBefore(_))
}
.map {
case None | Some(true) => true
case Some(false) => false
clock.realTimeInstant.map(_.isBefore(expiration))
}
.map(_.getOrElse(true))

def isExpired[F[_], A](entry: Entry[A])(implicit clock: Clock[F], applicative: Applicative[F]): F[Boolean] =
isBeforeExpiration[F, A](entry).map(b => !b)
}