/
api.go
2724 lines (2335 loc) · 98.1 KB
/
api.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 tablestore
import (
"bytes"
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/aliyun/aliyun-tablestore-go-sdk/common"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore/otsprotocol"
Fieldvalues "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore/timeseries/flatbuffer"
"github.com/golang/protobuf/proto"
lruCache "github.com/hashicorp/golang-lru"
)
const (
userAgent = "aliyun-tablestore-sdk-golang/4.0.2"
createTableUri = "/CreateTable"
listTableUri = "/ListTable"
deleteTableUri = "/DeleteTable"
describeTableUri = "/DescribeTable"
updateTableUri = "/UpdateTable"
putRowUri = "/PutRow"
deleteRowUri = "/DeleteRow"
getRowUri = "/GetRow"
updateRowUri = "/UpdateRow"
batchGetRowUri = "/BatchGetRow"
batchWriteRowUri = "/BatchWriteRow"
getRangeUri = "/GetRange"
listStreamUri = "/ListStream"
describeStreamUri = "/DescribeStream"
getShardIteratorUri = "/GetShardIterator"
getStreamRecordUri = "/GetStreamRecord"
computeSplitPointsBySizeRequestUri = "/ComputeSplitPointsBySize"
searchUri = "/Search"
createSearchIndexUri = "/CreateSearchIndex"
updateSearchIndexUri = "/UpdateSearchIndex"
listSearchIndexUri = "/ListSearchIndex"
deleteSearchIndexUri = "/DeleteSearchIndex"
describeSearchIndexUri = "/DescribeSearchIndex"
computeSplitsUri = "/ComputeSplits"
parallelScanUri = "/ParallelScan"
sqlQueryUri = "/SQLQuery"
createIndexUri = "/CreateIndex"
dropIndexUri = "/DropIndex"
createDeliveryTaskUri = "/CreateDeliveryTask"
deleteDeliveryTaskUri = "/DeleteDeliveryTask"
updateDeliveryTaskUri = "/UpdateDeliveryTask"
describeDeliveryTaskUri = "/DescribeDeliveryTask"
listDeliveryTaskUri = "/ListDeliveryTask"
createlocaltransactionuri = "/StartLocalTransaction"
committransactionuri = "/CommitTransaction"
aborttransactionuri = "/AbortTransaction"
adddefinedcolumnuri = "/AddDefinedColumn"
deletedefinedcolumnuri = "/DeleteDefinedColumn"
createTimeseriesTable = "/CreateTimeseriesTable"
putTimeseriesData = "/PutTimeseriesData"
getTimeseriesData = "/GetTimeseriesData"
queryTimeseriesMeta = "/QueryTimeseriesMeta"
listTimeseriesTable = "/ListTimeseriesTable"
deleteTimeseriesTable = "/DeleteTimeseriesTable"
describeTimeseriesTable = "/DescribeTimeseriesTable"
updateTimeseriesTable = "/UpdateTimeseriesTable"
updateTimeseriesMeta = "/UpdateTimeseriesMeta"
deleteTimeseriesMeta = "/DeleteTimeseriesMeta"
createTimeseriesAnalyticalStore = "/CreateTimeseriesAnalyticalStore"
deleteTimeseriesAnalyticalStore = "/DeleteTimeseriesAnalyticalStore"
describeTimeseriesAnalyticalStore = "/DescribeTimeseriesAnalyticalStore"
updateTimeseriesAnalyticalStore = "/UpdateTimeseriesAnalyticalStore"
)
// RowsSerializeType is used for tests only.
var RowsSerializeType = otsprotocol.RowsSerializeType_RST_FLAT_BUFFER
// Constructor: to create the client of TableStore service.
// 构造函数:创建表格存储服务的客户端。
//
// @param endPoint The address of TableStore service. 表格存储服务地址。
// @param instanceName
// @param accessId The Access ID. 用于标示用户的ID。
// @param accessKey The Access Key. 用于签名和验证的密钥。
// @param options set client config
func NewClient(endPoint, instanceName, accessKeyId, accessKeySecret string, options ...ClientOption) *TableStoreClient {
client := NewClientWithConfig(endPoint, instanceName, accessKeyId, accessKeySecret, "", nil, options...)
// client options parse
for _, option := range options {
option(client)
}
return client
}
type GetHttpClient func() IHttpClient
var currentGetHttpClientFunc GetHttpClient = func() IHttpClient {
return &TableStoreHttpClient{}
}
// Constructor: to create the client of OTS service. 传入config
// 构造函数:创建OTS服务的客户端。
func NewClientWithConfig(endPoint, instanceName, accessKeyId, accessKeySecret string, securityToken string, config *TableStoreConfig, options ...ClientOption) *TableStoreClient {
tableStoreClient := new(TableStoreClient)
tableStoreClient.internalClient = new(internalClient)
tableStoreClient.endPoint = endPoint
tableStoreClient.instanceName = instanceName
tableStoreClient.accessKeyId = accessKeyId
tableStoreClient.accessKeySecret = accessKeySecret
tableStoreClient.securityToken = securityToken
tableStoreClient.KeepDefaultRetryStrategyWhileUsingCustomizedRetryFunc = true
provider := &common.DefaultCredentialsProvider{AccessKeyID: accessKeyId, AccessKeySecret: accessKeySecret, SecurityToken: securityToken}
tableStoreClient.credentialsProvider = provider
for _, option := range options {
option(tableStoreClient)
}
if config == nil {
config = NewDefaultTableStoreConfig()
}
tableStoreClient.config = config
var tableStoreTransportProxy http.RoundTripper
if config.Transport != nil {
tableStoreTransportProxy = config.Transport
} else {
tableStoreTransportProxy = &http.Transport{
MaxIdleConnsPerHost: config.MaxIdleConnections,
IdleConnTimeout: config.IdleConnTimeout,
Dial: (&net.Dialer{
Timeout: config.HTTPTimeout.ConnectionTimeout,
}).Dial,
}
}
tableStoreClient.httpClient = currentGetHttpClientFunc()
httpClient := &http.Client{
Transport: tableStoreTransportProxy,
Timeout: tableStoreClient.config.HTTPTimeout.RequestTimeout,
}
tableStoreClient.httpClient.New(httpClient)
tableStoreClient.mu = &sync.Mutex{}
tableStoreClient.random = rand.New(rand.NewSource(time.Now().Unix()))
return tableStoreClient
}
func NewTimeseriesClient(endPoint, instanceName, accessKeyId, accessKeySecret string, options ...TimeseriesClientOption) *TimeseriesClient {
timeseriesClient := NewTimeseriesClientWithConfig(endPoint, instanceName, accessKeyId, accessKeySecret, "", nil, nil)
for _, option := range options {
option(timeseriesClient)
}
return timeseriesClient
}
func NewTimeseriesClientWithConfig(endPoint, instanceName, accessKeyId, accessKeySecret string, securityToken string, config *TableStoreConfig, timeseriesConfiguration *TimeseriesConfiguration, options ...TimeseriesClientOption) *TimeseriesClient {
timeseriesClient := new(TimeseriesClient)
timeseriesClient.internalClient = new(internalClient)
timeseriesClient.endPoint = endPoint
timeseriesClient.instanceName = instanceName
timeseriesClient.accessKeyId = accessKeyId
timeseriesClient.accessKeySecret = accessKeySecret
timeseriesClient.securityToken = securityToken
timeseriesClient.KeepDefaultRetryStrategyWhileUsingCustomizedRetryFunc = true
provider := &common.DefaultCredentialsProvider{AccessKeyID: accessKeyId, AccessKeySecret: accessKeySecret, SecurityToken: securityToken}
timeseriesClient.credentialsProvider = provider
for _, option := range options {
option(timeseriesClient)
}
if config == nil {
config = NewDefaultTableStoreConfig()
}
timeseriesClient.config = config
if timeseriesConfiguration == nil {
timeseriesConfiguration = NewTimeseriesConfiguration()
}
timeseriesClient.timeseriesConfiguration = timeseriesConfiguration
var tableStoreTransportProxy http.RoundTripper
if config.Transport != nil {
tableStoreTransportProxy = config.Transport
} else {
tableStoreTransportProxy = &http.Transport{
MaxIdleConnsPerHost: config.MaxIdleConnections,
IdleConnTimeout: config.IdleConnTimeout,
Dial: (&net.Dialer{
Timeout: config.HTTPTimeout.ConnectionTimeout,
}).Dial,
}
}
timeseriesClient.httpClient = currentGetHttpClientFunc()
httpClient := &http.Client{
Transport: tableStoreTransportProxy,
Timeout: timeseriesClient.config.HTTPTimeout.RequestTimeout,
}
timeseriesClient.httpClient.New(httpClient)
timeseriesClient.mu = &sync.Mutex{}
timeseriesClient.random = rand.New(rand.NewSource(time.Now().Unix()))
timeseriesMetaCache, _ := lruCache.New(timeseriesClient.timeseriesConfiguration.metaCacheMaxDataSize)
timeseriesClient.SetTimeseriesMetaCache(timeseriesMetaCache)
return timeseriesClient
}
func NewClientWithExternalHeader(endPoint, instanceName, accessKeyId, accessKeySecret string, securityToken string, config *TableStoreConfig, header map[string]string) *TableStoreClient {
tableStoreClient := NewClientWithConfig(endPoint, instanceName, accessKeyId, accessKeySecret, securityToken, config)
tableStoreClient.externalHeader = header
return tableStoreClient
}
type RetryNotify func(traceId, requestId string, err error, action string, backoffDuration time.Duration)
// 请求服务端
func (internalClient *internalClient) doRequestWithRetry(uri string, req, resp proto.Message, responseInfo *ResponseInfo, extraInfo ExtraRequestInfo) error {
end := time.Now().Add(internalClient.config.MaxRetryTime)
url := fmt.Sprintf("%s%s", internalClient.endPoint, uri)
/* request body */
var body []byte
var err error
if req != nil {
body, err = proto.Marshal(req)
if err != nil {
return err
}
} else {
body = nil
}
var value int64
var i uint
var respBody []byte
var requestId string
for i = 0; ; i++ {
respBody, err, requestId = internalClient.doRequest(url, uri, body, resp, extraInfo)
responseInfo.RequestId = requestId
if err == nil {
break
} else {
value = internalClient.getNextPause(err, i, end, value, uri)
// fmt.Println("hit retry", uri, err, *e.Code, Value)
if value <= 0 {
return err
}
if internalClient.RetryNotify != nil {
traceId := ""
if extraInfo.userTraceID != nil {
traceId = *extraInfo.userTraceID
}
internalClient.RetryNotify(traceId, requestId, err, uri, time.Duration(value)*time.Millisecond)
}
time.Sleep(time.Duration(value) * time.Millisecond)
}
}
if len(respBody) == 0 {
return nil
}
err = proto.Unmarshal(respBody, resp)
if err != nil {
return fmt.Errorf("decode resp failed: %s", err)
}
return nil
}
func (internalClient *internalClient) doBatchRequestWithRetry(uri string, req, resp proto.Message, responseInfo *ResponseInfo, extraInfo ExtraRequestInfo) error {
end := time.Now().Add(internalClient.config.MaxRetryTime)
url := fmt.Sprintf("%s%s", internalClient.endPoint, uri)
/* request body */
body, err := proto.Marshal(req)
if req != nil && err != nil {
return err
}
var value int64
var respBody []byte
var requestId string
for i := uint(0); ; i++ {
respBody, err, requestId = internalClient.doRequest(url, uri, body, resp, extraInfo)
responseInfo.RequestId = requestId
if err != nil {
value = internalClient.getNextPause(err, i, end, value, uri)
// fmt.Println("hit retry", uri, err, *e.Code, Value)
if value <= 0 {
return err
}
if internalClient.RetryNotify != nil {
traceId := ""
if extraInfo.userTraceID != nil {
traceId = *extraInfo.userTraceID
}
internalClient.RetryNotify(traceId, requestId, err, uri, time.Duration(value)*time.Millisecond)
}
time.Sleep(time.Duration(value) * time.Millisecond)
} else {
if len(respBody) == 0 {
return nil
}
if err = mergeBatchResponse(resp, respBody, uri); err != nil {
return err
}
var partitionFailedCouldRetry bool
body, partitionFailedCouldRetry, err = generateBatchRequest(resp, req, uri)
if err != nil || !partitionFailedCouldRetry {
return err
}
value = internalClient.getPartitionFailedNextPause(i, end, value)
if value <= 0 {
return nil
}
traceId := ""
if extraInfo.userTraceID != nil {
traceId = *extraInfo.userTraceID
}
if internalClient.RetryNotify != nil {
internalClient.RetryNotify(traceId, requestId, err, uri, time.Duration(value)*time.Millisecond)
}
time.Sleep(time.Duration(value) * time.Millisecond)
}
}
}
func mergeBatchResponse(previousResp proto.Message, currentRespBody []byte, uri string) error {
// merge result of currentRespBody into previousResp
var err error
switch uri {
case batchWriteRowUri:
// decode currentRespBody
if previousResp == nil ||
previousResp.(*otsprotocol.BatchWriteRowResponse).GetTables() == nil { // first response, no need to merge response
err = proto.Unmarshal(currentRespBody, previousResp)
return err
} else { // merge response
currentResp := new(otsprotocol.BatchWriteRowResponse)
err = proto.Unmarshal(currentRespBody, currentResp)
if err != nil {
return fmt.Errorf("decode resp failed: %s", err)
}
// parse currentResp into map
rowResultMap := map[string][]*otsprotocol.RowInBatchWriteRowResponse{}
for _, currentTable := range currentResp.Tables {
rowResultMap[currentTable.GetTableName()] = currentTable.GetRows()
}
// update failed partition in previousResponse
for _, previousTable := range previousResp.(*otsprotocol.BatchWriteRowResponse).Tables {
index := 0
for _, previousRowResult := range previousTable.GetRows() {
if !previousRowResult.GetIsOk() { // previous response failed
tmpRowResult := rowResultMap[previousTable.GetTableName()][index]
index++
if tmpRowResult.GetIsOk() { // new response success
*previousRowResult.IsOk = true
previousRowResult.Row = tmpRowResult.GetRow()
previousRowResult.Consumed = tmpRowResult.GetConsumed()
} else {
*previousRowResult.IsOk = false // new response failed
previousRowResult.Error = tmpRowResult.GetError()
previousRowResult.Row = tmpRowResult.GetRow()
}
}
}
}
return nil
}
case batchGetRowUri:
// decode currentRespBody
if previousResp == nil ||
previousResp.(*otsprotocol.BatchGetRowResponse).GetTables() == nil { // first response, no need to merge response
err = proto.Unmarshal(currentRespBody, previousResp)
return err
} else { // merge response
currentResp := new(otsprotocol.BatchGetRowResponse)
err = proto.Unmarshal(currentRespBody, currentResp)
if err != nil {
return fmt.Errorf("decode resp failed: %s", err)
}
rowResultMap := map[string][]*otsprotocol.RowInBatchGetRowResponse{}
for _, currentTable := range currentResp.Tables {
rowResultMap[currentTable.GetTableName()] = currentTable.GetRows()
}
// update failed partition in previousResponse
for _, previousTable := range previousResp.(*otsprotocol.BatchGetRowResponse).Tables {
index := 0
for _, previousRowResult := range previousTable.GetRows() {
if !previousRowResult.GetIsOk() { // previous response failed
tmpRowResult := rowResultMap[previousTable.GetTableName()][index]
index++
if tmpRowResult.GetIsOk() { // new response success
*previousRowResult.IsOk = true
previousRowResult.Row = tmpRowResult.GetRow()
previousRowResult.Consumed = tmpRowResult.GetConsumed()
} else {
*previousRowResult.IsOk = false // new response failed
previousRowResult.Error = tmpRowResult.GetError()
previousRowResult.Row = tmpRowResult.GetRow()
}
}
}
}
return nil
}
default:
return fmt.Errorf("unsupport batch handle function: %s", uri)
}
}
func generateBatchRequest(resp proto.Message, originRequest proto.Message, uri string) ([]byte, bool, error) {
// if all success or failure could not retry: return nil, false, nil
// if partition failed and could retry: return nextRequest, true, nil
respContainsFailedRows := false
switch uri {
case batchWriteRowUri:
tmpReq := new(otsprotocol.BatchWriteRowRequest)
var tablesInBatch []*otsprotocol.TableInBatchWriteRowRequest
// parse originRequest into map
rowRequestMap := map[string][]*otsprotocol.RowInBatchWriteRowRequest{}
for _, tableRequest := range originRequest.(*otsprotocol.BatchWriteRowRequest).Tables {
rowRequestMap[tableRequest.GetTableName()] = tableRequest.GetRows()
}
for _, table := range resp.(*otsprotocol.BatchWriteRowResponse).Tables {
tmpTable := new(otsprotocol.TableInBatchWriteRowRequest)
tmpTable.TableName = proto.String(table.GetTableName())
index := 0
for _, rowResult := range table.GetRows() {
if !rowResult.GetIsOk() {
// 只有所有失败的行可重试时,批量操作才可以重试
if !ShouldRetryViaErrorAndAction(rowResult.GetError().GetCode(), rowResult.GetError().GetMessage(), uri) {
return nil, false, nil
}
respContainsFailedRows = true
tmpTable.Rows = append(tmpTable.Rows, rowRequestMap[table.GetTableName()][index])
}
index++
}
if len(tmpTable.GetRows()) != 0 {
tablesInBatch = append(tablesInBatch, tmpTable)
}
}
tmpReq.Tables = tablesInBatch
tmpReq.IsAtomic = proto.Bool(originRequest.(*otsprotocol.BatchWriteRowRequest).GetIsAtomic())
// TODO: set TransactionId after go sdk support transaction.
newRequest, err := proto.Marshal(tmpReq)
return newRequest, respContainsFailedRows, err
case batchGetRowUri:
tmpReq := new(otsprotocol.BatchGetRowRequest)
// parse originRequest into map
rowRequestMap := map[string]*otsprotocol.TableInBatchGetRowRequest{}
for _, rowRequest := range originRequest.(*otsprotocol.BatchGetRowRequest).Tables {
rowRequestMap[rowRequest.GetTableName()] = rowRequest
}
for _, table := range resp.(*otsprotocol.BatchGetRowResponse).Tables {
tableRequest := new(otsprotocol.TableInBatchGetRowRequest)
tableRequest.TableName = rowRequestMap[table.GetTableName()].TableName
tableRequest.Token = rowRequestMap[table.GetTableName()].GetToken()
tableRequest.ColumnsToGet = rowRequestMap[table.GetTableName()].ColumnsToGet
tableRequest.TimeRange = rowRequestMap[table.GetTableName()].TimeRange
tableRequest.MaxVersions = rowRequestMap[table.GetTableName()].MaxVersions
tableRequest.CacheBlocks = rowRequestMap[table.GetTableName()].CacheBlocks
tableRequest.ColumnsToGet = rowRequestMap[table.GetTableName()].ColumnsToGet
tableRequest.Filter = rowRequestMap[table.GetTableName()].Filter
tableRequest.StartColumn = rowRequestMap[table.GetTableName()].StartColumn
tableRequest.EndColumn = rowRequestMap[table.GetTableName()].EndColumn
index := 0
for _, rowResult := range table.GetRows() {
if !rowResult.GetIsOk() {
// 只有所有失败的行可重试时,批量操作才可以重试
if !ShouldRetryViaErrorAndAction(rowResult.GetError().GetCode(), rowResult.GetError().GetMessage(), uri) {
return nil, false, nil
}
respContainsFailedRows = true
primaryKey := rowRequestMap[table.GetTableName()].GetPrimaryKey()[index]
if primaryKey == nil {
return nil, respContainsFailedRows, fmt.Errorf("can not find table '%s' with index %d", table.GetTableName(), index)
}
tableRequest.PrimaryKey = append(tableRequest.PrimaryKey, primaryKey)
}
index++
}
if len(tableRequest.PrimaryKey) != 0 {
tmpReq.Tables = append(tmpReq.Tables, tableRequest)
}
}
newRequest, err := proto.Marshal(tmpReq)
return newRequest, respContainsFailedRows, err
default:
return nil, respContainsFailedRows, fmt.Errorf("unsupport generate batch request handle function: %s", uri)
}
}
func (internalClient *internalClient) getPartitionFailedNextPause(count uint, end time.Time, lastInterval int64) int64 {
if internalClient.config.RetryTimes <= count || time.Now().After(end) {
return 0
}
newInterval := internalClient.computeNewRetryInterval(lastInterval)
return newInterval
}
func (internalClient *internalClient) getNextPause(err error, count uint, end time.Time, lastInterval int64, action string) int64 {
if internalClient.config.RetryTimes <= count || time.Now().After(end) {
return 0
}
var retry bool
if otsErr, ok := err.(*OtsError); ok {
retry = internalClient.shouldRetry(otsErr.Code, otsErr.Message, action, otsErr.HttpStatusCode)
} else {
if err == io.EOF || err == io.ErrUnexpectedEOF || //retry on special net error contains EOF or reset
strings.Contains(err.Error(), io.EOF.Error()) ||
strings.Contains(err.Error(), "server closed idle connection") ||
strings.Contains(err.Error(), "Connection reset by peer") ||
strings.Contains(err.Error(), "connection reset by peer") {
// server already close this connection, no need to delay
return 1
} else if strings.Contains(err.Error(), "connection refused") {
retry = true
} else if nErr, ok := err.(net.Error); ok {
retry = nErr.Temporary()
}
}
if retry {
newInterval := internalClient.computeNewRetryInterval(lastInterval)
return newInterval
}
return 0
}
func (internalClient *internalClient) computeNewRetryInterval(lastInterval int64) int64 {
defaultRetryInterval := internalClient.config.DefaultRetryInterval / time.Millisecond
if defaultRetryInterval <= 0 {
defaultRetryInterval = DefaultRetryInterval
}
maxRetryInterval := internalClient.config.MaxRetryInterval / time.Millisecond
if maxRetryInterval <= 0 {
maxRetryInterval = MaxRetryInterval
}
// lock/unlock when accessing the rand from a goroutine
internalClient.mu.Lock()
value := lastInterval*2 + internalClient.random.Int63n(int64(defaultRetryInterval) - 1) + 1
internalClient.mu.Unlock()
if value > int64(maxRetryInterval) {
value = int64(maxRetryInterval)
}
return value
}
func (internalClient *internalClient) postReq(req *http.Request, url string) ([]byte, error, string) {
resp, err := internalClient.httpClient.Do(req)
if err != nil {
return nil, err, ""
}
defer resp.Body.Close()
reqId := getRequestId(resp)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err, reqId
}
if (resp.StatusCode >= 200 && resp.StatusCode < 300) == false {
var retErr *OtsError
perr := new(otsprotocol.Error)
errUm := proto.Unmarshal(body, perr)
if errUm != nil {
retErr = rawHttpToOtsError(resp.StatusCode, body, reqId)
} else {
retErr = pbErrToOtsError(resp.StatusCode, perr, reqId)
}
return nil, retErr, reqId
}
return body, nil, reqId
}
func (internalClient *internalClient) shouldRetry(errorCode string, errorMsg string, action string, statusCode int) bool {
if internalClient.CustomizedRetryFunc != nil {
if internalClient.CustomizedRetryFunc(errorCode, errorMsg, action, statusCode) == true {
return true
} else if !internalClient.KeepDefaultRetryStrategyWhileUsingCustomizedRetryFunc {
return false
}
}
return ShouldRetryViaErrorAndAction(errorCode, errorMsg, action)
}
func ShouldRetryViaErrorAndAction(errorCode string, errorMsg string, action string) bool {
if retryNotMatterActions(errorCode, errorMsg) == true {
return true
}
if isIdempotent(action) &&
(errorCode == STORAGE_TIMEOUT || errorCode == INTERNAL_SERVER_ERROR || errorCode == SERVER_UNAVAILABLE) {
return true
}
return false
}
type CustomizedRetryNotMatterActions func(errorCode string, errorMsg string, action string, httpStatus int) bool
func retryNotMatterActions(errorCode string, errorMsg string) bool {
if errorCode == ROW_OPERATION_CONFLICT || errorCode == NOT_ENOUGH_CAPACITY_UNIT ||
errorCode == TABLE_NOT_READY || errorCode == PARTITION_UNAVAILABLE ||
errorCode == SERVER_BUSY || errorCode == STORAGE_SERVER_BUSY || (errorCode == QUOTA_EXHAUSTED && errorMsg == "Too frequent table operations.") {
return true
} else {
return false
}
}
func isIdempotent(action string) bool {
return action == batchGetRowUri || action == describeTableUri ||
action == getRangeUri || action == getRowUri ||
action == listTableUri || action == listStreamUri ||
action == getStreamRecordUri || action == describeStreamUri ||
action == computeSplitsUri || action == parallelScanUri ||
action == searchUri || action == describeSearchIndexUri ||
action == listSearchIndexUri
}
func (internalClient *internalClient) doRequest(url string, uri string, body []byte, resp proto.Message, extraInfo ExtraRequestInfo) ([]byte, error, string) {
hreq, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
return nil, err, ""
}
akInfo := internalClient.credentialsProvider.GetCredentials()
/* set headers */
hreq.Header.Set("User-Agent", userAgent)
date := time.Now().UTC().Format(xOtsDateFormat)
hreq.Header.Set(xOtsDate, date)
hreq.Header.Set(xOtsApiversion, ApiVersion)
hreq.Header.Set(xOtsAccesskeyid, akInfo.GetAccessKeyID())
hreq.Header.Set(xOtsInstanceName, internalClient.instanceName)
for key, value := range internalClient.externalHeader {
hreq.Header[key] = []string{value}
}
md5Byte := md5.Sum(body)
md5Base64 := base64.StdEncoding.EncodeToString(md5Byte[:16])
hreq.Header.Set(xOtsContentmd5, md5Base64)
otshead := createOtsHeaders(akInfo.GetAccessKeySecret())
otshead.set(xOtsDate, date)
otshead.set(xOtsApiversion, ApiVersion)
otshead.set(xOtsAccesskeyid, akInfo.GetAccessKeyID())
if extraInfo.userTraceID != nil && *extraInfo.userTraceID != "" {
hreq.Header.Set(xOtsHeaderSDKTraceID, *extraInfo.userTraceID)
otshead.set(xOtsHeaderSDKTraceID, *extraInfo.userTraceID)
}
if extraInfo.requestExtension != nil && extraInfo.requestExtension.priority != nil {
hreq.Header.Set(xOtsHeaderRequestPriority, strconv.Itoa(int(*extraInfo.requestExtension.priority)))
otshead.set(xOtsHeaderRequestPriority, strconv.Itoa(int(*extraInfo.requestExtension.priority)))
}
if extraInfo.requestExtension != nil && extraInfo.requestExtension.tag != nil && *extraInfo.requestExtension.tag != "" {
hreq.Header.Set(xOtsHeaderRequestTag, *extraInfo.requestExtension.tag)
otshead.set(xOtsHeaderRequestTag, *extraInfo.requestExtension.tag)
}
if akInfo.GetSecurityToken() != "" {
hreq.Header.Set(xOtsHeaderStsToken, akInfo.GetSecurityToken())
otshead.set(xOtsHeaderStsToken, akInfo.GetSecurityToken())
}
otshead.set(xOtsContentmd5, md5Base64)
otshead.set(xOtsInstanceName, internalClient.instanceName)
for key, value := range internalClient.externalHeader {
if strings.HasPrefix(key, xOtsPrefix) {
otshead.set(key, value)
}
}
sign, err := otshead.signature(uri, "POST", akInfo.GetAccessKeySecret())
if err != nil {
return nil, err, ""
}
hreq.Header.Set(xOtsSignature, sign)
/* end set headers */
return internalClient.postReq(hreq, url)
}
func (tableStoreClient *TableStoreClient) GetExternalHeader() map[string]string {
return tableStoreClient.externalHeader
}
func (tableStoreClient *TableStoreClient) GetRetryNotify() RetryNotify {
if tableStoreClient.internalClient == nil {
return nil
}
return tableStoreClient.RetryNotify
}
func (tableStoreClient *TableStoreClient) SetRetryNotify(retryNotify RetryNotify) {
if tableStoreClient.internalClient == nil {
return
}
tableStoreClient.RetryNotify = retryNotify
}
// table API
// Create a table with the CreateTableRequest, in which the table name and
// primary keys are required.
// 根据CreateTableRequest创建一个表,其中表名和主健列是必选项
//
// @param request of CreateTableRequest.
// @return Void. 无返回值。
func (tableStoreClient *TableStoreClient) CreateTable(request *CreateTableRequest) (*CreateTableResponse, error) {
if len(request.TableMeta.TableName) > maxTableNameLength {
return nil, errTableNameTooLong(request.TableMeta.TableName)
}
if len(request.TableMeta.SchemaEntry) > maxPrimaryKeyNum {
return nil, errPrimaryKeyTooMuch
}
if len(request.TableMeta.SchemaEntry) == 0 {
return nil, errCreateTableNoPrimaryKey
}
req := new(otsprotocol.CreateTableRequest)
req.TableMeta = new(otsprotocol.TableMeta)
req.TableMeta.TableName = proto.String(request.TableMeta.TableName)
if len(request.TableMeta.DefinedColumns) > 0 {
for _, value := range request.TableMeta.DefinedColumns {
req.TableMeta.DefinedColumn = append(req.TableMeta.DefinedColumn, &otsprotocol.DefinedColumnSchema{Name: &value.Name, Type: value.ColumnType.ConvertToPbDefinedColumnType().Enum()})
}
}
if len(request.IndexMetas) > 0 {
for _, value := range request.IndexMetas {
req.IndexMetas = append(req.IndexMetas, value.ConvertToPbIndexMeta())
}
}
for _, key := range request.TableMeta.SchemaEntry {
keyType := otsprotocol.PrimaryKeyType(*key.Type)
if key.Option != nil {
keyOption := otsprotocol.PrimaryKeyOption(*key.Option)
req.TableMeta.PrimaryKey = append(req.TableMeta.PrimaryKey, &otsprotocol.PrimaryKeySchema{Name: key.Name, Type: &keyType, Option: &keyOption})
} else {
req.TableMeta.PrimaryKey = append(req.TableMeta.PrimaryKey, &otsprotocol.PrimaryKeySchema{Name: key.Name, Type: &keyType})
}
}
req.ReservedThroughput = new(otsprotocol.ReservedThroughput)
req.ReservedThroughput.CapacityUnit = new(otsprotocol.CapacityUnit)
req.ReservedThroughput.CapacityUnit.Read = proto.Int32(int32(request.ReservedThroughput.Readcap))
req.ReservedThroughput.CapacityUnit.Write = proto.Int32(int32(request.ReservedThroughput.Writecap))
req.TableOptions = new(otsprotocol.TableOptions)
req.TableOptions.TimeToLive = proto.Int32(int32(request.TableOption.TimeToAlive))
req.TableOptions.MaxVersions = proto.Int32(int32(request.TableOption.MaxVersion))
if request.TableOption.AllowUpdate != nil {
req.TableOptions.AllowUpdate = proto.Bool(*request.TableOption.AllowUpdate)
}
if request.TableOption.DeviationCellVersionInSec > 0 {
req.TableOptions.DeviationCellVersionInSec = proto.Int64(request.TableOption.DeviationCellVersionInSec)
}
if request.StreamSpec != nil {
var ss otsprotocol.StreamSpecification
if request.StreamSpec.EnableStream {
ss = otsprotocol.StreamSpecification{
EnableStream: &request.StreamSpec.EnableStream,
ExpirationTime: &request.StreamSpec.ExpirationTime,
ColumnsToGet: request.StreamSpec.OriginColumnsToGet,
}
} else {
ss = otsprotocol.StreamSpecification{
EnableStream: &request.StreamSpec.EnableStream}
}
req.StreamSpec = &ss
}
if request.SSESpecification != nil {
if err := request.SSESpecification.CheckArguments(); err != nil {
return nil, err
}
sse := new(otsprotocol.SSESpecification)
sse.Enable = proto.Bool(request.SSESpecification.Enable)
if request.SSESpecification.KeyType != nil {
sseType := *request.SSESpecification.KeyType
switch sseType {
case SSE_KMS_SERVICE:
keyType := otsprotocol.SSEKeyType_SSE_KMS_SERVICE
sse.KeyType = &keyType
case SSE_BYOK:
keyType := otsprotocol.SSEKeyType_SSE_BYOK
sse.KeyType = &keyType
default:
return nil, errInvalidSSEKeyType(sseType.String())
}
}
if request.SSESpecification.KeyId != nil {
sse.KeyId = []byte(*request.SSESpecification.KeyId)
}
if request.SSESpecification.RoleArn != nil {
sse.RoleArn = []byte(*request.SSESpecification.RoleArn)
}
req.SseSpec = sse
}
if request.EnableLocalTxn != nil {
req.EnableLocalTxn = request.EnableLocalTxn
}
resp := new(otsprotocol.CreateTableResponse)
response := &CreateTableResponse{}
if err := tableStoreClient.doRequestWithRetry(createTableUri, req, resp, &response.ResponseInfo, request.ExtraRequestInfo); err != nil {
return nil, err
}
return response, nil
}
// Create a timeseries table with CreateTimeseriesTableRequest. in which the timeseriesname
// and tableOptions are required.
// 根据CreateTimeseriesTableRequest创建一个时序表,其中表名和表选项是必选项
//
// @param request of CreateTimeseriesTableRequest。
// @return Void. 无返回值。
func (timeseriesClient *TimeseriesClient) CreateTimeseriesTable(request *CreateTimeseriesTableRequest) (*CreateTimeseriesTableResponse, error) {
req := new(otsprotocol.CreateTimeseriesTableRequest)
req.TableMeta = new(otsprotocol.TimeseriesTableMeta)
req.TableMeta.TableName = proto.String(request.GetTimeseriesTableMeta().GetTimeseriesTableName())
req.TableMeta.TableOptions = new(otsprotocol.TimeseriesTableOptions)
req.TableMeta.TableOptions.TimeToLive = proto.Int32(int32(request.GetTimeseriesTableMeta().GetTimeseriesTableOPtions().GetTimeToLive()))
for _, analyticalStore := range request.GetAnalyticalStores() {
req.AnalyticalStores = append(req.AnalyticalStores, &otsprotocol.TimeseriesAnalyticalStore{
StoreName: proto.String(analyticalStore.StoreName),
TimeToLive: analyticalStore.TimeToLive,
SyncOption: (*otsprotocol.AnalyticalStoreSyncType)(analyticalStore.SyncOption),
})
}
req.EnableAnalyticalStore = proto.Bool(request.GetEnableAnalyticalStore())
resp := new(otsprotocol.CreateTimeseriesTableResponse)
response := &CreateTimeseriesTableResponse{}
if err := timeseriesClient.doRequestWithRetry(createTimeseriesTable, req, resp, &response.ResponseInfo, request.ExtraRequestInfo); err != nil {
return nil, err
}
return response, nil
}
// Put a row in a timeseries table. The timeseriesTableName and TimeseriesRow are required.
// 插入新的时序数据,其中时序表名和时序数据行(可多行)作为参数
//
// @param request of PutTimeseriesDataRequest。
// @return FailedRowResult
func (timeseriesClient *TimeseriesClient) PutTimeseriesData(request *PutTimeseriesDataRequest) (*PutTimeseriesDataResponse, error) {
if request == nil || request.timeseriesTableName == "" || request.rows == nil || len(request.rows) == 0 {
return nil, fmt.Errorf("PutTimeseriesDataRequest is empty")
}
var err error
req := new(otsprotocol.PutTimeseriesDataRequest)
req.TableName = proto.String(request.timeseriesTableName)
req.RowsData = new(otsprotocol.TimeseriesRows)
req.RowsData.Type = new(otsprotocol.RowsSerializeType)
req.RowsData.Type = RowsSerializeType.Enum()
switch RowsSerializeType {
case otsprotocol.RowsSerializeType_RST_FLAT_BUFFER:
req.RowsData.RowsData, err = BuildFlatbufferRows(request.rows, request.timeseriesTableName, timeseriesClient.timeseriesMetaCache)
case otsprotocol.RowsSerializeType_RST_PROTO_BUFFER:
req.RowsData.RowsData, err = buildProtocolBufferRows(request.rows, request.timeseriesTableName, timeseriesClient.timeseriesMetaCache)
default:
err = fmt.Errorf("Invalid rows serialize type")
}
if err != nil {
return nil, err
}
// Compute crc32
uint32_crc32 := crc32.Checksum(req.RowsData.RowsData, crc32.MakeTable(crc32.Castagnoli))
req.RowsData.FlatbufferCrc32C = proto.Int32(int32((uint32_crc32)))
resp := new(otsprotocol.PutTimeseriesDataResponse)
response := &PutTimeseriesDataResponse{}
if err := timeseriesClient.doRequestWithRetry(putTimeseriesData, req, resp, &response.ResponseInfo, request.ExtraRequestInfo); err != nil {
return nil, err
}
if len(resp.FailedRows) != 0 {
response.failedRowResults = []*FailedRowResult{}
for _, protoFailedRowResult := range resp.FailedRows {
var respFailedRowResult FailedRowResult
respFailedRowResult.Index = *protoFailedRowResult.RowIndex
respFailedRowResult.Error = fmt.Errorf("ErrorCode: %v, Message: %v", protoFailedRowResult.GetErrorCode(), protoFailedRowResult.GetErrorMessage())
respFailedRowResult.ErrorCode = protoFailedRowResult.GetErrorCode()
response.failedRowResults = append(response.failedRowResults, &respFailedRowResult)
}
}
if resp.GetMetaUpdateStatus() != nil && len(resp.GetMetaUpdateStatus().GetRowIds()) != 0 {
for i := 0; i < len(resp.GetMetaUpdateStatus().GetRowIds()); i++ {
if i >= len(resp.GetMetaUpdateStatus().GetMetaUpdateTimes()) {
break
}
idx := resp.GetMetaUpdateStatus().GetRowIds()[i]
if int(idx) < len(request.GetTimeseriesRows()) {
updateTimeInSec := uint32(resp.GetMetaUpdateStatus().GetMetaUpdateTimes()[i] & 0xffffffff)
if updateTimeInSec > 0 {
curRow := request.GetTimeseriesRows()[idx]
if curRow.timeseriesMetaKey == nil {
curRow.timeseriesMetaKey = new(string)
*curRow.timeseriesMetaKey, _ = curRow.timeseriesKey.buildTimeseriesMetaKey(request.GetTimeseriesTableName())
}
metaCacheKey := *curRow.timeseriesMetaKey
timeInCache, ok := timeseriesClient.GetTimeseriesMetaCache().Get(metaCacheKey)
if !ok || timeInCache.(uint32) < updateTimeInSec {
timeseriesClient.GetTimeseriesMetaCache().Add(metaCacheKey, updateTimeInSec)
}
}
}
}
}
return response, nil
}
// row API
// Get the timeseries data of a row or some columns.
// 获取某一时间线的一个或多个数据点
//
// @param GetTimeseriesDataRequest
// @return GetTimeseriesDataResponse
func (timeseriesClient *TimeseriesClient) GetTimeseriesData(request *GetTimeseriesDataRequest) (*GetTimeseriesDataResponse, error) {
if request == nil || request.GetTimeseriesTableName() == "" || request.GetTimeseriesKey() == nil {
return nil, fmt.Errorf("GetTimeseriesDataRequest is empty")
}
if request.GetBeginTimeInUs() >= request.GetEndTimeInUs() {
return nil, fmt.Errorf("End time should be large than begin time")
}
var err error
req := new(otsprotocol.GetTimeseriesDataRequest)
req.TableName = proto.String(request.GetTimeseriesTableName())
req.BeginTime = proto.Int64(request.GetBeginTimeInUs())
req.EndTime = proto.Int64(request.GetEndTimeInUs())
req.TimeSeriesKey, err = buildTimeseriesKey(request.GetTimeseriesKey())
if err != nil {
return nil, err
}
if request.GetLimit() > 0 {
req.Limit = proto.Int32(int32(request.GetLimit()))
}
if request.GetNextToken() != nil && len(request.GetNextToken()) != 0 {
req.Token = append([]byte{}, request.GetNextToken()...)
}
if request.backward {
req.Backward = proto.Bool(true)