From 45d1a468e83c12a45a655c5e3bb810bbbdb2d424 Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Thu, 12 Jan 2023 16:38:03 +0100 Subject: [PATCH] abi.go: Get rid of global state by defining an AbiManager struct. --- abi.go | 26 ++++++++++++++++++-------- main.go | 8 +++++--- ship_processor.go | 2 +- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/abi.go b/abi.go index 2d4a62e..4d60a57 100644 --- a/abi.go +++ b/abi.go @@ -1,7 +1,7 @@ package main import ( - "encoding/json" + "context" "fmt" "time" @@ -12,29 +12,39 @@ import ( redis_cache "github.com/go-redis/cache/v8" ) -var abiCache *abi_cache.Cache +type AbiManager struct { + cache *abi_cache.Cache + api *eos.API + ctx context.Context +} -func InitAbiCache(id string) { +func NewAbiManager(api *eos.API, id string) *AbiManager { // Init abi cache - abiCache = abi_cache.New("ship.cache."+id+".abi", &redis_cache.Options{ + cache := abi_cache.New("ship.cache."+id+".abi", &redis_cache.Options{ Redis: redis.Client(), // Cache 10k keys for 10 minutes. LocalCache: redis_cache.NewTinyLFU(10000, 10*time.Minute), }) + + return &AbiManager{ + cache: cache, + api: api, + ctx: context.Background(), + } } -func GetAbi(account eos.AccountName) (*eos.ABI, error) { +func (mgr *AbiManager) GetAbi(account eos.AccountName) (*eos.ABI, error) { key := string(account) - abi, err := abiCache.Get(key) + abi, err := mgr.cache.Get(key) if err != nil { - resp, err := eosClient.GetABI(eosClientCtx, account) + resp, err := mgr.api.GetABI(mgr.ctx, account) if err != nil { return nil, fmt.Errorf("api: %s", err) } abi = &resp.ABI - err = abiCache.Set(key, abi, time.Hour) + err = mgr.cache.Set(key, abi, time.Hour) if err != nil { return nil, fmt.Errorf("cache: %s", err) } diff --git a/main.go b/main.go index 9e1a2bf..d03f9fe 100644 --- a/main.go +++ b/main.go @@ -35,6 +35,8 @@ var ( eosClientCtx = context.Background() ) +var abi_mgr *AbiManager + var redisNs redis.Namespace // Reader states @@ -216,9 +218,6 @@ func main() { return } - // Init Abi cache - InitAbiCache(conf.Redis.CacheID) - // Connect client and get chain info. log.Printf("Get chain info from api at: %s", conf.Api) eosClient = eos.New(conf.Api) @@ -228,6 +227,9 @@ func main() { return } + // Init Abi cache + abi_mgr = abi.NewAbiManager(eosClient, conf.Redis.CacheID) + redisNs = redis.Namespace{ Prefix: conf.Redis.Prefix, ChainID: chainInfo.ChainID.String(), diff --git a/ship_processor.go b/ship_processor.go index e6f91d8..611cae3 100644 --- a/ship_processor.go +++ b/ship_processor.go @@ -91,7 +91,7 @@ func processTraces(traces []*ship.TransactionTraceV0) { HexData: hex.EncodeToString(act_trace.Act.Data), } - abi, err := GetAbi(act_trace.Act.Account) + abi, err := abi_mgr.GetAbi(act_trace.Act.Account) if err == nil { v, err := decodeAction(abi, act_trace.Act.Data, act_trace.Act.Name) if err != nil {