Skip to content

Commit

Permalink
WIP: minigc package with StarSystem
Browse files Browse the repository at this point in the history
  • Loading branch information
dfinkel committed Jan 13, 2025
1 parent 5440c82 commit c154aab
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions minigc/minigc.go
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
}

0 comments on commit c154aab

Please sign in to comment.