From dfe47d3683e3f0aaecfb410bbaa0b5d9ca259292 Mon Sep 17 00:00:00 2001 From: LUC DUZAN Date: Mon, 20 Jun 2022 18:59:58 +0200 Subject: [PATCH] fix managed cache invalidate not being lazy (#88) --- .../main/scala/zio/cache/ManagedCache.scala | 3 ++- .../scala/zio/cache/ManagedCacheSpec.scala | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/zio-cache/shared/src/main/scala/zio/cache/ManagedCache.scala b/zio-cache/shared/src/main/scala/zio/cache/ManagedCache.scala index 5819f4d..87ea97d 100644 --- a/zio-cache/shared/src/main/scala/zio/cache/ManagedCache.scala +++ b/zio-cache/shared/src/main/scala/zio/cache/ManagedCache.scala @@ -238,12 +238,13 @@ object ManagedCache { finalManaged.flatMap(_.use_(ZIO.unit)) } - override def invalidate(k: Key): UIO[Unit] = + override def invalidate(k: Key): UIO[Unit] = UIO.effectSuspendTotal { map.remove(k) match { case complete @ MapValue.Complete(_, _, _, _, _) => complete.releaseOwner case MapValue.Refreshing(_, complete) => complete.releaseOwner case _ => UIO.unit } + } override def invalidateAll: UIO[Unit] = ZIO.foreachPar_(map.keySet().asScala)(invalidate) diff --git a/zio-cache/shared/src/test/scala/zio/cache/ManagedCacheSpec.scala b/zio-cache/shared/src/test/scala/zio/cache/ManagedCacheSpec.scala index de17251..8e78653 100644 --- a/zio-cache/shared/src/test/scala/zio/cache/ManagedCacheSpec.scala +++ b/zio-cache/shared/src/test/scala/zio/cache/ManagedCacheSpec.scala @@ -56,6 +56,32 @@ object ManagedCacheSpec extends DefaultRunnableSpec { } } yield result }, + testM("invalidate should not invalidate anything before effect is evaluated") { + for { + observablesResource <- ObservableResourceForTest.makeUnit + managedCache = + ManagedCache.make( + capacity = 4, + timeToLive = Duration.Infinity, + lookup = ManagedLookup((_: Unit) => observablesResource.managed) + ) + result <- + managedCache.use { cache => + for { + _ <- cache.get(key = ()).use_(ZIO.unit) + invalidateEffect = cache.invalidate(key = ()) + cacheContainsKey42BeforeInvalidate <- cache.contains(key = ()) + resourceNotCleanedBeforeInvalidate <- observablesResource.assertAcquiredOnceAndNotCleaned + _ <- cache.get(()).use_(ZIO.unit) + _ <- invalidateEffect + cacheContainsKey42AfterInvalidate <- cache.contains(key = ()) + resourceCleanedAfterInvalidate <- observablesResource.assertAcquiredOnceAndCleaned + } yield assert(cacheContainsKey42BeforeInvalidate)(isTrue) && assert(cacheContainsKey42AfterInvalidate)( + isFalse + ) && resourceNotCleanedBeforeInvalidate && resourceCleanedAfterInvalidate + } + } yield result + }, testM("invalidateAll should properly remove and clean all resource from the cache") { val capacity = 100 for {