/
store.go
307 lines (266 loc) · 9.12 KB
/
store.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"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/cometbft/cometbft/libs/bytes"
"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"
"gorm.io/gorm/clause"
)
// Store handles saving data to the database in na robust way.
// - groups incoming Interactions into batches,
// - ensures data isn't stuck even if a batch isn't big enough
type Store struct {
*task.Processor[*Payload, *Payload]
DB *gorm.DB
monitor monitoring.Monitor
savedBlockHeight uint64
finishedTimestamp uint64
finishedHeight uint64
finishedBlockHash bytes.HexBytes
isReplacing bool
}
func NewStore(config *config.Config) (self *Store) {
self = new(Store)
self.Processor = task.NewProcessor[*Payload, *Payload](config, "store").
WithBatchSize(config.Relayer.StoreBatchSize).
WithOnFlush(config.Relayer.StoreMaxTimeInQueue, self.flush).
WithOnProcess(self.process).
WithBackoff(0, config.Relayer.StoreMaxBackoffInterval)
return
}
func (self *Store) WithMonitor(v monitoring.Monitor) *Store {
self.monitor = v
return self
}
func (self *Store) WithIsReplacing(v bool) *Store {
self.isReplacing = v
return self
}
func (self *Store) WithInputChannel(v chan *Payload) *Store {
self.Processor = self.Processor.WithInputChannel(v)
return self
}
func (self *Store) WithDB(v *gorm.DB) *Store {
self.DB = v
return self
}
func (self *Store) process(payload *Payload) (out []*Payload, err error) {
// self.Log.WithField("height", payload.SequencerBlockHeight).Debug("Processing")
self.finishedTimestamp = uint64(payload.SequencerBlockTimestamp)
self.finishedHeight = uint64(payload.SequencerBlockHeight)
self.finishedBlockHash = payload.SequencerBlockHash
out = []*Payload{payload}
return
}
func (self *Store) flush(payloads []*Payload) (out []*Payload, err error) {
if self.savedBlockHeight == self.finishedHeight && len(payloads) == 0 {
// No need to flush, nothing changed
return
}
self.Log.WithField("sequencer_height", self.finishedHeight).WithField("num", len(payloads)).Trace("-> Saving blocks")
defer self.Log.WithField("sequencer_height", self.finishedHeight).WithField("num", len(payloads)).Trace("<- Saving blocks")
if self.finishedHeight <= 0 {
err = errors.New("block height too small")
return
}
// Get data from payloads
lastArweaveBlock, arweaveInteractions, interactions, bundleItems, dataItems, err := self.getData(payloads)
if err != nil {
return
}
err = self.DB.WithContext(self.Ctx).
// Debug().
Transaction(func(tx *gorm.DB) error {
err = tx.WithContext(self.Ctx).
Model(&model.State{
Name: model.SyncedComponentRelayer,
}).
// State struct accepts block hash as bytes, but here we have only a string
Updates(map[string]interface{}{
"finished_block_timestamp": self.finishedTimestamp,
"finished_block_height": self.finishedHeight,
"finished_block_hash": self.finishedBlockHash.String(),
}).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to update last transaction block height")
return err
}
if lastArweaveBlock != nil {
// Save L1 interactions if there are any
err = tx.WithContext(self.Ctx).
Table(model.TableInteraction).
Clauses(clause.OnConflict{
DoNothing: !self.isReplacing,
Columns: []clause.Column{{Name: "interaction_id"}},
UpdateAll: self.isReplacing,
}, clause.Returning{Columns: []clause.Column{{Name: "id"}}}).
CreateInBatches(arweaveInteractions, self.Config.Relayer.StoreBatchSize).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to insert Arweave interactions")
return err
}
// Meta info about L1 interactions
if len(dataItems) != 0 {
err = tx.WithContext(self.Ctx).
Table(model.TableDataItem).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "data_item_id"}},
DoNothing: true,
}).
Create(&dataItems).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to insert data items")
return err
}
}
// Arweave interactions are saved in this transactions
err = self.updateFinishedArweaveBlock(tx, lastArweaveBlock)
if err != nil {
return err
}
}
if len(interactions) != 0 {
// Save L2 interactions if there are any
err = tx.WithContext(self.Ctx).
Clauses(clause.OnConflict{
DoNothing: !self.isReplacing,
Columns: []clause.Column{{Name: "interaction_id"}},
UpdateAll: self.isReplacing,
}).
CreateInBatches(&interactions, self.Config.Relayer.StoreBatchSize).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to insert Interactions")
return err
}
// Connect bundle items with interactions
// L1 interactions don't have corresponding bundle items
// FIXME: Handle bundle items with arweave interactions order
for idx := range interactions {
bundleItems[idx].InteractionID = interactions[idx].ID
}
// Save bundle items if there are any
err = tx.WithContext(self.Ctx).
Table(model.TableBundleItem).
Clauses(clause.OnConflict{
DoNothing: true,
Columns: []clause.Column{{Name: "interaction_id"}},
UpdateAll: false,
}).
CreateInBatches(bundleItems, self.Config.Relayer.StoreBatchSize).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to insert bundle items")
return err
}
}
return nil
})
if err != nil {
if errors.Is(err, context.Canceled) {
self.Log.WithError(err).Warn("Failed to insert bundle items, interactions and update state (context canceled)")
err = backoff.Permanent(err)
return
}
self.Log.WithError(err).Error("Failed to insert bundle items, interactions and update state")
return
}
// Update saved block height
self.savedBlockHeight = self.finishedHeight
// Successfuly saved interactions
self.monitor.GetReport().Relayer.State.InteractionsSaved.Add(uint64(len(interactions) + len(arweaveInteractions)))
self.monitor.GetReport().Relayer.State.L1InteractionsSaved.Add(uint64(len(arweaveInteractions)))
self.monitor.GetReport().Relayer.State.L2InteractionsSaved.Add(uint64(len(interactions)))
// Bundle items saved
self.monitor.GetReport().Relayer.State.BundleItemsSaved.Store(uint64(len(bundleItems)))
// Finished height of sequencer and arweave
self.monitor.GetReport().Relayer.State.SequencerFinishedHeight.Store(int64(self.savedBlockHeight))
if lastArweaveBlock != nil {
self.monitor.GetReport().Relayer.State.ArwaeveFinishedHeight.Store(int64(lastArweaveBlock.Block.Height))
}
// Processing stops here, no need to return anything
out = nil
return
}
func (self *Store) getData(payloads []*Payload) (
lastArweaveBlock *ArweaveBlock,
arweaveInteractions []*model.Interaction,
interactions []*model.Interaction,
bundleItems []*model.BundleItem,
dataItems []*model.DataItem,
err error) {
// Concatenate data from all payloads
for _, payload := range payloads {
if len(payload.ArweaveBlocks) > 0 {
for _, arweaveBlock := range payload.ArweaveBlocks {
arweaveInteractions = append(arweaveInteractions, arweaveBlock.Interactions...)
dataItems = append(dataItems, arweaveBlock.MetaInfoDataItems...)
}
lastArweaveBlock = payload.ArweaveBlocks[len(payload.ArweaveBlocks)-1]
}
interactions = append(interactions, payload.Interactions...)
bundleItems = append(bundleItems, payload.BundleItems...)
}
// Set sync timestamp
now := time.Now().UnixMilli()
for _, interaction := range interactions {
err = interaction.SyncTimestamp.Set(now)
if err != nil {
self.Log.WithError(err).Error("Failed to set sync_timestamp")
return
}
}
for _, interaction := range arweaveInteractions {
err = interaction.SyncTimestamp.Set(now)
if err != nil {
self.Log.WithError(err).Error("Failed to set sync_timestamp")
return
}
}
if len(interactions) != len(bundleItems) {
err = errors.New("bundle items and interactions count mismatch")
self.Log.WithError(err).Error("Bundle items and interactions count mismatch")
return
}
return
}
func (self *Store) updateFinishedArweaveBlock(tx *gorm.DB, arweaveBlock *ArweaveBlock) (err error) {
var state model.State
err = tx.WithContext(self.Ctx).
Where("name = ?", model.SyncedComponentInteractions).
First(&state).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to get state")
self.monitor.GetReport().Relayer.Errors.DbError.Inc()
return err
}
// Replace finished block info, if it's newer
if state.FinishedBlockHeight < uint64(arweaveBlock.Block.Height) {
err = tx.WithContext(self.Ctx).
Model(&model.State{
Name: model.SyncedComponentInteractions,
}).
Updates(model.State{
FinishedBlockTimestamp: uint64(arweaveBlock.Block.Timestamp),
FinishedBlockHeight: uint64(arweaveBlock.Block.Height),
FinishedBlockHash: arweaveBlock.Block.IndepHash,
}).
Error
if err != nil {
self.Log.WithError(err).Error("Failed to update last transaction block height")
self.monitor.GetReport().Relayer.Errors.DbError.Inc()
return err
}
}
return
}