-
Notifications
You must be signed in to change notification settings - Fork 479
/
mongodb.go
702 lines (604 loc) · 17.7 KB
/
mongodb.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package mongodb is an implementation of StateStore interface to perform operations on store
package mongodb
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/state"
"github.com/dapr/components-contrib/state/query"
stateutils "github.com/dapr/components-contrib/state/utils"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/ptr"
)
const (
host = "host"
username = "username"
password = "password"
databaseName = "databaseName"
collectionName = "collectionName"
server = "server"
operationTimeout = "operationTimeout"
params = "params"
id = "_id"
value = "value"
etag = "_etag"
ttl = "_ttl"
defaultTimeout = 5 * time.Second
defaultDatabaseName = "daprStore"
defaultCollectionName = "daprCollection"
// mongodb://<username>:<password@<host>/<database><params>
connectionURIFormatWithAuthentication = "mongodb://%s:%s@%s/%s%s"
// mongodb://<host>/<database><params>
connectionURIFormat = "mongodb://%s/%s%s"
// mongodb+srv://<server>/<params>
connectionURIFormatWithSrv = "mongodb+srv://%s/%s"
// mongodb+srv://<username>:<password>@<server>/<params>
connectionURIFormatWithSrvAndCredentials = "mongodb+srv://%s:%s@%s/%s%s" //nolint:gosec
)
// MongoDB is a state store implementation for MongoDB.
type MongoDB struct {
state.BulkStore
client *mongo.Client
collection *mongo.Collection
operationTimeout time.Duration
metadata mongoDBMetadata
features []state.Feature
logger logger.Logger
isReplicaSet bool
}
type mongoDBMetadata struct {
Host string
Username string
Password string
DatabaseName string
CollectionName string
Server string
Writeconcern string
Readconcern string
Params string
ConnectionString string
OperationTimeout time.Duration
}
// Item is Mongodb document wrapper.
type Item struct {
Key string `bson:"_id"`
Value interface{} `bson:"value"`
Etag string `bson:"_etag"`
TTL *time.Time `bson:"_ttl,omitempty"`
}
// NewMongoDB returns a new MongoDB state store.
func NewMongoDB(logger logger.Logger) state.Store {
s := &MongoDB{
features: []state.Feature{
state.FeatureETag,
state.FeatureTransactional,
state.FeatureQueryAPI,
state.FeatureTTL,
},
logger: logger,
}
s.BulkStore = state.NewDefaultBulkStore(s)
return s
}
// Init establishes connection to the store based on the metadata.
func (m *MongoDB) Init(ctx context.Context, metadata state.Metadata) (err error) {
m.metadata, err = getMongoDBMetaData(metadata)
if err != nil {
return err
}
m.operationTimeout = m.metadata.OperationTimeout
client, err := m.getMongoDBClient(ctx)
if err != nil {
return fmt.Errorf("error in creating mongodb client: %s", err)
}
if err = client.Ping(ctx, nil); err != nil {
return fmt.Errorf("error in connecting to mongodb, host: %s error: %s", m.metadata.Host, err)
}
m.client = client
// get the write concern
wc, err := getWriteConcernObject(m.metadata.Writeconcern)
if err != nil {
return fmt.Errorf("error in getting write concern object: %s", err)
}
// get the read concern
rc, err := getReadConcernObject(m.metadata.Readconcern)
if err != nil {
return fmt.Errorf("error in getting read concern object: %s", err)
}
opts := options.Collection().SetWriteConcern(wc).SetReadConcern(rc)
m.collection = m.client.Database(m.metadata.DatabaseName).Collection(m.metadata.CollectionName, opts)
// Set expireAfterSeconds index on ttl field with a value of 0 to delete
// values immediately when the TTL value is reached.
// MongoDB TTL Indexes: https://docs.mongodb.com/manual/core/index-ttl/
// TTL fields are deleted at most 60 seconds after the TTL value is reached.
_, err = m.collection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.M{ttl: 1},
Options: options.Index().SetExpireAfterSeconds(0),
})
if err != nil {
return fmt.Errorf("error in creating ttl index: %s", err)
}
if !m.isReplicaSet {
m.logger.Info("Connected to MongoDB without a replica set. Transactions are not available, and the component cannot be used as actor state store.")
}
return nil
}
// Features returns the features available in this state store.
func (m *MongoDB) Features() []state.Feature {
return m.features
}
// Set saves state into MongoDB.
func (m *MongoDB) Set(ctx context.Context, req *state.SetRequest) error {
err := m.setInternal(ctx, req)
if err != nil {
return err
}
return nil
}
func (m *MongoDB) Ping(ctx context.Context) error {
if err := m.client.Ping(ctx, nil); err != nil {
return fmt.Errorf("error connecting to mongoDB at %s: %s", m.metadata.Host, err)
}
return nil
}
func (m *MongoDB) setInternal(ctx context.Context, req *state.SetRequest) error {
var v interface{}
switch obj := req.Value.(type) {
case []byte:
v = string(obj)
case string:
v = fmt.Sprintf("%q", obj)
default:
v = req.Value
}
// create a document based on request key and value
filter := bson.M{id: req.Key}
if req.HasETag() {
filter[etag] = *req.ETag
} else if req.Options.Concurrency == state.FirstWrite {
uuid, err := uuid.NewRandom()
if err != nil {
return err
}
filter[etag] = uuid.String()
}
reqTTL, err := stateutils.ParseTTL(req.Metadata)
if err != nil {
return fmt.Errorf("failed to parse TTL: %w", err)
}
etagV, err := uuid.NewRandom()
if err != nil {
return err
}
update := make(mongo.Pipeline, 2)
update[0] = bson.D{{Key: "$set", Value: bson.D{
{Key: id, Value: req.Key},
{Key: value, Value: v},
{Key: etag, Value: etagV.String()},
}}}
if reqTTL != nil {
update[1] = primitive.D{{
Key: "$addFields", Value: bson.D{
{
Key: ttl, Value: bson.D{
{
Key: "$add", Value: bson.A{
// MongoDB stores time in milliseconds so multiply seconds by 1000.
"$$NOW", *reqTTL * 1000,
},
},
},
},
},
}}
} else {
update[1] = primitive.D{
{Key: "$addFields", Value: bson.D{
{Key: ttl, Value: nil},
}},
}
}
_, err = m.collection.UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
if err != nil {
if mongo.IsDuplicateKeyError(err) {
return state.NewETagError(state.ETagMismatch, err)
}
return fmt.Errorf("error in updating document: %w", err)
}
return nil
}
// Get retrieves state from MongoDB with a key.
func (m *MongoDB) Get(ctx context.Context, req *state.GetRequest) (*state.GetResponse, error) {
filter := bson.D{
{Key: "$and", Value: bson.A{
bson.D{{Key: id, Value: bson.M{"$eq": req.Key}}},
getFilterTTL(),
}},
}
var result Item
err := m.collection.
FindOne(ctx, filter).
Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
// Key not found, not an error.
// To behave the same as other state stores in conf tests.
err = nil
}
return &state.GetResponse{}, err
}
data, err := m.decodeData(result.Value)
if err != nil {
return &state.GetResponse{}, err
}
var metadata map[string]string
if result.TTL != nil {
metadata = map[string]string{
state.GetRespMetaKeyTTLExpireTime: result.TTL.UTC().Format(time.RFC3339),
}
}
return &state.GetResponse{
Data: data,
ETag: ptr.Of(result.Etag),
Metadata: metadata,
}, nil
}
func (m *MongoDB) BulkGet(ctx context.Context, req []state.GetRequest, _ state.BulkGetOpts) ([]state.BulkGetResponse, error) {
// If nothing is being requested, short-circuit
if len(req) == 0 {
return nil, nil
}
// Get all the keys
keys := make(bson.A, len(req))
for i, r := range req {
keys[i] = r.Key
}
// Perform the query
filter := bson.D{
{Key: "$and", Value: bson.A{
bson.D{
{Key: id, Value: bson.M{"$in": keys}},
},
getFilterTTL(),
}},
}
cur, err := m.collection.Find(ctx, filter)
if err != nil {
if err == mongo.ErrNoDocuments {
// No documents found, just return an empty list
err = nil
}
return nil, err
}
defer cur.Close(ctx)
// Read all results
res := make([]state.BulkGetResponse, 0, len(keys))
foundKeys := make(map[string]struct{}, len(keys))
for cur.Next(ctx) {
var (
doc Item
data []byte
)
err = cur.Decode(&doc)
if err != nil {
return nil, err
}
bgr := state.BulkGetResponse{
Key: doc.Key,
}
if doc.Etag != "" {
bgr.ETag = ptr.Of(doc.Etag)
}
if doc.TTL != nil {
bgr.Metadata = map[string]string{
state.GetRespMetaKeyTTLExpireTime: doc.TTL.UTC().Format(time.RFC3339),
}
}
data, err = m.decodeData(doc.Value)
if err != nil {
bgr.Error = err.Error()
} else {
bgr.Data = data
}
res = append(res, bgr)
foundKeys[bgr.Key] = struct{}{}
}
err = cur.Err()
if err != nil {
return res, err
}
// Populate missing keys with empty values
// This is to ensure consistency with the other state stores that implement BulkGet as a loop over Get, and with the Get method
if len(foundKeys) < len(req) {
var ok bool
for _, r := range req {
_, ok = foundKeys[r.Key]
if !ok {
res = append(res, state.BulkGetResponse{
Key: r.Key,
})
}
}
}
return res, nil
}
func getFilterTTL() bson.D {
// Since MongoDB doesn't delete the document immediately when the TTL value
// is reached, we need to filter out the documents with TTL value less than
// the current time.
return bson.D{{Key: "$expr", Value: bson.D{
{Key: "$or", Value: bson.A{
bson.D{{Key: "$eq", Value: bson.A{"$_ttl", primitive.Null{}}}},
bson.D{{Key: "$gte", Value: bson.A{"$_ttl", "$$NOW"}}},
}},
}}}
}
func (m *MongoDB) decodeData(resValue any) (data []byte, err error) {
switch obj := resValue.(type) {
case string:
data = []byte(obj)
case primitive.D, primitive.M:
if data, err = bson.MarshalExtJSON(obj, true, true); err != nil {
return nil, err
}
vr, errvr := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true)
if err != nil {
return nil, errvr
}
decoder, cerr := bson.NewDecoder(vr)
if cerr != nil {
return nil, cerr
}
var output map[string]interface{}
if err = decoder.Decode(&output); err != nil {
return nil, err
}
data, err = json.Marshal(output)
if err != nil {
return nil, err
}
case primitive.A:
newobj := bson.D{{Key: value, Value: obj}}
if data, err = bson.MarshalExtJSON(newobj, true, true); err != nil {
return nil, err
}
vr, errvr := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), true)
if err != nil {
return nil, errvr
}
decoder, cerr := bson.NewDecoder(vr)
if cerr != nil {
return nil, cerr
}
var input map[string]interface{}
if err = decoder.Decode(&input); err != nil {
return nil, err
}
value := input[value]
if data, err = json.Marshal(value); err != nil {
return nil, err
}
default:
data, err = json.Marshal(obj)
if err != nil {
return nil, err
}
}
return data, nil
}
// Delete performs a delete operation.
func (m *MongoDB) Delete(ctx context.Context, req *state.DeleteRequest) error {
err := m.deleteInternal(ctx, req)
if err != nil {
return err
}
return nil
}
func (m *MongoDB) deleteInternal(ctx context.Context, req *state.DeleteRequest) error {
filter := bson.M{id: req.Key}
if req.HasETag() {
filter[etag] = *req.ETag
}
result, err := m.collection.DeleteOne(ctx, filter)
if err != nil {
return err
}
if result.DeletedCount == 0 && req.ETag != nil && *req.ETag != "" {
return state.NewETagError(state.ETagMismatch, err)
}
return nil
}
// Multi performs a transactional operation. succeeds only if all operations succeed, and fails if one or more operations fail.
func (m *MongoDB) Multi(ctx context.Context, request *state.TransactionalStateRequest) error {
if !m.isReplicaSet {
return errors.New("using transactions with MongoDB requires connecting to a replica set")
}
sess, err := m.client.StartSession()
if err != nil {
return fmt.Errorf("error starting the transaction: %w", err)
}
defer sess.EndSession(ctx)
txnOpts := options.Transaction().
SetReadConcern(readconcern.Snapshot()).
SetWriteConcern(writeconcern.Majority())
sess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
err = m.doTransaction(sessCtx, request.Operations)
return nil, err
}, txnOpts)
return err
}
func (m *MongoDB) doTransaction(sessCtx mongo.SessionContext, operations []state.TransactionalStateOperation) error {
for _, o := range operations {
var err error
switch req := o.(type) {
case state.SetRequest:
err = m.setInternal(sessCtx, &req)
case state.DeleteRequest:
err = m.deleteInternal(sessCtx, &req)
}
if err != nil {
sessCtx.AbortTransaction(sessCtx)
return fmt.Errorf("error during transaction, aborting the transaction: %w", err)
}
}
return nil
}
// Query executes a query against store.
func (m *MongoDB) Query(ctx context.Context, req *state.QueryRequest) (*state.QueryResponse, error) {
q := &Query{}
qbuilder := query.NewQueryBuilder(q)
if err := qbuilder.BuildQuery(&req.Query); err != nil {
return &state.QueryResponse{}, err
}
data, token, err := q.execute(ctx, m.collection)
if err != nil {
return &state.QueryResponse{}, err
}
return &state.QueryResponse{
Results: data,
Token: token,
}, nil
}
func (metadata *mongoDBMetadata) getMongoConnectionString() string {
if metadata.ConnectionString != "" {
return metadata.ConnectionString
}
if len(metadata.Server) != 0 {
if metadata.Username != "" && metadata.Password != "" {
return fmt.Sprintf(connectionURIFormatWithSrvAndCredentials, metadata.Username, metadata.Password, metadata.Server, metadata.DatabaseName, metadata.Params)
}
return fmt.Sprintf(connectionURIFormatWithSrv, metadata.Server, metadata.Params)
}
if metadata.Username != "" && metadata.Password != "" {
return fmt.Sprintf(connectionURIFormatWithAuthentication, metadata.Username, metadata.Password, metadata.Host, metadata.DatabaseName, metadata.Params)
}
return fmt.Sprintf(connectionURIFormat, metadata.Host, metadata.DatabaseName, metadata.Params)
}
func (m *MongoDB) getMongoDBClient(ctx context.Context) (*mongo.Client, error) {
uri := m.metadata.getMongoConnectionString()
// Set client options
clientOptions := options.Client().ApplyURI(uri)
m.isReplicaSet = clientOptions.ReplicaSet != nil
// Connect to MongoDB
ctx, cancel := context.WithTimeout(ctx, m.metadata.OperationTimeout)
defer cancel()
daprUserAgent := "dapr-" + logger.DaprVersion
if clientOptions.AppName != nil {
clientOptions.SetAppName(daprUserAgent + ":" + *clientOptions.AppName)
} else {
clientOptions.SetAppName(daprUserAgent)
}
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
return nil, err
}
return client, nil
}
func getMongoDBMetaData(meta state.Metadata) (mongoDBMetadata, error) {
m := mongoDBMetadata{
DatabaseName: defaultDatabaseName,
CollectionName: defaultCollectionName,
OperationTimeout: defaultTimeout,
}
decodeErr := metadata.DecodeMetadata(meta.Properties, &m)
if decodeErr != nil {
return m, decodeErr
}
if m.ConnectionString == "" {
if len(m.Host) == 0 && len(m.Server) == 0 {
return m, errors.New("must set 'host' or 'server' fields in metadata")
}
if len(m.Host) != 0 && len(m.Server) != 0 {
return m, errors.New("'host' or 'server' fields are mutually exclusive")
}
// Ensure that params, if set, start with ?
if m.Params != "" && !strings.HasPrefix(m.Params, "?") {
m.Params = "?" + m.Params
}
}
var err error
if val, ok := meta.Properties[operationTimeout]; ok && val != "" {
m.OperationTimeout, err = time.ParseDuration(val)
if err != nil {
return m, errors.New("incorrect operationTimeout field from metadata")
}
}
return m, nil
}
func getWriteConcernObject(cn string) (*writeconcern.WriteConcern, error) {
var wc *writeconcern.WriteConcern
if cn != "" {
if cn == "majority" {
wc = writeconcern.Majority()
} else {
w, err := strconv.Atoi(cn)
if err != nil {
return nil, err
}
wc = &writeconcern.WriteConcern{
W: w,
}
}
} else {
wc = writeconcern.W1()
}
wc.Journal = ptr.Of(true)
wc.WTimeout = defaultTimeout
return wc, nil
}
func getReadConcernObject(cn string) (*readconcern.ReadConcern, error) {
switch cn {
case "local":
return readconcern.Local(), nil
case "majority":
return readconcern.Majority(), nil
case "available":
return readconcern.Available(), nil
case "linearizable":
return readconcern.Linearizable(), nil
case "snapshot":
return readconcern.Snapshot(), nil
case "":
return readconcern.Local(), nil
}
return nil, fmt.Errorf("readConcern %s not found", cn)
}
func (m *MongoDB) GetComponentMetadata() (metadataInfo metadata.MetadataMap) {
metadataStruct := mongoDBMetadata{}
metadata.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, metadata.StateStoreType)
return
}
// Close connection to the database.
func (m *MongoDB) Close(ctx context.Context) (err error) {
if m.client == nil {
return nil
}
return m.client.Disconnect(ctx)
}