-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrestclient.go
1982 lines (1839 loc) · 74.2 KB
/
restclient.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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gocosmos
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/btnguyen2k/consu/checksum"
"github.com/btnguyen2k/consu/gjrc"
"github.com/btnguyen2k/consu/reddo"
"github.com/btnguyen2k/consu/semita"
)
const (
settingEndpoint = "ACCOUNTENDPOINT"
settingAccountKey = "ACCOUNTKEY"
settingTimeout = "TIMEOUTMS"
settingVersion = "VERSION"
settingAutoId = "AUTOID"
settingInsecureSkipVerify = "INSECURESKIPVERIFY"
// DefaultApiVersion holds the default REST API version if not specified in the connection string.
//
// See: https://learn.microsoft.com/en-us/rest/api/cosmos-db/#supported-rest-api-versions
//
// @Available since v0.3.0
DefaultApiVersion = "2020-07-15"
)
// NewRestClient constructs a new RestClient instance from the supplied connection string.
//
// httpClient is reused if supplied. Otherwise, a new http.Client instance is created.
// connStr is expected to be in the following format:
//
// AccountEndpoint=<cosmosdb-restapi-endpoint>;AccountKey=<account-key>[;TimeoutMs=<timeout-in-ms>][;Version=<cosmosdb-api-version>][;AutoId=<true/false>][;InsecureSkipVerify=<true/false>]
//
// If not supplied, default value for TimeoutMs is 10 seconds, Version is DefaultApiVersion (which is "2020-07-15"), AutoId is true, and InsecureSkipVerify is false
//
// - AutoId is added since v0.1.2
// - InsecureSkipVerify is added since v0.1.4
func NewRestClient(httpClient *http.Client, connStr string) (*RestClient, error) {
params := make(map[string]string)
parts := strings.Split(connStr, ";")
for _, part := range parts {
tokens := strings.SplitN(part, "=", 2)
key := strings.ToUpper(strings.TrimSpace(tokens[0]))
if len(tokens) == 2 {
params[key] = strings.TrimSpace(tokens[1])
} else {
params[key] = ""
}
}
endpoint := strings.TrimSuffix(params[settingEndpoint], "/")
if endpoint == "" {
return nil, errors.New("AccountEndpoint not found in connection string")
}
accountKey := params[settingAccountKey]
if accountKey == "" {
return nil, errors.New("AccountKey not found in connection string")
}
key, err := base64.StdEncoding.DecodeString(accountKey)
if err != nil {
return nil, fmt.Errorf("cannot base64 decode account key: %s", err)
}
timeoutMs, err := strconv.Atoi(params[settingTimeout])
if err != nil || timeoutMs < 0 {
timeoutMs = 10000
}
apiVersion := params[settingVersion]
if apiVersion == "" {
apiVersion = DefaultApiVersion
}
autoId, err := strconv.ParseBool(params[settingAutoId])
if err != nil {
autoId = true
}
insecureSkipVerify, err := strconv.ParseBool(params[settingInsecureSkipVerify])
if err != nil {
insecureSkipVerify = false
}
if httpClient == nil {
httpClient = &http.Client{
Timeout: time.Duration(timeoutMs) * time.Millisecond,
Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify}},
}
}
return &RestClient{
client: gjrc.NewGjrc(httpClient, time.Duration(timeoutMs)*time.Millisecond),
endpoint: endpoint,
authKey: key,
apiVersion: apiVersion,
autoId: autoId,
params: params,
}, nil
}
// RestClient is REST-based client for Azure Cosmos DB
type RestClient struct {
client *gjrc.Gjrc
endpoint string // Azure Cosmos DB endpoint
authKey []byte // Account key to authenticate
apiVersion string // Azure Cosmos DB API version
autoId bool // if true and value for 'id' field is not specified, CreateDocument
params map[string]string // parsed parameters
}
func (c *RestClient) buildJsonRequest(method, url string, params interface{}) (*http.Request, error) {
var r *bytes.Reader
if params != nil {
js, _ := json.Marshal(params)
r = bytes.NewReader(js)
} else {
r = bytes.NewReader([]byte{})
}
req, err := http.NewRequest(method, url, r)
if err != nil {
return nil, err
}
req.Header.Set(httpHeaderContentType, "application/json")
req.Header.Set(httpHeaderAccept, "application/json")
req.Header.Set(restApiHeaderVersion, c.apiVersion)
return req, nil
}
func (c *RestClient) addAuthHeader(req *http.Request, method, resType, resId string) *http.Request {
now := time.Now().In(locGmt)
/*
* M.A.I. 2022-02-16
* The original statement had a single ToLower. In the resulting string the resId gets lowered when from MS Docs it should be left unaltered
* I came across an error on a collection with a mixed case name...
* stringToSign := strings.ToLower(fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n", method, resType, resId, now.Format(time.RFC1123), ""))
*/
stringToSign := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n", strings.ToLower(method), strings.ToLower(resType), resId, strings.ToLower(now.Format(time.RFC1123)), "")
h := hmac.New(sha256.New, c.authKey)
h.Write([]byte(stringToSign))
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
authHeader := "type=master&ver=1.0&sig=" + signature
authHeader = url.QueryEscape(authHeader)
req.Header.Set(httpHeaderAuthorization, authHeader)
req.Header.Set(restApiHeaderDate, now.Format(time.RFC1123))
return req
}
func (c *RestClient) buildRestResponse(resp *gjrc.GjrcResponse) RestResponse {
result := RestResponse{CallErr: resp.Error()}
if result.CallErr != nil {
httpResp := resp.HttpResponse()
if httpResp != nil {
result.StatusCode = resp.StatusCode()
if result.StatusCode == 204 || result.StatusCode == 304 {
//Ref: https://learn.microsoft.com/en-us/rest/api/cosmos-db/http-status-codes-for-cosmosdb
//The DELETE operation is successful, no content is returned.
//Server may return status "304 Not Modified", no content is returned.
result.CallErr = nil
} else {
result.RespBody, _ = resp.Body()
}
}
if result.CallErr != nil {
result.CallErr = fmt.Errorf("status-code: %d / error: %s / response-body: %s", result.StatusCode, result.CallErr, result.RespBody)
}
}
if result.CallErr == nil {
result.StatusCode = resp.StatusCode()
result.RespBody, _ = resp.Body()
result.RespHeader = make(map[string]string)
for k, v := range resp.HttpResponse().Header {
if len(v) > 0 {
result.RespHeader[strings.ToUpper(k)] = v[0]
}
}
if v, err := strconv.ParseFloat(result.RespHeader[respHeaderRequestCharge], 64); err == nil {
result.RequestCharge = v
} else {
result.RequestCharge = -1
}
result.SessionToken = result.RespHeader[respHeaderSessionToken]
if result.StatusCode >= 400 {
result.ApiErr = fmt.Errorf("error executing Azure Cosmos DB command; StatusCode=%d;Body=%s", result.StatusCode, result.RespBody)
}
}
return result
}
// GetApiVersion returns the Azure Cosmos DB APi version string, either from connection string or default value.
//
// @Available since v1.0.0
func (c *RestClient) GetApiVersion() string {
return c.apiVersion
}
// GetAutoId returns the auto-id flag.
//
// @Available since v1.0.0
func (c *RestClient) GetAutoId() bool {
return c.autoId
}
// SetAutoId sets value for the auto-id flag.
//
// @Available since v1.0.0
func (c *RestClient) SetAutoId(value bool) *RestClient {
c.autoId = value
return c
}
/*----------------------------------------------------------------------*/
// DatabaseSpec specifies a Cosmos DB database specifications for creation.
type DatabaseSpec struct {
Id string
Ru, MaxRu int
}
// CreateDatabase invokes Cosmos DB API to create a new database.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/create-a-database.
//
// Note: ru and maxru must not be supplied together!
func (c *RestClient) CreateDatabase(spec DatabaseSpec) *RespCreateDb {
method, urlEndpoint := "POST", c.endpoint+"/dbs"
req, err := c.buildJsonRequest(method, urlEndpoint, map[string]interface{}{"id": spec.Id})
if err != nil {
return &RespCreateDb{RestResponse: RestResponse{CallErr: err}, DbInfo: DbInfo{Id: spec.Id}}
}
req = c.addAuthHeader(req, method, "dbs", "")
if spec.Ru > 0 {
req.Header.Set(restApiHeaderOfferThroughput, strconv.Itoa(spec.Ru))
}
if spec.MaxRu > 0 {
req.Header.Set(restApiHeaderOfferAutopilotSettings, fmt.Sprintf(`{"maxThroughput":%d}`, spec.MaxRu))
}
resp := c.client.Do(req)
result := &RespCreateDb{RestResponse: c.buildRestResponse(resp), DbInfo: DbInfo{Id: spec.Id}}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.DbInfo))
}
return result
}
// GetDatabase invokes Cosmos DB API to get an existing database.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-database.
func (c *RestClient) GetDatabase(dbName string) *RespGetDb {
method, urlEndpoint := "GET", c.endpoint+"/dbs/"+dbName
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespGetDb{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "dbs", "dbs/"+dbName)
resp := c.client.Do(req)
result := &RespGetDb{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.DbInfo))
}
return result
}
// DeleteDatabase invokes Cosmos DB API to delete an existing database.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-database.
func (c *RestClient) DeleteDatabase(dbName string) *RespDeleteDb {
method, urlEndpoint := "DELETE", c.endpoint+"/dbs/"+dbName
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespDeleteDb{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "dbs", "dbs/"+dbName)
resp := c.client.Do(req)
result := &RespDeleteDb{RestResponse: c.buildRestResponse(resp)}
return result
}
// ListDatabases invokes Cosmos DB API to list all available databases.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/list-databases.
func (c *RestClient) ListDatabases() *RespListDb {
method, urlEndpoint := "GET", c.endpoint+"/dbs"
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespListDb{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "dbs", "")
resp := c.client.Do(req)
result := &RespListDb{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &result)
if result.CallErr == nil {
sort.Slice(result.Databases, func(i, j int) bool {
// sort databases by id
return result.Databases[i].Id < result.Databases[j].Id
})
}
}
return result
}
/*----------------------------------------------------------------------*/
// CollectionSpec specifies a Cosmos DB collection specifications for creation.
type CollectionSpec struct {
DbName, CollName string
Ru, MaxRu int
// PartitionKeyInfo specifies the collection's partition key.
// At the minimum, the partition key info is a map: {paths:[/path],"kind":"Hash"}
// If partition key is larger than 100 bytes, specify {"Version":2}
PartitionKeyInfo map[string]interface{}
IndexingPolicy map[string]interface{}
UniqueKeyPolicy map[string]interface{}
}
// CreateCollection invokes Cosmos DB API to create a new collection.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/create-a-collection.
//
// Note: ru and maxru must not be supplied together!
func (c *RestClient) CreateCollection(spec CollectionSpec) *RespCreateColl {
method, urlEndpoint := "POST", c.endpoint+"/dbs/"+spec.DbName+"/colls"
params := map[string]interface{}{"id": spec.CollName, "partitionKey": spec.PartitionKeyInfo}
if spec.IndexingPolicy != nil {
params[restApiParamIndexingPolicy] = spec.IndexingPolicy
}
if spec.UniqueKeyPolicy != nil {
params[restApiParamUniqueKeyPolicy] = spec.UniqueKeyPolicy
}
req, err := c.buildJsonRequest(method, urlEndpoint, params)
if err != nil {
return &RespCreateColl{RestResponse: RestResponse{CallErr: err}, CollInfo: CollInfo{Id: spec.CollName}}
}
req = c.addAuthHeader(req, method, "colls", "dbs/"+spec.DbName)
if spec.Ru > 0 {
req.Header.Set(restApiHeaderOfferThroughput, strconv.Itoa(spec.Ru))
}
if spec.MaxRu > 0 {
req.Header.Set(restApiHeaderOfferAutopilotSettings, fmt.Sprintf(`{"maxThroughput":%d}`, spec.MaxRu))
}
resp := c.client.Do(req)
result := &RespCreateColl{RestResponse: c.buildRestResponse(resp), CollInfo: CollInfo{Id: spec.CollName}}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.CollInfo))
}
return result
}
// ReplaceCollection invokes Cosmos DB API to replace an existing collection.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/replace-a-collection.
//
// Note: ru and maxru must not be supplied together!
func (c *RestClient) ReplaceCollection(spec CollectionSpec) *RespReplaceColl {
method, urlEndpoint := "PUT", c.endpoint+"/dbs/"+spec.DbName+"/colls/"+spec.CollName
params := map[string]interface{}{"id": spec.CollName}
if spec.PartitionKeyInfo != nil {
params[restApiParamPartitionKey] = spec.PartitionKeyInfo
}
if spec.IndexingPolicy != nil {
params[restApiParamIndexingPolicy] = spec.IndexingPolicy
}
// The unique index cannot be modified. To change the unique index, remove the collection and re-create a new one.
// if spec.UniqueKeyPolicy != nil {
// params[restApiParamUniqueKeyPolicy] = spec.UniqueKeyPolicy
// }
req, err := c.buildJsonRequest(method, urlEndpoint, params)
if err != nil {
return &RespReplaceColl{RestResponse: RestResponse{CallErr: err}, CollInfo: CollInfo{Id: spec.CollName}}
}
req = c.addAuthHeader(req, method, "colls", "dbs/"+spec.DbName+"/colls/"+spec.CollName)
if spec.Ru > 0 {
req.Header.Set(restApiHeaderOfferThroughput, strconv.Itoa(spec.Ru))
}
if spec.MaxRu > 0 {
req.Header.Set(restApiHeaderOfferAutopilotSettings, fmt.Sprintf(`{"maxThroughput":%d}`, spec.MaxRu))
}
resp := c.client.Do(req)
result := &RespReplaceColl{RestResponse: c.buildRestResponse(resp), CollInfo: CollInfo{Id: spec.CollName}}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.CollInfo))
}
return result
}
// GetCollection invokes Cosmos DB API to get an existing collection.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-collection
func (c *RestClient) GetCollection(dbName, collName string) *RespGetColl {
method, urlEndpoint := "GET", c.endpoint+"/dbs/"+dbName+"/colls/"+collName
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespGetColl{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "colls", "dbs/"+dbName+"/colls/"+collName)
resp := c.client.Do(req)
result := &RespGetColl{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.CollInfo))
}
return result
}
// DeleteCollection invokes Cosmos DB API to delete an existing collection.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-collection.
func (c *RestClient) DeleteCollection(dbName, collName string) *RespDeleteColl {
method, urlEndpoint := "DELETE", c.endpoint+"/dbs/"+dbName+"/colls/"+collName
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespDeleteColl{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "colls", "dbs/"+dbName+"/colls/"+collName)
resp := c.client.Do(req)
result := &RespDeleteColl{RestResponse: c.buildRestResponse(resp)}
return result
}
// ListCollections invokes Cosmos DB API to list all available collections.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/list-collections.
func (c *RestClient) ListCollections(dbName string) *RespListColl {
method, urlEndpoint := "GET", c.endpoint+"/dbs/"+dbName+"/colls"
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespListColl{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "colls", "dbs/"+dbName)
resp := c.client.Do(req)
result := &RespListColl{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &result)
if result.CallErr == nil {
sort.Slice(result.Collections, func(i, j int) bool {
// sort collections by id
return result.Collections[i].Id < result.Collections[j].Id
})
}
}
return result
}
// GetPkranges invokes Cosmos DB API to retrieves the list of partition key ranges for a collection.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-partition-key-ranges.
//
// Available since v0.1.3
func (c *RestClient) GetPkranges(dbName, collName string) *RespGetPkranges {
method, urlEndpoint := "GET", c.endpoint+"/dbs/"+dbName+"/colls/"+collName+"/pkranges"
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespGetPkranges{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "pkranges", "dbs/"+dbName+"/colls/"+collName)
resp := c.client.Do(req)
result := &RespGetPkranges{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &result)
}
return result
}
/*----------------------------------------------------------------------*/
// DocumentSpec specifies a Cosmos DB document specifications for creation.
type DocumentSpec struct {
DbName, CollName string
IsUpsert bool
IndexingDirective string // accepted value "", "Include" or "Exclude"
PartitionKeyValues []interface{}
DocumentData DocInfo
}
// CreateDocument invokes Cosmos DB API to create a new document.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/create-a-document.
func (c *RestClient) CreateDocument(spec DocumentSpec) *RespCreateDoc {
method, urlEndpoint := "POST", c.endpoint+"/dbs/"+spec.DbName+"/colls/"+spec.CollName+"/docs"
if c.autoId {
if id, ok := spec.DocumentData[docFieldId].(string); !ok || strings.TrimSpace(id) == "" {
spec.DocumentData[docFieldId] = strings.ToLower(idGen.Id128Hex())
}
}
req, err := c.buildJsonRequest(method, urlEndpoint, spec.DocumentData)
if err != nil {
return &RespCreateDoc{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "docs", "dbs/"+spec.DbName+"/colls/"+spec.CollName)
if spec.IsUpsert {
req.Header.Set(restApiHeaderIsUpsert, "true")
}
if spec.IndexingDirective != "" {
req.Header.Set(restApiHeaderIndexingDirective, spec.IndexingDirective)
}
jsPkValues, _ := json.Marshal(spec.PartitionKeyValues)
req.Header.Set(restApiHeaderPartitionKey, string(jsPkValues))
resp := c.client.Do(req)
result := &RespCreateDoc{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.DocInfo))
}
return result
}
// ReplaceDocument invokes Cosmos DB API to replace an existing document.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/replace-a-document.
func (c *RestClient) ReplaceDocument(matchEtag string, spec DocumentSpec) *RespReplaceDoc {
id, _ := spec.DocumentData[docFieldId].(string)
method, urlEndpoint := "PUT", c.endpoint+"/dbs/"+spec.DbName+"/colls/"+spec.CollName+"/docs/"+id
req, err := c.buildJsonRequest(method, urlEndpoint, spec.DocumentData)
if err != nil {
return &RespReplaceDoc{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "docs", "dbs/"+spec.DbName+"/colls/"+spec.CollName+"/docs/"+id)
if matchEtag != "" {
req.Header.Set(httpHeaderIfMatch, matchEtag)
}
jsPkValues, _ := json.Marshal(spec.PartitionKeyValues)
req.Header.Set(restApiHeaderPartitionKey, string(jsPkValues))
resp := c.client.Do(req)
result := &RespReplaceDoc{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &(result.DocInfo))
}
return result
}
// DocReq specifies a document request.
type DocReq struct {
DbName, CollName, DocId string
PartitionKeyValues []interface{}
MatchEtag string // if not empty, add "If-Match" header to request
NotMatchEtag string // if not empty, add "If-None-Match" header to request
ConsistencyLevel string // accepted values: "", "Strong", "Bounded", "Session" or "Eventual"
SessionToken string // string token used with session level consistency
}
// GetDocument invokes Cosmos DB API to get an existing document.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-document.
func (c *RestClient) GetDocument(r DocReq) *RespGetDoc {
method, urlEndpoint := "GET", c.endpoint+"/dbs/"+r.DbName+"/colls/"+r.CollName+"/docs/"+r.DocId
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespGetDoc{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "docs", "dbs/"+r.DbName+"/colls/"+r.CollName+"/docs/"+r.DocId)
jsPkValues, _ := json.Marshal(r.PartitionKeyValues)
req.Header.Set(restApiHeaderPartitionKey, string(jsPkValues))
if r.NotMatchEtag != "" {
req.Header.Set(httpHeaderIfNoneMatch, r.NotMatchEtag)
}
if r.ConsistencyLevel != "" {
req.Header.Set(restApiHeaderConsistencyLevel, r.ConsistencyLevel)
}
if r.SessionToken != "" {
req.Header.Set(restApiHeaderSessionToken, r.SessionToken)
}
resp := c.client.Do(req)
result := &RespGetDoc{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil && result.StatusCode != 304 {
result.CallErr = json.Unmarshal(result.RespBody, &(result.DocInfo))
}
return result
}
// DeleteDocument invokes Cosmos DB API to delete an existing document.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-document.
func (c *RestClient) DeleteDocument(r DocReq) *RespDeleteDoc {
method, urlEndpoint := "DELETE", c.endpoint+"/dbs/"+r.DbName+"/colls/"+r.CollName+"/docs/"+r.DocId
req, err := c.buildJsonRequest(method, urlEndpoint, nil)
if err != nil {
return &RespDeleteDoc{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "docs", "dbs/"+r.DbName+"/colls/"+r.CollName+"/docs/"+r.DocId)
jsPkValues, _ := json.Marshal(r.PartitionKeyValues)
req.Header.Set(restApiHeaderPartitionKey, string(jsPkValues))
if r.MatchEtag != "" {
req.Header.Set(httpHeaderIfMatch, r.MatchEtag)
}
resp := c.client.Do(req)
result := &RespDeleteDoc{RestResponse: c.buildRestResponse(resp)}
return result
}
// QueryReq specifies a query request to query for documents.
type QueryReq struct {
DbName, CollName string
Query string
Params []interface{}
MaxItemCount int // if max-item-count = 0: use server side default value, (since v0.1.8) if max-item-count < 0: client will fetch all returned documents from server
PkRangeId string // (since v0.1.8) if non-empty, query will perform only on this PkRangeId (if PkRangeId and PkValue are specified, PkRangeId takes priority)
PkValue string // (since v0.1.8) if non-empty, query will perform only on the partition that PkValue maps to (if PkRangeId and PkValue are specified, PkRangeId takes priority)
ContinuationToken string
CrossPartitionEnabled bool
ConsistencyLevel string // accepted values: "", "Strong", "Bounded", "Session" or "Eventual"
SessionToken string // string token used with session level consistency
}
func (c *RestClient) buildQueryRequest(query QueryReq) (*http.Request, error) {
method, urlEndpoint := "POST", c.endpoint+"/dbs/"+query.DbName+"/colls/"+query.CollName+"/docs"
requestBody := make(map[string]interface{}, 0)
requestBody[restApiParamQuery] = query.Query
if query.Params != nil {
// M.A.I. 2022-02-16: server will complain if parameter set to nil
requestBody[restApiParamParameters] = query.Params
}
req, err := c.buildJsonRequest(method, urlEndpoint, requestBody)
if err != nil {
return nil, err
}
req = c.addAuthHeader(req, method, "docs", "dbs/"+query.DbName+"/colls/"+query.CollName)
req.Header.Set(httpHeaderContentType, "application/query+json")
req.Header.Set(restApiHeaderIsQuery, "true")
req.Header.Set(restApiHeaderPopulateMetrics, "true")
if query.MaxItemCount > 0 {
req.Header.Set(restApiHeaderPageSize, strconv.Itoa(query.MaxItemCount))
}
if query.ContinuationToken != "" {
req.Header.Set(restApiHeaderContinuation, query.ContinuationToken)
}
if query.ConsistencyLevel != "" {
req.Header.Set(restApiHeaderConsistencyLevel, query.ConsistencyLevel)
}
if query.SessionToken != "" {
req.Header.Set(restApiHeaderSessionToken, query.SessionToken)
}
if query.PkRangeId != "" {
req.Header.Set(restApiHeaderPartitionKeyRangeId, query.PkRangeId)
} else if query.PkValue != "" {
req.Header.Set(restApiHeaderPartitionKey, `["`+query.PkValue+`"]`)
}
if query.CrossPartitionEnabled {
req.Header.Set(restApiHeaderEnableCrossPartitionQuery, "true")
}
return req, nil
}
func (c *RestClient) mergeQueryResults(existingResp, newResp *RespQueryDocs, queryPlan *RespQueryPlan) *RespQueryDocs {
temp := *newResp
result := &temp
if existingResp != nil {
result.RequestCharge += existingResp.RequestCharge
if newResp.Error() == nil {
result = result.merge(queryPlan, existingResp)
}
} else if queryPlan.IsDistinctQuery() {
result.Documents = result.Documents.ReduceDistinct(queryPlan)
result.Count = len(result.Documents)
}
if queryPlan.QueryInfo.RewrittenQuery != "" {
result.populateRewrittenDocuments(queryPlan)
}
return result
}
// Note: the query is executed as-is, not rewritten!
func (c *RestClient) queryAllAndMerge(query QueryReq, queryPlan *RespQueryPlan) *RespQueryDocs {
var result *RespQueryDocs
for {
result = c.mergeQueryResults(result, c.queryDocumentsCall(query), queryPlan)
if result.Error() != nil || result.ContinuationToken == "" || (query.MaxItemCount > 0 && result.Count >= query.MaxItemCount) {
break
}
query.ContinuationToken = result.ContinuationToken
}
return result
}
// queryAndMerge queries documents then performs merging to build the final result.
//
// Note: query is rewritten, executed and flattened (transformed) before returned!
func (c *RestClient) queryAndMerge(query QueryReq, pkranges *RespGetPkranges, queryPlan *RespQueryPlan) *RespQueryDocs {
queryRewritten := queryPlan.QueryInfo.RewrittenQuery != ""
if queryRewritten {
query.Query = strings.ReplaceAll(queryPlan.QueryInfo.RewrittenQuery, "{documentdb-formattableorderbyquery-filter}", "true")
}
var result *RespQueryDocs
savedContinuationToken := query.ContinuationToken
if query.PkValue != "" || query.PkRangeId != "" || pkranges.Count == 1 {
if query.PkValue == "" && query.PkRangeId == "" {
query.PkRangeId = pkranges.Pkranges[0].Id
}
result = c.queryDocumentsSimple(query, queryPlan)
} else {
var cctResult, cctQuery = make(map[string]string), make(map[string]string)
if err := json.Unmarshal([]byte(query.ContinuationToken), &cctQuery); err != nil || query.ContinuationToken == "" {
cctQuery = make(map[string]string)
for _, pkrange := range pkranges.Pkranges {
cctQuery[pkrange.Id] = ""
}
}
for k, v := range cctQuery {
cctResult[k] = v
}
savedMaxItemCount := query.MaxItemCount
for _, pkrange := range pkranges.Pkranges {
if continuationToken, ok := cctQuery[pkrange.Id]; !ok {
// all documents from this pk-range had been queried
continue
} else {
query.ContinuationToken = continuationToken
query.PkRangeId = pkrange.Id
}
result = c.mergeQueryResults(result, c.queryAllAndMerge(query, queryPlan), queryPlan)
if result.Error() != nil {
break
}
if result.ContinuationToken == "" {
delete(cctResult, pkrange.Id)
} else {
cctResult[pkrange.Id] = result.ContinuationToken
}
if len(cctResult) > 0 {
js, _ := json.Marshal(cctResult)
result.ContinuationToken = string(js)
} else {
result.ContinuationToken = ""
}
if query.MaxItemCount > 0 {
// honor MaxItemCount setting
if queryPlan.IsGroupByQuery() && result.Count > query.MaxItemCount {
break
}
if result.Count >= query.MaxItemCount {
break
}
query.MaxItemCount = savedMaxItemCount - result.Count
if query.MaxItemCount <= 0 {
break
}
}
if queryPlan.QueryInfo.Limit > 0 && !queryPlan.IsGroupByQuery() && result.Count >= queryPlan.QueryInfo.Offset+queryPlan.QueryInfo.Limit {
break
}
}
}
return c.finalPrepareResult(result, queryPlan, savedContinuationToken)
}
func (c *RestClient) finalPrepareResult(result *RespQueryDocs, queryPlan *RespQueryPlan, savedContinuationToken string) *RespQueryDocs {
queryRewritten := queryPlan.QueryInfo.RewrittenQuery != ""
if queryPlan.IsDistinctQuery() || queryPlan.IsGroupByQuery() {
if queryPlan.IsDistinctQuery() {
result.Documents = result.Documents.ReduceDistinct(queryPlan)
} else {
result.Documents = result.Documents.ReduceGroupBy(queryPlan)
}
result.Count = len(result.Documents)
result.populateRewrittenDocuments(queryPlan)
}
if queryRewritten {
result.Documents = result.Documents.Flatten(queryPlan)
result.Count = len(result.Documents)
}
if queryPlan.QueryInfo.Limit > 0 {
offset, limit := queryPlan.QueryInfo.Offset, queryPlan.QueryInfo.Limit
if savedContinuationToken != "" && queryRewritten {
offset = 0
}
if len(result.Documents)-offset < limit {
limit = len(result.Documents) - offset
}
if limit > 0 {
result.Documents = result.Documents[offset : offset+limit]
if result.RewrittenDocuments != nil {
result.RewrittenDocuments = result.RewrittenDocuments[offset : offset+limit]
}
} else {
result.Documents = result.Documents[0:0]
if result.RewrittenDocuments != nil {
result.RewrittenDocuments = result.RewrittenDocuments[0:0]
}
}
result.Count = len(result.Documents)
}
return result
}
// queryDocumentsSimple handle a query-documents request with simple SQL query.
//
// If QueryReq.MaxItemCount <= 0, all matched documents will be returned
//
// Note: query is executed as-is, not rewritten!
func (c *RestClient) queryDocumentsSimple(query QueryReq, queryPlan *RespQueryPlan) *RespQueryDocs {
req, err := c.buildQueryRequest(query)
if err != nil {
return &RespQueryDocs{RestResponse: RestResponse{CallErr: err}}
}
var result *RespQueryDocs
if query.MaxItemCount <= 0 {
// request chunk by chunk as it would have negative impact if we fetch a large number of documents in one go
req.Header.Set(restApiHeaderPageSize, "100")
}
for {
resp := c.client.Do(req)
tempResult := &RespQueryDocs{RestResponse: c.buildRestResponse(resp)}
if tempResult.CallErr == nil {
tempResult.ContinuationToken = tempResult.RespHeader[respHeaderContinuation]
tempResult.CallErr = json.Unmarshal(tempResult.RespBody, &tempResult)
}
if result != nil {
// append returned document list
tempResult.Count += result.Count
tempResult.RequestCharge += result.RequestCharge
tempResult.Documents = append(result.Documents, tempResult.Documents...)
}
result = tempResult
if result.Error() != nil || query.MaxItemCount > 0 || result.ContinuationToken == "" {
break
}
req.Header.Set(restApiHeaderContinuation, tempResult.ContinuationToken)
}
return result.populateRewrittenDocuments(queryPlan)
}
// queryDocumentsCall makes a single query-documents API call.
//
// Note: the query is executed as-is!
func (c *RestClient) queryDocumentsCall(query QueryReq) *RespQueryDocs {
req, err := c.buildQueryRequest(query)
if err != nil {
return &RespQueryDocs{RestResponse: RestResponse{CallErr: err}}
}
resp := c.client.Do(req)
result := &RespQueryDocs{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.ContinuationToken = result.RespHeader[respHeaderContinuation]
result.CallErr = json.Unmarshal(result.RespBody, &result)
}
return result
}
// QueryDocuments invokes Cosmos DB API to query a collection for documents.
//
// See: https://docs.microsoft.com/en-us/rest/api/cosmos-db/query-documents.
//
// Known issues:
// - (*) `GROUP BY` with `ORDER BY` queries are currently not supported by Cosmos DB! Resolution/Workaround: NONE!
// - Paging a cross-partition `OFFSET...LIMIT` query using QueryReq.MaxItemCount: it would not work. Moreover, the
// result returned from QueryDocumentsCrossPartition might be different from or the one returned from call to
// QueryDocuments without pagination. Resolution/Workaround: NONE!
// - Paging a cross-partition `ORDER BY` query using QueryReq.MaxItemCount would not work: returned rows might not be
// in the expected order. Resolution/Workaround: use QueryDocumentsCrossPartition or QueryDocuments without paging
// (caution: intermediate results are kept in memory, be alerted for out-of-memory error).
// - Paging a cross-partition `SELECT DISTINCT/VALUE` query using QueryReq.MaxItemCount would not work: returned rows
// might be duplicated. Resolution/Workaround: use QueryDocumentsCrossPartition or QueryDocuments without paging
// (caution: intermediate results are kept in memory, be alerted for out-of-memory error).
// - Cross-partition queries that combine `GROUP BY` with QueryReq.MaxItemCount would not work: the aggregate function
// might not work properly. Resolution/Workaround: use QueryDocumentsCrossPartition or QueryDocuments without
// QueryReq.MaxItemCount (caution: intermediate results are kept in memory, be alerted for out-of-memory error).
func (c *RestClient) QueryDocuments(query QueryReq) *RespQueryDocs {
queryPlan := c.QueryPlan(query)
if queryPlan.Error() != nil {
return &RespQueryDocs{RestResponse: queryPlan.RestResponse}
}
if queryPlan.QueryInfo.DistinctType != "None" || queryPlan.QueryInfo.RewrittenQuery != "" {
pkranges := c.GetPkranges(query.DbName, query.CollName)
if pkranges.Error() != nil {
return &RespQueryDocs{RestResponse: pkranges.RestResponse}
}
return c.queryAndMerge(query, pkranges, queryPlan)
}
return c.queryDocumentsSimple(query, queryPlan)
}
// QueryDocumentsCrossPartition can be used as a workaround for known issues with QueryDocuments.
//
// Caution: intermediate results are kept in memory, and all matched rows are returned. Be alerted for out-of-memory error!
//
// Available since v0.2.0
func (c *RestClient) QueryDocumentsCrossPartition(query QueryReq) *RespQueryDocs {
query.CrossPartitionEnabled = true
queryPlan := c.QueryPlan(query)
if queryPlan.Error() != nil {
return &RespQueryDocs{RestResponse: queryPlan.RestResponse}
}
queryRewritten := queryPlan.QueryInfo.RewrittenQuery != ""
pkranges := c.GetPkranges(query.DbName, query.CollName)
if pkranges.Error() != nil {
return &RespQueryDocs{RestResponse: pkranges.RestResponse}
}
if queryRewritten {
query.Query = strings.ReplaceAll(queryPlan.QueryInfo.RewrittenQuery, "{documentdb-formattableorderbyquery-filter}", "true")
}
var result *RespQueryDocs
savedContinuationToken := query.ContinuationToken
for _, pkrange := range pkranges.Pkranges {
query.PkRangeId = pkrange.Id
for {
result = c.mergeQueryResults(result, c.queryAllAndMerge(query, queryPlan), queryPlan)
// fmt.Printf("\tDEBUG: num rows: %5d\n", result.Count)
if result.Error() != nil || result.ContinuationToken == "" {
break
}
query.ContinuationToken = result.ContinuationToken
}
if result.Error() != nil {
return result
}
query.ContinuationToken = ""
}
return c.finalPrepareResult(result, queryPlan, savedContinuationToken)
}
// QueryPlan invokes Cosmos DB API to generate query plan.
//
// Available since v0.1.8
func (c *RestClient) QueryPlan(query QueryReq) *RespQueryPlan {
method, urlEndpoint := "POST", c.endpoint+"/dbs/"+query.DbName+"/colls/"+query.CollName+"/docs"
requestBody := make(map[string]interface{}, 0)
requestBody[restApiParamQuery] = query.Query
if query.Params != nil {
requestBody[restApiParamParameters] = query.Params
}
req, err := c.buildJsonRequest(method, urlEndpoint, requestBody)
if err != nil {
return &RespQueryPlan{RestResponse: RestResponse{CallErr: err}}
}
req = c.addAuthHeader(req, method, "docs", "dbs/"+query.DbName+"/colls/"+query.CollName)
req.Header.Set(httpHeaderContentType, "application/query+json")
if query.MaxItemCount > 0 {
req.Header.Set(restApiHeaderPageSize, strconv.Itoa(query.MaxItemCount))
}
if query.ContinuationToken != "" {
req.Header.Set(restApiHeaderContinuation, query.ContinuationToken)
}
if query.ConsistencyLevel != "" {
req.Header.Set(restApiHeaderConsistencyLevel, query.ConsistencyLevel)
}
if query.SessionToken != "" {
req.Header.Set(restApiHeaderSessionToken, query.SessionToken)
}
req.Header.Set(restApiHeaderIsQueryPlanRequest, "True") // Caution: as of Dec-2022 "true" (lower-cased "t") does not work
req.Header.Set(restApiHeaderSupportedQueryFeatures, "NonValueAggregate, Aggregate, Distinct, MultipleOrderBy, OffsetAndLimit, OrderBy, Top, CompositeAggregate, GroupBy, MultipleAggregates")
req.Header.Set(restApiHeaderEnableCrossPartitionQuery, "true")
req.Header.Set(restApiHeaderParallelizeCrossPartitionQuery, "true")
resp := c.client.Do(req)
result := &RespQueryPlan{RestResponse: c.buildRestResponse(resp)}
if result.CallErr == nil {
result.CallErr = json.Unmarshal(result.RespBody, &result)
}
return result
}
// ListDocsReq specifies a list documents request.
type ListDocsReq struct {
DbName, CollName string
MaxItemCount int
ContinuationToken string
ConsistencyLevel string // accepted values: "", "Strong", "Bounded", "Session" or "Eventual"
SessionToken string // string token used with session level consistency
NotMatchEtag string
PkRangeId string
IsIncrementalFeed bool // (available since v0.1.9) if "true", the request is used to fetch the incremental changes to documents within the collection
}
func (c *RestClient) getChangeFeed(r ListDocsReq, req *http.Request) *RespListDocs {
var result *RespListDocs
for {
resp := c.client.Do(req)
tempResult := &RespListDocs{RestResponse: c.buildRestResponse(resp)}
if 300 <= tempResult.StatusCode && tempResult.StatusCode < 400 {
// not an error, the status code 3xx indicates that there is currently no item from the change feed
} else if tempResult.CallErr == nil {
tempResult.ContinuationToken = tempResult.RespHeader[respHeaderContinuation]
tempResult.Etag = tempResult.RespHeader[respHeaderEtag]
tempResult.CallErr = json.Unmarshal(tempResult.RespBody, &tempResult)