forked from orijtech/groupcache
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package minigc | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
|
||
"github.com/vimeo/galaxycache/lru" | ||
) | ||
|
||
type HydrateCB[K comparable, V any] func(ctx context.Context, key K) (V, error) | ||
|
||
// StarSystem is an in-process cache intended for in-memory data | ||
// It's a thin wrapper around another cache implementation that takes care of | ||
// filling cache misses instead of requiring Add() calls. | ||
// Note: the underlying cache implementation may change at any time. | ||
type StarSystem[K comparable, V any] struct { | ||
lru lru.TypedCache[K, V] | ||
hydrateCB HydrateCB[K, V] | ||
mu sync.Mutex | ||
} | ||
|
||
type StarSystemParams[K comparable, V any] struct { | ||
// MaxEntries is the maximum number of cache entries before | ||
// an item is evicted. Zero means no limit. | ||
MaxEntries int | ||
|
||
// OnEvicted optionally specificies a callback function to be | ||
// executed when an typedEntry is purged from the cache. | ||
OnEvicted func(key K, value V) | ||
} | ||
|
||
func NewStarSystem[K comparable, V any](cb HydrateCB[K, V], params StarSystemParams[K, V]) *StarSystem[K, V] { | ||
return &StarSystem[K, V]{ | ||
hydrateCB: cb, | ||
lru: lru.TypedCache[K, V]{ | ||
MaxEntries: params.MaxEntries, | ||
OnEvicted: params.OnEvicted, | ||
}, | ||
} | ||
} | ||
|
||
func (s *StarSystem[K, V]) Get(ctx context.Context, key K) (V, error) { | ||
s.mu.Lock() | ||
defer s.mu.Unlock() | ||
if v, ok := s.lru.Get(key); ok { | ||
return v, nil | ||
} | ||
val, hydErr := s.hydrateCB(ctx, key) | ||
if hydErr != nil { | ||
var zv V | ||
return zv, hydErr | ||
} | ||
s.lru.Add(key, val) | ||
return val, nil | ||
} |