From 490e9b34d2ca7802239991150ecf423983532aae Mon Sep 17 00:00:00 2001 From: Adam Fraser Date: Thu, 19 Oct 2023 10:41:29 -0700 Subject: [PATCH 1/2] do not increment cache hits for expired entries --- .../src/main/scala/zio/cache/Cache.scala | 2 +- .../src/test/scala/zio/cache/CacheSpec.scala | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/zio-cache/shared/src/main/scala/zio/cache/Cache.scala b/zio-cache/shared/src/main/scala/zio/cache/Cache.scala index da44d61..3eeeb67 100644 --- a/zio-cache/shared/src/main/scala/zio/cache/Cache.scala +++ b/zio-cache/shared/src/main/scala/zio/cache/Cache.scala @@ -225,11 +225,11 @@ object Cache { promise.await case MapValue.Complete(key, exit, _, timeToLive) => trackAccess(key) - trackHit() if (hasExpired(timeToLive)) { map.remove(k, value) get(in) } else { + trackHit() ZIO.done(exit) } case MapValue.Refreshing( diff --git a/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala b/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala index 3d2cf46..d021898 100644 --- a/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala +++ b/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala @@ -1,14 +1,17 @@ package zio.cache -import zio.test.Assertion._ +import zio._ import zio.test._ -import zio.{Duration, Ref, Scope, UIO, ZIO, duration2DurationOps} +import zio.test.Assertion._ object CacheSpec extends ZIOSpecDefault { def hash(x: Int): Int => UIO[Int] = y => ZIO.succeed((x ^ y).hashCode) + val identity: Int => UIO[Int] = + ZIO.succeed(_) + def spec: Spec[TestEnvironment with Scope, Any] = suite("CacheSpec")( test("cacheStats") { check(Gen.int) { salt => @@ -142,6 +145,18 @@ object CacheSpec extends ZIOSpecDefault { size <- cache.size } yield assertTrue(size == 10) } + }, + test("cache hits should not be incremented for expired entries") { + for { + cache <- Cache.make(100, 1.second, Lookup(identity)) + _ <- cache.get(42) + _ <- TestClock.adjust(2.seconds) + _ <- cache.get(42) + cacheStats <- cache.cacheStats + hits = cacheStats.hits + misses = cacheStats.misses + } yield assertTrue(hits == 0L) && + assertTrue(misses == 2L) } ) } From 61fc8e196e183620acd76ddf3d46a21ec261ecee Mon Sep 17 00:00:00 2001 From: Adam Fraser Date: Thu, 19 Oct 2023 10:52:38 -0700 Subject: [PATCH 2/2] format --- zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala b/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala index d021898..620c02a 100644 --- a/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala +++ b/zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala @@ -1,8 +1,8 @@ package zio.cache import zio._ -import zio.test._ import zio.test.Assertion._ +import zio.test._ object CacheSpec extends ZIOSpecDefault {