-
Notifications
You must be signed in to change notification settings - Fork 25
/
documentdb.go
438 lines (379 loc) · 12.2 KB
/
documentdb.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
//
// This project start as a fork of `github.com/nerdylikeme/go-documentdb` version
// but changed, and may be changed later
//
// Goal: add the full functionality of documentdb, align with the other sdks
// and make it more testable
//
package documentdb
import (
"bytes"
"context"
"errors"
"net/http"
"reflect"
"strings"
"sync"
)
const (
ClientName = "documentdb-go"
)
var buffers = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer([]byte{})
},
}
var errAAD = errors.New("cannot perform CRUD operations on stored procedures or UDF's while authenticating with Azure AD")
// IdentificationHydrator defines interface for ID hydrators
// that can prepopulate struct with default values
type IdentificationHydrator func(config *Config, doc interface{})
// DefaultIdentificationHydrator fills Id
func DefaultIdentificationHydrator(config *Config, doc interface{}) {
id := reflect.ValueOf(doc).Elem().FieldByName(config.IdentificationPropertyName)
if id.IsValid() && id.String() == "" {
id.SetString(uuid())
}
}
type Config struct {
MasterKey *Key
ServicePrincipal ServicePrincipalProvider
Client http.Client
IdentificationHydrator IdentificationHydrator
IdentificationPropertyName string
AppIdentifier string
}
func NewConfig(key *Key) *Config {
return &Config{
MasterKey: key,
IdentificationHydrator: DefaultIdentificationHydrator,
IdentificationPropertyName: "Id",
}
}
// NewConfigWithServicePrincipal creates a new Config object that uses Azure AD (via a service principal) for authentication
func NewConfigWithServicePrincipal(servicePrincipal ServicePrincipalProvider) *Config {
return &Config{
ServicePrincipal: servicePrincipal,
IdentificationHydrator: DefaultIdentificationHydrator,
IdentificationPropertyName: "Id",
}
}
// WithClient stores given http client for later use by documentdb client.
func (c *Config) WithClient(client http.Client) *Config {
c.Client = client
return c
}
func (c *Config) WithAppIdentifier(appIdentifier string) *Config {
c.AppIdentifier = appIdentifier
return c
}
type DocumentDB struct {
client Clienter
config *Config
}
// New creates DocumentDBClient
func New(url string, config *Config) *DocumentDB {
client := &Client{
Client: config.Client,
}
client.Url = url
client.Config = config
client.UserAgent = strings.Join([]string{ClientName, "/", ReadClientVersion(), " ", config.AppIdentifier}, "")
return &DocumentDB{client: client, config: config}
}
// TODO: Add `requestOptions` arguments
// Read database by self link
func (c *DocumentDB) ReadDatabase(link string, opts ...CallOption) (db *Database, err error) {
_, err = c.client.Read(link, &db, opts...)
if err != nil {
return nil, err
}
return
}
// Read collection by self link
func (c *DocumentDB) ReadCollection(link string, opts ...CallOption) (coll *Collection, err error) {
_, err = c.client.Read(link, &coll, opts...)
if err != nil {
return nil, err
}
return
}
// Read document by self link
func (c *DocumentDB) ReadDocument(link string, doc interface{}, opts ...CallOption) (err error) {
_, err = c.client.Read(link, &doc, opts...)
return
}
// Read sporc by self link
func (c *DocumentDB) ReadStoredProcedure(link string, opts ...CallOption) (sproc *Sproc, err error) {
if c.usesAAD() {
return nil, errAAD
}
_, err = c.client.Read(link, &sproc, opts...)
if err != nil {
return nil, err
}
return
}
// Read udf by self link
func (c *DocumentDB) ReadUserDefinedFunction(link string, opts ...CallOption) (udf *UDF, err error) {
if c.usesAAD() {
return nil, errAAD
}
_, err = c.client.Read(link, &udf, opts...)
if err != nil {
return nil, err
}
return
}
// Read all databases
func (c *DocumentDB) ReadDatabases(opts ...CallOption) (dbs []Database, err error) {
return c.QueryDatabases(nil, opts...)
}
// Read all collections by db selflink
func (c *DocumentDB) ReadCollections(db string, opts ...CallOption) (colls []Collection, err error) {
return c.QueryCollections(db, nil, opts...)
}
// Read all sprocs by collection self link
func (c *DocumentDB) ReadStoredProcedures(coll string, opts ...CallOption) (sprocs []Sproc, err error) {
if c.usesAAD() {
return nil, errAAD
}
return c.QueryStoredProcedures(coll, nil, opts...)
}
// Read pall udfs by collection self link
func (c *DocumentDB) ReadUserDefinedFunctions(coll string, opts ...CallOption) (udfs []UDF, err error) {
if c.usesAAD() {
return nil, errAAD
}
return c.QueryUserDefinedFunctions(coll, nil, opts...)
}
// Read all collection documents by self link
// TODO: use iterator for heavy transactions
func (c *DocumentDB) ReadDocuments(coll string, docs interface{}, opts ...CallOption) (r *Response, err error) {
return c.QueryDocuments(coll, nil, docs, opts...)
}
// Read all databases that satisfy a query
func (c *DocumentDB) QueryDatabases(query *Query, opts ...CallOption) (dbs Databases, err error) {
data := struct {
Databases Databases `json:"Databases,omitempty"`
Count int `json:"_count,omitempty"`
}{}
if query != nil {
_, err = c.client.Query("dbs", query, &data, opts...)
} else {
_, err = c.client.Read("dbs", &data, opts...)
}
if dbs = data.Databases; err != nil {
dbs = nil
}
return
}
// Read all db-collection that satisfy a query
func (c *DocumentDB) QueryCollections(db string, query *Query, opts ...CallOption) (colls []Collection, err error) {
data := struct {
Collections []Collection `json:"DocumentCollections,omitempty"`
Count int `json:"_count,omitempty"`
}{}
if query != nil {
_, err = c.client.Query(db+"colls/", query, &data, opts...)
} else {
_, err = c.client.Read(db+"colls/", &data, opts...)
}
if colls = data.Collections; err != nil {
colls = nil
}
return
}
// Read all collection `sprocs` that satisfy a query
func (c *DocumentDB) QueryStoredProcedures(coll string, query *Query, opts ...CallOption) (sprocs []Sproc, err error) {
if c.usesAAD() {
return nil, errAAD
}
data := struct {
Sprocs []Sproc `json:"StoredProcedures,omitempty"`
Count int `json:"_count,omitempty"`
}{}
if query != nil {
_, err = c.client.Query(coll+"sprocs/", query, &data, opts...)
} else {
_, err = c.client.Read(coll+"sprocs/", &data, opts...)
}
if sprocs = data.Sprocs; err != nil {
sprocs = nil
}
return
}
// Read all collection `udfs` that satisfy a query
func (c *DocumentDB) QueryUserDefinedFunctions(coll string, query *Query, opts ...CallOption) (udfs []UDF, err error) {
if c.usesAAD() {
return nil, errAAD
}
data := struct {
Udfs []UDF `json:"UserDefinedFunctions,omitempty"`
Count int `json:"_count,omitempty"`
}{}
if query != nil {
_, err = c.client.Query(coll+"udfs/", query, &data, opts...)
} else {
_, err = c.client.Read(coll+"udfs/", &data, opts...)
}
if udfs = data.Udfs; err != nil {
udfs = nil
}
return
}
// Read all documents in a collection that satisfy a query
func (c *DocumentDB) QueryDocuments(coll string, query *Query, docs interface{}, opts ...CallOption) (response *Response, err error) {
data := struct {
Documents interface{} `json:"Documents,omitempty"`
Count int `json:"_count,omitempty"`
}{Documents: docs}
if query != nil {
response, err = c.client.Query(coll+"docs/", query, &data, opts...)
} else {
response, err = c.client.Read(coll+"docs/", &data, opts...)
}
return
}
// Read collection's partition ranges
func (c *DocumentDB) QueryPartitionKeyRanges(coll string, query *Query, opts ...CallOption) (ranges []PartitionKeyRange, err error) {
data := queryPartitionKeyRangesRequest{}
if query != nil {
_, err = c.client.Query(coll+"pkranges/", query, &data, opts...)
} else {
_, err = c.client.Read(coll+"pkranges/", &data, opts...)
}
if ranges = data.Ranges; err != nil {
ranges = nil
}
return
}
// Create database
func (c *DocumentDB) CreateDatabase(body interface{}, opts ...CallOption) (db *Database, err error) {
_, err = c.client.Create("dbs", body, &db, opts...)
if err != nil {
return nil, err
}
return
}
// Create collection
func (c *DocumentDB) CreateCollection(db string, body interface{}, opts ...CallOption) (coll *Collection, err error) {
_, err = c.client.Create(db+"colls/", body, &coll, opts...)
if err != nil {
return nil, err
}
return
}
// Create stored procedure
func (c *DocumentDB) CreateStoredProcedure(coll string, body interface{}, opts ...CallOption) (sproc *Sproc, err error) {
if c.usesAAD() {
return nil, errAAD
}
_, err = c.client.Create(coll+"sprocs/", body, &sproc, opts...)
if err != nil {
return nil, err
}
return
}
// Create user defined function
func (c *DocumentDB) CreateUserDefinedFunction(coll string, body interface{}, opts ...CallOption) (udf *UDF, err error) {
if c.usesAAD() {
return nil, errAAD
}
_, err = c.client.Create(coll+"udfs/", body, &udf, opts...)
if err != nil {
return nil, err
}
return
}
// Create document
func (c *DocumentDB) CreateDocument(coll string, doc interface{}, opts ...CallOption) (*Response, error) {
if c.config != nil && c.config.IdentificationHydrator != nil {
c.config.IdentificationHydrator(c.config, doc)
}
return c.client.Create(coll+"docs/", doc, &doc, opts...)
}
// Upsert document
func (c *DocumentDB) UpsertDocument(coll string, doc interface{}, opts ...CallOption) (*Response, error) {
if c.config != nil && c.config.IdentificationHydrator != nil {
c.config.IdentificationHydrator(c.config, doc)
}
return c.client.Upsert(coll+"docs/", doc, &doc, opts...)
}
// TODO: DRY, but the sdk want that[mm.. maybe just client.Delete(self_link)]
// Delete database
func (c *DocumentDB) DeleteDatabase(link string, opts ...CallOption) (*Response, error) {
return c.client.Delete(link, opts...)
}
// Delete collection
func (c *DocumentDB) DeleteCollection(link string, opts ...CallOption) (*Response, error) {
return c.client.Delete(link, opts...)
}
// Delete document
func (c *DocumentDB) DeleteDocument(link string, opts ...CallOption) (*Response, error) {
return c.client.Delete(link, opts...)
}
// Delete stored procedure
func (c *DocumentDB) DeleteStoredProcedure(link string, opts ...CallOption) (*Response, error) {
if c.usesAAD() {
return nil, errAAD
}
return c.client.Delete(link, opts...)
}
// Delete user defined function
func (c *DocumentDB) DeleteUserDefinedFunction(link string, opts ...CallOption) (*Response, error) {
if c.usesAAD() {
return nil, errAAD
}
return c.client.Delete(link, opts...)
}
// Replace database
func (c *DocumentDB) ReplaceDatabase(link string, body interface{}, opts ...CallOption) (db *Database, err error) {
_, err = c.client.Replace(link, body, &db)
if err != nil {
return nil, err
}
return
}
// Replace document
func (c *DocumentDB) ReplaceDocument(link string, doc interface{}, opts ...CallOption) (*Response, error) {
return c.client.Replace(link, doc, &doc, opts...)
}
// Replace stored procedure
func (c *DocumentDB) ReplaceStoredProcedure(link string, body interface{}, opts ...CallOption) (sproc *Sproc, err error) {
if c.usesAAD() {
return nil, errAAD
}
_, err = c.client.Replace(link, body, &sproc, opts...)
if err != nil {
return nil, err
}
return
}
// Replace stored procedure
func (c *DocumentDB) ReplaceUserDefinedFunction(link string, body interface{}, opts ...CallOption) (udf *UDF, err error) {
if c.usesAAD() {
return nil, errAAD
}
_, err = c.client.Replace(link, body, &udf, opts...)
if err != nil {
return nil, err
}
return
}
// Execute stored procedure
func (c *DocumentDB) ExecuteStoredProcedure(link string, params, body interface{}, opts ...CallOption) (err error) {
_, err = c.client.Execute(link, params, &body, opts...)
return
}
// usesAAD returns true if the client is authenticated with Azure AD
func (c *DocumentDB) usesAAD() bool {
return c.config.ServicePrincipal != nil
}
// ServicePrincipalProvider is an interface for an object that provides an Azure service principal
// It's normally used with *adal.ServicePrincipalToken objects from github.com/Azure/go-autorest/autorest/adal
type ServicePrincipalProvider interface {
// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use.
EnsureFreshWithContext(ctx context.Context) error
// OAuthToken returns the current access token.
OAuthToken() string
}