forked from EOS-Nation/dfuse-leap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapper.go
331 lines (268 loc) · 8.78 KB
/
mapper.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package search
import (
"fmt"
"strings"
"github.com/blevesearch/bleve"
"github.com/blevesearch/bleve/analysis/analyzer/keyword"
"github.com/blevesearch/bleve/document"
"github.com/blevesearch/bleve/mapping"
"github.com/dfuse-io/bstream"
pbcodec "github.com/dfuse-io/dfuse-eosio/pb/dfuse/eosio/codec/v1"
"github.com/dfuse-io/search"
"go.uber.org/zap"
)
type BatchActionUpdater = func(trxID string, idx int, data map[string]interface{}) error
// eventsConfig contains specific configuration for the correct indexation of
// dfuse Events, our special methodology to index the action from your smart contract
// the way the developer like it.
type eventsConfig struct {
actionName string
unrestricted bool
}
type BlockMapper struct {
*mapping.IndexMappingImpl
eventsConfig eventsConfig
indexed *IndexedTerms
tokenizer tokenizer
}
func NewBlockMapper(eventsActionName string, eventsUnrestricted bool, indexedTermsSpecs string) (*BlockMapper, error) {
indexed, err := NewIndexedTerms(indexedTermsSpecs)
if err != nil {
return nil, fmt.Errorf("indexed terms: %w", err)
}
return &BlockMapper{
IndexMappingImpl: buildBleveIndexMapper(),
eventsConfig: eventsConfig{
actionName: eventsActionName,
unrestricted: eventsUnrestricted,
},
indexed: indexed,
tokenizer: tokenizer{indexedTerms: indexed},
}, nil
}
func buildBleveIndexMapper() *mapping.IndexMappingImpl {
// db ops
dbDocMapping := bleve.NewDocumentMapping()
dbDocMapping.AddFieldMappingsAt("key", search.TxtFieldMapping)
dbDocMapping.AddFieldMappingsAt("table", search.TxtFieldMapping)
// ram ops
ramDocMapping := bleve.NewDocumentMapping()
ramDocMapping.AddFieldMappingsAt("consumed", search.TxtFieldMapping)
ramDocMapping.AddFieldMappingsAt("released", search.TxtFieldMapping)
// Root doc
rootDocMapping := bleve.NewDocumentStaticMapping()
// Sortable internals
rootDocMapping.AddFieldMappingsAt("act_idx", search.SortableNumericFieldMapping)
rootDocMapping.AddFieldMappingsAt("block_num", search.SortableNumericFieldMapping)
rootDocMapping.AddFieldMappingsAt("trx_idx", search.SortableNumericFieldMapping)
rootDocMapping.AddFieldMappingsAt("receiver", search.TxtFieldMapping)
rootDocMapping.AddFieldMappingsAt("account", search.TxtFieldMapping)
rootDocMapping.AddFieldMappingsAt("action", search.TxtFieldMapping)
rootDocMapping.AddFieldMappingsAt("auth", search.TxtFieldMapping)
rootDocMapping.AddFieldMappingsAt("input", search.BoolFieldMapping)
rootDocMapping.AddFieldMappingsAt("notif", search.BoolFieldMapping)
rootDocMapping.AddFieldMappingsAt("scheduled", search.BoolFieldMapping)
// add other sub-sections here
rootDocMapping.AddSubDocumentMapping("data", search.DynamicNestedDocMapping)
rootDocMapping.AddSubDocumentMapping("db", dbDocMapping)
rootDocMapping.AddSubDocumentMapping("ram", ramDocMapping)
rootDocMapping.AddSubDocumentMapping("event", search.DynamicNestedDocMapping)
// this disables the _all field
rootDocMapping.AddSubDocumentMapping("_all", search.DisabledMapping)
mapper := bleve.NewIndexMapping()
mapper.DefaultAnalyzer = keyword.Name
mapper.StoreDynamic = false
mapper.IndexDynamic = true
mapper.DocValuesDynamic = false
mapper.DefaultMapping = rootDocMapping
return mapper
}
func (m *BlockMapper) IndexedTerms() *IndexedTerms { return m.indexed }
func (m *BlockMapper) Map(block *bstream.Block) ([]*document.Document, error) {
blk := block.ToNative().(*pbcodec.Block)
actionsCount := 0
var docsList []*document.Document
batchActionUpdater := func(trxID string, idx int, data map[string]interface{}) error {
doc := document.NewDocument(newDocumentID(blk.Num(), trxID, idx))
err := m.MapDocument(doc, data)
if err != nil {
return err
}
actionsCount++
docsList = append(docsList, doc)
return nil
}
err := m.prepareBatchDocuments(blk, batchActionUpdater)
if err != nil {
return nil, err
}
metaDoc := document.NewDocument(fmt.Sprintf("meta:blknum:%d", blk.Num()))
err = m.MapDocument(metaDoc, map[string]interface{}{
"act_count": actionsCount,
})
if err != nil {
return nil, err
}
docsList = append(docsList, metaDoc)
return docsList, nil
}
func (m *BlockMapper) prepareBatchDocuments(blk *pbcodec.Block, batchUpdater BatchActionUpdater) error {
for _, trxTrace := range blk.TransactionTraces() {
// We only index transaction trace that were correctly recorded in the blockchain
if trxTrace.HasBeenReverted() {
continue
}
trxID := trxTrace.Id
scheduled := trxTrace.Scheduled
type prepedDoc struct {
trxID string
idx int
data map[string]interface{}
}
tokenizedActions := map[uint32]prepedDoc{}
actionMatcher := blk.FilteringActionMatcher(trxTrace, isRequiredSystemAction)
for idx, actTrace := range trxTrace.ActionTraces {
if !actionMatcher.Matched(actTrace.ExecutionIndex) {
continue
}
data := m.tokenizer.tokenize(actTrace)
// `block_num`, `trx_idx`: used for sorting
data["block_num"] = blk.Num()
data["trx_idx"] = trxTrace.Index
if m.indexed.Notif {
data["notif"] = actTrace.Receipt.Receiver != actTrace.Action.Account
}
if m.indexed.Input {
data["input"] = actTrace.IsInput()
}
if m.indexed.Scheduled {
data["scheduled"] = scheduled
}
if m.indexed.Event {
if actTrace.SimpleName() == m.eventsConfig.actionName && !actTrace.IsInput() {
eventFields := m.tokenizer.tokenizeEvent(m.eventsConfig, actTrace.GetData("key").String(), actTrace.GetData("data").String())
if len(eventFields) > 0 {
tokenizedActions[actTrace.CreatorActionOrdinal].data["event"] = eventFields
}
}
}
// NOTE: we're still missing the RAM accounting for `hard_fail` and
// `expired` transactions. `expired` transactions do not have actions, so
// we can't even have something to index here.
if m.indexed.RAMConsumed || m.indexed.RAMReleased {
ramData := m.processRAMOps(trxTrace.RAMOpsForAction(uint32(idx)))
if len(ramData) > 0 {
data["ram"] = ramData
}
}
if m.indexed.DBKey || m.indexed.DBTable {
dbData := m.processDBOps(trxTrace.DBOpsForAction(uint32(idx)))
if len(dbData) > 0 {
data["db"] = dbData
}
}
tokenizedActions[actTrace.ActionOrdinal] = prepedDoc{
trxID: trxID,
idx: idx,
data: data,
}
}
// Loop and batch update all the actions
for _, doc := range tokenizedActions {
err := batchUpdater(doc.trxID, doc.idx, doc.data)
if err != nil {
return err
}
}
}
return nil
}
func isRequiredSystemAction(actTrace *pbcodec.ActionTrace) bool {
return actTrace.Receiver == "eosio" && actTrace.Action.Account == "eosio" && actTrace.Action.Name == "setabi"
}
func (m *BlockMapper) processRAMOps(ramOps []*pbcodec.RAMOp) map[string][]string {
if len(ramOps) <= 0 {
return nil
}
var consumedRAM map[string]bool
if m.indexed.RAMConsumed {
consumedRAM = make(map[string]bool)
}
var releasedRAM map[string]bool
if m.indexed.RAMReleased {
releasedRAM = make(map[string]bool)
}
for _, ramop := range ramOps {
if ramop.Delta == 0 {
continue
}
if ramop.Delta > 0 {
consumedRAM[ramop.Payer] = true
} else {
releasedRAM[ramop.Payer] = true
}
}
ramData := make(map[string][]string)
if len(consumedRAM) != 0 {
ramData["consumed"] = toList(consumedRAM)
}
if len(releasedRAM) != 0 {
ramData["released"] = toList(releasedRAM)
}
return ramData
}
func (m *BlockMapper) processDBOps(dbOps []*pbcodec.DBOp) map[string][]string {
dbOpCount := len(dbOps)
if dbOpCount <= 0 {
return nil
}
var keys map[string]bool
if m.indexed.DBKey {
keys = make(map[string]bool, dbOpCount)
}
var tables map[string]bool
if m.indexed.DBTable {
tables = make(map[string]bool, dbOpCount)
}
for _, op := range dbOps {
if m.indexed.DBKey {
keys[fmt.Sprintf("%s/%s/%s", op.TableName, op.Scope, op.PrimaryKey)] = true
}
if m.indexed.DBTable {
tables[fmt.Sprintf("%s/%s", op.TableName, op.Scope)] = true
tables[string(op.TableName)] = true
}
}
opData := make(map[string][]string)
if len(keys) != 0 {
opData["key"] = toList(keys)
}
if len(tables) != 0 {
opData["table"] = toList(tables)
}
return opData
}
func newDocumentID(blockNum uint64, transactionID string, actionIndex int) string {
// 128 bits collision protection
return fmt.Sprintf("%016x", blockNum) + ":" + transactionID[:32] + ":" + fmt.Sprintf("%04x", actionIndex)
}
func explodeDocumentID(ref string) (blockNum uint64, trxID string, actionIdx uint16, skip bool) {
var err error
chunks := strings.Split(ref, ":")
chunksCount := len(chunks)
if chunksCount != 3 || chunks[0] == "meta" { // meta, flatten, etc.
skip = true
return
}
blockNum32, err := fromHexUint32(chunks[0])
if err != nil {
zlog.Panic("block num invalid", zap.Error(err))
}
blockNum = uint64(blockNum32)
trxID = chunks[1]
actionIdx, err = fromHexUint16(chunks[2])
if err != nil {
zlog.Panic("action index invalid", zap.Error(err))
}
return
}