Debian Codegraph @

autorest/client.go

raw
1 package autorest
2
3 // Copyright 2017 Microsoft Corporation
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 import (
18 "bytes"
19 "crypto/tls"
20 "errors"
21 "fmt"
22 "io"
23 "io/ioutil"
24 "log"
25 "net/http"
26 "strings"
27 "time"
28
29 "github.com/Azure/go-autorest/logger"
30 )
31
32 const (
33 // DefaultPollingDelay is a reasonable delay between polling requests.
34 DefaultPollingDelay = 30 * time.Second
35
36 // DefaultPollingDuration is a reasonable total polling duration.
37 DefaultPollingDuration = 15 * time.Minute
38
39 // DefaultRetryAttempts is number of attempts for retry status codes (5xx).
40 DefaultRetryAttempts = 3
41
42 // DefaultRetryDuration is the duration to wait between retries.
43 DefaultRetryDuration = 30 * time.Second
44 )
45
46 var (
47 // StatusCodesForRetry are a defined group of status code for which the client will retry
48 StatusCodesForRetry = []int{
49 http.StatusRequestTimeout, // 408
50 http.StatusTooManyRequests, // 429
51 http.StatusInternalServerError, // 500
52 http.StatusBadGateway, // 502
53 http.StatusServiceUnavailable, // 503
54 http.StatusGatewayTimeout, // 504
55 }
56 )
57
58 const (
59 requestFormat = `HTTP Request Begin ===================================================
60 %s
61 ===================================================== HTTP Request End
62 `
63 responseFormat = `HTTP Response Begin ===================================================
64 %s
65 ===================================================== HTTP Response End
66 `
67 )
68
69 // Response serves as the base for all responses from generated clients. It provides access to the
70 // last http.Response.
71 type Response struct {
72 *http.Response `json:"-"`
73 }
74
75 // IsHTTPStatus returns true if the returned HTTP status code matches the provided status code.
76 // If there was no response (i.e. the underlying http.Response is nil) the return value is false.
77 func (r Response) IsHTTPStatus(statusCode int) bool {
78 if r.Response == nil {
79 return false
80 }
81 return r.Response.StatusCode == statusCode
82 }
83
84 // HasHTTPStatus returns true if the returned HTTP status code matches one of the provided status codes.
85 // If there was no response (i.e. the underlying http.Response is nil) or not status codes are provided
86 // the return value is false.
87 func (r Response) HasHTTPStatus(statusCodes ...int) bool {
88 return ResponseHasStatusCode(r.Response, statusCodes...)
89 }
90
91 // LoggingInspector implements request and response inspectors that log the full request and
92 // response to a supplied log.
93 type LoggingInspector struct {
94 Logger *log.Logger
95 }
96
97 // WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The
98 // body is restored after being emitted.
99 //
100 // Note: Since it reads the entire Body, this decorator should not be used where body streaming is
101 // important. It is best used to trace JSON or similar body values.
102 func (li LoggingInspector) WithInspection() PrepareDecorator {
103 return func(p Preparer) Preparer {
104 return PreparerFunc(func(r *http.Request) (*http.Request, error) {
105 var body, b bytes.Buffer
106
107 defer r.Body.Close()
108
109 r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body))
110 if err := r.Write(&b); err != nil {
111 return nil, fmt.Errorf("Failed to write response: %v", err)
112 }
113
114 li.Logger.Printf(requestFormat, b.String())
115
116 r.Body = ioutil.NopCloser(&body)
117 return p.Prepare(r)
118 })
119 }
120 }
121
122 // ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The
123 // body is restored after being emitted.
124 //
125 // Note: Since it reads the entire Body, this decorator should not be used where body streaming is
126 // important. It is best used to trace JSON or similar body values.
127 func (li LoggingInspector) ByInspecting() RespondDecorator {
128 return func(r Responder) Responder {
129 return ResponderFunc(func(resp *http.Response) error {
130 var body, b bytes.Buffer
131 defer resp.Body.Close()
132 resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body))
133 if err := resp.Write(&b); err != nil {
134 return fmt.Errorf("Failed to write response: %v", err)
135 }
136
137 li.Logger.Printf(responseFormat, b.String())
138
139 resp.Body = ioutil.NopCloser(&body)
140 return r.Respond(resp)
141 })
142 }
143 }
144
145 // Client is the base for autorest generated clients. It provides default, "do nothing"
146 // implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the
147 // standard, undecorated http.Client as a default Sender.
148 //
149 // Generated clients should also use Error (see NewError and NewErrorWithError) for errors and
150 // return responses that compose with Response.
151 //
152 // Most customization of generated clients is best achieved by supplying a custom Authorizer, custom
153 // RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit
154 // breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence
155 // sending the request by providing a decorated Sender.
156 type Client struct {
157 Authorizer Authorizer
158 Sender Sender
159 RequestInspector PrepareDecorator
160 ResponseInspector RespondDecorator
161
162 // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header
163 PollingDelay time.Duration
164
165 // PollingDuration sets the maximum polling time after which an error is returned.
166 // Setting this to zero will use the provided context to control the duration.
167 PollingDuration time.Duration
168
169 // RetryAttempts sets the total number of times the client will attempt to make an HTTP request.
170 // Set the value to 1 to disable retries. DO NOT set the value to less than 1.
171 RetryAttempts int
172
173 // RetryDuration sets the delay duration for retries.
174 RetryDuration time.Duration
175
176 // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent
177 // through the Do method.
178 UserAgent string
179
180 Jar http.CookieJar
181
182 // Set to true to skip attempted registration of resource providers (false by default).
183 SkipResourceProviderRegistration bool
184
185 // SendDecorators can be used to override the default chain of SendDecorators.
186 // This can be used to specify things like a custom retry SendDecorator.
187 // Set this to an empty slice to use no SendDecorators.
188 SendDecorators []SendDecorator
189 }
190
191 // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed
192 // string.
193 func NewClientWithUserAgent(ua string) Client {
194 return newClient(ua, tls.RenegotiateNever)
195 }
196
197 // ClientOptions contains various Client configuration options.
198 type ClientOptions struct {
199 // UserAgent is an optional user-agent string to append to the default user agent.
200 UserAgent string
201
202 // Renegotiation is an optional setting to control client-side TLS renegotiation.
203 Renegotiation tls.RenegotiationSupport
204 }
205
206 // NewClientWithOptions returns an instance of a Client with the specified values.
207 func NewClientWithOptions(options ClientOptions) Client {
208 return newClient(options.UserAgent, options.Renegotiation)
209 }
210
211 func newClient(ua string, renegotiation tls.RenegotiationSupport) Client {
212 c := Client{
213 PollingDelay: DefaultPollingDelay,
214 PollingDuration: DefaultPollingDuration,
215 RetryAttempts: DefaultRetryAttempts,
216 RetryDuration: DefaultRetryDuration,
217 UserAgent: UserAgent(),
218 }
219 c.Sender = c.sender(renegotiation)
220 c.AddToUserAgent(ua)
221 return c
222 }
223
224 // AddToUserAgent adds an extension to the current user agent
225 func (c *Client) AddToUserAgent(extension string) error {
226 if extension != "" {
227 c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension)
228 return nil
229 }
230 return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent)
231 }
232
233 // Do implements the Sender interface by invoking the active Sender after applying authorization.
234 // If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent
235 // is set, apply set the User-Agent header.
236 func (c Client) Do(r *http.Request) (*http.Response, error) {
237 if r.UserAgent() == "" {
238 r, _ = Prepare(r,
239 WithUserAgent(c.UserAgent))
240 }
241 // NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations
242 r, err := Prepare(r,
243 c.WithAuthorization(),
244 c.WithInspection())
245 if err != nil {
246 var resp *http.Response
247 if detErr, ok := err.(DetailedError); ok {
248 // if the authorization failed (e.g. invalid credentials) there will
249 // be a response associated with the error, be sure to return it.
250 resp = detErr.Response
251 }
252 return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed")
253 }
254 logger.Instance.WriteRequest(r, logger.Filter{
255 Header: func(k string, v []string) (bool, []string) {
256 // remove the auth token from the log
257 if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") {
258 v = []string{"**REDACTED**"}
259 }
260 return true, v
261 },
262 })
263 resp, err := SendWithSender(c.sender(tls.RenegotiateNever), r)
264 if resp == nil && err == nil {
265 err = errors.New("autorest: received nil response and error")
266 }
267 logger.Instance.WriteResponse(resp, logger.Filter{})
268 Respond(resp, c.ByInspecting())
269 return resp, err
270 }
271
272 // sender returns the Sender to which to send requests.
273 func (c Client) sender(renengotiation tls.RenegotiationSupport) Sender {
274 if c.Sender == nil {
275 return sender(renengotiation)
276 }
277 return c.Sender
278 }
279
280 // WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator
281 // from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer.
282 func (c Client) WithAuthorization() PrepareDecorator {
283 return c.authorizer().WithAuthorization()
284 }
285
286 // authorizer returns the Authorizer to use.
287 func (c Client) authorizer() Authorizer {
288 if c.Authorizer == nil {
289 return NullAuthorizer{}
290 }
291 return c.Authorizer
292 }
293
294 // WithInspection is a convenience method that passes the request to the supplied RequestInspector,
295 // if present, or returns the WithNothing PrepareDecorator otherwise.
296 func (c Client) WithInspection() PrepareDecorator {
297 if c.RequestInspector == nil {
298 return WithNothing()
299 }
300 return c.RequestInspector
301 }
302
303 // ByInspecting is a convenience method that passes the response to the supplied ResponseInspector,
304 // if present, or returns the ByIgnoring RespondDecorator otherwise.
305 func (c Client) ByInspecting() RespondDecorator {
306 if c.ResponseInspector == nil {
307 return ByIgnoring()
308 }
309 return c.ResponseInspector
310 }
311
312 // Send sends the provided http.Request using the client's Sender or the default sender.
313 // It returns the http.Response and possible error. It also accepts a, possibly empty,
314 // default set of SendDecorators used when sending the request.
315 // SendDecorators have the following precedence:
316 // 1. In a request's context via WithSendDecorators()
317 // 2. Specified on the client in SendDecorators
318 // 3. The default values specified in this method
319 func (c Client) Send(req *http.Request, decorators ...SendDecorator) (*http.Response, error) {
320 if c.SendDecorators != nil {
321 decorators = c.SendDecorators
322 }
323 inCtx := req.Context().Value(ctxSendDecorators{})
324 if sd, ok := inCtx.([]SendDecorator); ok {
325 decorators = sd
326 }
327 return SendWithSender(c, req, decorators...)
328 }