-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
head_listener.go
188 lines (160 loc) · 5.14 KB
/
head_listener.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package headtracker
import (
"context"
"fmt"
"time"
"github.com/ethereum/go-ethereum"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/atomic"
evmclient "github.com/smartcontractkit/chainlink/core/chains/evm/client"
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"
"github.com/smartcontractkit/chainlink/core/utils"
)
var (
promNumHeadsReceived = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "head_tracker_heads_received",
Help: "The total number of heads seen",
}, []string{"evmChainID"})
promEthConnectionErrors = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "head_tracker_eth_connection_errors",
Help: "The total number of eth node connection errors",
}, []string{"evmChainID"})
)
type headListener struct {
config Config
ethClient evmclient.Client
logger logger.Logger
chStop chan struct{}
chHeaders chan *evmtypes.Head
headSubscription ethereum.Subscription
connected atomic.Bool
receivingHeads atomic.Bool
}
// NewHeadListener creates a new HeadListener
func NewHeadListener(lggr logger.Logger, ethClient evmclient.Client, config Config, chStop chan struct{}) httypes.HeadListener {
return &headListener{
config: config,
ethClient: ethClient,
logger: lggr.Named("HeadListener"),
chStop: chStop,
}
}
func (hl *headListener) ListenForNewHeads(handleNewHead httypes.NewHeadHandler, done func()) {
defer done()
defer hl.unsubscribe()
ctx, cancel := utils.ContextFromChan(hl.chStop)
defer cancel()
for {
if !hl.subscribe(ctx) {
break
}
err := hl.receiveHeaders(ctx, handleNewHead)
if ctx.Err() != nil {
break
} else if err != nil {
hl.logger.Errorw(fmt.Sprintf("Error in new head subscription, unsubscribed: %s", err.Error()), "err", err)
continue
} else {
break
}
}
}
func (hl *headListener) ReceivingHeads() bool {
return hl.receivingHeads.Load()
}
func (hl *headListener) Connected() bool {
return hl.connected.Load()
}
func (hl *headListener) receiveHeaders(ctx context.Context, handleNewHead httypes.NewHeadHandler) error {
var noHeadsAlarmC <-chan time.Time
var noHeadsAlarmT *time.Ticker
noHeadsAlarmDuration := hl.config.BlockEmissionIdleWarningThreshold()
if noHeadsAlarmDuration > 0 {
noHeadsAlarmT = time.NewTicker(noHeadsAlarmDuration)
noHeadsAlarmC = noHeadsAlarmT.C
}
for {
select {
case <-hl.chStop:
return nil
case blockHeader, open := <-hl.chHeaders:
if noHeadsAlarmT != nil {
// We've received a head, reset the no heads alarm
noHeadsAlarmT.Stop()
noHeadsAlarmT = time.NewTicker(noHeadsAlarmDuration)
noHeadsAlarmC = noHeadsAlarmT.C
}
hl.receivingHeads.Store(true)
if !open {
return errors.New("head listener: chHeaders prematurely closed")
}
if blockHeader == nil {
hl.logger.Error("got nil block header")
continue
}
if blockHeader.EVMChainID == nil || !utils.NewBig(hl.ethClient.ChainID()).Equal(blockHeader.EVMChainID) {
hl.logger.Panicf("head listener for %s received block header for %s", hl.ethClient.ChainID(), blockHeader.EVMChainID)
}
promNumHeadsReceived.WithLabelValues(hl.ethClient.ChainID().String()).Inc()
err := handleNewHead(ctx, blockHeader)
if ctx.Err() != nil {
return nil
} else if err != nil {
return err
}
case err, open := <-hl.headSubscription.Err():
// err can be nil, because of using chainIDSubForwarder
if !open || err == nil {
return errors.New("head listener: subscription Err channel prematurely closed")
}
return err
case <-noHeadsAlarmC:
// We haven't received a head on the channel for a long time, log a warning
hl.logger.Warn(fmt.Sprintf("have not received a head for %v", noHeadsAlarmDuration))
hl.receivingHeads.Store(false)
}
}
}
func (hl *headListener) subscribe(ctx context.Context) bool {
subscribeRetryBackoff := utils.NewRedialBackoff()
chainID := hl.ethClient.ChainID().String()
for {
hl.unsubscribe()
hl.logger.Debugf("Subscribing to new heads on chain %s", chainID)
select {
case <-hl.chStop:
return false
case <-time.After(subscribeRetryBackoff.Duration()):
err := hl.subscribeToHead(ctx)
if err != nil {
promEthConnectionErrors.WithLabelValues(hl.ethClient.ChainID().String()).Inc()
hl.logger.Warnw(fmt.Sprintf("Failed to subscribe to heads on chain %s", chainID), "err", err)
} else {
hl.logger.Debugf("Subscribed to heads on chain %s", chainID)
return true
}
}
}
}
func (hl *headListener) subscribeToHead(ctx context.Context) error {
hl.chHeaders = make(chan *evmtypes.Head)
var err error
hl.headSubscription, err = hl.ethClient.SubscribeNewHead(ctx, hl.chHeaders)
if err != nil {
close(hl.chHeaders)
return errors.Wrap(err, "EthClient#SubscribeNewHead")
}
hl.connected.Store(true)
return nil
}
func (hl *headListener) unsubscribe() {
if hl.headSubscription != nil {
hl.connected.Store(false)
hl.headSubscription.Unsubscribe()
hl.headSubscription = nil
}
}