-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery_rpc.go
More file actions
341 lines (275 loc) · 8.68 KB
/
query_rpc.go
File metadata and controls
341 lines (275 loc) · 8.68 KB
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
332
333
334
335
336
337
338
339
340
341
package sqlitebitmapstore
import (
"context"
"encoding/json"
"fmt"
"slices"
"strings"
"time"
"github.com/Arkiv-Network/sqlite-bitmap-store/query"
"github.com/Arkiv-Network/sqlite-bitmap-store/store"
"github.com/RoaringBitmap/roaring/v2/roaring64"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
const QueryResultCountLimit uint64 = 200
type IncludeData struct {
Key bool `json:"key"`
Attributes bool `json:"attributes"`
SyntheticAttributes bool `json:"syntheticAttributes"`
Payload bool `json:"payload"`
ContentType bool `json:"contentType"`
Expiration bool `json:"expiration"`
Creator bool `json:"creator"`
Owner bool `json:"owner"`
CreatedAtBlock bool `json:"createdAtBlock"`
LastModifiedAtBlock bool `json:"lastModifiedAtBlock"`
TransactionIndexInBlock bool `json:"transactionIndexInBlock"`
OperationIndexInTransaction bool `json:"operationIndexInTransaction"`
}
type Options struct {
AtBlock *hexutil.Uint64 `json:"atBlock,omitempty"`
IncludeData *IncludeData `json:"includeData,omitempty"`
ResultsPerPage *hexutil.Uint64 `json:"resultsPerPage,omitempty"`
Cursor string `json:"cursor,omitempty"`
}
func (o *Options) GetAtBlock() uint64 {
if o == nil || o.AtBlock == nil {
return 0
}
return uint64(*o.AtBlock)
}
func (o *Options) GetResultsPerPage() uint64 {
if o == nil || o.ResultsPerPage == nil || uint64(*o.ResultsPerPage) > QueryResultCountLimit {
return QueryResultCountLimit
}
return uint64(*o.ResultsPerPage)
}
func (o *Options) GetIncludeData() IncludeData {
if o == nil || o.IncludeData == nil {
return IncludeData{
Key: true,
ContentType: true,
Payload: true,
Creator: true,
Owner: true,
Attributes: true,
Expiration: true,
}
}
return *o.IncludeData
}
func (o *Options) GetCursor() (*uint64, error) {
if o == nil || o.Cursor == "" {
return nil, nil
}
cursor, err := hexutil.DecodeUint64(o.Cursor)
if err != nil {
return nil, fmt.Errorf("error decoding cursor: %w", err)
}
return &cursor, nil
}
type QueryResponse struct {
Data []json.RawMessage `json:"data"`
BlockNumber hexutil.Uint64 `json:"blockNumber"`
Cursor *string `json:"cursor,omitempty"`
}
type EntityData struct {
Key *common.Hash `json:"key,omitempty"`
Value hexutil.Bytes `json:"value,omitempty"`
ContentType *string `json:"contentType,omitempty"`
ExpiresAt *uint64 `json:"expiresAt,omitempty"`
Creator *common.Address `json:"creator,omitempty"`
Owner *common.Address `json:"owner,omitempty"`
CreatedAtBlock *uint64 `json:"createdAtBlock,omitempty"`
LastModifiedAtBlock *uint64 `json:"lastModifiedAtBlock,omitempty"`
TransactionIndexInBlock *uint64 `json:"transactionIndexInBlock,omitempty"`
OperationIndexInTransaction *uint64 `json:"operationIndexInTransaction,omitempty"`
StringAttributes []Attribute[string] `json:"stringAttributes,omitempty"`
NumericAttributes []Attribute[uint64] `json:"numericAttributes,omitempty"`
}
type Attribute[T any] struct {
Key string `json:"key"`
Value T `json:"value"`
}
const maxResultBytes = 512 * 1024 * 1024
func (s *SQLiteStore) QueryEntities(
ctx context.Context,
queryStr string,
options *Options,
) (*QueryResponse, error) {
// TODO: wait for the block height
res := &QueryResponse{
Data: []json.RawMessage{},
BlockNumber: 0,
Cursor: nil,
}
{
q := s.NewQueries()
timeoutCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
for {
lastBlock, err := q.GetLastBlock(ctx)
if err != nil {
return nil, fmt.Errorf("error getting last block: %w", err)
}
if lastBlock >= options.GetAtBlock() {
break
}
select {
case <-timeoutCtx.Done():
return nil, fmt.Errorf("context cancelled: %w", ctx.Err())
case <-time.After(100 * time.Millisecond):
continue
}
}
cancel()
}
q, err := query.Parse(queryStr)
if err != nil {
return nil, fmt.Errorf("error parsing query: %w", err)
}
err = s.ReadTransaction(ctx, func(queries *store.Queries) error {
bitmap, err := q.Evaluate(
ctx,
queries,
)
if err != nil {
return fmt.Errorf("error evaluating query: %w", err)
}
cursor, err := options.GetCursor()
if err != nil {
return fmt.Errorf("error decoding cursor: %w", err)
}
// The cursor contains the last value that was included in the previous page.
// We create a bitmask by creating an empty bitmap, and then flipping the bits
// from 0 to (cursor - 1) to 1, so that we only include values below the cursor
// value.
if cursor != nil {
s.log.Info("decoded cursor", "value", *cursor)
cursorMask := roaring64.New()
cursorMask.AddRange(0, *cursor)
bitmap.And(cursorMask)
}
it := bitmap.ReverseIterator()
maxResults := options.GetResultsPerPage()
nextIDs := func(max uint64) []uint64 {
ids := []uint64{}
for range max {
if !it.HasNext() {
break
}
ids = append(ids, it.Next())
}
return ids
}
totalBytes := uint64(0)
finished := true
var lastID *uint64
fillLoop:
for it.HasNext() {
nextBatchSize := min(maxResults-uint64(len(res.Data)), 10)
nextIDs := nextIDs(nextBatchSize)
payloads, err := queries.RetrievePayloads(ctx, nextIDs)
if err != nil {
return fmt.Errorf("error retrieving payloads: %w", err)
}
for _, payload := range payloads {
lastID = &payload.ID
ed := toPayload(payload, options.GetIncludeData())
d, err := json.Marshal(ed)
if err != nil {
return fmt.Errorf("error marshalling entity data: %w", err)
}
res.Data = append(res.Data, d)
totalBytes += uint64(len(d))
if totalBytes > maxResultBytes {
finished = false
break fillLoop
}
if uint64(len(res.Data)) >= maxResults {
finished = false
break fillLoop
}
}
}
if !finished {
res.Cursor = pointerOf(hexutil.EncodeUint64(*lastID))
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error peforming query: %w", err)
}
return res, nil
}
func pointerOf[T any](v T) *T {
return &v
}
func filterAttributes[T any](predicate func(string) bool, m map[string]T) []Attribute[T] {
res := []Attribute[T]{}
for k, v := range m {
if !predicate(k) {
continue
}
res = append(res, Attribute[T]{Key: k, Value: v})
}
slices.SortFunc(res, func(i, j Attribute[T]) int {
return strings.Compare(i.Key, j.Key)
})
return res
}
func syntheticPredicate(k string) bool {
return strings.HasPrefix(k, "$")
}
func nonSyntheticPredicate(k string) bool {
return !strings.HasPrefix(k, "$")
}
func anyPredicate(string) bool {
return true
}
func toPayload(r store.RetrievePayloadsRow, includeData IncludeData) *EntityData {
res := &EntityData{}
if includeData.Key {
res.Key = pointerOf(common.BytesToHash(r.EntityKey))
}
if includeData.Payload {
res.Value = r.Payload
}
if includeData.ContentType {
res.ContentType = &r.ContentType
}
switch {
case includeData.Attributes && includeData.SyntheticAttributes:
res.StringAttributes = filterAttributes(anyPredicate, r.StringAttributes.Values)
res.NumericAttributes = filterAttributes(anyPredicate, r.NumericAttributes.Values)
case includeData.Attributes:
res.StringAttributes = filterAttributes(nonSyntheticPredicate, r.StringAttributes.Values)
res.NumericAttributes = filterAttributes(nonSyntheticPredicate, r.NumericAttributes.Values)
case includeData.SyntheticAttributes:
res.StringAttributes = filterAttributes(syntheticPredicate, r.StringAttributes.Values)
res.NumericAttributes = filterAttributes(syntheticPredicate, r.NumericAttributes.Values)
}
if includeData.Expiration {
res.ExpiresAt = pointerOf(r.NumericAttributes.Values["$expiration"])
}
if includeData.Creator {
res.Creator = pointerOf(common.HexToAddress(r.StringAttributes.Values["$creator"]))
}
if includeData.Owner {
res.Owner = pointerOf(common.HexToAddress(r.StringAttributes.Values["$owner"]))
}
if includeData.CreatedAtBlock {
res.CreatedAtBlock = pointerOf(r.NumericAttributes.Values["$createdAtBlock"])
}
if includeData.LastModifiedAtBlock {
res.LastModifiedAtBlock = pointerOf(r.NumericAttributes.Values["$lastModifiedAtBlock"])
}
if includeData.TransactionIndexInBlock {
res.TransactionIndexInBlock = pointerOf(r.NumericAttributes.Values["$txIndex"])
}
if includeData.OperationIndexInTransaction {
res.OperationIndexInTransaction = pointerOf(r.NumericAttributes.Values["$opIndex"])
}
return res
}