-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
273 lines (223 loc) · 6.99 KB
/
request.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
package pubnub
import (
"bytes"
"fmt"
"github.com/pubnub/go/pnerr"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// StatusResponse is used to store the usable properties in the response of an request.
type StatusResponse struct {
Error error
Category StatusCategory
Operation OperationType
StatusCode int
TLSEnabled bool
UUID string
AuthKey string
Origin string
OriginalResponse string
Request string
AffectedChannels []string
AffectedChannelGroups []string
}
// ResponseInfo is used to store the properties in the response of an request.
type ResponseInfo struct {
Operation OperationType
StatusCode int
TLSEnabled bool
Origin string
UUID string
AuthKey string
OriginalResponse *http.Response
}
func addToJobQ(req *http.Request, client *http.Client, opts endpointOpts, j chan *JobQResponse) {
jqi := &JobQItem{
Req: req,
Client: client,
JobResponse: j,
}
opts.jobQueue() <- jqi
}
func executeRequest(opts endpointOpts) ([]byte, StatusResponse, error) {
err := opts.validate()
if err != nil {
opts.config().Log.Println("PNUnknownCategory", err)
return nil,
createStatus(PNUnknownCategory, "", ResponseInfo{}, err),
err
}
url, err := buildURL(opts)
if err != nil {
opts.config().Log.Println("PNUnknownCategory", err)
return nil,
createStatus(PNUnknownCategory, "", ResponseInfo{}, err),
err
}
opts.config().Log.Println(fmt.Sprintf("url:%s\nmethod:%s", url, opts.httpMethod()))
var req *http.Request
if opts.httpMethod() == "POST" {
b, err := opts.buildBody()
if err != nil {
opts.config().Log.Println("PNUnknownCategory", err, url)
return nil,
createStatus(PNUnknownCategory, "", ResponseInfo{}, err),
err
}
body := bytes.NewReader(b)
req, err = newRequest("POST", url, body, opts.config().UseHTTP2)
} else if opts.httpMethod() == "DELETE" {
req, err = newRequest("DELETE", url, nil, opts.config().UseHTTP2)
} else {
req, err = newRequest("GET", url, nil, opts.config().UseHTTP2)
}
if err != nil {
opts.config().Log.Println("PNUnknownCategory", err, url)
return nil,
createStatus(PNUnknownCategory, "", ResponseInfo{}, err),
err
}
ctx := opts.context()
if ctx != nil {
// with !go1.7 you can't assign context directly to a request,
// the request.cancel is mapped to the ctx.Done() channel instead
// go1.7 can assign context to an executed request
req = setRequestContext(req, ctx)
}
client := opts.client()
startTimestamp := time.Now()
var res *http.Response
runRequestWorker := false
switch opts.operationType() {
case PNPublishOperation, PNAccessManagerGrant:
runRequestWorker = true
}
if runRequestWorker && opts.config().MaxWorkers > 0 {
j := make(chan *JobQResponse)
go addToJobQ(req, client, opts, j)
jr := <-j
close(j)
res = jr.Resp
err = jr.Error
} else {
res, err = client.Do(req)
}
// Host lookup failed
if err != nil {
opts.config().Log.Println("err.Error()", err.Error())
e := pnerr.NewConnectionError("Failed to execute request", err)
opts.config().Log.Println("PNUnknownCategory", e.Error(), url)
return nil,
createStatus(PNUnknownCategory, "", ResponseInfo{}, e),
e
}
val, status, err := parseResponse(res, opts)
// Already wrapped error
if err != nil {
opts.config().Log.Println("res.StatusCode, status, err.Error()", res.StatusCode, status, err.Error())
return nil, status, err
}
elapsedTime := time.Since(startTimestamp)
manager := opts.telemetryManager()
manager.StoreLatency(elapsedTime.Seconds(), opts.operationType())
responseInfo := ResponseInfo{
StatusCode: res.StatusCode,
OriginalResponse: res,
Operation: opts.operationType(),
Origin: url.Host,
}
if url.Scheme == "https" {
responseInfo.TLSEnabled = true
}
if uuid, ok := url.Query()["uuid"]; ok {
responseInfo.UUID = uuid[0]
}
if auth, ok := url.Query()["auth"]; ok {
responseInfo.AuthKey = auth[0]
}
status = createStatus(PNUnknownCategory, string(val), responseInfo, nil)
return val, status, nil
}
func newRequest(method string, u *url.URL, body io.Reader, useHTTP2 bool) (*http.Request,
error) {
rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
rc = ioutil.NopCloser(body)
}
if useHTTP2 {
req := &http.Request{
Method: method,
URL: u,
Proto: "HTTP/2.0",
ProtoMajor: 2,
ProtoMinor: 0,
Header: make(http.Header),
Body: rc,
Host: u.Host,
}
return req, nil
}
req := &http.Request{
Method: method,
URL: u,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Body: rc,
Host: u.Host,
}
return req, nil
}
func parseResponse(resp *http.Response, opts endpointOpts) ([]byte, StatusResponse, error) {
status := StatusResponse{}
if resp.StatusCode != 200 {
// Errors like 400, 403, 500
e := pnerr.NewServerError(resp.StatusCode, resp.Body)
opts.config().Log.Println(e.Error())
if resp.StatusCode == 408 {
opts.config().Log.Println("PNTimeoutCategory: resp.StatusCode, resp.Body, resp.Request.URL", resp.StatusCode, resp.Body, resp.Request.URL)
status = createStatus(PNTimeoutCategory, "", ResponseInfo{StatusCode: resp.StatusCode}, e)
return nil, status, e
}
if resp.StatusCode == 400 {
opts.config().Log.Println("PNBadRequestCategory: resp.StatusCode, resp.Body, resp.Request.URL", resp.StatusCode, resp.Body, resp.Request.URL)
status = createStatus(PNBadRequestCategory, "", ResponseInfo{StatusCode: resp.StatusCode}, e)
return nil, status, e
}
opts.config().Log.Println("PNUnknownCategory: resp.StatusCode, resp.Body, resp.Request.URL", resp.StatusCode, resp.Body, resp.Request.URL)
status = createStatus(PNUnknownCategory, "", ResponseInfo{StatusCode: resp.StatusCode, Operation: opts.operationType()}, e)
return nil, status, e
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
e := pnerr.NewResponseParsingError("Error reading response body", resp.Body, err)
opts.config().Log.Println("Read All error: resp.Body, resp.Request.URL, e", resp.StatusCode, resp.Body, resp.Request.URL, e)
return nil, status, e
}
opts.config().Log.Println("200 OK: resp.StatusCode, resp.Status, resp.Body, resp.Request.URL, string(body)", resp.StatusCode, resp.Status, resp.Body, resp.Request.URL, string(body))
return body, status, nil
}
func createStatus(category StatusCategory, response string,
responseInfo ResponseInfo, err error) StatusResponse {
resp := StatusResponse{}
if response != "" {
resp.OriginalResponse = response
}
if err != nil {
resp.Error = err
}
resp.StatusCode = responseInfo.StatusCode
resp.TLSEnabled = responseInfo.TLSEnabled
resp.Origin = responseInfo.Origin
resp.UUID = responseInfo.UUID
resp.AuthKey = responseInfo.AuthKey
resp.Operation = responseInfo.Operation
resp.Category = category
resp.AffectedChannels = []string{}
resp.AffectedChannelGroups = []string{}
return resp
}