/*
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 System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Logging;
using Google.Apis.Util;
namespace Google.Apis.Http
{
///
/// A thread-safe back-off handler which handles an abnormal HTTP response or an exception with
/// .
///
public class BackOffHandler : IHttpUnsuccessfulResponseHandler, IHttpExceptionHandler
{
private static readonly ILogger Logger = ApplicationContext.Logger.ForType();
/// An initializer class to initialize a back-off handler.
public class Initializer
{
/// Gets the back-off policy used by this back-off handler.
public IBackOff BackOff { get; private set; }
///
/// Gets or sets the maximum time span to wait. If the back-off instance returns a greater time span than
/// this value, this handler returns false to both HandleExceptionAsync and
/// HandleResponseAsync. Default value is 16 seconds per a retry request.
///
public TimeSpan MaxTimeSpan { get; set; }
///
/// Gets or sets a delegate function which indicates whether this back-off handler should handle an
/// abnormal HTTP response. The default is .
///
public Func HandleUnsuccessfulResponseFunc { get; set; }
///
/// Gets or sets a delegate function which indicates whether this back-off handler should handle an
/// exception. The default is .
///
public Func HandleExceptionFunc { get; set; }
/// Default function which handles server errors (503).
public static readonly Func DefaultHandleUnsuccessfulResponseFunc =
(r) => (int)r.StatusCode == 503;
///
/// Default function which handles exception which aren't
/// or
/// . Those exceptions represent a task or an operation
/// which was canceled and shouldn't be retried.
///
public static readonly Func DefaultHandleExceptionFunc =
(ex) => !(ex is TaskCanceledException || ex is OperationCanceledException);
/// Constructs a new initializer by the given back-off.
public Initializer(IBackOff backOff)
{
BackOff = backOff;
HandleExceptionFunc = DefaultHandleExceptionFunc;
HandleUnsuccessfulResponseFunc = DefaultHandleUnsuccessfulResponseFunc;
MaxTimeSpan = TimeSpan.FromSeconds(16);
}
}
/// Gets the back-off policy used by this back-off handler.
public IBackOff BackOff { get; private set; }
///
/// Gets the maximum time span to wait. If the back-off instance returns a greater time span, the handle method
/// returns false. Default value is 16 seconds per a retry request.
///
public TimeSpan MaxTimeSpan { get; private set; }
///
/// Gets a delegate function which indicates whether this back-off handler should handle an abnormal HTTP
/// response. The default is .
///
public Func HandleUnsuccessfulResponseFunc { get; private set; }
///
/// Gets a delegate function which indicates whether this back-off handler should handle an exception. The
/// default is .
///
public Func HandleExceptionFunc { get; private set; }
/// Constructs a new back-off handler with the given back-off.
/// The back-off policy.
public BackOffHandler(IBackOff backOff)
: this(new Initializer(backOff))
{
}
/// Constructs a new back-off handler with the given initializer.
public BackOffHandler(Initializer initializer)
{
BackOff = initializer.BackOff;
MaxTimeSpan = initializer.MaxTimeSpan;
HandleExceptionFunc = initializer.HandleExceptionFunc;
HandleUnsuccessfulResponseFunc = initializer.HandleUnsuccessfulResponseFunc;
}
#region IHttpUnsuccessfulResponseHandler
///
public virtual async Task HandleResponseAsync(HandleUnsuccessfulResponseArgs args)
{
// if the func returns true try to handle this current failed try
if (HandleUnsuccessfulResponseFunc != null && HandleUnsuccessfulResponseFunc(args.Response))
{
return await HandleAsync(args.SupportsRetry, args.CurrentFailedTry, args.CancellationToken)
.ConfigureAwait(false);
}
return false;
}
#endregion
#region IHttpExceptionHandler
///
public virtual async Task HandleExceptionAsync(HandleExceptionArgs args)
{
// if the func returns true try to handle this current failed try
if (HandleExceptionFunc != null && HandleExceptionFunc(args.Exception))
{
return await HandleAsync(args.SupportsRetry, args.CurrentFailedTry, args.CancellationToken)
.ConfigureAwait(false);
}
return false;
}
#endregion
///
/// Handles back-off. In case the request doesn't support retry or the back-off time span is greater than the
/// maximum time span allowed for a request, the handler returns false. Otherwise the current thread
/// will block for x milliseconds (x is defined by the instance), and this handler
/// returns true.
///
private async Task HandleAsync(bool supportsRetry, int currentFailedTry,
CancellationToken cancellationToken)
{
if (!supportsRetry || BackOff.MaxNumOfRetries < currentFailedTry)
{
return false;
}
TimeSpan ts = BackOff.GetNextBackOff(currentFailedTry);
if (ts > MaxTimeSpan || ts < TimeSpan.Zero)
{
return false;
}
await Wait(ts, cancellationToken).ConfigureAwait(false);
Logger.Debug("Back-Off handled the error. Waited {0}ms before next retry...", ts.TotalMilliseconds);
return true;
}
/// Waits the given time span. Overriding this method is recommended for mocking purposes.
/// TimeSpan to wait (and block the current thread).
/// The cancellation token in case the user wants to cancel the operation in
/// the middle.
protected virtual async Task Wait(TimeSpan ts, CancellationToken cancellationToken)
{
await Task.Delay(ts, cancellationToken).ConfigureAwait(false);
}
}
}