-
Notifications
You must be signed in to change notification settings - Fork 466
/
cosmosdb.go
366 lines (308 loc) · 9.77 KB
/
cosmosdb.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
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
package cosmosdb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/dapr/components-contrib/state"
"github.com/dapr/dapr/pkg/logger"
jsoniter "github.com/json-iterator/go"
"github.com/a8m/documentdb"
)
// StateStore is a CosmosDB state store
type StateStore struct {
client *documentdb.DocumentDB
collection *documentdb.Collection
db *documentdb.Database
sp *documentdb.Sproc
logger logger.Logger
}
type credentials struct {
URL string `json:"url"`
MasterKey string `json:"masterKey"`
Database string `json:"database"`
Collection string `json:"collection"`
}
// CosmosItem is a wrapper around a CosmosDB document
type CosmosItem struct {
documentdb.Document
ID string `json:"id"`
Value interface{} `json:"value"`
PartitionKey string `json:"partitionKey"`
}
// CosmosItemWithRawMessage is a version of CosmosItem with a Value of RawMessage so this field
// is not marshalled. If it is marshalled it will end up in a form that
// cannot be unmarshalled. This type is used when SetRequest.Value arrives as bytes.
type CosmosItemWithRawMessage struct {
documentdb.Document
ID string `json:"id"`
Value jsoniter.RawMessage `json:"value"`
PartitionKey string `json:"partitionKey"`
}
type storedProcedureDefinition struct {
ID string `json:"id"`
Body string `json:"body"`
}
const (
storedProcedureName = "__dapr__"
metadataPartitionKey = "partitionKey"
unknownPartitionKey = "__UNKNOWN__"
)
// NewCosmosDBStateStore returns a new CosmosDB state store
func NewCosmosDBStateStore(logger logger.Logger) *StateStore {
return &StateStore{logger: logger}
}
// Init does metadata and connection parsing
func (c *StateStore) Init(metadata state.Metadata) error {
c.logger.Debugf("CosmosDB init start")
connInfo := metadata.Properties
b, err := json.Marshal(connInfo)
if err != nil {
return err
}
var creds credentials
err = json.Unmarshal(b, &creds)
if err != nil {
return err
}
client := documentdb.New(creds.URL, &documentdb.Config{
MasterKey: &documentdb.Key{
Key: creds.MasterKey,
},
})
dbs, err := client.QueryDatabases(&documentdb.Query{
Query: "SELECT * FROM ROOT r WHERE r.id=@id",
Parameters: []documentdb.Parameter{
{Name: "@id", Value: creds.Database},
},
})
if err != nil {
return err
} else if len(dbs) == 0 {
return fmt.Errorf("database %s for CosmosDB state store not found", creds.Database)
}
c.db = &dbs[0]
colls, err := client.QueryCollections(c.db.Self, &documentdb.Query{
Query: "SELECT * FROM ROOT r WHERE r.id=@id",
Parameters: []documentdb.Parameter{
{Name: "@id", Value: creds.Collection},
},
})
if err != nil {
return err
} else if len(colls) == 0 {
return fmt.Errorf("collection %s for CosmosDB state store not found. This must be created before Dapr uses it", creds.Collection)
}
c.collection = &colls[0]
c.client = client
sps, err := c.client.ReadStoredProcedures(c.collection.Self)
if err != nil {
return err
}
// get a link to the sp
for _, proc := range sps {
if proc.Id == storedProcedureName {
c.sp = &proc
break
}
}
if c.sp == nil {
// register the stored procedure
createspBody := storedProcedureDefinition{ID: storedProcedureName, Body: spDefinition}
c.sp, err = c.client.CreateStoredProcedure(c.collection.Self, createspBody)
if err != nil {
// if it already exists that is success
if !strings.HasPrefix(err.Error(), "Conflict") {
return err
}
}
}
c.logger.Debug("cosmos Init done")
return nil
}
// Get retrieves a CosmosDB item
func (c *StateStore) Get(req *state.GetRequest) (*state.GetResponse, error) {
key := req.Key
partitionKey := populatePartitionMetadata(req.Key, req.Metadata)
items := []CosmosItem{}
options := []documentdb.CallOption{documentdb.PartitionKey(partitionKey)}
if req.Options.Consistency == state.Strong {
options = append(options, documentdb.ConsistencyLevel(documentdb.Strong))
}
if req.Options.Consistency == state.Eventual {
options = append(options, documentdb.ConsistencyLevel(documentdb.Eventual))
}
_, err := c.client.QueryDocuments(
c.collection.Self,
documentdb.NewQuery("SELECT * FROM ROOT r WHERE r.id=@id", documentdb.P{Name: "@id", Value: key}),
&items,
options...,
)
if err != nil {
return nil, err
} else if len(items) == 0 {
return &state.GetResponse{}, nil
}
b, err := jsoniter.ConfigFastest.Marshal(&items[0].Value)
if err != nil {
return nil, err
}
return &state.GetResponse{
Data: b,
ETag: items[0].Etag,
}, nil
}
// Set saves a CosmosDB item
func (c *StateStore) Set(req *state.SetRequest) error {
err := state.CheckRequestOptions(req.Options)
if err != nil {
return err
}
partitionKey := populatePartitionMetadata(req.Key, req.Metadata)
options := []documentdb.CallOption{documentdb.PartitionKey(partitionKey)}
if req.ETag != "" {
options = append(options, documentdb.IfMatch((req.ETag)))
}
if req.Options.Consistency == state.Strong {
options = append(options, documentdb.ConsistencyLevel(documentdb.Strong))
}
if req.Options.Consistency == state.Eventual {
options = append(options, documentdb.ConsistencyLevel(documentdb.Eventual))
}
b, ok := req.Value.([]uint8)
if ok {
// data arrived in bytes and already json. Don't marshal the Value field again.
item := CosmosItemWithRawMessage{ID: req.Key, Value: b, PartitionKey: partitionKey}
var marshalled []byte
marshalled, err = convertToJSONWithoutEscapes(item)
if err != nil {
return err
}
_, err = c.client.UpsertDocument(c.collection.Self, marshalled, options...)
} else {
// data arrived as non-bytes, just pass it through.
_, err = c.client.UpsertDocument(c.collection.Self, CosmosItem{ID: req.Key, Value: req.Value, PartitionKey: partitionKey}, options...)
}
if err != nil {
return err
}
return nil
}
// BulkSet performs a bulk set operation
func (c *StateStore) BulkSet(req []state.SetRequest) error {
for i := range req {
err := c.Set(&req[i])
if err != nil {
return err
}
}
return nil
}
// Delete performs a delete operation
func (c *StateStore) Delete(req *state.DeleteRequest) error {
err := state.CheckRequestOptions(req.Options)
if err != nil {
return err
}
partitionKey := populatePartitionMetadata(req.Key, req.Metadata)
options := []documentdb.CallOption{documentdb.PartitionKey(partitionKey)}
items := []CosmosItem{}
_, err = c.client.QueryDocuments(
c.collection.Self,
documentdb.NewQuery("SELECT * FROM ROOT r WHERE r.id=@id", documentdb.P{Name: "@id", Value: req.Key}),
&items,
options...,
)
if err != nil {
return err
} else if len(items) == 0 {
return nil
}
if req.ETag != "" {
options = append(options, documentdb.IfMatch((req.ETag)))
}
if req.Options.Consistency == state.Strong {
options = append(options, documentdb.ConsistencyLevel(documentdb.Strong))
}
if req.Options.Consistency == state.Eventual {
options = append(options, documentdb.ConsistencyLevel(documentdb.Eventual))
}
_, err = c.client.DeleteDocument(items[0].Self, options...)
if err != nil {
c.logger.Debugf("Error from cosmos.DeleteDocument e=%e, e.Error=%s", err, err.Error())
}
return err
}
// BulkDelete performs a bulk delete operation
func (c *StateStore) BulkDelete(req []state.DeleteRequest) error {
for i := range req {
err := c.Delete(&req[i])
if err != nil {
return err
}
}
return nil
}
// Multi performs a transactional operation. succeeds only if all operations succeed, and fails if one or more operations fail
func (c *StateStore) Multi(request *state.TransactionalStateRequest) error {
upserts := []CosmosItem{}
deletes := []CosmosItem{}
partitionKey := unknownPartitionKey
previousPartitionKey := unknownPartitionKey
for _, o := range request.Operations {
t := o.Request.(state.KeyInt)
key := t.GetKey()
metadata := t.GetMetadata()
partitionKey = populatePartitionMetadata(key, metadata)
if previousPartitionKey != unknownPartitionKey &&
partitionKey != previousPartitionKey {
return errors.New("all objects used in Multi() must have the same partition key")
}
previousPartitionKey = partitionKey
if o.Operation == state.Upsert {
req := o.Request.(state.SetRequest)
upsertOperation := CosmosItem{
ID: req.Key,
Value: req.Value,
PartitionKey: partitionKey}
upserts = append(upserts, upsertOperation)
} else if o.Operation == state.Delete {
req := o.Request.(state.DeleteRequest)
deleteOperation := CosmosItem{
ID: req.Key,
Value: "", // Value does not need to be specified
PartitionKey: partitionKey}
deletes = append(deletes, deleteOperation)
}
}
c.logger.Debugf("#upserts=%d,#deletes=%d, partitionkey=%s", len(upserts), len(deletes), partitionKey)
options := []documentdb.CallOption{documentdb.PartitionKey(partitionKey)}
var retString string
// The stored procedure throws if it failed, which sets err to non-nil. It doesn't return anything else.
err := c.client.ExecuteStoredProcedure(c.sp.Self, [...]interface{}{upserts, deletes}, &retString, options...)
if err != nil {
c.logger.Debugf("error=%e", err)
return err
}
return nil
}
// This is a helper to return the partition key to use. If if metadata["partitionkey"] is present,
// use that, otherwise use what's in "key".
func populatePartitionMetadata(key string, requestMetadata map[string]string) string {
if val, found := requestMetadata[metadataPartitionKey]; found {
return val
}
return key
}
func convertToJSONWithoutEscapes(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := jsoniter.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}