github.com/storacha/go-ucanto@v0.7.2/server/retrieval/cache.go (about) 1 package retrieval 2 3 import ( 4 "context" 5 "fmt" 6 7 lru "github.com/hashicorp/golang-lru/v2" 8 "github.com/storacha/go-ucanto/core/delegation" 9 "github.com/storacha/go-ucanto/core/ipld" 10 ) 11 12 const MemoryDelegationCacheSize = 100 13 14 type MemoryDelegationCache struct { 15 data *lru.Cache[string, delegation.Delegation] 16 } 17 18 func (m *MemoryDelegationCache) Get(ctx context.Context, root ipld.Link) (delegation.Delegation, bool, error) { 19 d, ok := m.data.Get(root.String()) 20 return d, ok, nil 21 } 22 23 func (m *MemoryDelegationCache) Put(ctx context.Context, d delegation.Delegation) error { 24 m.data.Add(d.Link().String(), d) 25 return nil 26 } 27 28 var _ delegation.Store = (*MemoryDelegationCache)(nil) 29 30 // NewMemoryDelegationCache creates a new in memory LRU cache for delegations 31 // that implements [DelegationStore]. The size parameter controls the maximum 32 // number of delegations that can be cached. Pass a value less than 1 to use the 33 // default cache size [MemoryDelegationCacheSize]. 34 func NewMemoryDelegationCache(size int) (*MemoryDelegationCache, error) { 35 if size <= 0 { 36 size = MemoryDelegationCacheSize 37 } 38 cache, err := lru.New[string, delegation.Delegation](size) 39 if err != nil { 40 return nil, fmt.Errorf("creating delegation LRU: %w", err) 41 } 42 return &MemoryDelegationCache{data: cache}, nil 43 }