fix(pkg/cache/disk): LRU 节点类型断言失败时降级而非 panic

items 与 evictList 的不变量一旦被破坏,读、写、删除与淘汰路径上的裸类型断言
会直接崩掉进程。改为带 ok 检查:Get 退化为缓存未命中,Set 报告污染条目,
deleteUnlocked 跳过容量回退,evict 移除坏节点后继续。

新增 cache_corruption_test.go 锁住该行为:去掉守卫后用例会以
「interface conversion: interface {} is string, not *disk.cacheItem」失败,
加上守卫后 4 个用例全通过。

验证:go build 通过;go test ./pkg/cache/disk/ 全绿(含原有 5 个用例);
golangci-lint 0 issues;check_cordis_architecture.sh 0 violations。
This commit is contained in:
ryan
2026-08-30 01:00:02 +08:00
parent 8ff017b5e8
commit f3d85d51fb
2 changed files with 91 additions and 7 deletions
+28 -7
View File
@@ -143,7 +143,10 @@ func (c *Cache) Set(key string, value []byte, ttl time.Duration) error {
// Update memory tracker
if elem, ok := c.items[key]; ok {
item := elem.Value.(*cacheItem)
item, ok := elem.Value.(*cacheItem)
if !ok {
return fmt.Errorf("cache: evict list entry for %q has invalid type %T", key, elem.Value)
}
c.currentSize += size - item.size
item.size = size
item.expiredAt = expiredAt
@@ -174,7 +177,11 @@ func (c *Cache) Get(key string) ([]byte, error) {
return nil, ErrCacheMiss
}
item := elem.Value.(*cacheItem)
item, ok := elem.Value.(*cacheItem)
if !ok {
c.mu.RUnlock()
return nil, ErrCacheMiss
}
if !item.expiredAt.IsZero() && time.Now().After(item.expiredAt) {
c.mu.RUnlock()
return c.getAndDeleteIfExpired(key)
@@ -224,7 +231,11 @@ func (c *Cache) getAndDeleteIfExpired(key string) ([]byte, error) {
return nil, ErrCacheMiss
}
item := elem.Value.(*cacheItem)
item, ok := elem.Value.(*cacheItem)
if !ok {
_ = c.deleteUnlocked(key)
return nil, ErrCacheMiss
}
if !item.expiredAt.IsZero() && time.Now().After(item.expiredAt) {
_ = c.deleteUnlocked(key)
return nil, ErrCacheMiss
@@ -254,8 +265,9 @@ func (c *Cache) Delete(key string) error {
func (c *Cache) deleteUnlocked(key string) error {
if elem, ok := c.items[key]; ok {
item := elem.Value.(*cacheItem)
c.currentSize -= item.size
if item, ok := elem.Value.(*cacheItem); ok {
c.currentSize -= item.size
}
c.evictList.Remove(elem)
delete(c.items, key)
}
@@ -308,7 +320,11 @@ func (c *Cache) evict() {
for c.currentSize > c.maxSize && c.evictList.Len() > 0 {
elem := c.evictList.Back()
item := elem.Value.(*cacheItem)
item, ok := elem.Value.(*cacheItem)
if !ok {
c.evictList.Remove(elem)
continue
}
c.currentSize -= item.size
c.evictList.Remove(elem)
delete(c.items, item.key)
@@ -400,7 +416,12 @@ func (c *Cache) cleanExpired() {
now := time.Now()
for key, elem := range c.items {
item := elem.Value.(*cacheItem)
item, ok := elem.Value.(*cacheItem)
if !ok {
c.evictList.Remove(elem)
delete(c.items, key)
continue
}
if !item.expiredAt.IsZero() && now.After(item.expiredAt) {
c.currentSize -= item.size
c.evictList.Remove(elem)