-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.go
307 lines (258 loc) · 7.84 KB
/
source.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package relay
import (
"context"
"errors"
"sync"
"github.com/cenkalti/backoff"
rpchttp "github.com/cometbft/cometbft/rpc/client/http"
ctypes "github.com/cometbft/cometbft/rpc/core/types"
"github.com/cometbft/cometbft/types"
"github.com/warp-contracts/syncer/src/utils/config"
"github.com/warp-contracts/syncer/src/utils/model"
"github.com/warp-contracts/syncer/src/utils/monitoring"
"github.com/warp-contracts/syncer/src/utils/task"
"gorm.io/gorm"
)
// Produces a stream of Sequencer's blocks
// Blocks are put on the Output channel in order of height
// It uses Streamer to get new blocks from the Sequencer
// It uses Sequencer's REST API to download historical or missing blocks
// Handles gaps in the input stream
type Source struct {
*task.Task
input <-chan *types.Block
Output chan *types.Block
db *gorm.DB
monitor monitoring.Monitor
client *rpchttp.HTTP
lastSyncedHeight uint64
}
func NewSource(config *config.Config) (self *Source) {
self = new(Source)
self.Output = make(chan *types.Block, 1)
self.Task = task.NewTask(config, "source").
WithWorkerPool(config.Relayer.SourceMaxWorkers, config.Relayer.SourceMaxQueueSize).
WithSubtaskFunc(self.run).
WithOnAfterStop(func() {
close(self.Output)
})
return
}
func (self *Source) WithMonitor(monitor monitoring.Monitor) *Source {
self.monitor = monitor
return self
}
func (self *Source) WithDB(db *gorm.DB) *Source {
self.db = db
return self
}
func (self *Source) WithInputChannel(input <-chan *types.Block) *Source {
self.input = input
return self
}
func (self *Source) WithClient(client *rpchttp.HTTP) *Source {
self.client = client
return self
}
func (self *Source) initLastSyncedHeight() (err error) {
var state model.State
err = self.db.WithContext(self.Ctx).
First(&state, model.SyncedComponentRelayer).
Error
if err == nil {
// NO ERROR
self.lastSyncedHeight = state.FinishedBlockHeight
self.Log.WithField("height", self.lastSyncedHeight).Info("Found sync state of the relayer")
return
}
// ERROR
if !errors.Is(err, gorm.ErrRecordNotFound) {
self.Log.WithError(err).Error("Failed to get sync state of the relayer")
return
}
// No record found, create one
if !self.Config.IsDevelopment {
// In production
self.lastSyncedHeight = 0
} else {
// In development start syncing from the present block
status, err := self.client.Status(self.Ctx)
if err != nil {
self.Log.Error("Failed to get status of the blockchain")
return err
}
self.lastSyncedHeight = uint64(status.SyncInfo.LatestBlockHeight)
}
// Save the initial state to the database
state = model.State{
Name: model.SyncedComponentRelayer,
FinishedBlockHeight: self.lastSyncedHeight,
}
err = self.db.WithContext(self.Ctx).
Table(model.TableState).
Save(&state).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to update sync state after last block")
return err
}
self.Log.WithField("height", self.lastSyncedHeight).Info("Initialized sync state of the relayer")
return
}
func (self *Source) send(block *types.Block) (err error) {
if self.lastSyncedHeight+1 != uint64(block.Height) {
self.monitor.GetReport().Relayer.Errors.SequencerPermanentBlockDownloadError.Inc()
err = errors.New("gap in the blocks stream")
self.Log.WithField("last_synced_height", self.lastSyncedHeight).
WithField("block_height", block.Height).
WithError(err).
Error("Gap in the blocks stream")
return
}
select {
case <-self.Ctx.Done():
err = errors.New("task closing")
return
case self.Output <- block:
self.lastSyncedHeight = uint64(block.Height)
}
self.monitor.GetReport().Relayer.State.SequencerBlocksDownloaded.Inc()
return
}
// Downloads blocks in parallel
func (self *Source) download(len int) (err error) {
out := make([]*types.Block, len)
// Sync between workers
var mtx sync.Mutex
var wg sync.WaitGroup
wg.Add(len)
for i := 0; i < len; i++ {
i := i
height := int64(self.lastSyncedHeight) + int64(i+1)
self.SubmitToWorker(func() {
// Current height to download should
var (
errWorker error
block *ctypes.ResultBlock
)
// Retries downloading transaction until success or permanent error
errWorker = task.NewRetry().
WithContext(self.Ctx).
WithMaxElapsedTime(self.Config.Relayer.SourceBackoffMaxElapsedTime).
WithMaxInterval(self.Config.Relayer.SourceBackoffMaxInterval).
WithAcceptableDuration(self.Config.Relayer.SourceBackoffMaxInterval * 10).
WithOnError(func(err error, isDurationAcceptable bool) error {
self.Log.WithError(err).WithField("height", height).Warn("Failed to download Sequencer's block, retrying after timeout")
if errors.Is(err, context.Canceled) && self.IsStopping.Load() {
// Stopping
return backoff.Permanent(err)
}
self.monitor.GetReport().Relayer.Errors.SequencerBlockDownloadError.Inc()
return err
}).
Run(func() error {
var errBlock error
block, errBlock = self.client.Block(self.Ctx, &height)
return errBlock
})
if errWorker != nil {
// Permanent error
self.monitor.GetReport().Relayer.Errors.SequencerPermanentBlockDownloadError.Inc()
self.Log.WithError(errWorker).WithField("height", height).Error("Failed to download sequencer block, giving up")
if !self.IsStopping.Load() {
mtx.Lock()
err = errWorker
mtx.Unlock()
}
goto end
}
// Update monitoring
self.monitor.GetReport().Relayer.State.SequencerBlocksCatchedUp.Inc()
// Add to output
mtx.Lock()
out[i] = block.Block
mtx.Unlock()
end:
wg.Done()
})
}
// Wait for workers to finish
wg.Wait()
if err != nil {
// There was a permanent error
// This is serious, we cannot continue
self.Log.WithError(err).Error("Permanent error in one of the workers, can't continue")
return
}
// Put blocks into the Output channel
for _, block := range out {
err = self.send(block)
if err != nil {
return
}
}
return
}
// Download blocks from last synced blocked to the specified height (inclusive; height is downloaded)
func (self *Source) catchUp(height int64) (err error) {
len := height - int64(self.lastSyncedHeight)
if len <= 0 {
self.Log.WithField("last_synced_height", self.lastSyncedHeight).
WithField("desired_height", height).
Info("Catch up not possible")
return
}
self.Log.WithField("last_synced_height", self.lastSyncedHeight).
WithField("desired_height", height).
WithField("num_blocks_to_catch_up", len).
Info("-> Catching up")
defer self.Log.WithField("last_synced_height", self.lastSyncedHeight).
WithField("desired_height", height).
WithField("num_blocks_to_catch_up", len).
Info("<- Catching up")
// Divide remaining blocks into batches that are downloaded in parallel and put into the Output channel
// This is to avoid big pauses in block processing needed for downloading all blocks at once
numBatches := int(len) / self.Config.Relayer.SourceBatchSize
for i := 0; i < numBatches; i++ {
err = self.download(self.Config.Relayer.SourceBatchSize)
if err != nil {
return
}
}
// Last batch that contains less than SourceBatchSize blocks
lastBatchSize := int(len) % self.Config.Relayer.SourceBatchSize
if lastBatchSize != 0 {
err = self.download(lastBatchSize)
if err != nil {
return
}
}
return
}
func (self *Source) run() (err error) {
err = self.initLastSyncedHeight()
if err != nil {
return
}
for block := range self.input {
if uint64(block.Height) > self.lastSyncedHeight+1 {
err = self.catchUp(block.Height - 1)
if err != nil {
if self.IsStopping.Load() {
return nil
}
self.Log.WithError(err).
WithField("last_synced_height", self.lastSyncedHeight).
WithField("height", block.Height).
Error("Failed to catch up")
// This is a serious error, better stop the application
panic(err)
}
}
err = self.send(block)
if err != nil {
return
}
}
return
}