|
| 1 | +// Package cache implements bridge to fast in-memory object cache. |
| 2 | +package cache |
| 3 | + |
| 4 | +import ( |
| 5 | + "fantom-api-graphql/internal/types" |
| 6 | + "github.com/ethereum/go-ethereum/common" |
| 7 | + "github.com/ethereum/go-ethereum/common/hexutil" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// delegationCacheKey generates cache key for the given delegation. |
| 12 | +func delegationCacheKey(adr common.Address, valID *hexutil.Big) string { |
| 13 | + var key strings.Builder |
| 14 | + key.WriteString("dlg") |
| 15 | + key.WriteString(adr.String()) |
| 16 | + key.WriteString("to") |
| 17 | + key.WriteString(valID.String()) |
| 18 | + return key.String() |
| 19 | +} |
| 20 | + |
| 21 | +// PullDelegation tries to pull delegation from the given address to the given validator |
| 22 | +// from internal in-memory cache. |
| 23 | +func (b *MemBridge) PullDelegation(adr common.Address, valID *hexutil.Big) *types.Delegation { |
| 24 | + // try to get the account data from the cache |
| 25 | + data, err := b.cache.Get(delegationCacheKey(adr, valID)) |
| 26 | + if err != nil { |
| 27 | + return nil |
| 28 | + } |
| 29 | + |
| 30 | + // do we have the data? |
| 31 | + dlg := new(types.Delegation) |
| 32 | + if err := dlg.UnmarshalBSON(data); err != nil { |
| 33 | + b.log.Criticalf("can not decode delegation data from in-memory cache; %s", err.Error()) |
| 34 | + return nil |
| 35 | + } |
| 36 | + return dlg |
| 37 | +} |
| 38 | + |
| 39 | +// PushDelegation stored the given delegation in memory cache. |
| 40 | +func (b *MemBridge) PushDelegation(dlg *types.Delegation) { |
| 41 | + // no need to store nil |
| 42 | + if dlg == nil { |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + // encode account |
| 47 | + data, err := dlg.MarshalBSON() |
| 48 | + if err != nil { |
| 49 | + b.log.Criticalf("can not marshal delegation of %s to #%d; %s", dlg.Address.String(), dlg.ToStakerId.ToInt().Uint64(), err.Error()) |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + // set the data to cache by block number |
| 54 | + if err := b.cache.Set(delegationCacheKey(dlg.Address, dlg.ToStakerId), data); err != nil { |
| 55 | + b.log.Criticalf("can not cache delegation of %s to #%d; %s", dlg.Address.String(), dlg.ToStakerId.ToInt().Uint64(), err.Error()) |
| 56 | + } |
| 57 | +} |
0 commit comments