/
store.go
372 lines (291 loc) · 9.44 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package store
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/hyperledger/aries-framework-go-ext/component/storage/mongodb"
"github.com/hyperledger/aries-framework-go/spi/storage"
"github.com/trustbloc/logutil-go/pkg/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
mongoopts "go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
logfields "github.com/trustbloc/orb/internal/pkg/log"
)
var logger = log.New("store")
const idField = "_id"
// TagGroup defines a group of tags that may be used to create a compound index.
type TagGroup []string
// Open opens the store for the given namespace and creates the necessary indexes. As an optimization,
// this function uses vendor-specific APIs (for supported databases) in order to optimize performance.
func Open(provider storage.Provider, namespace string, tagGroups ...TagGroup) (storage.Store, error) {
store, err := provider.OpenStore(namespace)
if err != nil {
return nil, fmt.Errorf("open store [%s]: %w", namespace, err)
}
s, ok, err := newVendorStore(provider, store, namespace, tagGroups)
if err != nil {
return nil, fmt.Errorf("new vendor store: %w", err)
}
if !ok {
// A vendor-specific store was not found. Use the generic API.
err := provider.SetStoreConfig(namespace, storage.StoreConfiguration{TagNames: uniqueTags(tagGroups)})
if err != nil {
return nil, fmt.Errorf("set store configuration for [%s]: %w", namespace, err)
}
s = store
}
return s, nil
}
// NewTagGroup is a convenience function that returns a TagGroup from the given set of tags.
func NewTagGroup(tags ...string) TagGroup {
return tags
}
func newVendorStore(provider storage.Provider, store storage.Store, namespace string, tagGroups []TagGroup) (storage.Store, bool, error) {
// Currently, only MongoDB is supported.
mongoDBProvider, ok := provider.(mongoDBProvider)
if !ok {
return nil, false, nil
}
logger.Info("Using MongoDB optimized interface", logfields.WithStoreName(namespace))
ms := newMongoDBWrapper(namespace, mongoDBProvider, store)
if err := ms.createIndexes(tagGroups); err != nil {
return nil, true, fmt.Errorf("create MongoDB indexes: %w", err)
}
return ms, true, nil
}
type mongoDBStore interface {
PutAsJSON(key string, value interface{}) error
BulkWrite(models []mongo.WriteModel, opts ...*mongoopts.BulkWriteOptions) error
GetAsRawMap(id string) (map[string]interface{}, error)
GetBulkAsRawMap(ids ...string) ([]map[string]interface{}, error)
QueryCustom(filter interface{}, options ...*mongoopts.FindOptions) (mongodb.Iterator, error)
CreateMongoDBFindOptions(options []storage.QueryOption, isJSONQuery bool) *mongoopts.FindOptions
}
type mongoDBProvider interface {
CreateCustomIndexes(storeName string, model ...mongo.IndexModel) error
}
type mongoDBWrapper struct {
namespace string
provider mongoDBProvider
store storage.Store
ms mongoDBStore
marshal func(v interface{}) ([]byte, error)
}
func newMongoDBWrapper(namespace string, provider mongoDBProvider, store storage.Store) *mongoDBWrapper {
ms, ok := store.(mongoDBStore)
if !ok {
// If this happens then it's a bug.
panic(fmt.Errorf("expecting MongoDB provider for [%s]", namespace))
}
return &mongoDBWrapper{
namespace: namespace,
provider: provider,
store: store,
ms: ms,
marshal: json.Marshal,
}
}
func (s *mongoDBWrapper) createIndexes(tags []TagGroup) error {
if len(tags) == 0 {
// Nothing to do.
return nil
}
for _, tagGroup := range tags {
logger.Info("Creating MongoDB indexes", logfields.WithStoreName(s.namespace),
zap.Inline(logfields.NewObjectMarshaller("tags", tagGroup)))
keys := make(bson.D, len(tagGroup))
for i, tag := range tagGroup {
keys[i] = bson.E{Key: tag, Value: 1}
}
model := mongo.IndexModel{Keys: keys}
err := s.provider.CreateCustomIndexes(s.namespace, model)
if err != nil {
return fmt.Errorf("create index for [%s]: %w", s.namespace, err)
}
}
return nil
}
// Put persists the given key-value pair. Tags are unused.
func (s *mongoDBWrapper) Put(key string, value []byte, _ ...storage.Tag) error {
var doc map[string]interface{}
if err := json.Unmarshal(value, &doc); err != nil {
return fmt.Errorf("unmarshal document [%s-%s]: %w", s.namespace, key, err)
}
if err := s.ms.PutAsJSON(key, doc); err != nil {
return fmt.Errorf("put as JSON failed [%s-%s]: %w", s.namespace, key, err)
}
return nil
}
// Get returns the value for the given key.
func (s *mongoDBWrapper) Get(key string) ([]byte, error) {
doc, err := s.ms.GetAsRawMap(key)
if err != nil {
return nil, fmt.Errorf("get [%s-%s]: %w", s.namespace, key, err)
}
delete(doc, idField)
docBytes, err := s.marshal(doc)
if err != nil {
return nil, err
}
return docBytes, nil
}
// GetBulk returns the value for the given keys.
func (s *mongoDBWrapper) GetBulk(keys ...string) ([][]byte, error) {
docs, err := s.ms.GetBulkAsRawMap(keys...)
if err != nil {
return nil, fmt.Errorf("get bulk for [%s]: %w", s.namespace, err)
}
docsBytes := make([][]byte, len(docs))
for i, doc := range docs {
var docBytes []byte
var e error
if doc != nil {
delete(doc, idField)
docBytes, e = s.marshal(doc)
if e != nil {
return nil, e
}
}
docsBytes[i] = docBytes
}
return docsBytes, nil
}
// Query searches the database using the given expression and returns an iterator that may
// be used to retrieve the values.
func (s *mongoDBWrapper) Query(expression string, options ...storage.QueryOption) (storage.Iterator, error) {
filter, err := mongodb.PrepareFilter(strings.Split(expression, "&&"), true)
if err != nil {
return nil, fmt.Errorf("convert expression [%s] to MongoDB filter: %w", expression, err)
}
iterator, err := s.ms.QueryCustom(postProcess(filter), s.ms.CreateMongoDBFindOptions(options, true))
if err != nil {
return nil, fmt.Errorf("query MongoDB store [%s] - expression [%s]: %w",
s.namespace, expression, err)
}
return newMongoDBIteratorWrapper(iterator), nil
}
// Batch performs multiple Put and/or Delete operations in order.
func (s *mongoDBWrapper) Batch(operations []storage.Operation) error {
writeModels := make([]mongo.WriteModel, len(operations))
for i, op := range operations {
if len(op.Value) > 0 {
var valueAsMap map[string]interface{}
jsonDecoder := json.NewDecoder(bytes.NewReader(op.Value))
jsonDecoder.UseNumber()
err := jsonDecoder.Decode(&valueAsMap)
if err != nil {
return err
}
valueAsMap["_id"] = op.Key
if op.PutOptions != nil && op.PutOptions.IsNewKey {
writeModels[i] = mongo.NewInsertOneModel().SetDocument(valueAsMap)
} else {
filter := bson.M{"_id": op.Key}
writeModels[i] = mongo.NewReplaceOneModel().SetFilter(filter).
SetReplacement(valueAsMap).
SetUpsert(true)
}
} else {
writeModels[i] = mongo.NewDeleteOneModel().SetFilter(bson.M{"_id": op.Key})
}
}
if err := s.ms.BulkWrite(writeModels); err != nil {
return fmt.Errorf("bulk write failed for [%s]: %w", s.namespace, err)
}
return nil
}
// GetTags returns the tags for the given key.
func (s *mongoDBWrapper) GetTags(string) ([]storage.Tag, error) {
panic("not implemented")
}
// Delete deletes the key + value pair (and all tags) associated with key.
func (s *mongoDBWrapper) Delete(key string) error {
return s.store.Delete(key)
}
// Flush forces any queued up Put and/or Delete operations to execute.
func (s *mongoDBWrapper) Flush() error {
return s.store.Flush()
}
// Close closes this store object, freeing resources.
func (s *mongoDBWrapper) Close() error {
return s.store.Close()
}
type mongoDBIteratorWrapper struct {
mongodb.Iterator
marshal func(v interface{}) ([]byte, error)
}
func newMongoDBIteratorWrapper(it mongodb.Iterator) *mongoDBIteratorWrapper {
return &mongoDBIteratorWrapper{
Iterator: it,
marshal: json.Marshal,
}
}
func (it *mongoDBIteratorWrapper) Value() ([]byte, error) {
doc, err := it.ValueAsRawMap()
if err != nil {
return nil, err
}
delete(doc, idField)
value, err := it.marshal(doc)
if err != nil {
return nil, fmt.Errorf("marshal document: %w", err)
}
return value, nil
}
func uniqueTags(tagGroups []TagGroup) []string {
var tags []string
for _, tagGroup := range tagGroups {
for _, tag := range tagGroup {
if !contains(tag, tags) {
tags = append(tags, tag)
}
}
}
return tags
}
func contains(tag string, tags []string) bool {
for _, t := range tags {
if t == tag {
return true
}
}
return false
}
// CloseIterator closes the given iterator, logging a warning if the operation fails.
func CloseIterator(it io.Closer) {
if err := it.Close(); err != nil {
log.CloseIteratorError(logger, err)
}
}
// postProcess modifies the filter to add support for "not exists". For example, the query expression, "!key1",
// generates a BSON that assumes $exists=true and will be transformed as follows:
// {Key: "!key1", Value: [{Key: "$exists", Value: true}}} ==> {Key: "key1", Value: [{Key: "$exists", Value: false}}}
// TODO: Remove this hack when support for 'not exists' is added to ariesframework-go-ext.
func postProcess(filter bson.D) bson.D {
for i, f := range filter {
if f.Key == "" || f.Key[0] != '!' {
continue
}
d, ok := f.Value.(primitive.D)
if !ok {
continue
}
for j, dv := range d {
if dv.Key != "$exists" {
continue
}
f.Key = f.Key[1:]
d[j].Value = false
filter[i] = f
}
}
return filter
}