Skip to content

Commit

Permalink
Fix expired in get
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhang Hongyu authored and maypok86 committed Aug 14, 2024
1 parent a828b6e commit 3880b58
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
22 changes: 22 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,3 +488,25 @@ func (h *optimalHeap) Pop() any {
*h = old[0 : n-1]
return x
}

func Test_GetExpired(t *testing.T) {
c, err := MustBuilder[string, string](1000000).
CollectStats().
DeletionListener(func(key string, value string, cause DeletionCause) {
fmt.Println(cause)
if cause != Expired {
t.Fatalf("err not expired: %v", cause)
}
}).
WithVariableTTL().
Build()
if err != nil {
t.Fatal(err)
}
c.Set("test1", "123456", time.Duration(12)*time.Second)
for i := 0; i < 5; i++ {
c.Get("test1")
time.Sleep(3 * time.Second)
}
time.Sleep(1 * time.Second)
}
7 changes: 6 additions & 1 deletion internal/core/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,8 @@ func (c *Cache[K, V]) GetNode(key K) (node.Node[K, V], bool) {
}

if n.HasExpired() {
c.writeBuffer.Push(newDeleteTask(n))
n.Die()
c.writeBuffer.Push(newExpiredTask(n))
c.stats.IncMisses()
return nil, false
}
Expand Down Expand Up @@ -437,6 +438,10 @@ func (c *Cache[K, V]) onWrite(t task[K, V]) {
c.expiryPolicy.Delete(n)
c.policy.Delete(n)
c.notifyDeletion(n.Key(), n.Value(), Explicit)
case t.isExpired():
c.expiryPolicy.Delete(n)
c.policy.Delete(n)
c.notifyDeletion(n.Key(), n.Value(), Expired)
}
}

Expand Down
14 changes: 14 additions & 0 deletions internal/core/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const (
updateReason
clearReason
closeReason
expiredReason
)

// task is a set of information to update the cache:
Expand All @@ -53,6 +54,14 @@ func newDeleteTask[K comparable, V any](n node.Node[K, V]) task[K, V] {
}
}

// newExpireTask creates a task to delete a expired node from policies.
func newExpiredTask[K comparable, V any](n node.Node[K, V]) task[K, V] {
return task[K, V]{
n: n,
writeReason: expiredReason,
}
}

// newUpdateTask creates a task to update the node in the policies.
func newUpdateTask[K comparable, V any](n, oldNode node.Node[K, V]) task[K, V] {
return task[K, V]{
Expand Down Expand Up @@ -96,6 +105,11 @@ func (t *task[K, V]) isDelete() bool {
return t.writeReason == deleteReason
}

// isExpired returns true if this is an expired task.
func (t *task[K, V]) isExpired() bool {
return t.writeReason == expiredReason
}

// isUpdate returns true if this is an update task.
func (t *task[K, V]) isUpdate() bool {
return t.writeReason == updateReason
Expand Down

0 comments on commit 3880b58

Please sign in to comment.