-
Notifications
You must be signed in to change notification settings - Fork 30
/
http.go
608 lines (516 loc) · 15.7 KB
/
http.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
package zboxutil
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"time"
"github.com/0chain/errors"
"github.com/0chain/gosdk/core/encryption"
"github.com/0chain/gosdk/core/util"
"github.com/0chain/gosdk/zboxcore/blockchain"
"github.com/0chain/gosdk/zboxcore/client"
)
const SC_REST_API_URL = "v1/screst/"
const REGISTER_CLIENT = "v1/client/put"
const MAX_RETRIES = 5
const SLEEP_BETWEEN_RETRIES = 5
// In percentage
const consensusThresh = float32(25.0)
type SCRestAPIHandler func(response map[string][]byte, numSharders int, err error)
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
var Client HttpClient
const (
ALLOCATION_ENDPOINT = "/allocation"
UPLOAD_ENDPOINT = "/v1/file/upload/"
RENAME_ENDPOINT = "/v1/file/rename/"
COPY_ENDPOINT = "/v1/file/copy/"
LIST_ENDPOINT = "/v1/file/list/"
REFERENCE_ENDPOINT = "/v1/file/referencepath/"
CONNECTION_ENDPOINT = "/v1/connection/details/"
COMMIT_ENDPOINT = "/v1/connection/commit/"
DOWNLOAD_ENDPOINT = "/v1/file/download/"
LATEST_READ_MARKER = "/v1/readmarker/latest"
FILE_META_ENDPOINT = "/v1/file/meta/"
FILE_STATS_ENDPOINT = "/v1/file/stats/"
OBJECT_TREE_ENDPOINT = "/v1/file/objecttree/"
REFS_ENDPOINT = "/v1/file/refs/"
COMMIT_META_TXN_ENDPOINT = "/v1/file/commitmetatxn/"
COLLABORATOR_ENDPOINT = "/v1/file/collaborator/"
CALCULATE_HASH_ENDPOINT = "/v1/file/calculatehash/"
SHARE_ENDPOINT = "/v1/marketplace/shareinfo/"
DIR_ENDPOINT = "/v1/dir/"
// CLIENT_SIGNATURE_HEADER represents http request header contains signature.
CLIENT_SIGNATURE_HEADER = "X-App-Client-Signature"
)
func getEnvAny(names ...string) string {
for _, n := range names {
if val := os.Getenv(n); val != "" {
return val
}
}
return ""
}
type proxyFromEnv struct {
HTTPProxy string
HTTPSProxy string
NoProxy string
http, https *url.URL
}
func (pfe *proxyFromEnv) initialize() {
pfe.HTTPProxy = getEnvAny("HTTP_PROXY", "http_proxy")
pfe.HTTPSProxy = getEnvAny("HTTPS_PROXY", "https_proxy")
pfe.NoProxy = getEnvAny("NO_PROXY", "no_proxy")
if pfe.NoProxy != "" {
return
}
if pfe.HTTPProxy != "" {
pfe.http, _ = url.Parse(pfe.HTTPProxy)
}
if pfe.HTTPSProxy != "" {
pfe.https, _ = url.Parse(pfe.HTTPSProxy)
}
}
func (pfe *proxyFromEnv) isLoopback(host string) (ok bool) {
host, _, _ = net.SplitHostPort(host)
if host == "localhost" {
return true
}
return net.ParseIP(host).IsLoopback()
}
func (pfe *proxyFromEnv) Proxy(req *http.Request) (proxy *url.URL, err error) {
if pfe.isLoopback(req.URL.Host) {
switch req.URL.Scheme {
case "http":
return pfe.http, nil
case "https":
return pfe.https, nil
default:
}
}
return http.ProxyFromEnvironment(req)
}
var envProxy proxyFromEnv
func init() {
Client = &http.Client{
Transport: DefaultTransport,
}
envProxy.initialize()
}
func NewHTTPRequest(method string, url string, data []byte) (*http.Request, context.Context, context.CancelFunc, error) {
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Access-Control-Allow-Origin", "*")
ctx, cncl := context.WithTimeout(context.Background(), time.Second*10)
return req, ctx, cncl, err
}
func setClientInfo(req *http.Request) {
req.Header.Set("X-App-Client-ID", client.GetClientID())
req.Header.Set("X-App-Client-Key", client.GetClientPublicKey())
}
func setClientInfoWithSign(req *http.Request, allocation string) error {
setClientInfo(req)
sign, err := client.Sign(encryption.Hash(allocation))
if err != nil {
return err
}
req.Header.Set(CLIENT_SIGNATURE_HEADER, sign)
return nil
}
func NewCommitRequest(baseUrl, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, COMMIT_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
setClientInfo(req)
return req, nil
}
func NewReferencePathRequest(baseUrl, allocation string, paths []string) (*http.Request, error) {
nurl, err := url.Parse(baseUrl)
if err != nil {
return nil, err
}
nurl.Path += REFERENCE_ENDPOINT + allocation
pathBytes, err := json.Marshal(paths)
if err != nil {
return nil, err
}
params := url.Values{}
params.Add("paths", string(pathBytes))
//url := fmt.Sprintf("%s%s%s?path=%s", baseUrl, LIST_ENDPOINT, allocation, path)
nurl.RawQuery = params.Encode() // Escape Query Parameters
req, err := http.NewRequest(http.MethodGet, nurl.String(), nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewCalculateHashRequest(baseUrl, allocation string, paths []string) (*http.Request, error) {
nurl, err := url.Parse(baseUrl)
if err != nil {
return nil, err
}
nurl.Path += CALCULATE_HASH_ENDPOINT + allocation
pathBytes, err := json.Marshal(paths)
if err != nil {
return nil, err
}
params := url.Values{}
params.Add("paths", string(pathBytes))
nurl.RawQuery = params.Encode() // Escape Query Parameters
req, err := http.NewRequest(http.MethodPost, nurl.String(), nil)
if err != nil {
return nil, err
}
setClientInfo(req)
return req, nil
}
func NewObjectTreeRequest(baseUrl, allocation string, path string) (*http.Request, error) {
nurl, err := url.Parse(baseUrl)
if err != nil {
return nil, err
}
nurl.Path += OBJECT_TREE_ENDPOINT + allocation
params := url.Values{}
params.Add("path", path)
//url := fmt.Sprintf("%s%s%s?path=%s", baseUrl, LIST_ENDPOINT, allocation, path)
nurl.RawQuery = params.Encode() // Escape Query Parameters
req, err := http.NewRequest(http.MethodGet, nurl.String(), nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewRefsRequest(baseUrl, allocationID, path, offsetPath, updatedDate, offsetDate, fileType, refType string, level, pageLimit int) (*http.Request, error) {
nUrl, err := url.Parse(baseUrl)
if err != nil {
return nil, err
}
nUrl.Path += REFS_ENDPOINT + allocationID
params := url.Values{}
params.Add("path", path)
params.Add("offsetPath", offsetPath)
params.Add("pageLimit", strconv.Itoa(pageLimit))
params.Add("updatedDate", updatedDate)
params.Add("offsetDate", offsetDate)
params.Add("fileType", fileType)
params.Add("refType", refType)
params.Add("level", strconv.Itoa(level))
nUrl.RawQuery = params.Encode()
req, err := http.NewRequest(http.MethodGet, nUrl.String(), nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocationID); err != nil {
return nil, err
}
return req, nil
}
func NewAllocationRequest(baseUrl, allocation string) (*http.Request, error) {
nurl, err := url.Parse(baseUrl)
if err != nil {
return nil, err
}
nurl.Path += ALLOCATION_ENDPOINT
params := url.Values{}
params.Add("id", allocation)
nurl.RawQuery = params.Encode() // Escape Query Parameters
req, err := http.NewRequest(http.MethodGet, nurl.String(), nil)
if err != nil {
return nil, err
}
setClientInfo(req)
return req, nil
}
func NewCommitMetaTxnRequest(baseUrl string, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, COMMIT_META_TXN_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
setClientInfo(req)
return req, nil
}
func NewCollaboratorRequest(baseUrl string, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, COLLABORATOR_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func GetCollaboratorsRequest(baseUrl string, allocation string, query *url.Values) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s?%s", baseUrl, COLLABORATOR_ENDPOINT, allocation, query.Encode())
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func DeleteCollaboratorRequest(baseUrl string, allocation string, query *url.Values) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s?%s", baseUrl, COLLABORATOR_ENDPOINT, allocation, query.Encode())
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewFileMetaRequest(baseUrl string, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, FILE_META_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
err = setClientInfoWithSign(req, allocation)
if err != nil {
return nil, err
}
return req, nil
}
func NewFileStatsRequest(baseUrl string, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, FILE_STATS_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewListRequest(baseUrl, allocation string, path, pathHash string, auth_token string) (*http.Request, error) {
nurl, err := url.Parse(baseUrl)
if err != nil {
return nil, err
}
nurl.Path += LIST_ENDPOINT + allocation
params := url.Values{}
params.Add("path", path)
params.Add("path_hash", pathHash)
params.Add("auth_token", auth_token)
//url := fmt.Sprintf("%s%s%s?path=%s", baseUrl, LIST_ENDPOINT, allocation, path)
nurl.RawQuery = params.Encode() // Escape Query Parameters
req, err := http.NewRequest(http.MethodGet, nurl.String(), nil)
if err != nil {
return nil, err
}
setClientInfo(req)
return req, nil
}
// NewUploadRequestWithMethod create a http reqeust of upload
func NewUploadRequestWithMethod(baseURL, allocation string, body io.Reader, method string) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseURL, UPLOAD_ENDPOINT, allocation)
var req *http.Request
var err error
req, err = http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewUploadRequest(baseUrl, allocation string, body io.Reader, update bool) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, UPLOAD_ENDPOINT, allocation)
var req *http.Request
var err error
if update {
req, err = http.NewRequest(http.MethodPut, url, body)
} else {
req, err = http.NewRequest(http.MethodPost, url, body)
}
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewRenameRequest(baseUrl, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, RENAME_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewCopyRequest(baseUrl, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, COPY_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewDownloadRequest(baseUrl, allocation string) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, DOWNLOAD_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
setClientInfo(req)
return req, nil
}
func NewDeleteRequest(baseUrl, allocation string, query *url.Values) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s?%s", baseUrl, UPLOAD_ENDPOINT, allocation, query.Encode())
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewCreateDirRequest(baseUrl, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, DIR_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewShareRequest(baseUrl, allocation string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s", baseUrl, SHARE_ENDPOINT, allocation)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func NewRevokeShareRequest(baseUrl, allocation string, query *url.Values) (*http.Request, error) {
url := fmt.Sprintf("%s%s%s?%s", baseUrl, SHARE_ENDPOINT, allocation, query.Encode())
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return nil, err
}
if err := setClientInfoWithSign(req, allocation); err != nil {
return nil, err
}
return req, nil
}
func MakeSCRestAPICall(scAddress string, relativePath string, params map[string]string, handler SCRestAPIHandler) ([]byte, error) {
numSharders := len(blockchain.GetSharders())
sharders := blockchain.GetSharders()
responses := make(map[int]int)
mu := &sync.Mutex{}
entityResult := make(map[string][]byte)
var retObj []byte
maxCount := 0
wg := sync.WaitGroup{}
for _, sharder := range util.Shuffle(sharders) {
wg.Add(1)
go func(sharder string) {
defer wg.Done()
urlString := fmt.Sprintf("%v/%v%v%v", sharder, SC_REST_API_URL, scAddress, relativePath)
urlObj, _ := url.Parse(urlString)
q := urlObj.Query()
for k, v := range params {
q.Add(k, v)
}
urlObj.RawQuery = q.Encode()
client := &http.Client{Transport: DefaultTransport}
response, err := client.Get(urlObj.String())
if err == nil {
defer response.Body.Close()
entityBytes, _ := ioutil.ReadAll(response.Body)
mu.Lock()
responses[response.StatusCode]++
if responses[response.StatusCode] > maxCount {
maxCount = responses[response.StatusCode]
retObj = entityBytes
}
entityResult[sharder] = retObj
mu.Unlock()
}
}(sharder)
}
wg.Wait()
var err error
rate := float32(maxCount*100) / float32(numSharders)
if rate < consensusThresh {
err = errors.New("consensus_failed", "consensus failed on sharders")
}
c := 0
dominant := 200
for code, count := range responses {
if count > c {
dominant = code
}
}
if dominant != 200 {
var objmap map[string]json.RawMessage
err := json.Unmarshal(retObj, &objmap)
if err != nil {
return nil, errors.New("", string(retObj))
}
var parsed string
err = json.Unmarshal(objmap["error"], &parsed)
if err != nil || parsed == "" {
return nil, errors.New("", string(retObj))
}
return nil, errors.New("", parsed)
}
if handler != nil {
handler(entityResult, numSharders, err)
}
if rate > consensusThresh {
return retObj, nil
}
return nil, err
}
func HttpDo(ctx context.Context, cncl context.CancelFunc, req *http.Request, f func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to f.
c := make(chan error, 1)
go func() { c <- f(Client.Do(req.WithContext(ctx))) }()
// TODO: Check cncl context required in any case
// defer cncl()
select {
case <-ctx.Done():
DefaultTransport.CancelRequest(req)
<-c // Wait for f to return.
return ctx.Err()
case err := <-c:
return err
}
}