-
Notifications
You must be signed in to change notification settings - Fork 1
/
mai.go
265 lines (206 loc) · 6.19 KB
/
mai.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package mai
import (
"context"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/trylotus/connector"
"github.com/trylotus/connector/chain/ethereum"
lotuscommon "github.com/trylotus/connector/common"
"github.com/trylotus/connector/kafkautils"
"github.com/rs/zerolog/log"
)
type Config struct {
Blockchain string
FromBlock uint64
NumBlocks uint64
}
type Connector struct {
*ethereum.Connector
*Config
addresses []common.Address
blockRetry blocksToRetry
contracts map[string]*Contract
}
type blocksToRetry struct {
blocks []uint64
mu sync.Mutex
}
func New(conf *Config) *Connector {
adr := ContractAddresses[conf.Blockchain]
addresses := GetAddresses(adr)
contracts := GetContracts(adr)
opts := make([]connector.Option, 0)
if conf.FromBlock > 0 || conf.NumBlocks > 0 {
opts = append(opts, connector.BackfillOption())
}
ec := ethereum.NewConnector(context.Background(), addresses, conf.Blockchain, opts...)
return &Connector{
Config: conf,
Connector: ec,
addresses: addresses,
blockRetry: blocksToRetry{blocks: make([]uint64, 0)},
contracts: contracts,
}
}
func (c *Connector) Start() {
ctx := context.TODO()
c.Connector.RegisterProtos(kafkautils.MsgTypeBf, protos...)
backfillSignal := make(chan struct{})
if c.FromBlock == 0 && c.NumBlocks == 0 {
// LIVE DATA
// Backfill last few blocks at every start
const defaultBackfill = 100
go c.backfill(ctx, nil, 0, defaultBackfill)
// Listen live data
go c.listenLogs(ctx)
} else {
// HISTORICAL DATA
go c.backfill(ctx, backfillSignal, c.FromBlock, c.NumBlocks)
}
// Retry failed blocks
c.retry(ctx, backfillSignal)
log.Info().Msg("shutting down connector...")
time.Sleep(5 * time.Second)
c.Sub.Close()
}
// backfill queries for historical data and pushes them to Kafka.
func (c *Connector) backfill(ctx context.Context, sig chan struct{}, fromBlock, numBlocks uint64) {
if sig != nil {
defer close(sig)
}
var blockNumber uint64
messages := make([]*kafkautils.Message, 0)
if logs, err := ethereum.BackfillEventsWithQueryParams(ctx, c.Client, c.addresses, fromBlock, numBlocks); err == nil {
for bfLog := range logs {
select {
case <-c.Sub.Done():
return
default:
if msg := c.parse(kafkautils.MsgTypeBf, ethereum.Log{Log: bfLog}); msg != nil {
messages = append(messages, msg)
// Commit messages at every new block
if blockNumber != bfLog.BlockNumber {
c.Connector.ProduceWithTransaction(messages)
blockNumber = bfLog.BlockNumber
messages = make([]*kafkautils.Message, 0)
}
}
}
}
// Flush out last messages
c.Connector.ProduceWithTransaction(messages)
}
log.Info().Uint64("from", fromBlock).Uint64("num blocks", numBlocks).Msg("backfill completed")
}
// listenLogs subscribes to live data and pushes incoming logs to Kafka.
func (c *Connector) listenLogs(ctx context.Context) {
// Register topic and protobuf type mappings
c.RegisterProtos(kafkautils.MsgTypeFct, protos...)
c.Sub.Subscribe(ctx)
var blockNumber uint64
messages := make([]*kafkautils.Message, 0)
for vLog := range c.Sub.Logs() {
if msg := c.parse(kafkautils.MsgTypeFct, vLog); msg != nil {
messages = append(messages, msg)
// Commit messages at every new block
if blockNumber != vLog.BlockNumber {
c.Connector.ProduceWithTransaction(messages)
blockNumber = vLog.BlockNumber
messages = make([]*kafkautils.Message, 0)
}
}
}
// Flush out last messages
c.Connector.ProduceWithTransaction(messages)
}
// parse extracts data from incoming event log and converts into a Kafka message.
func (c *Connector) parse(msgType kafkautils.MsgType, vLog ethereum.Log) *kafkautils.Message {
address := vLog.Address.String()
if c.contracts[address] == nil {
log.Info().Str("address", address).Msg("Event from unsupported address")
return nil
}
contract := c.contracts[address]
contractAbi := contract.ABI
contractName := contract.Name
eventParser := contract.MessageParser
abiEvent, err := contractAbi.EventByID(vLog.Topics[0])
if err != nil {
log.Warn().Str("contract name", contractName).Err(err).Msg("Failed to get event from ABI")
return nil
}
bt, err := c.Sub.GetBlockTime(context.Background(), vLog.Log)
if err != nil {
log.Error().Str("contract name", contractName).Err(err).Msg("Failed to retrieve timestamp")
}
timestamp := lotuscommon.UnixToTimestampPb(int64(bt * 1000))
msg := eventParser.Message(abiEvent.Name, contractAbi, vLog.Log, timestamp)
if msg == nil {
log.Warn().Str("event", abiEvent.Name).Msg("event is not defined")
return nil
}
return &kafkautils.Message{
MsgType: msgType,
ProtoMsg: msg,
}
}
func (c *Connector) retry(ctx context.Context, backfillSignal chan struct{}) {
const (
initialBackoff = time.Second
maxBackoff = 24 * time.Hour
)
backoff := initialBackoff
for {
select {
case <-c.Sub.Done():
return
case <-backfillSignal:
// Wait until all blocks in the queue are retried
if len(c.blockRetry.blocks) == 0 {
return
}
default:
if len(c.blockRetry.blocks) > 0 {
blockNo := c.blockRetry.pop()
logs, err := ethereum.HistoricalEventsWithQueryParams(ctx, c.Client, nil, blockNo, 1)
if err != nil {
time.Sleep(backoff)
log.Warn().Err(err).Uint64("block", blockNo).Uint("backoff seconds", uint(backoff.Seconds())).Msg("failed to retrieve block, skipping...")
c.blockRetry.push(blockNo)
backoff *= 2
} else {
messages := make([]*kafkautils.Message, 0)
for bfLog := range logs {
if msg := c.parse(kafkautils.MsgTypeBf, ethereum.Log{Log: bfLog}); msg != nil {
messages = append(messages, msg)
}
c.Connector.ProduceWithTransaction(messages)
}
backoff = initialBackoff
}
} else {
time.Sleep(backoff)
}
}
if backoff > maxBackoff {
for i := 0; i < len(c.blockRetry.blocks); i++ {
blockNo := c.blockRetry.pop()
log.Error().Uint64("block", blockNo).Msg("failed to retrieve block permanently")
}
return
}
}
}
func (b *blocksToRetry) push(blockNo uint64) {
b.mu.Lock()
defer b.mu.Unlock()
b.blocks = append(b.blocks, blockNo)
}
func (b *blocksToRetry) pop() uint64 {
b.mu.Lock()
defer b.mu.Unlock()
blockNo := b.blocks[0]
b.blocks = b.blocks[1:]
return blockNo
}