-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
217 lines (188 loc) · 5.68 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
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
)
const (
DefaultScheme = "https"
DefaultPort = 7443
DefaultPathPrefix = "/api/public"
// RecommendedMinimumRequestTTL is the minimum recommended timeout value for any given context used during an api
// request to the VSZ. This is designed to provide enough time to allow for re-authentication to happen if need be.
//
// There is no guard against setting a TTL lower than this value. It is merely here as a suggestion.
RecommendedMinimumRequestTTL = 2500 * time.Millisecond
)
type Config struct {
Hostname string // REQUIRED hostname of your VSZ
Port int // OPTIONAL defaults to 7443
Scheme string // OPTIONAL defaults to https
PathPrefix string // OPTIONAL defaults to "/api/public"
}
// DefaultConfig creates a new ClientConfig object with a non-pooled client
func DefaultConfig(hostname string) *Config {
return defaultConfig(hostname)
}
func defaultConfig(hostname string) *Config {
return &Config{
Hostname: hostname,
Scheme: DefaultScheme,
Port: DefaultPort,
PathPrefix: DefaultPathPrefix,
}
}
type Client struct {
*bridge
config *Config
client *http.Client
auth Authenticator
}
func NewClient(conf *Config, authenticator Authenticator, client *http.Client) (*Client, error) {
if authenticator == nil {
return nil, errors.New("authenticator cannot be nil")
}
if conf == nil {
return nil, errors.New("config cannot be nil")
}
def := defaultConfig(conf.Hostname)
if conf.Scheme != "" {
def.Scheme = conf.Scheme
}
if conf.Port > 0 {
def.Port = conf.Port
}
if conf.PathPrefix != "" {
def.PathPrefix = conf.PathPrefix
}
if client == nil {
// shamelessly borrowed from https://github.com/hashicorp/go-cleanhttp/blob/master/cleanhttp.go
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: true,
MaxIdleConnsPerHost: -1,
},
}
}
c := &Client{
config: conf,
client: client,
auth: authenticator,
}
c.bridge = newBridge(c)
return c, nil
}
func (c *Client) ClientConfig() Config {
return *c.config
}
func (c *Client) Do(ctx context.Context, request *Request) (*http.Response, error) {
_, httpResponse, err := c.do(ctx, request)
return httpResponse, err
}
// Ensure will attempt to execute the request, initiating an Authenticator Invalidate -> Refresh loop if a 401 is seen.
//
// If the "success" status code is seen, it will further attempt to unmarshal the response into a pointer provided
// to "out". Failing that, this method will attempt to unmarshal the seen response into an VSZError struct
func (c *Client) Ensure(ctx context.Context, request *Request, successCode int, out interface{}) (*http.Response, []byte, error) {
var httpResponse *http.Response
var cas AuthCAS
var buff []byte
var err error
if cas, httpResponse, err = c.do(ctx, request); err != nil {
return nil, nil, err
}
// read everything out of the body and close it.
buff, err = ioutil.ReadAll(httpResponse.Body)
httpResponse.Body.Close()
if err != nil {
return httpResponse, nil, err
}
// check for and attempt to handle 401 unauthorized
if httpResponse.StatusCode == 401 && request.authenticated {
// invalidate authenticator state
if _, err = c.auth.Invalidate(ctx, cas); err != nil {
return nil, nil, err
}
// attempt request again.
if httpResponse, _, err = c.tryDo(ctx, request); err != nil {
if httpResponse != nil {
httpResponse.Body.Close()
}
return nil, nil, err
}
// read everything out of the body and close it.
buff, err = ioutil.ReadAll(httpResponse.Body)
httpResponse.Body.Close()
if err != nil {
return httpResponse, nil, err
}
}
// test for "success"
if httpResponse.StatusCode == successCode {
if out != nil {
err = json.Unmarshal(buff, out)
}
return httpResponse, buff, err
}
// finally, try to unmarshal response body into Error type
err2 := &VSZError{}
err = json.Unmarshal(buff, err2)
if err != nil {
log.Printf("[request-%d] ERROR: Unable to unmarshal response: %s", request.id, err)
log.Printf("[request-%d] ERROR: Response: %s", request.id, string(buff))
err = fmt.Errorf("expected \"%d\", saw \"%s\"", successCode, httpResponse.Status)
} else {
err = *err2
}
return httpResponse, buff, err
}
func (c *Client) tryDo(ctx context.Context, request *Request) (*http.Response, AuthCAS, error) {
var httpRequest *http.Request
var httpResponse *http.Response
var cas AuthCAS
var err error
if httpRequest, err = request.toHTTP(ctx, c.config); err != nil {
return nil, cas, err
}
// if this api requires an active auth session, try to locate cookie
if request.authenticated {
if cas, err = c.auth.Decorate(ctx, httpRequest); err != nil {
if cas, err = c.auth.Refresh(ctx, c, cas); err != nil {
return nil, cas, err
} else if cas, err = c.auth.Decorate(ctx, httpRequest); err != nil {
return nil, cas, err
}
}
}
httpResponse, err = c.client.Do(httpRequest)
return httpResponse, cas, err
}
func (c *Client) do(ctx context.Context, request *Request) (AuthCAS, *http.Response, error) {
if ctx == nil {
return 0, nil, errors.New("ctx must not be nil")
}
var httpResponse *http.Response
var cas AuthCAS
var err error
if httpResponse, cas, err = c.tryDo(ctx, request); err != nil {
if httpResponse != nil {
httpResponse.Body.Close()
}
return cas, nil, err
}
return cas, httpResponse, err
}