~tsileo/blobstash

ref: b178995e346d blobstash/pkg/client/clientutil/clientutil.go -rw-r--r-- 13.1 KiB
b178995eThomas Sileo vendor: update deps 2 years ago
                                                                                
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
package clientutil // import "a4.io/blobstash/pkg/client/clientutil"

import (
	"bytes"
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/golang/snappy"
	"github.com/vmihailenco/msgpack"
)

var ErrBlobNotFound = errors.New("blob not found")
var ErrNotFound = errors.New("not found")

// FIXME(tsileo): more sensible default?
var transport http.RoundTripper = &http.Transport{
	Proxy: http.ProxyFromEnvironment,
	Dial: (&net.Dialer{
		Timeout:   10 * time.Second,
		KeepAlive: 30 * time.Second,
	}).Dial,
	TLSHandshakeTimeout: 5 * time.Second,
}

// Opts holds the client configuration
type Opts struct {
	Host   string // BlobStash host (with proto and without trailing slash) e.g. "https://blobtash.com"
	APIKey string // BlobStash API key

	Namespace string // BlobStash namespace

	Headers   map[string]string // Headers added to each request
	UserAgent string            // Custom User-Agent

	SnappyCompression bool // Enable snappy compression for the HTTP requests
}

// SetNamespace is a shortcut for setting the namespace at the client level
func (opts *Opts) SetNamespace(ns string) *Opts {
	opts.Namespace = ns
	return opts
}

// SetHost is a configuration shortcut for setting the API hostname and the API key
func (opts *Opts) SetHost(host, apiKey string) *Opts {
	if host != "" {
		opts.Host = host
	}
	if apiKey != "" {
		opts.APIKey = apiKey
	}
	return opts
}

type Client struct {
	opts   *Opts
	client *http.Client

	sessionID string
	mu        sync.Mutex // mutex for keeping the sessionID safe
}

// New initializes an HTTP client
func New(opts *Opts) *Client {
	if opts == nil {
		panic("missing clientutil.Client opts")
	}
	client := &http.Client{
		Transport: transport,
	}
	return &Client{
		client: client,
		opts:   opts,
	}
}

// ClientID returns a unique "session ID" that won't change for the lifetime of the client
func (client *Client) SessionID() string {
	client.mu.Lock()
	defer client.mu.Unlock()
	if client.sessionID != "" {
		return client.sessionID
	}
	data := make([]byte, 16)
	if _, err := rand.Read(data); err != nil {
		panic(err)
	}
	return hex.EncodeToString(data)
}

// Opts returns the current opts
func (client *Client) Opts() *Opts {
	return client.opts
}

// DoReq "do" the request and returns the `*http.Response`
func (client *Client) DoReq(ctx context.Context, method, path string, headers map[string]string, body io.Reader) (*http.Response, error) {
	request, err := http.NewRequest(method, fmt.Sprintf("%s%s", client.opts.Host, path), body)
	if err != nil {
		return nil, err
	}

	request = request.WithContext(ctx)

	request.Header.Set("BlobStash-Session-ID", client.SessionID())
	if client.opts.APIKey != "" {
		request.SetBasicAuth("", client.opts.APIKey)
	}

	// Set our custom user agent
	if client.opts.UserAgent != "" {
		request.Header.Set("User-Agent", client.opts.UserAgent)
	}

	if client.opts.Namespace != "" {
		request.Header.Set("BlobStash-Namespace", client.opts.Namespace)
	}

	// Check if we should request compressed data
	if client.opts.SnappyCompression {
		request.Header.Set("Accept-Encoding", "snappy")
	}

	// Add custom headers
	for header, val := range client.opts.Headers {
		request.Header.Set(header, val)
	}
	for header, val := range headers {
		request.Header.Set(header, val)
	}
	return client.client.Do(request)
}

func WithHeaders(headers map[string]string) func(*http.Request) error {
	return func(request *http.Request) error {
		for header, val := range headers {
			request.Header.Set(header, val)
		}
		return nil
	}
}

func WithQueryArgs(query map[string]string) func(*http.Request) error {
	return func(request *http.Request) error {
		q := request.URL.Query()
		for k, v := range query {
			q.Set(k, v)
		}
		request.URL.RawQuery = q.Encode()
		return nil
	}
}

func WithQueryArg(name, value string) func(*http.Request) error {
	return func(request *http.Request) error {
		q := request.URL.Query()
		q.Set(name, value)
		request.URL.RawQuery = q.Encode()
		return nil
	}
}

func WithAPIKey(apiKey string) func(*http.Request) error {
	return func(request *http.Request) error {
		request.SetBasicAuth("", apiKey)
		return nil
	}
}

func WithHeader(name, value string) func(*http.Request) error {
	return func(request *http.Request) error {
		request.Header.Set(name, value)
		return nil
	}
}

func WithUserAgent(ua string) func(*http.Request) error {
	return WithHeader("User-Agent", ua)
}

func EnableMsgpack() func(*http.Request) error {
	return WithHeader("Accept", "application/msgpack")
}

func EnableJSON() func(*http.Request) error {
	return WithHeader("Accept", "application/json")
}

func EnableSnappyEncoding() func(*http.Request) error {
	return WithHeader("Accept-Encoding", "snappy")
}

func WithNamespace(ns string) func(*http.Request) error {
	return WithHeader("BlobStash-Namespace", ns)
}

type ClientUtil struct {
	host    string
	client  *http.Client
	options []func(*http.Request) error
}

// New initializes an HTTP client
func NewClientUtil(host string, options ...func(*http.Request) error) *ClientUtil {
	return &ClientUtil{
		host:    host,
		client:  http.DefaultClient,
		options: options,
	}
}

type BadStatusCodeError struct {
	Expected           int
	ResponseStatusCode int
	ResponseBody       []byte
	RequestMethod      string
	RequestURL         string

	// In case it failed before getting the response
	Err error
}

func (e *BadStatusCodeError) IsNotFound() (res bool) {
	if e.ResponseStatusCode == http.StatusNotFound {
		res = true
	}
	return
}

func (e *BadStatusCodeError) IsUnauthorized() (res bool) {
	if e.ResponseStatusCode == http.StatusUnauthorized {
		res = true
	}
	return
}

func (e *BadStatusCodeError) Error() string {
	if e.Err != nil {
		return e.Err.Error()
	}

	return fmt.Sprintf("got status %d (expected %d) for %s request for %s: %s",
		e.ResponseStatusCode, e.Expected, e.RequestMethod, e.RequestURL, e.ResponseBody)
}

func ExpectStatusCode(resp *http.Response, status int) *BadStatusCodeError {
	if resp.StatusCode == status {
		return nil
	}

	// Not the expected status
	body, err := Decode(resp)
	if err != nil {
		return &BadStatusCodeError{Err: err}
	}

	return &BadStatusCodeError{
		Expected:           status,
		ResponseStatusCode: resp.StatusCode,
		ResponseBody:       body,
		RequestURL:         resp.Request.URL.String(),
		RequestMethod:      resp.Request.Method,
	}
}

func Decode(resp *http.Response) ([]byte, error) {
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	// FIXME(tsileo): use a sync.Pool for the snappy reader (thanks to Reset on the snappy reader)
	if resp.Header.Get("Content-Encoding") == "snappy" {
		return snappy.Decode(nil, body)
	}

	return body, nil
}

func Unmarshal(resp *http.Response, out interface{}) error {
	body, err := Decode(resp)
	if err != nil {
		return err
	}

	contentType := resp.Header.Get("Content-Type")
	switch contentType {
	case "application/json":
		if err := json.Unmarshal(body, out); err != nil {
			return err
		}
		return nil
	case "application/msgpack":
		if err := msgpack.Unmarshal(body, out); err != nil {
			return err
		}
		return nil
	}
	return fmt.Errorf("unsupported \"%s\" content type", contentType)
}

func (client *ClientUtil) Delete(path string, options ...func(*http.Request) error) (*http.Response, error) {
	return client.Do("DELETE", path, nil, options...)
}

func (client *ClientUtil) Head(path string, options ...func(*http.Request) error) (*http.Response, error) {
	return client.Do("HEAD", path, nil, options...)
}

func (client *ClientUtil) Get(path string, options ...func(*http.Request) error) (*http.Response, error) {
	return client.Do("GET", path, nil, options...)
}

func (client *ClientUtil) Post(path string, data []byte, options ...func(*http.Request) error) (*http.Response, error) {
	body := bytes.NewReader(snappy.Encode(nil, data))
	options = append(options, WithHeader("Content-Type", "snappy"))

	return client.Do("POST", path, body, options...)
}

func (client *ClientUtil) doWithMsgpackBody(method, path string, payload interface{}, options ...func(*http.Request) error) (*http.Response, error) {
	var body io.Reader
	if payload != nil {
		encoded, err := msgpack.Marshal(payload)
		if err != nil {
			return nil, fmt.Errorf("failed to marshal payload: %v", err)
		}
		body = bytes.NewReader(encoded)
	}

	options = append(options, WithHeader("Content-Type", "application/msgpack"))
	return client.Do(method, path, body, options...)
}

func (client *ClientUtil) doWithJSONBody(method, path string, payload interface{}, options ...func(*http.Request) error) (*http.Response, error) {
	var body io.Reader
	if payload != nil {
		encoded, err := json.Marshal(payload)
		if err != nil {
			return nil, fmt.Errorf("failed to marshal payload: %v", err)
		}
		body = bytes.NewReader(encoded)
	}

	options = append(options, WithHeader("Content-Type", "application/json"))
	return client.Do(method, path, body, options...)
}

func (client *ClientUtil) PatchMsgpack(path string, payload interface{}, options ...func(*http.Request) error) (*http.Response, error) {
	return client.doWithMsgpackBody("PATCH", path, payload, options...)
}

func (client *ClientUtil) PostMsgpack(path string, payload interface{}, options ...func(*http.Request) error) (*http.Response, error) {
	return client.doWithMsgpackBody("POST", path, payload, options...)
}

func (client *ClientUtil) PostJSON(path string, payload interface{}, options ...func(*http.Request) error) (*http.Response, error) {
	return client.doWithJSONBody("POST", path, payload, options...)
}

func (client *ClientUtil) PatchJSON(path string, payload interface{}, options ...func(*http.Request) error) (*http.Response, error) {
	return client.doWithJSONBody("PATCH", path, payload, options...)
}

// DoReq "do" the request and returns the `*http.Response`
func (client *ClientUtil) Do(method, path string, body io.Reader, options ...func(*http.Request) error) (*http.Response, error) {
	// TODO(tsileo): a special/helper error for bad status code in Do that can return a BadStatusCodeError?
	request, err := http.NewRequest(method, fmt.Sprintf("%s%s", client.host, path), body)
	if err != nil {
		return nil, err
	}

	for _, option := range client.options {
		if err := option(request); err != nil {
			return nil, fmt.Errorf("failed to set client option: %v", err)
		}
	}

	for _, option := range options {
		if err := option(request); err != nil {
			return nil, fmt.Errorf("failed to set request option: %v", err)
		}
	}

	return client.client.Do(request)
}

func (client *ClientUtil) CheckAuth() (bool, error) {
	if client.host == "" {
		return false, fmt.Errorf("missing hostname")
	}
	resp, err := client.Get("/api/ping")
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()

	serr := ExpectStatusCode(resp, http.StatusOK)

	if serr == nil {
		return true, nil
	}

	if serr.IsUnauthorized() {
		return false, nil
	}

	return false, serr
}

type capabilitiesResp struct {
	Data *Caps `json:"data"`
}

type Caps struct {
	ReplicationEnabled bool `json:"replication_enabled"`
}

func (client *ClientUtil) Capabilities() (*Caps, error) {
	// Fetch the node via the FileTree FS API
	resp, err := client.Get(
		"/api/capabilities/",
		EnableJSON(),
	)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if err := ExpectStatusCode(resp, http.StatusOK); err != nil {
		return nil, err
	}

	capResp := &capabilitiesResp{}
	if err := Unmarshal(resp, capResp); err != nil {
		return nil, err
	}

	return capResp.Data, nil
}

// DoReq "do" the request and returns the `*http.Response`
func (client *Client) DoReqWithQuery(ctx context.Context, method, path string, query map[string]string, headers map[string]string, body io.Reader) (*http.Response, error) {
	request, err := http.NewRequest(method, fmt.Sprintf("%s%s", client.opts.Host, path), body)
	if err != nil {
		return nil, err
	}

	q := request.URL.Query()
	for k, v := range query {
		q.Set(k, v)
	}
	request.URL.RawQuery = q.Encode()

	request = request.WithContext(ctx)

	request.Header.Set("BlobStash-Session-ID", client.SessionID())
	if client.opts.APIKey != "" {
		request.SetBasicAuth("", client.opts.APIKey)
	}

	// Set our custom user agent
	if client.opts.UserAgent != "" {
		request.Header.Set("User-Agent", client.opts.UserAgent)
	}

	if client.opts.Namespace != "" {
		request.Header.Set("BlobStash-Namespace", client.opts.Namespace)
	}

	// Check if we should request compressed data
	if client.opts.SnappyCompression {
		request.Header.Set("Accept-Encoding", "snappy")
	}

	// Add custom headers
	for header, val := range client.opts.Headers {
		request.Header.Set(header, val)
	}
	for header, val := range headers {
		request.Header.Set(header, val)
	}
	return client.client.Do(request)
}

func (client *Client) GetJSON(ctx context.Context, path string, headers map[string]string, out interface{}) error {
	resp, err := client.DoReq(ctx, "GET", path, headers, nil)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		if resp.StatusCode == 404 {
			return ErrNotFound
		}
		return fmt.Errorf("API call failed with status %d: %s", resp.StatusCode, body)
	}
	if err := json.Unmarshal(body, out); err != nil {
		return fmt.Errorf("failed to unmarshal: %v", err)
	}
	return nil
}