infra/proxyd/proxyd/consensus_tracker.go

73 lines
1.9 KiB
Go
Raw Normal View History

2023-04-18 21:57:55 +03:00
package proxyd
import (
"context"
"fmt"
"sync"
2023-04-21 20:36:42 +03:00
"github.com/ethereum/go-ethereum/common/hexutil"
2023-04-18 21:57:55 +03:00
"github.com/go-redis/redis/v8"
)
// ConsensusTracker abstracts how we store and retrieve the current consensus
// allowing it to be stored locally in-memory or in a shared Redis cluster
type ConsensusTracker interface {
2023-04-21 20:36:42 +03:00
GetConsensusBlockNumber() hexutil.Uint64
SetConsensusBlockNumber(blockNumber hexutil.Uint64)
2023-04-18 21:57:55 +03:00
}
// InMemoryConsensusTracker store and retrieve in memory, async-safe
type InMemoryConsensusTracker struct {
2023-04-21 20:36:42 +03:00
consensusBlockNumber hexutil.Uint64
2023-04-18 21:57:55 +03:00
mutex sync.Mutex
}
func NewInMemoryConsensusTracker() ConsensusTracker {
return &InMemoryConsensusTracker{
2023-04-21 20:36:42 +03:00
consensusBlockNumber: 0,
2023-04-18 21:57:55 +03:00
mutex: sync.Mutex{},
}
}
2023-04-21 20:36:42 +03:00
func (ct *InMemoryConsensusTracker) GetConsensusBlockNumber() hexutil.Uint64 {
2023-04-18 21:57:55 +03:00
defer ct.mutex.Unlock()
ct.mutex.Lock()
return ct.consensusBlockNumber
}
2023-04-21 20:36:42 +03:00
func (ct *InMemoryConsensusTracker) SetConsensusBlockNumber(blockNumber hexutil.Uint64) {
2023-04-18 21:57:55 +03:00
defer ct.mutex.Unlock()
ct.mutex.Lock()
ct.consensusBlockNumber = blockNumber
}
// RedisConsensusTracker uses a Redis `client` to store and retrieve consensus, async-safe
type RedisConsensusTracker struct {
ctx context.Context
client *redis.Client
backendGroup string
}
func NewRedisConsensusTracker(ctx context.Context, r *redis.Client, namespace string) ConsensusTracker {
return &RedisConsensusTracker{
ctx: ctx,
client: r,
backendGroup: namespace,
}
}
func (ct *RedisConsensusTracker) key() string {
return fmt.Sprintf("consensus_latest_block:%s", ct.backendGroup)
}
2023-04-21 20:36:42 +03:00
func (ct *RedisConsensusTracker) GetConsensusBlockNumber() hexutil.Uint64 {
return hexutil.Uint64(hexutil.MustDecodeUint64(ct.client.Get(ct.ctx, ct.key()).Val()))
2023-04-18 21:57:55 +03:00
}
2023-04-21 20:36:42 +03:00
func (ct *RedisConsensusTracker) SetConsensusBlockNumber(blockNumber hexutil.Uint64) {
2023-04-18 21:57:55 +03:00
ct.client.Set(ct.ctx, ct.key(), blockNumber, 0)
}