feat: add cache implementation

This commit is contained in:
2024-04-17 13:36:26 +08:00
parent 7263fc1950
commit 0aa1db902e
9 changed files with 107 additions and 14 deletions

38
internal/cache/cache.go vendored Normal file
View File

@@ -0,0 +1,38 @@
package cache
import (
"log/slog"
"github.com/grassrootseconomics/celo-tracker/internal/chain"
)
type (
Cache interface {
Purge() error
Exists(string) bool
Add(string) bool
Size() int
}
CacheOpts struct {
Logg *slog.Logger
Chain *chain.Chain
CacheType string
}
)
func New(o CacheOpts) Cache {
var (
cache Cache
)
switch o.CacheType {
case "map":
cache = NewMapCache()
default:
cache = NewMapCache()
}
o.Logg.Debug("bootstrapping cache")
return cache
}

39
internal/cache/map.go vendored Normal file
View File

@@ -0,0 +1,39 @@
package cache
import (
"log/slog"
"github.com/puzpuzpuz/xsync/v3"
)
type (
MapCache struct {
mapCache *xsync.Map
logg *slog.Logger
}
)
func NewMapCache() *MapCache {
return &MapCache{
mapCache: xsync.NewMap(),
}
}
func (c *MapCache) Purge() error {
c.mapCache.Clear()
return nil
}
func (c *MapCache) Exists(key string) bool {
_, ok := c.mapCache.Load(key)
return ok
}
func (c *MapCache) Add(key string) bool {
c.mapCache.Store(key, nil)
return true
}
func (c *MapCache) Size() int {
return c.mapCache.Size()
}