github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/app/rpc/namespaces/eth/state/lru.go (about)

     1  package state
     2  
     3  import (
     4  	"errors"
     5  	"sync"
     6  
     7  	"github.com/spf13/viper"
     8  	"github.com/tendermint/go-amino"
     9  
    10  	lru "github.com/hashicorp/golang-lru"
    11  )
    12  
    13  //the default lru cache size is 1kw, that means the max memory size we needs is (32 + 32 + 4) * 10000000, about 700MB
    14  var (
    15  	defaultLruSize int = 10000000
    16  	gStateLru      *lru.Cache
    17  	once           sync.Once
    18  )
    19  
    20  //redefine fast-query to avoid cycle package import
    21  const FlagFastQuery = "fast-query"
    22  
    23  func isWatcherEnabled() bool {
    24  	return viper.GetBool(FlagFastQuery)
    25  }
    26  
    27  func InstanceOfStateLru() *lru.Cache {
    28  	once.Do(func() {
    29  		if isWatcherEnabled() {
    30  			var e error = nil
    31  			gStateLru, e = lru.New(defaultLruSize)
    32  			if e != nil {
    33  				panic(errors.New("Failed to call InstanceOfStateLru cause :" + e.Error()))
    34  			}
    35  		}
    36  	})
    37  	return gStateLru
    38  }
    39  
    40  func GetStateFromLru(key []byte) []byte {
    41  	cache := InstanceOfStateLru()
    42  	if cache == nil {
    43  		return nil
    44  	}
    45  	value, ok := cache.Get(amino.BytesToStr(key))
    46  	if ok {
    47  		ret, ok := value.([]byte)
    48  		if ok {
    49  			return ret
    50  		}
    51  	}
    52  	return nil
    53  }
    54  
    55  func SetStateToLru(key []byte, value []byte) {
    56  	cache := InstanceOfStateLru()
    57  	if cache == nil {
    58  		return
    59  	}
    60  	cache.Add(amino.BytesToStr(key), value)
    61  }