-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
310 lines (262 loc) · 7.95 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
package fasthttp
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"sync"
"time"
e "github.com/domsolutions/xk6-fasthttp/errors"
"github.com/domsolutions/xk6-fasthttp/metrics"
"github.com/domsolutions/xk6-fasthttp/tracer"
"github.com/grafana/sobek"
http "github.com/valyala/fasthttp"
proxy "github.com/valyala/fasthttp/fasthttpproxy"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules"
"go.k6.io/k6/lib/netext/httpext"
)
const (
defaultDialTimeout = 5 * time.Second
defaultMaxConnsPerHost = 1
)
type ClientConfig struct {
DialTimeout int
Proxy string
MaxConnDuration int
UserAgent string
ReadBufferSize int
WriteBufferSize int
ReadTimeout int
WriteTimeout int
MaxConnsPerHost int
TLSConfig TLSConfig
}
type TLSConfig struct {
InsecureSkipVerify bool
PrivateKey string
Certificate string
}
type Client struct {
fhc *http.Client
vu modules.VU
metrics *metrics.MetricDispatcher
metricsSetupOnce *sync.Once
}
func (mi *ModuleInstance) Client(call sobek.ConstructorCall, rt *sobek.Runtime) *sobek.Object {
if mi.vu.State() != nil {
common.Throw(rt, errors.New("creating client objects is allowed only in the Init context"))
}
var config ClientConfig
err := rt.ExportTo(call.Argument(0), &config)
if err != nil {
common.Throw(rt, fmt.Errorf("client constructor expects first argument to be ClientConfig got error %v", err))
}
var fhc *http.Client
if fhc, err = parseClientConfig(config); err != nil {
common.Throw(rt, err)
}
c := &Client{fhc: fhc, vu: mi.vu, metricsSetupOnce: &sync.Once{}}
return rt.ToValue(c).ToObject(rt)
}
func parseClientConfig(config ClientConfig) (*http.Client, error) {
if config.TLSConfig.PrivateKey != "" && config.TLSConfig.Certificate == "" {
return nil, errors.New("blank certificate")
}
if config.TLSConfig.PrivateKey == "" && config.TLSConfig.Certificate != "" {
return nil, errors.New("blank private key")
}
tlsConfig := &tls.Config{
InsecureSkipVerify: config.TLSConfig.InsecureSkipVerify,
}
if config.TLSConfig.Certificate != "" && config.TLSConfig.PrivateKey != "" {
cert, err := tls.LoadX509KeyPair(config.TLSConfig.Certificate, config.TLSConfig.PrivateKey)
if err != nil {
return nil, fmt.Errorf("failed to load key/cert; %v", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
maxConnsPerHost := defaultMaxConnsPerHost
if config.MaxConnsPerHost > 0 {
maxConnsPerHost = config.MaxConnsPerHost
}
fhc := &http.Client{
Name: config.UserAgent,
MaxConnDuration: time.Duration(config.MaxConnDuration) * time.Second,
ReadBufferSize: config.ReadBufferSize,
WriteBufferSize: config.WriteBufferSize,
WriteTimeout: time.Duration(config.WriteTimeout) * time.Second,
ReadTimeout: time.Duration(config.ReadTimeout) * time.Second,
MaxConnsPerHost: maxConnsPerHost,
DisableHeaderNamesNormalizing: true,
TLSConfig: tlsConfig,
Dial: func(addr string) (net.Conn, error) {
timeout := defaultDialTimeout
if config.DialTimeout > 0 {
timeout = time.Duration(config.DialTimeout) * time.Second
}
if config.Proxy != "" {
return proxy.FasthttpHTTPDialerTimeout(config.Proxy, timeout)(addr)
}
return http.DialTimeout(addr, timeout)
},
}
return fhc, nil
}
func (c *Client) verifyReq(r *sobek.Object) {
if _, ok := r.Export().(*RequestWrapper); !ok {
common.Throw(c.vu.Runtime(), errors.New("object not a Request"))
}
}
func (c *Client) Options(r *sobek.Object) (*Response, error) {
c.verifyReq(r)
return c.makeReq(r.Export().(*RequestWrapper), http.MethodOptions)
}
func (c *Client) Put(r *sobek.Object) (*Response, error) {
c.verifyReq(r)
return c.makeReq(r.Export().(*RequestWrapper), http.MethodPut)
}
func (c *Client) Patch(r *sobek.Object) (*Response, error) {
c.verifyReq(r)
return c.makeReq(r.Export().(*RequestWrapper), http.MethodPatch)
}
func (c *Client) Delete(r *sobek.Object) (*Response, error) {
c.verifyReq(r)
return c.makeReq(r.Export().(*RequestWrapper), http.MethodDelete)
}
func (c *Client) Post(r *sobek.Object) (*Response, error) {
c.verifyReq(r)
return c.makeReq(r.Export().(*RequestWrapper), http.MethodPost)
}
func (c *Client) Get(r *sobek.Object) (*Response, error) {
c.verifyReq(r)
return c.makeReq(r.Export().(*RequestWrapper), http.MethodGet)
}
func setBody(method string, body interface{}) bool {
return body != nil && method != http.MethodHead && method != http.MethodGet
}
func (c *Client) setupCachedReq(reqw *RequestWrapper, method string) error {
if setBody(method, reqw.Body) {
switch reqw.Body.(type) {
case *FileStream:
f := reqw.Body.(*FileStream)
// reset to beginning of file
if _, err := f.Seek(0, 0); err != nil {
c.vu.State().Logger.WithError(err).Error("Failed to reset stream to beginning")
return err
}
reqw.req.SetBodyStream(f, -1)
}
return nil
}
// reset body as req may be a GET request which should have no body but cached req may have a body
reqw.req.SetBody(nil)
reqw.req.SetBodyStream(nil, 0)
reqw.req.Header.SetMethod(method)
return nil
}
func (c *Client) setupNewReq(reqw *RequestWrapper, method string) error {
reqw.req.SetRequestURI(reqw.Url)
if reqw.Host != "" {
reqw.req.UseHostHeader = true
reqw.req.Header.SetHost(reqw.Host)
}
if setBody(method, reqw.Body) {
switch reqw.Body.(type) {
case string:
reqw.req.SetBody([]byte(reqw.Body.(string)))
case sobek.ArrayBuffer:
reqw.req.SetBody(reqw.Body.(sobek.ArrayBuffer).Bytes())
case *FileStream:
f := reqw.Body.(*FileStream)
// reset to beginning of file for fresh request
if _, err := f.Seek(0, 0); err != nil {
c.vu.State().Logger.WithError(err).Error("Failed to reset stream to beginning")
return err
}
reqw.req.SetBodyStream(f, -1)
default:
return errors.New("req body type not supported")
}
}
if reqw.DisableKeepAlive {
reqw.req.Header.SetConnectionClose()
}
for field, val := range reqw.Headers {
reqw.req.Header.Set(field, val)
}
reqw.req.Header.SetMethod(method)
return nil
}
func (c *Client) makeReq(req *RequestWrapper, method string) (*Response, error) {
if r := req.reqPool.Get(); r != nil {
req.req = r.(*http.Request)
if err := c.setupCachedReq(req, method); err != nil {
return nil, err
}
} else {
req.req = http.AcquireRequest()
if err := c.setupNewReq(req, method); err != nil {
return nil, err
}
}
defer func() {
req.reqPool.Put(req.req)
req.req = nil
}()
c.metricsSetupOnce.Do(func() {
tags := c.vu.State().Tags.GetCurrentValues()
c.metrics = metrics.NewMetricDispatcher(&tags, c.vu.State())
})
var resp *Response
var err error
if resp, err = c.do(c.vu.Context(), req); err != nil {
return nil, err
}
return resp, nil
}
func (c *Client) do(ctx context.Context, req *RequestWrapper) (response *Response, err error) {
resp := http.AcquireResponse()
defer func() {
http.ReleaseResponse(resp)
if !req.Throw {
err = nil
}
}()
c.metrics.ProcessLastSavedRequest(c.vu.Context(), nil)
t1 := time.Now()
// send request on wire
err = c.fhc.Do(req.req, resp)
trial := &tracer.Trail{Duration: time.Since(t1)}
c.metrics.SaveCurrentRequest(c.vu.Context(), &metrics.UnfinishedRequest{
Ctx: ctx,
Trail: trial,
Request: req.req,
Response: resp,
Err: err,
})
if err != nil {
if !req.Throw {
c.vu.State().Logger.WithError(err).Warn("Request Failed")
}
return nil, err
}
r := &httpext.Response{}
r.Status = resp.StatusCode()
r.RemoteIP = resp.RemoteAddr().String()
r.URL = req.req.URI().String()
r.Headers = make(map[string]string)
resp.Header.VisitAll(func(key, value []byte) {
r.Headers[string(key)] = string(value)
})
response = &Response{Response: r, client: c}
response.Body, err = readResponseBody(req.responseType, resp)
if err != nil {
var code e.ErrCode
code, response.Error = e.ErrorCodeForError(err)
response.ErrorCode = int(code)
return response, err
}
return response, nil
}