-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
631 lines (567 loc) · 17.9 KB
/
client.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
package common
import (
"encoding/hex"
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"time"
tcerr "github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/errors"
tchttp "github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/http"
"github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/json"
"github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/profile"
)
const (
octetStream = "application/octet-stream"
)
var DefaultHttpClient *http.Client
type Client struct {
region string
httpClient *http.Client
httpProfile *profile.HttpProfile
profile *profile.ClientProfile
credential CredentialIface
signMethod string
unsignedPayload bool
debug bool
rb *circuitBreaker
logger Logger
requestClient string
}
func (c *Client) Send(request tchttp.Request, response tchttp.Response) (err error) {
c.completeRequest(request)
tchttp.CompleteCommonParams(request, c.GetRegion(), c.requestClient)
// reflect to inject client if field ClientToken exists and retry feature is enabled
if c.profile.NetworkFailureMaxRetries > 0 || c.profile.RateLimitExceededMaxRetries > 0 {
safeInjectClientToken(request)
}
if request.GetSkipSign() {
// Some APIs can skip signature.
return c.sendWithoutSignature(request, response)
} else if c.profile.DisableRegionBreaker == true || c.rb == nil {
return c.sendWithSignature(request, response)
} else {
return c.sendWithRegionBreaker(request, response)
}
}
func (c *Client) completeRequest(request tchttp.Request) {
if request.GetScheme() == "" {
request.SetScheme(c.httpProfile.Scheme)
}
if request.GetRootDomain() == "" {
request.SetRootDomain(c.httpProfile.RootDomain)
}
if request.GetDomain() == "" {
domain := c.httpProfile.Endpoint
if domain == "" {
domain = request.GetServiceDomain(request.GetService())
}
request.SetDomain(domain)
}
if request.GetHttpMethod() == "" {
request.SetHttpMethod(c.httpProfile.ReqMethod)
}
if c.profile.UnsafeRetryOnConnectionFailure {
header := request.GetHeader()
if header == nil {
header = map[string]string{}
}
// http.Transport will automatically retry the request that considered Idempotent
// see http.Request.isReplayable
header["X-Idempotency-Key"] = "x"
request.SetHeader(header)
}
}
func (c *Client) sendWithRegionBreaker(request tchttp.Request, response tchttp.Response) (err error) {
defer func() {
e := recover()
if e != nil {
msg := fmt.Sprintf("%s", e)
err = tcerr.NewTencentCloudSDKError("ClientError.CircuitBreakerError", msg, "")
}
}()
ge, err := c.rb.beforeRequest()
if err == errOpenState {
newEndpoint := request.GetService() + "." + c.rb.backupEndpoint
request.SetDomain(newEndpoint)
}
err = c.sendWithSignature(request, response)
isSuccess := false
// Success is considered only when the server returns an effective response (have requestId and the code is not InternalError )
if e, ok := err.(*tcerr.TencentCloudSDKError); ok {
if e.GetRequestId() != "" && e.GetCode() != "InternalError" {
isSuccess = true
}
}
c.rb.afterRequest(ge, isSuccess)
return err
}
func (c *Client) sendWithSignature(request tchttp.Request, response tchttp.Response) (err error) {
if c.signMethod == "HmacSHA1" || c.signMethod == "HmacSHA256" {
return c.sendWithSignatureV1(request, response)
} else {
return c.sendWithSignatureV3(request, response)
}
}
func (c *Client) sendWithoutSignature(request tchttp.Request, response tchttp.Response) error {
headers := map[string]string{
"Host": request.GetDomain(),
"X-TC-Action": request.GetAction(),
"X-TC-Version": request.GetVersion(),
"X-TC-Timestamp": request.GetParams()["Timestamp"],
"X-TC-RequestClient": request.GetParams()["RequestClient"],
"X-TC-Language": c.profile.Language,
"Authorization": "SKIP",
}
if c.region != "" {
headers["X-TC-Region"] = c.region
}
if c.credential != nil && c.credential.GetToken() != "" {
headers["X-TC-Token"] = c.credential.GetToken()
}
if request.GetHttpMethod() == "GET" {
headers["Content-Type"] = "application/x-www-form-urlencoded"
} else {
headers["Content-Type"] = "application/json"
}
isOctetStream := false
cr := &tchttp.CommonRequest{}
ok := false
var octetStreamBody []byte
if cr, ok = request.(*tchttp.CommonRequest); ok {
if cr.IsOctetStream() {
isOctetStream = true
// custom headers must contain Content-Type : application/octet-stream
// todo:the custom header may overwrite headers
for k, v := range cr.GetHeader() {
headers[k] = v
}
octetStreamBody = cr.GetOctetStreamBody()
}
}
for k, v := range request.GetHeader() {
switch k {
case "X-TC-Action", "X-TC-Version", "X-TC-Timestamp", "X-TC-RequestClient",
"X-TC-Language", "Content-Type", "X-TC-Region", "X-TC-Token":
c.logger.Printf("Skip header \"%s\": can not specify built-in header", k)
default:
headers[k] = v
}
}
if !isOctetStream && request.GetContentType() == octetStream {
isOctetStream = true
b, _ := json.Marshal(request)
var m map[string]string
_ = json.Unmarshal(b, &m)
for k, v := range m {
key := "X-" + strings.ToUpper(request.GetService()) + "-" + k
headers[key] = v
}
headers["Content-Type"] = octetStream
octetStreamBody = request.GetBody()
}
// start signature v3 process
// build canonical request string
httpRequestMethod := request.GetHttpMethod()
canonicalQueryString := ""
if httpRequestMethod == "GET" {
err := tchttp.ConstructParams(request)
if err != nil {
return err
}
params := make(map[string]string)
for key, value := range request.GetParams() {
params[key] = value
}
delete(params, "Action")
delete(params, "Version")
delete(params, "Nonce")
delete(params, "Region")
delete(params, "RequestClient")
delete(params, "Timestamp")
canonicalQueryString = tchttp.GetUrlQueriesEncoded(params)
}
requestPayload := ""
if httpRequestMethod == "POST" {
if isOctetStream {
// todo Conversion comparison between string and []byte affects performance much
requestPayload = string(octetStreamBody)
} else {
b, err := json.Marshal(request)
if err != nil {
return err
}
requestPayload = string(b)
}
}
if c.unsignedPayload {
headers["X-TC-Content-SHA256"] = "UNSIGNED-PAYLOAD"
}
url := request.GetScheme() + "://" + request.GetDomain() + request.GetPath()
if canonicalQueryString != "" {
url = url + "?" + canonicalQueryString
}
httpRequest, err := http.NewRequest(httpRequestMethod, url, strings.NewReader(requestPayload))
if err != nil {
return err
}
httpRequest = httpRequest.WithContext(request.GetContext())
for k, v := range headers {
httpRequest.Header[k] = []string{v}
}
httpResponse, err := c.sendWithRateLimitRetry(httpRequest, isRetryable(request))
if err != nil {
return err
}
err = tchttp.ParseFromHttpResponse(httpResponse, response)
return err
}
func (c *Client) sendWithSignatureV1(request tchttp.Request, response tchttp.Response) (err error) {
// TODO: not an elegant way, it should be done in common params, but finally it need to refactor
request.GetParams()["Language"] = c.profile.Language
err = tchttp.ConstructParams(request)
if err != nil {
return err
}
err = signRequest(request, c.credential, c.signMethod)
if err != nil {
return err
}
httpRequest, err := http.NewRequest(request.GetHttpMethod(), request.GetUrl(), request.GetBodyReader())
if err != nil {
return err
}
httpRequest = httpRequest.WithContext(request.GetContext())
if request.GetHttpMethod() == "POST" {
httpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
for k, v := range request.GetHeader() {
httpRequest.Header.Set(k, v)
}
httpResponse, err := c.sendWithRateLimitRetry(httpRequest, isRetryable(request))
if err != nil {
return err
}
err = tchttp.ParseFromHttpResponse(httpResponse, response)
return err
}
func (c *Client) sendWithSignatureV3(request tchttp.Request, response tchttp.Response) (err error) {
headers := map[string]string{
"Host": request.GetDomain(),
"X-TC-Action": request.GetAction(),
"X-TC-Version": request.GetVersion(),
"X-TC-Timestamp": request.GetParams()["Timestamp"],
"X-TC-RequestClient": request.GetParams()["RequestClient"],
"X-TC-Language": c.profile.Language,
}
if c.region != "" {
headers["X-TC-Region"] = c.region
}
secId, secKey, token := c.credential.GetCredential()
if token != "" {
headers["X-TC-Token"] = token
}
if request.GetHttpMethod() == "GET" {
headers["Content-Type"] = "application/x-www-form-urlencoded"
} else {
headers["Content-Type"] = "application/json"
}
isOctetStream := false
cr := &tchttp.CommonRequest{}
ok := false
var octetStreamBody []byte
if cr, ok = request.(*tchttp.CommonRequest); ok {
if cr.IsOctetStream() {
isOctetStream = true
// custom headers must contain Content-Type : application/octet-stream
// todo:the custom header may overwrite headers
for k, v := range cr.GetHeader() {
headers[k] = v
}
octetStreamBody = cr.GetOctetStreamBody()
}
}
for k, v := range request.GetHeader() {
switch k {
case "X-TC-Action", "X-TC-Version", "X-TC-Timestamp", "X-TC-RequestClient",
"X-TC-Language", "X-TC-Region", "X-TC-Token":
c.logger.Printf("Skip header \"%s\": can not specify built-in header", k)
default:
headers[k] = v
}
}
if !isOctetStream && request.GetContentType() == octetStream {
isOctetStream = true
b, _ := json.Marshal(request)
var m map[string]string
_ = json.Unmarshal(b, &m)
for k, v := range m {
key := "X-" + strings.ToUpper(request.GetService()) + "-" + k
headers[key] = v
}
headers["Content-Type"] = octetStream
octetStreamBody = request.GetBody()
}
// start signature v3 process
// build canonical request string
httpRequestMethod := request.GetHttpMethod()
canonicalURI := "/"
canonicalQueryString := ""
if httpRequestMethod == "GET" {
err = tchttp.ConstructParams(request)
if err != nil {
return err
}
params := make(map[string]string)
for key, value := range request.GetParams() {
params[key] = value
}
delete(params, "Action")
delete(params, "Version")
delete(params, "Nonce")
delete(params, "Region")
delete(params, "RequestClient")
delete(params, "Timestamp")
canonicalQueryString = tchttp.GetUrlQueriesEncoded(params)
}
canonicalHeaders := fmt.Sprintf("content-type:%s\nhost:%s\n", headers["Content-Type"], headers["Host"])
signedHeaders := "content-type;host"
requestPayload := ""
if httpRequestMethod == "POST" {
if isOctetStream {
// todo Conversion comparison between string and []byte affects performance much
requestPayload = string(octetStreamBody)
} else {
b, err := json.Marshal(request)
if err != nil {
return err
}
requestPayload = string(b)
}
}
hashedRequestPayload := ""
if c.unsignedPayload {
hashedRequestPayload = sha256hex("UNSIGNED-PAYLOAD")
headers["X-TC-Content-SHA256"] = "UNSIGNED-PAYLOAD"
} else {
hashedRequestPayload = sha256hex(requestPayload)
}
canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s",
httpRequestMethod,
canonicalURI,
canonicalQueryString,
canonicalHeaders,
signedHeaders,
hashedRequestPayload)
//log.Println("canonicalRequest:", canonicalRequest)
// build string to sign
algorithm := "TC3-HMAC-SHA256"
requestTimestamp := headers["X-TC-Timestamp"]
timestamp, _ := strconv.ParseInt(requestTimestamp, 10, 64)
t := time.Unix(timestamp, 0).UTC()
// must be the format 2006-01-02, ref to package time for more info
date := t.Format("2006-01-02")
credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, request.GetService())
hashedCanonicalRequest := sha256hex(canonicalRequest)
string2sign := fmt.Sprintf("%s\n%s\n%s\n%s",
algorithm,
requestTimestamp,
credentialScope,
hashedCanonicalRequest)
//log.Println("string2sign", string2sign)
// sign string
secretDate := hmacsha256(date, "TC3"+secKey)
secretService := hmacsha256(request.GetService(), secretDate)
secretKey := hmacsha256("tc3_request", secretService)
signature := hex.EncodeToString([]byte(hmacsha256(string2sign, secretKey)))
//log.Println("signature", signature)
// build authorization
authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
algorithm,
secId,
credentialScope,
signedHeaders,
signature)
//log.Println("authorization", authorization)
headers["Authorization"] = authorization
url := request.GetScheme() + "://" + request.GetDomain() + request.GetPath()
if canonicalQueryString != "" {
url = url + "?" + canonicalQueryString
}
httpRequest, err := http.NewRequest(httpRequestMethod, url, strings.NewReader(requestPayload))
if err != nil {
return err
}
httpRequest = httpRequest.WithContext(request.GetContext())
for k, v := range headers {
httpRequest.Header[k] = []string{v}
}
httpResponse, err := c.sendWithRateLimitRetry(httpRequest, isRetryable(request))
if err != nil {
return err
}
err = tchttp.ParseFromHttpResponse(httpResponse, response)
return err
}
// send http request
func (c *Client) sendHttp(request *http.Request) (response *http.Response, err error) {
if len(c.httpProfile.ApigwEndpoint) > 0 {
request.URL.Host = c.httpProfile.ApigwEndpoint
request.Host = c.httpProfile.ApigwEndpoint
}
if c.debug && request != nil {
outBytes, err := httputil.DumpRequest(request, true)
if err != nil {
c.logger.Printf("[ERROR] dump request failed: %s", err)
} else {
c.logger.Printf("[DEBUG] http request: %s", outBytes)
}
}
response, err = c.httpClient.Do(request)
if c.debug && response != nil {
dumpBody := true
switch response.Header.Get("Content-Type") {
case "text/event-stream", "application/octet-stream":
dumpBody = false
}
out, err := httputil.DumpResponse(response, dumpBody)
if err != nil {
c.logger.Printf("[ERROR] dump response failed: %s", err)
} else {
c.logger.Printf("[DEBUG] http response: %s", out)
}
}
return response, err
}
func (c *Client) GetRegion() string {
return c.region
}
func (c *Client) Init(region string) *Client {
if DefaultHttpClient == nil {
// try not to modify http.DefaultTransport if possible
// since we could possibly modify Transport.Proxy
transport := http.DefaultTransport
if _, ok := transport.(*http.Transport); ok {
// http.Transport.Clone is only available after go1.12
if cloneMethod, hasClone := reflect.TypeOf(transport).MethodByName("Clone"); hasClone {
transport = cloneMethod.Func.Call([]reflect.Value{reflect.ValueOf(transport)})[0].Interface().(http.RoundTripper)
}
}
c.httpClient = &http.Client{Transport: transport}
} else {
c.httpClient = DefaultHttpClient
}
c.region = region
c.signMethod = "TC3-HMAC-SHA256"
c.debug = false
c.logger = log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile)
return c
}
func (c *Client) WithSecretId(secretId, secretKey string) *Client {
c.credential = NewCredential(secretId, secretKey)
return c
}
func (c *Client) WithCredential(cred CredentialIface) *Client {
c.credential = cred
return c
}
func (c *Client) WithRequestClient(rc string) *Client {
const reRequestClient = "^[0-9a-zA-Z-_ ,;.]+$"
if len(rc) > 128 {
c.logger.Printf("the length of RequestClient should be within 128 characters, it will be truncated")
rc = rc[:128]
}
match, err := regexp.MatchString(reRequestClient, rc)
if err != nil {
c.logger.Printf("regexp is wrong: %s", reRequestClient)
return c
}
if !match {
c.logger.Printf("RequestClient not match the regexp: %s, ignored", reRequestClient)
return c
}
c.requestClient = rc
return c
}
func (c *Client) GetCredential() CredentialIface {
return c.credential
}
func (c *Client) WithProfile(clientProfile *profile.ClientProfile) *Client {
c.profile = clientProfile
if c.profile.DisableRegionBreaker == false {
c.withRegionBreaker()
}
c.signMethod = clientProfile.SignMethod
c.unsignedPayload = clientProfile.UnsignedPayload
c.httpProfile = clientProfile.HttpProfile
c.debug = clientProfile.Debug
c.httpClient.Timeout = time.Duration(c.httpProfile.ReqTimeout) * time.Second
if c.httpProfile.Proxy != "" {
u, err := url.Parse(c.httpProfile.Proxy)
if err != nil {
panic(err)
}
if c.httpClient.Transport == nil {
c.logger.Printf("trying to set proxy when httpClient.Transport is nil")
}
if _, ok := c.httpClient.Transport.(*http.Transport); ok {
c.httpClient.Transport.(*http.Transport).Proxy = http.ProxyURL(u)
} else {
c.logger.Printf("setting proxy while httpClient.Transport is not a http.Transport is not supported")
}
}
return c
}
func (c *Client) WithSignatureMethod(method string) *Client {
c.signMethod = method
return c
}
func (c *Client) WithHttpTransport(transport http.RoundTripper) *Client {
c.httpClient.Transport = transport
return c
}
func (c *Client) WithDebug(flag bool) *Client {
c.debug = flag
return c
}
// WithProvider use specify provider to get a credential and use it to build a client
func (c *Client) WithProvider(provider Provider) (*Client, error) {
cred, err := provider.GetCredential()
if err != nil {
return nil, err
}
return c.WithCredential(cred), nil
}
func (c *Client) withRegionBreaker() *Client {
rb := defaultRegionBreaker()
if c.profile.BackupEndpoint != "" {
rb.backupEndpoint = c.profile.BackupEndpoint
} else if c.profile.BackupEndPoint != "" {
rb.backupEndpoint = c.profile.BackupEndPoint
}
c.rb = rb
return c
}
func NewClientWithSecretId(secretId, secretKey, region string) (client *Client, err error) {
client = &Client{}
client.Init(region).WithSecretId(secretId, secretKey)
return
}
// NewClientWithProviders build client with your custom providers;
// If you don't specify the providers, it will use the DefaultProviderChain to find credential
func NewClientWithProviders(region string, providers ...Provider) (client *Client, err error) {
client = (&Client{}).Init(region)
var pc Provider
if len(providers) == 0 {
pc = DefaultProviderChain()
} else {
pc = NewProviderChain(providers)
}
return client.WithProvider(pc)
}