fix(cache): update LastAccess on file cache hit to prevent stale entries
This commit is contained in:
parent
f240892475
commit
1899964ee4
11
internal/cache/file_cache.go
vendored
11
internal/cache/file_cache.go
vendored
@ -148,6 +148,17 @@ func (c *FileCache) Get(path string) (*FileEntry, bool) {
|
||||
return entry, true
|
||||
}
|
||||
|
||||
// 更新近似 LRU 访问时间(每 5 秒或超过 10% inactive 间隔才写,减少锁竞争)
|
||||
const accessUpdateInterval = 5 * time.Second
|
||||
if time.Since(entry.LastAccess) > accessUpdateInterval {
|
||||
c.mu.Lock()
|
||||
if e, ok := c.entries[path]; ok && e == entry {
|
||||
e.LastAccess = time.Now()
|
||||
c.lruList.MoveToFront(e.element)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// 近似 LRU: 不更新 LastAccess/LRU 位置,直接返回
|
||||
// 精确 LRU 由 Set/Delete/evict 操作保证
|
||||
return entry, true
|
||||
|
||||
24
internal/cache/file_cache_test.go
vendored
Normal file
24
internal/cache/file_cache_test.go
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
// Package cache 提供文件缓存功能测试。
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFileCacheLastAccessUpdatedOnHit(t *testing.T) {
|
||||
c := NewFileCache(1, 1<<20, 10*time.Second)
|
||||
c.Set("/x", []byte("data"), 4, time.Now(), "text/plain")
|
||||
|
||||
entry := c.entries["/x"]
|
||||
before := entry.LastAccess
|
||||
// 将访问时间设为过去,确保超过 accessUpdateInterval 阈值但不超过 inactive
|
||||
entry.LastAccess = before.Add(-7 * time.Second)
|
||||
|
||||
c.Get("/x")
|
||||
after := c.entries["/x"].LastAccess
|
||||
|
||||
if !after.After(before) {
|
||||
t.Fatal("LastAccess was not updated on cache hit")
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user