Skip to content

Commit

Permalink
Avoid incrementing cache hits for expired entries (#2159)
Browse files Browse the repository at this point in the history
  • Loading branch information
IMax153 authored Feb 15, 2024
1 parent bc8404d commit 2c5cbcd
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/forty-coins-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

Avoid incrementing cache hits for expired entries
2 changes: 1 addition & 1 deletion packages/effect/src/internal/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,11 +551,11 @@ class CacheImpl<in out Key, in out Error, in out Value> implements Cache.Cache<K
switch (value._tag) {
case "Complete": {
this.trackAccess(value.key)
this.trackHit()
if (this.hasExpired(clock, value.timeToLiveMillis)) {
MutableHashMap.remove(this.cacheState.map, value.key.current)
return core.succeed(Option.none<Value>())
}
this.trackHit()
return core.map(value.exit, Option.some)
}
case "Pending": {
Expand Down
22 changes: 22 additions & 0 deletions packages/effect/test/Cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import * as it from "effect-test/utils/extend"
import * as Cache from "effect/Cache"
import * as Effect from "effect/Effect"
import * as TestClock from "effect/TestClock"
import { describe, expect } from "vitest"

describe("Cache", () => {
it.effect("should not increment cache hits on expired entries", () =>
Effect.gen(function*(_) {
const cache = yield* _(Cache.make({
capacity: 100,
timeToLive: "1 seconds",
lookup: (n: number) => Effect.succeed(n)
}))
yield* _(cache.get(42))
yield* _(TestClock.adjust("2 seconds"))
yield* _(cache.get(42))
const { hits, misses } = yield* _(cache.cacheStats)
expect(hits).toBe(0)
expect(misses).toBe(2)
}))
})

0 comments on commit 2c5cbcd

Please sign in to comment.