-
Notifications
You must be signed in to change notification settings - Fork 66
/
client_http_request.go
232 lines (203 loc) · 7.24 KB
/
client_http_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
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package zanzibar
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/uber/zanzibar/runtime/jsonwrapper"
"go.uber.org/zap"
)
var metricNormalizer = strings.NewReplacer("::", "--")
// ClientHTTPRequest is the struct for making a single client request using an outbound http client.
type ClientHTTPRequest struct {
ClientID string
ClientTargetEndpoint string
MethodName string
Metrics ContextMetrics
client *HTTPClient
httpReq *http.Request
res *ClientHTTPResponse
started bool
startTime time.Time
Logger *zap.Logger
ContextLogger ContextLogger
rawBody []byte
defaultHeaders map[string]string
ctx context.Context
jsonWrapper jsonwrapper.JSONWrapper
}
// NewClientHTTPRequest allocates a ClientHTTPRequest. The ctx parameter is the context associated with the outbound requests.
func NewClientHTTPRequest(
ctx context.Context,
clientID string,
clientMethod string,
clientTargetEndpoint string,
client *HTTPClient,
) *ClientHTTPRequest {
scopeTags := map[string]string{
scopeTagClientMethod: clientMethod,
scopeTagClient: clientID,
scopeTagsTargetEndpoint: metricNormalizer.Replace(clientTargetEndpoint),
}
ctx = WithScopeTags(ctx, scopeTags)
req := &ClientHTTPRequest{
ClientID: clientID,
MethodName: clientMethod,
ClientTargetEndpoint: clientTargetEndpoint,
Metrics: client.contextMetrics,
client: client,
ContextLogger: client.ContextLogger,
defaultHeaders: client.DefaultHeaders,
ctx: ctx,
jsonWrapper: client.JSONWrapper,
}
req.res = NewClientHTTPResponse(req)
req.start()
return req
}
// Start the request, do some metrics book keeping
func (req *ClientHTTPRequest) start() {
if req.started {
/* coverage ignore next line */
req.ContextLogger.ErrorZ(req.ctx, "Cannot start ClientHTTPRequest twice")
/* coverage ignore next line */
return
}
req.started = true
req.startTime = time.Now()
}
// CheckHeaders verifies that the outbound request contains required headers
func (req *ClientHTTPRequest) CheckHeaders(expected []string) error {
if req.httpReq == nil {
/* coverage ignore next line */
panic("must call `req.WriteJSON()` before `req.CheckHeaders()`")
}
actualHeaders := req.httpReq.Header
for _, headerName := range expected {
// headerName is case insensitive, http.Header Get canonicalize the key
headerValue := actualHeaders.Get(headerName)
if headerValue == "" {
req.ContextLogger.WarnZ(req.ctx, "Got outbound request without mandatory header",
zap.String("headerName", headerName),
)
return errors.New("Missing mandatory header: " + headerName)
}
}
return nil
}
// WriteJSON materialize the HTTP request with given method, url, headers and body.
func (req *ClientHTTPRequest) WriteJSON(
method, url string,
headers map[string]string,
body interface{},
) error {
var rawBody []byte
if body != nil {
var err error
rawBody, err = req.jsonWrapper.Marshal(body)
if err != nil {
req.ContextLogger.ErrorZ(req.ctx, "Could not serialize request json", zap.Error(err))
return errors.Wrapf(
err, "Could not serialize %s.%s request json",
req.ClientID, req.MethodName,
)
}
}
return req.WriteBytes(method, url, headers, rawBody)
}
// WriteBytes materialize the HTTP request with given method, url, headers and body.
// Body is assumed to be a byte array.s
func (req *ClientHTTPRequest) WriteBytes(
method, url string,
headers map[string]string,
rawBody []byte,
) error {
var httpReq *http.Request
var httpErr error
if rawBody != nil {
req.rawBody = rawBody
httpReq, httpErr = http.NewRequest(method, url, bytes.NewReader(rawBody))
} else {
httpReq, httpErr = http.NewRequest(method, url, nil)
}
if httpErr != nil {
req.ContextLogger.ErrorZ(req.ctx, "Could not create outbound request", zap.Error(httpErr))
return errors.Wrapf(
httpErr, "Could not create outbound %s.%s request",
req.ClientID, req.MethodName,
)
}
// Using `Add` over `Set` intentionally, allowing us to create a list
// of headerValues for a given key.
for headerKey, headerValue := range req.defaultHeaders {
httpReq.Header.Set(headerKey, headerValue)
}
for k := range headers {
httpReq.Header.Set(k, headers[k])
}
req.httpReq = httpReq
req.ctx = WithLogFields(req.ctx,
zap.String(logFieldClientHTTPMethod, method),
zap.String(logFieldRequestURL, url),
zap.Time(logFieldRequestStartTime, req.startTime),
)
return nil
}
// Do will send the request out.
func (req *ClientHTTPRequest) Do() (*ClientHTTPResponse, error) {
opName := fmt.Sprintf("%s.%s(%s)", req.ClientID, req.MethodName, req.ClientTargetEndpoint)
urlTag := opentracing.Tag{Key: "URL", Value: req.httpReq.URL}
methodTag := opentracing.Tag{Key: "Method", Value: req.httpReq.Method}
span, ctx := opentracing.StartSpanFromContext(req.ctx, opName, urlTag, methodTag)
err := req.InjectSpanToHeader(span, opentracing.HTTPHeaders)
if err != nil {
/* coverage ignore next line */
req.ContextLogger.ErrorZ(req.ctx, "Fail to inject span to headers", zap.Error(err))
/* coverage ignore next line */
return nil, err
}
res, err := req.client.Client.Do(req.httpReq.WithContext(ctx))
span.Finish()
if err != nil {
req.ContextLogger.ErrorZ(req.ctx, "Could not make outbound request", zap.Error(err))
return nil, err
}
// emit metrics
req.Metrics.IncCounter(req.ctx, clientRequest, 1)
req.res.setRawHTTPResponse(res)
return req.res, nil
}
// InjectSpanToHeader will inject span to request header
// This method is current used for unit tests
// TODO: we need to set source and test code as same pkg name which would makes UTs easier
func (req *ClientHTTPRequest) InjectSpanToHeader(span opentracing.Span, format interface{}) error {
carrier := opentracing.HTTPHeadersCarrier(req.httpReq.Header)
if err := span.Tracer().Inject(span.Context(), format, carrier); err != nil {
req.ContextLogger.ErrorZ(req.ctx, "Failed to inject tracing span.", zap.Error(err))
return err
}
return nil
}