From f46fe4996bc4b798f63737d33699239f709912dd Mon Sep 17 00:00:00 2001 From: Aayush Date: Fri, 12 May 2023 17:28:51 -0400 Subject: [PATCH] feat: chainstore: remove locking in index cache --- chain/store/index.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/chain/store/index.go b/chain/store/index.go index 620cb2dee..0690c87d4 100644 --- a/chain/store/index.go +++ b/chain/store/index.go @@ -4,7 +4,8 @@ import ( "context" "os" "strconv" - "sync" + + lru "github.com/hashicorp/golang-lru/v2" "golang.org/x/xerrors" @@ -27,8 +28,7 @@ func init() { } type ChainIndex struct { - indexCacheLk sync.Mutex - indexCache map[types.TipSetKey]*lbEntry + indexCache *lru.ARCCache[types.TipSetKey, *lbEntry] loadTipSet loadTipSetFunc @@ -37,8 +37,9 @@ type ChainIndex struct { type loadTipSetFunc func(context.Context, types.TipSetKey) (*types.TipSet, error) func NewChainIndex(lts loadTipSetFunc) *ChainIndex { + sc, _ := lru.NewARC[types.TipSetKey, *lbEntry](DefaultChainIndexCacheSize) return &ChainIndex{ - indexCache: make(map[types.TipSetKey]*lbEntry, DefaultChainIndexCacheSize), + indexCache: sc, loadTipSet: lts, skipLength: 20, } @@ -59,11 +60,9 @@ func (ci *ChainIndex) GetTipsetByHeight(ctx context.Context, from *types.TipSet, return nil, xerrors.Errorf("failed to round down: %w", err) } - ci.indexCacheLk.Lock() - defer ci.indexCacheLk.Unlock() cur := rounded.Key() for { - lbe, ok := ci.indexCache[cur] + lbe, ok := ci.indexCache.Get(cur) if !ok { fc, err := ci.fillCache(ctx, cur) if err != nil { @@ -137,7 +136,7 @@ func (ci *ChainIndex) fillCache(ctx context.Context, tsk types.TipSetKey) (*lbEn targetHeight: skipTarget.Height(), target: skipTarget.Key(), } - ci.indexCache[tsk] = lbe + ci.indexCache.Add(tsk, lbe) return lbe, nil }