File size: 32,523 Bytes
7b715bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
/*
Copyright 2013 Google Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using Google.Apis.Core.Util;
using Google.Apis.Logging;
using Google.Apis.Testing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Apis.Http
{
    /// <summary>
    /// A message handler which contains the main logic of our HTTP requests. It contains a list of 
    /// <see cref="IHttpUnsuccessfulResponseHandler"/>s for handling abnormal responses, a list of 
    /// <see cref="IHttpExceptionHandler"/>s for handling exception in a request and a list of 
    /// <see cref="IHttpExecuteInterceptor"/>s for intercepting a request before it has been sent to the server.
    /// It also contains important properties like number of tries, follow redirect, etc.
    /// </summary>
    public class ConfigurableMessageHandler : DelegatingHandler
    {
        private const string QuotaProjectHeaderName = "x-goog-user-project";

        /// <summary>The class logger.</summary>
        private static readonly ILogger Logger = ApplicationContext.Logger.ForType<ConfigurableMessageHandler>();

        /// <summary>Maximum allowed number of tries.</summary>
        [VisibleForTestOnly]
        public const int MaxAllowedNumTries = 20;

        /// <summary>
        /// Key for unsuccessful response handlers in an <see cref="HttpRequestMessage"/> options.
        /// </summary>
        public const string UnsuccessfulResponseHandlerKey = "__UnsuccessfulResponseHandlerKey";

        /// <summary>
        /// Key for exception handlers in an <see cref="HttpRequestMessage"/> options.
        /// </summary>
        public const string ExceptionHandlerKey = "__ExceptionHandlerKey";

        /// <summary>
        /// Key for execute handlers in an <see cref="HttpRequestMessage"/> options.
        /// </summary>
        public const string ExecuteInterceptorKey = "__ExecuteInterceptorKey";

        /// <summary>
        /// Key for a stream response interceptor provider in an <see cref="HttpRequestMessage"/> options.
        /// </summary>
        public const string ResponseStreamInterceptorProviderKey = "__ResponseStreamInterceptorProviderKey";

        /// <summary>
        /// Key for a credential in a <see cref="HttpRequestMessage"/> options.
        /// </summary>
        public const string CredentialKey = "__CredentialKey";

        /// <summary>
        /// Key for a universe domain in a <see cref="HttpRequestMessage"/> options.
        /// </summary>
        internal const string UniverseDomainKey = "__UniverseDomainKey";

        /// <summary>
        /// Key for request specific max retries.
        /// </summary>
        public const string MaxRetriesKey = "__MaxRetriesKey";

        /// <summary>The current API version of this client library.</summary>
        private static readonly string ApiVersion = Google.Apis.Util.Utilities.GetLibraryVersion();

        /// <summary>The User-Agent suffix header which contains the <see cref="ApiVersion"/>.</summary>
        private static readonly string UserAgentSuffix = "google-api-dotnet-client/" + ApiVersion + " (gzip)";

        #region IHttpUnsuccessfulResponseHandler, IHttpExceptionHandler and IHttpExecuteInterceptor lists

        #region Lock objects

        // The following lock objects are used to lock the list of handlers and interceptors in order to be able to
        // iterate over them from several threads and to keep this class thread-safe.
        private readonly object unsuccessfulResponseHandlersLock = new object();
        private readonly object exceptionHandlersLock = new object();
        private readonly object executeInterceptorsLock = new object();

        #endregion

        /// <summary>A list of <see cref="IHttpUnsuccessfulResponseHandler"/>.</summary>
        private readonly IList<IHttpUnsuccessfulResponseHandler> unsuccessfulResponseHandlers =
            new List<IHttpUnsuccessfulResponseHandler>();

        /// <summary>A list of <see cref="IHttpExceptionHandler"/>.</summary>
        private readonly IList<IHttpExceptionHandler> exceptionHandlers =
            new List<IHttpExceptionHandler>();

        /// <summary>A list of <see cref="IHttpExecuteInterceptor"/>.</summary>
        private readonly IList<IHttpExecuteInterceptor> executeInterceptors =
            new List<IHttpExecuteInterceptor>();

        /// <summary>
        /// Gets a list of <see cref="IHttpUnsuccessfulResponseHandler"/>s.
        /// <remarks>
        /// Since version 1.10, <see cref="AddUnsuccessfulResponseHandler"/> and
        /// <see cref="RemoveUnsuccessfulResponseHandler"/> were added in order to keep this class thread-safe.
        /// More information is available on
        /// <a href="https://github.com/google/google-api-dotnet-client/issues/592">#592</a>.
        /// </remarks>
        /// </summary>
        [Obsolete("Use AddUnsuccessfulResponseHandler or RemoveUnsuccessfulResponseHandler instead.")]
        public IList<IHttpUnsuccessfulResponseHandler> UnsuccessfulResponseHandlers
        {
            get { return unsuccessfulResponseHandlers; }
        }

        /// <summary>Adds the specified handler to the list of unsuccessful response handlers.</summary>
        public void AddUnsuccessfulResponseHandler(IHttpUnsuccessfulResponseHandler handler)
        {
            lock (unsuccessfulResponseHandlersLock)
            {
                unsuccessfulResponseHandlers.Add(handler);
            }
        }

        /// <summary>Removes the specified handler from the list of unsuccessful response handlers.</summary>
        public void RemoveUnsuccessfulResponseHandler(IHttpUnsuccessfulResponseHandler handler)
        {
            lock (unsuccessfulResponseHandlersLock)
            {
                unsuccessfulResponseHandlers.Remove(handler);
            }
        }

        /// <summary>
        /// Gets a list of <see cref="IHttpExceptionHandler"/>s.
        /// <remarks>
        /// Since version 1.10, <see cref="AddExceptionHandler"/> and <see cref="RemoveExceptionHandler"/> were added
        /// in order to keep this class thread-safe.  More information is available on
        /// <a href="https://github.com/google/google-api-dotnet-client/issues/592">#592</a>.
        /// </remarks>
        /// </summary>
        [Obsolete("Use AddExceptionHandler or RemoveExceptionHandler instead.")]
        public IList<IHttpExceptionHandler> ExceptionHandlers
        {
            get { return exceptionHandlers; }
        }

        /// <summary>Adds the specified handler to the list of exception handlers.</summary>
        public void AddExceptionHandler(IHttpExceptionHandler handler)
        {
            lock (exceptionHandlersLock)
            {
                exceptionHandlers.Add(handler);
            }
        }

        /// <summary>Removes the specified handler from the list of exception handlers.</summary>
        public void RemoveExceptionHandler(IHttpExceptionHandler handler)
        {
            lock (exceptionHandlersLock)
            {
                exceptionHandlers.Remove(handler);
            }
        }

        /// <summary>
        /// Gets a list of <see cref="IHttpExecuteInterceptor"/>s.
        /// <remarks>
        /// Since version 1.10, <see cref="AddExecuteInterceptor"/> and <see cref="RemoveExecuteInterceptor"/> were
        /// added in order to keep this class thread-safe.  More information is available on
        /// <a href="https://github.com/google/google-api-dotnet-client/issues/592">#592</a>.
        /// </remarks>
        /// </summary>
        [Obsolete("Use AddExecuteInterceptor or RemoveExecuteInterceptor instead.")]
        public IList<IHttpExecuteInterceptor> ExecuteInterceptors
        {
            get { return executeInterceptors; }
        }

        /// <summary>Adds the specified interceptor to the list of execute interceptors.</summary>
        public void AddExecuteInterceptor(IHttpExecuteInterceptor interceptor)
        {
            lock (executeInterceptorsLock)
            {
                executeInterceptors.Add(interceptor);
            }
        }

        /// <summary>Removes the specified interceptor from the list of execute interceptors.</summary>
        public void RemoveExecuteInterceptor(IHttpExecuteInterceptor interceptor)
        {
            lock (executeInterceptorsLock)
            {
                executeInterceptors.Remove(interceptor);
            }
        }

        #endregion

        private int _loggingRequestId = 0;

        private ILogger _instanceLogger = Logger;

        /// <summary>
        /// For testing only.
        /// This defaults to the static <see cref="Logger"/>, but can be overridden for fine-grain testing. 
        /// </summary>
        internal ILogger InstanceLogger
        {
            get { return _instanceLogger; }
            set { _instanceLogger = value.ForType<ConfigurableMessageHandler>(); }
        }

        /// <summary>Number of tries. Default is <c>3</c>.</summary>
        private int numTries = 3;

        /// <summary>
        /// Gets or sets the number of tries that will be allowed to execute. Retries occur as a result of either
        /// <see cref="IHttpUnsuccessfulResponseHandler"/> or <see cref="IHttpExceptionHandler"/> which handles the
        /// abnormal HTTP response or exception before being terminated. 
        /// Set <c>1</c> for not retrying requests. The default value is <c>3</c>.
        /// <remarks>
        /// The number of allowed redirects (3xx) is defined by <see cref="NumRedirects"/>. This property defines
        /// only the allowed tries for >=400 responses, or when an exception is thrown. For example if you set 
        /// <see cref="NumTries"/> to 1 and <see cref="NumRedirects"/> to 5, the library will send up to five redirect
        /// requests, but will not send any retry requests due to an error HTTP status code.
        /// </remarks>
        /// </summary>
        public int NumTries
        {
            get { return numTries; }
            set
            {
                if (value > MaxAllowedNumTries || value < 1)
                {
                    throw new ArgumentOutOfRangeException("NumTries");
                }
                numTries = value;
            }
        }

        /// <summary>Number of redirects allowed. Default is <c>10</c>.</summary>
        private int numRedirects = 10;

        /// <summary>
        /// Gets or sets the number of redirects that will be allowed to execute. The default value is <c>10</c>.
        /// See <see cref="NumTries"/> for more information.
        /// </summary>
        public int NumRedirects
        {
            get { return numRedirects; }
            set
            {
                if (value > MaxAllowedNumTries || value < 1)
                {
                    throw new ArgumentOutOfRangeException("NumRedirects");
                }
                numRedirects = value;
            }
        }

        /// <summary>
        /// Gets or sets whether the handler should follow a redirect when a redirect response is received. Default 
        /// value is <c>true</c>.
        /// </summary>
        public bool FollowRedirect { get; set; }

        /// <summary>Gets or sets whether logging is enabled. Default value is <c>true</c>.</summary>
        public bool IsLoggingEnabled { get; set; }

        /// <summary>
        /// Specifies the type(s) of request/response events to log.
        /// </summary>
        [Flags]
        public enum LogEventType
        {
            /// <summary>
            /// Log no request/response information.
            /// </summary>
            None = 0,

            /// <summary>
            /// Log the request URI.
            /// </summary>
            RequestUri = 1,

            /// <summary>
            /// Log the request headers.
            /// </summary>
            RequestHeaders = 2,

            /// <summary>
            /// Log the request body. The body is assumed to be ASCII, and non-printable charaters are replaced by '.'.
            /// Warning: This causes the body content to be buffered in memory, so use with care for large requests.
            /// </summary>
            RequestBody = 4,

            /// <summary>
            /// Log the response status.
            /// </summary>
            ResponseStatus = 8,

            /// <summary>
            /// Log the response headers.
            /// </summary>
            ResponseHeaders = 16,

            /// <summary>
            /// Log the response body. The body is assumed to be ASCII, and non-printable characters are replaced by '.'.
            /// Warning: This causes the body content to be buffered in memory, so use with care for large responses.
            /// </summary>
            ResponseBody = 32,

            /// <summary>
            /// Log abnormal response messages.
            /// </summary>
            ResponseAbnormal = 64,
        }

        /// <summary>
        /// The request/response types to log.
        /// </summary>
        public LogEventType LogEvents { get; set; }

        /// <summary>Gets or sets the application name which will be used on the User-Agent header.</summary>
        public string ApplicationName { get; set; }

        /// <summary>Gets or sets the value set for the x-goog-api-client header.</summary>
        public string GoogleApiClientHeader { get; set; }

        /// <summary>
        /// The credential to apply to all requests made with this client,
        /// unless theres a specific call credential set.
        /// If <see cref="Credential"/> implements <see cref="IHttpUnsuccessfulResponseHandler"/>
        /// then it will also be included as a handler of an unsuccessful response.
        /// </summary>
        public IHttpExecuteInterceptor Credential { get; set; }

        /// <summary>
        /// The universe domain to include as an option in the request.
        /// This may be used by the <see cref="Credential"/> to validate against its own universe domain.
        /// May be null, in which case no universe domain will be included in the request.
        /// </summary>
        public string UniverseDomain { get; set; }

        /// <summary>Constructs a new configurable message handler.</summary>
        public ConfigurableMessageHandler(HttpMessageHandler httpMessageHandler)
            : base(httpMessageHandler)
        {
            // set default values
            FollowRedirect = true;
            IsLoggingEnabled = true;
            LogEvents = LogEventType.RequestUri | LogEventType.ResponseStatus | LogEventType.ResponseAbnormal;
        }

        private void LogHeaders(string initialText, HttpHeaders headers1, HttpHeaders headers2)
        {
            var headers = (headers1 ?? Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>())
                .Concat(headers2 ?? Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>()).ToList();
            var args = new object[headers.Count * 2];
            var fmt = new StringBuilder(headers.Count * 32);
            fmt.Append(initialText);
            var argBuilder = new StringBuilder();
            for (int i = 0; i < headers.Count; i++)
            {
                fmt.Append($"\n  [{{{i * 2}}}] '{{{1 + i * 2}}}'");
                args[i * 2] = headers[i].Key;
                argBuilder.Clear();
                args[1 + i * 2] = string.Join("; ", headers[i].Value);
            }
            InstanceLogger.Debug(fmt.ToString(), args);
        }

        private async Task LogBody(string fmtText, HttpContent content)
        {
            // This buffers the body content within the HttpContent if required.
            var bodyBytes = content != null ? await content.ReadAsByteArrayAsync().ConfigureAwait(false) : new byte[0];
            char[] bodyChars = new char[bodyBytes.Length];
            for (int i = 0; i < bodyBytes.Length; i++)
            {
                var b = bodyBytes[i];
                bodyChars[i] = b >= 32 && b <= 126 ? (char) b : '.';
            }
            InstanceLogger.Debug(fmtText, new string(bodyChars));
        }

        /// <summary>
        /// The main logic of sending a request to the server. This send method adds the User-Agent header to a request
        /// with <see cref="ApplicationName"/> and the library version. It also calls interceptors before each attempt,
        /// and unsuccessful response handler or exception handlers when abnormal response or exception occurred.
        /// </summary>
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var loggable = IsLoggingEnabled && InstanceLogger.IsDebugEnabled;
            string loggingRequestId = "";
            if (loggable)
            {
                loggingRequestId = Interlocked.Increment(ref _loggingRequestId).ToString("X8");
            }

            int maxRetries = GetEffectiveMaxRetries(request);
            int triesRemaining = maxRetries;
            int redirectRemaining = NumRedirects;

            Exception lastException = null;

            // Set User-Agent header.
            var userAgent = (ApplicationName == null ? "" : ApplicationName + " ") + UserAgentSuffix;
            // TODO: setting the User-Agent won't work on Silverlight. We may need to create a special callback here to 
            // set it correctly.
            request.Headers.Add("User-Agent", userAgent);
            var apiClientHeader = GoogleApiClientHeader;
            if (apiClientHeader != null)
            {
                request.Headers.Add("x-goog-api-client", apiClientHeader);
            }

            // Set the universe domain as a request option. Credentials may use it to validate it
            // against their own universe domain.
            if (UniverseDomain is not null)
            {
                request.SetOption(UniverseDomainKey, UniverseDomain);
            }

            HttpResponseMessage response = null;
            do // While (triesRemaining > 0)
            {
                response?.Dispose();
                response = null;
                lastException = null;

                // Check after previous response (if any) has been disposed of.
                cancellationToken.ThrowIfCancellationRequested();

                // We keep a local list of the interceptors, since we can't call await inside lock.
                List<IHttpExecuteInterceptor> interceptors;
                lock (executeInterceptorsLock)
                {
                    interceptors = executeInterceptors.ToList();
                }
                if (request.TryGetOption(ExecuteInterceptorKey, out List<IHttpExecuteInterceptor> perCallinterceptors))
                {
                    interceptors.AddRange(perCallinterceptors);
                }

                // Intercept the request.
                foreach (var interceptor in interceptors)
                {
                    await interceptor.InterceptAsync(request, cancellationToken).ConfigureAwait(false);
                }

                // Before having the credential intercept the call, check that quota project hasn't
                // been added as a header. Quota project cannot be added except through the credential.
                CheckValidAfterInterceptors(request);

                await CredentialInterceptAsync(request, cancellationToken).ConfigureAwait(false);

                if (loggable)
                {
                    if ((LogEvents & LogEventType.RequestUri) != 0)
                    {
                        InstanceLogger.Debug("Request[{0}] (triesRemaining={1}) URI: '{2}'", loggingRequestId, triesRemaining, request.RequestUri);
                    }
                    if ((LogEvents & LogEventType.RequestHeaders) != 0)
                    {
                        LogHeaders($"Request[{loggingRequestId}] Headers:", request.Headers, request.Content?.Headers);
                    }
                    if ((LogEvents & LogEventType.RequestBody) != 0)
                    {
                        await LogBody($"Request[{loggingRequestId}] Body: '{{0}}'", request.Content).ConfigureAwait(false);
                    }
                }
                try
                {
                    // Send the request!
                    response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    lastException = ex;
                }

                // Decrease the number of retries.
                if (response == null || ((int) response.StatusCode >= 400 || (int) response.StatusCode < 200))
                {
                    triesRemaining--;
                }

                // Exception was thrown, try to handle it.
                if (response == null)
                {
                    var exceptionHandled = false;

                    // We keep a local list of the handlers, since we can't call await inside lock.
                    List<IHttpExceptionHandler> handlers;
                    lock (exceptionHandlersLock)
                    {
                        handlers = exceptionHandlers.ToList();
                    }
                    if (request.TryGetOption(ExceptionHandlerKey, out List<IHttpExceptionHandler> perCallHandlers))
                    {
                        handlers.AddRange(perCallHandlers);
                    }

                    // Try to handle the exception with each handler.
                    foreach (var handler in handlers)
                    {
                        exceptionHandled |= await handler.HandleExceptionAsync(new HandleExceptionArgs
                        {
                            Request = request,
                            Exception = lastException,
                            TotalTries = maxRetries,
                            CurrentFailedTry = maxRetries - triesRemaining,
                            CancellationToken = cancellationToken
                        }).ConfigureAwait(false);
                    }

                    if (!exceptionHandled)
                    {
                        InstanceLogger.Error(lastException,
                            "Response[{0}] Exception was thrown while executing a HTTP request and it wasn't handled", loggingRequestId);
                        throw lastException;
                    }
                    else if (loggable && (LogEvents & LogEventType.ResponseAbnormal) != 0)
                    {
                        InstanceLogger.Debug("Response[{0}] Exception {1} was thrown, but it was handled by an exception handler",
                            loggingRequestId, lastException.Message);
                    }
                }
                else
                {
                    if (loggable)
                    {
                        if ((LogEvents & LogEventType.ResponseStatus) != 0)
                        {
                            InstanceLogger.Debug("Response[{0}] Response status: {1} '{2}'", loggingRequestId, response.StatusCode, response.ReasonPhrase);
                        }
                        if ((LogEvents & LogEventType.ResponseHeaders) != 0)
                        {
                            LogHeaders($"Response[{loggingRequestId}] Headers:", response.Headers, response.Content?.Headers);
                        }
                        if ((LogEvents & LogEventType.ResponseBody) != 0)
                        {
                            await LogBody($"Response[{loggingRequestId}] Body: '{{0}}'", response.Content).ConfigureAwait(false);
                        }
                    }
                    if (response.IsSuccessStatusCode)
                    {
                        // No need to retry, the response was successful.
                        triesRemaining = 0;
                    }
                    else
                    {
                        bool errorHandled = false;

                        // We keep a local list of the handlers, since we can't call await inside lock.
                        List<IHttpUnsuccessfulResponseHandler> handlers;
                        lock (unsuccessfulResponseHandlersLock)
                        {
                            handlers = unsuccessfulResponseHandlers.ToList();
                        }
                        if (request.TryGetOption(UnsuccessfulResponseHandlerKey, out List<IHttpUnsuccessfulResponseHandler> perCallHandlers))
                        {
                            handlers.AddRange(perCallHandlers);
                        }

                        var handlerArgs = new HandleUnsuccessfulResponseArgs
                        {
                            Request = request,
                            Response = response,
                            TotalTries = maxRetries,
                            CurrentFailedTry = maxRetries - triesRemaining,
                            CancellationToken = cancellationToken
                        };

                        // Try to handle the abnormal HTTP response with each handler.
                        foreach (var handler in handlers)
                        {
                            try
                            {
                                errorHandled |= await handler.HandleResponseAsync(handlerArgs).ConfigureAwait(false);
                            }
                            catch when (DisposeAndReturnFalse(response)) { }

                            bool DisposeAndReturnFalse(IDisposable disposable)
                            {
                                disposable.Dispose();
                                return false;
                            }
                        }

                        errorHandled |= await CredentialHandleResponseAsync(handlerArgs).ConfigureAwait(false);

                        if (!errorHandled)
                        {
                            if (FollowRedirect && HandleRedirect(response))
                            {
                                if (redirectRemaining-- == 0)
                                {
                                    triesRemaining = 0;
                                }

                                errorHandled = true;
                                if (loggable && (LogEvents & LogEventType.ResponseAbnormal) != 0)
                                {
                                    InstanceLogger.Debug("Response[{0}] Redirect response was handled successfully. Redirect to {1}",
                                        loggingRequestId, response.Headers.Location);
                                }
                            }
                            else
                            {
                                if (loggable && (LogEvents & LogEventType.ResponseAbnormal) != 0)
                                {
                                    InstanceLogger.Debug("Response[{0}] An abnormal response wasn't handled. Status code is {1}",
                                        loggingRequestId, response.StatusCode);
                                }

                                // No need to retry, because no handler handled the abnormal response.
                                triesRemaining = 0;
                            }
                        }
                        else if (loggable && (LogEvents & LogEventType.ResponseAbnormal) != 0)
                        {
                            InstanceLogger.Debug("Response[{0}] An abnormal response was handled by an unsuccessful response handler. " +
                                "Status Code is {1}", loggingRequestId, response.StatusCode);
                        }
                    }
                }
            } while (triesRemaining > 0); // Not a successful status code but it was handled.

            // If the response is null, we should throw the last exception.
            if (response == null)
            {
                InstanceLogger.Error(lastException, "Request[{0}] Exception was thrown while executing a HTTP request", loggingRequestId);
                throw lastException;
            }
            else if (!response.IsSuccessStatusCode && loggable && (LogEvents & LogEventType.ResponseAbnormal) != 0)
            {
                InstanceLogger.Debug("Response[{0}] Abnormal response is being returned. Status Code is {1}", loggingRequestId, response.StatusCode);
            }

            return response;
        }

        private void CheckValidAfterInterceptors(HttpRequestMessage request)
        {
            if (request.Headers.Contains(QuotaProjectHeaderName))
            {
                throw new InvalidOperationException($"{QuotaProjectHeaderName} header can only be added through the credential or through the <Product>ClientBuilder.");
            }
        }

        private async Task CredentialInterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var effectiveCredential = GetEffectiveCredential(request);
            if (effectiveCredential != null)
            {
                await effectiveCredential.InterceptAsync(request, cancellationToken).ConfigureAwait(false);
            }
        }

        private async Task<bool> CredentialHandleResponseAsync(HandleUnsuccessfulResponseArgs args)
        {
            var effectiveCredential = GetEffectiveCredential(args.Request);
            if (effectiveCredential is IHttpUnsuccessfulResponseHandler handler)
            {
                return await handler.HandleResponseAsync(args).ConfigureAwait(false);
            }

            return false;
        }

        private IHttpExecuteInterceptor GetEffectiveCredential(HttpRequestMessage request) =>
            request.TryGetOption(CredentialKey, out IHttpExecuteInterceptor callCredential) ? callCredential : Credential;

        private int GetEffectiveMaxRetries(HttpRequestMessage request) =>
            request.TryGetOption(MaxRetriesKey, out int perRequestMaxRetries) ? perRequestMaxRetries : NumTries;

        /// <summary>
        /// Handles redirect if the response's status code is redirect, redirects are turned on, and the header has
        /// a location.
        /// When the status code is <c>303</c> the method on the request is changed to a GET as per the RFC2616 
        /// specification. On a redirect, it also removes the <c>Authorization</c> and all <c>If-*</c> request headers.
        /// </summary>
        /// <returns> Whether this method changed the request and handled redirect successfully. </returns>
        private bool HandleRedirect(HttpResponseMessage message)
        {
            // TODO(peleyal): think if it's better to move that code to RedirectUnsucessfulResponseHandler
            var uri = message.Headers.Location;
            if (!message.IsRedirectStatusCode() || uri == null)
            {
                return false;
            }

            var request = message.RequestMessage;
            request.RequestUri = new Uri(request.RequestUri, uri);
            // Status code for a resource that has moved to a new URI and should be retrieved using GET.
            if (message.StatusCode == HttpStatusCode.SeeOther)
            {
                request.Method = HttpMethod.Get;
            }
            // Clear Authorization and If-* headers.
            request.Headers.Remove("Authorization");
            request.Headers.IfMatch.Clear();
            request.Headers.IfNoneMatch.Clear();
            request.Headers.IfModifiedSince = null;
            request.Headers.IfUnmodifiedSince = null;
            request.Headers.Remove("If-Range");
            return true;
        }
    }
}