Skip to content

Commit 5f77dd6

Browse files
upstream: fix(cache): avoid double prefix when removing expired entries (goharbor/harbor#23913)
Signed-off-by: Hanabi <317387557+Hanabi9248@users.noreply.github.com> (cherry picked from commit 8ca2cc23229e577fa72ddb9f0088bdd5beda827f) Upstream-Commit: 8ca2cc23229e577fa72ddb9f0088bdd5beda827f Upstream-PR: goharbor/harbor#23913 Upstream-Author: @Hanabi9248 Cherry-Pick-Status: clean Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 51dda34 commit 5f77dd6

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

src/lib/cache/memory/memory.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func (c *Cache) Contains(ctx context.Context, key string) bool {
5151
}
5252

5353
if e.(*entry).isExpirated() {
54-
err := c.Delete(ctx, c.opts.Key(key))
54+
err := c.Delete(ctx, key)
5555
log.Errorf("failed to delete cache in Contains() method when it's expired, error: %v", err)
5656
return false
5757
}
@@ -74,7 +74,7 @@ func (c *Cache) Fetch(ctx context.Context, key string, value any) error {
7474

7575
e := v.(*entry)
7676
if e.isExpirated() {
77-
err := c.Delete(ctx, c.opts.Key(key))
77+
err := c.Delete(ctx, key)
7878
if err != nil {
7979
log.Errorf("failed to delete cache in Fetch() method when it's expired, error: %v", err)
8080
}

src/lib/cache/memory/memory_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"testing"
2121
"time"
2222

23+
"github.com/stretchr/testify/require"
2324
"github.com/stretchr/testify/suite"
2425

2526
"github.com/goharbor/harbor/src/lib/cache"
@@ -164,6 +165,29 @@ func TestCacheTestSuite(t *testing.T) {
164165
suite.Run(t, new(CacheTestSuite))
165166
}
166167

168+
func TestExpiredPrefixedEntry(t *testing.T) {
169+
for _, operation := range []string{"contains", "fetch"} {
170+
t.Run(operation, func(t *testing.T) {
171+
ctx := context.Background()
172+
c, err := cache.New("memory", cache.Prefix("prefix:"))
173+
require.NoError(t, err)
174+
require.NoError(t, c.Save(ctx, "key", "expired", -time.Second))
175+
require.NoError(t, c.Save(ctx, "prefix:key", "live"))
176+
if operation == "contains" {
177+
require.False(t, c.Contains(ctx, "key"))
178+
} else {
179+
var value string
180+
require.ErrorIs(t, c.Fetch(ctx, "key", &value), cache.ErrNotFound)
181+
}
182+
var value string
183+
require.NoError(t, c.Fetch(ctx, "prefix:key", &value))
184+
require.Equal(t, "live", value)
185+
_, exists := c.(*Cache).storage.Load("prefix:key")
186+
require.False(t, exists, "the expired entry must be removed")
187+
})
188+
}
189+
}
190+
167191
func BenchmarkCacheFetchParallel(b *testing.B) {
168192
key := "benchmark"
169193
cache, _ := cache.New("memory")

0 commit comments

Comments
 (0)