-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
head_saver.go
78 lines (62 loc) · 2.28 KB
/
head_saver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package headtracker
import (
"context"
"github.com/ethereum/go-ethereum/common"
httypes "github.com/smartcontractkit/chainlink/core/chains/evm/headtracker/types"
evmtypes "github.com/smartcontractkit/chainlink/core/chains/evm/types"
"github.com/smartcontractkit/chainlink/core/logger"
)
type headSaver struct {
orm ORM
config Config
logger logger.Logger
heads Heads
}
func NewHeadSaver(lggr logger.Logger, orm ORM, config Config) httypes.HeadSaver {
return &headSaver{
orm: orm,
config: config,
logger: lggr.Named("HeadSaver"),
heads: NewHeads(),
}
}
func (hs *headSaver) Save(ctx context.Context, head *evmtypes.Head) error {
if err := hs.orm.IdempotentInsertHead(ctx, head); err != nil {
return err
}
historyDepth := uint(hs.config.EvmHeadTrackerHistoryDepth())
hs.heads.AddHeads(historyDepth, head)
return hs.orm.TrimOldHeads(ctx, historyDepth)
}
func (hs *headSaver) LoadFromDB(ctx context.Context) (chain *evmtypes.Head, err error) {
historyDepth := uint(hs.config.EvmHeadTrackerHistoryDepth())
heads, err := hs.orm.LatestHeads(ctx, historyDepth)
if err != nil {
return nil, err
}
hs.heads.AddHeads(historyDepth, heads...)
return hs.heads.LatestHead(), nil
}
func (hs *headSaver) LatestHeadFromDB(ctx context.Context) (head *evmtypes.Head, err error) {
return hs.orm.LatestHead(ctx)
}
func (hs *headSaver) LatestChain() *evmtypes.Head {
head := hs.heads.LatestHead()
if head == nil {
return nil
}
if head.ChainLength() < hs.config.EvmFinalityDepth() {
hs.logger.Debugw("chain shorter than EvmFinalityDepth", "chainLen", head.ChainLength(), "evmFinalityDepth", hs.config.EvmFinalityDepth())
}
return head
}
func (hs *headSaver) Chain(hash common.Hash) *evmtypes.Head {
return hs.heads.HeadByHash(hash)
}
var NullSaver httypes.HeadSaver = &nullSaver{}
type nullSaver struct{}
func (*nullSaver) Save(ctx context.Context, head *evmtypes.Head) error { return nil }
func (*nullSaver) LoadFromDB(ctx context.Context) (*evmtypes.Head, error) { return nil, nil }
func (*nullSaver) LatestHeadFromDB(ctx context.Context) (*evmtypes.Head, error) { return nil, nil }
func (*nullSaver) LatestChain() *evmtypes.Head { return nil }
func (*nullSaver) Chain(hash common.Hash) *evmtypes.Head { return nil }