Skip to content

Commit

Permalink
fix concurrent cache issues
Browse files Browse the repository at this point in the history
  • Loading branch information
xrstf committed Apr 19, 2022
1 parent 62c6e3d commit 526d60a
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cache

import (
"fmt"
"sync"
"time"

"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
Expand All @@ -14,15 +15,20 @@ type cacheItem struct {

type ResourceCache struct {
resources map[string]cacheItem
lock *sync.RWMutex
}

func NewCache() *ResourceCache {
return &ResourceCache{
resources: map[string]cacheItem{},
lock: &sync.RWMutex{},
}
}

func (rc *ResourceCache) Get(obj *unstructured.Unstructured) (*unstructured.Unstructured, time.Time) {
rc.lock.RLock()
defer rc.lock.RUnlock()

existing, exists := rc.resources[rc.objectKey(obj)]
if !exists {
return nil, time.Time{}
Expand All @@ -32,13 +38,19 @@ func (rc *ResourceCache) Get(obj *unstructured.Unstructured) (*unstructured.Unst
}

func (rc *ResourceCache) Set(obj *unstructured.Unstructured) {
rc.lock.Lock()
defer rc.lock.Unlock()

rc.resources[rc.objectKey(obj)] = cacheItem{
resource: obj.DeepCopy(),
lastSeen: time.Now(),
}
}

func (rc *ResourceCache) Delete(obj *unstructured.Unstructured) {
rc.lock.Lock()
defer rc.lock.Unlock()

delete(rc.resources, rc.objectKey(obj))
}

Expand Down

0 comments on commit 526d60a

Please sign in to comment.