BatchInProgressErrorPolicyFactory
using Polly;
using Relativity.Logging;
using System;
using System.Threading.Tasks;
namespace Relativity.DataExchange.Service
{
public class BatchInProgressErrorPolicyFactory : IKeplerRetryPolicyFactory
{
private readonly IAppSettings settings;
private readonly ILog logger;
private readonly Action<Exception, TimeSpan, int, Context> onRetry;
public BatchInProgressErrorPolicyFactory(IAppSettings settings, ILog logger)
{
this.settings = settings;
this.logger = logger;
}
public BatchInProgressErrorPolicyFactory(IAppSettings settings, ILog logger, Action<Exception, TimeSpan, int, Context> onRetry)
{
this.settings = settings;
this.logger = logger;
this.onRetry = onRetry;
}
public IAsyncPolicy CreateRetryPolicy()
{
return RetrySyntaxAsync.WaitAndRetryAsync(Policy.Handle<Exception>((Func<Exception, bool>)IsRetryableException), settings.BatchInProgressNumberOfRetries, (Func<int, TimeSpan>)((int retryAttempt) => TimeSpan.FromSeconds((double)settings.BatchInProgressWaitTimeInSeconds)), (Func<Exception, TimeSpan, int, Context, Task>)OnRetry);
}
public IAsyncPolicy<T> CreateRetryPolicy<T>()
{
return RetryTResultSyntaxAsync.WaitAndRetryAsync<T>(Policy<Exception>.Handle<Exception>((Func<Exception, bool>)IsRetryableException), settings.BatchInProgressNumberOfRetries, (Func<int, TimeSpan>)((int retryAttempt) => TimeSpan.FromSeconds((double)settings.BatchInProgressWaitTimeInSeconds)), (Func<DelegateResult<T>, TimeSpan, int, Context, Task>)this.OnRetry<T>);
}
private bool IsRetryableException(Exception exception)
{
bool flag = ExceptionHelper.IsBatchInProgressException(exception);
return (exception.GetType() == typeof(TaskCanceledException)) | flag;
}
private Task OnRetry<TResult>(DelegateResult<TResult> result, TimeSpan timeSpan, int retryCount, Context context)
{
return OnRetry(result.get_Exception(), timeSpan, retryCount, context);
}
private Task OnRetry(Exception exception, TimeSpan duration, int retryCount, Context context)
{
if (onRetry == null)
logger.LogWarning(exception, "BatchInProgressErrorPolicyFactory: Call to Kepler service failed due to {ExceptionType}. Currently on attempt {RetryCount} out of {MaxRetries} and waiting {WaitSeconds} seconds before the next retry attempt.", new object[4] {
exception.GetType(),
retryCount,
settings.BatchInProgressNumberOfRetries,
duration.TotalSeconds
});
else
onRetry(exception, duration, retryCount, context);
return Task.CompletedTask;
}
}
}