diff --git a/Directory.Packages.props b/Directory.Packages.props
index 3dbdea9a1b..2bebf56d64 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -140,8 +140,6 @@
-
-
diff --git a/docs/en/release-info/migration-guides/abp-11-0.md b/docs/en/release-info/migration-guides/abp-11-0.md
new file mode 100644
index 0000000000..03a3fc4868
--- /dev/null
+++ b/docs/en/release-info/migration-guides/abp-11-0.md
@@ -0,0 +1,75 @@
+```json
+//[doc-seo]
+{
+ "Description": "Upgrade your ABP solutions from v10.x to v11.0 with this migration guide covering important behavior and integration changes."
+}
+```
+
+# ABP Version 11.0 Migration Guide
+
+This document is a guide for upgrading ABP v10.x solutions to ABP v11.0. There are some changes in this version that may affect your applications. Please read them carefully and apply the necessary changes to your application.
+
+> **Package Version Changes:** Before upgrading, review the [Package Version Changes](../../package-version-changes.md) document to see version changes on dependent NuGet and NPM packages and align your project with ABP's internal package versions.
+
+## Open-Source (Framework)
+
+This version contains the following changes on the open-source side:
+
+### Polly Is No Longer Referenced
+
+**Who is affected**
+
+- Applications that use Polly in their own code without referencing the `Polly` package themselves, and get it through one of the ABP packages below.
+
+**What changed**
+
+- ABP retries its own HTTP requests and file operations with `Volo.Abp.Threading.RetryHelper`, so these packages no longer reference `Polly`:
+
+| Package | Removed reference |
+|---------|-------------------|
+| Volo.Abp.BlobStoring.FileSystem | Polly |
+| Volo.Abp.Cli.Core | Polly, Polly.Extensions.Http |
+| Volo.Abp.FeatureManagement.Domain | Polly |
+| Volo.Abp.PermissionManagement.Domain | Polly |
+| Volo.Abp.SettingManagement.Domain | Polly |
+
+- The number of attempts, the delays between them and the failures that are retried are unchanged in all of them.
+- No ABP API takes or returns a Polly type, so nothing else changes for an application that does not use Polly itself.
+
+**What to do**
+
+Reference the package in the projects that use it. `abp update` rewrites `Volo.*` references only, so it does not add this one. ABP referenced Polly 8.6.3 up to v10.7, so that version keeps the behavior you had:
+
+```xml
+
+```
+
+`RetryHelper` is an alternative if you use Polly only to retry a failing call:
+
+```csharp
+await RetryHelper.ExecuteAsync(
+ async cancellationToken => await httpClient.GetAsync(url, cancellationToken),
+ new RetryOptions
+ {
+ MaxRetryCount = 3,
+ ShouldRetryOnResult = response => !response.IsSuccessStatusCode
+ });
+```
+
+## Pro
+
+This version contains the following changes on the PRO side:
+
+### Polly Is No Longer Referenced
+
+**Who is affected**
+
+- Applications that use Polly in their own code without referencing the `Polly` package themselves, and get it through `Volo.Abp.LanguageManagement.Domain` or `Volo.Abp.TextTemplateManagement.Domain`.
+
+**What changed**
+
+- Both packages retry with `Volo.Abp.Threading.RetryHelper` instead of Polly and no longer reference it. The number of attempts, the delays between them and the failures that are retried are unchanged.
+
+**What to do**
+
+Reference the `Polly` package in the projects that use it, as described in the open-source section above.
diff --git a/docs/en/release-info/migration-guides/index.md b/docs/en/release-info/migration-guides/index.md
index 772a7b09f1..3965c6c9a2 100644
--- a/docs/en/release-info/migration-guides/index.md
+++ b/docs/en/release-info/migration-guides/index.md
@@ -9,6 +9,7 @@
The following documents explain how to migrate your existing ABP applications. We write migration documents only if you need to take an action while upgrading your solution. Otherwise, you can easily upgrade your solution using the [abp update command](../upgrading.md).
+- [10.x to 11.0](abp-11-0.md)
- [10.6 to 10.7](abp-10-7.md)
- [10.5 to 10.6](abp-10-6.md)
- [10.4 to 10.5](abp-10-5.md)
diff --git a/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo.Abp.BlobStoring.FileSystem.csproj b/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo.Abp.BlobStoring.FileSystem.csproj
index 38be0da5ae..76c01d33da 100644
--- a/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo.Abp.BlobStoring.FileSystem.csproj
+++ b/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo.Abp.BlobStoring.FileSystem.csproj
@@ -18,7 +18,6 @@
-
diff --git a/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobProvider.cs b/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobProvider.cs
index 75edbc2ac9..9ce41a5f00 100644
--- a/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobProvider.cs
+++ b/framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobProvider.cs
@@ -1,9 +1,9 @@
using System;
using System.IO;
using System.Threading.Tasks;
-using Polly;
using Volo.Abp.DependencyInjection;
using Volo.Abp.IO;
+using Volo.Abp.Threading;
namespace Volo.Abp.BlobStoring.FileSystem;
@@ -48,9 +48,8 @@ public class FileSystemBlobProvider : BlobProviderBase, ITransientDependency
var targetOpened = false;
- await Policy.Handle(_ => sourcePosition >= 0 || !targetOpened)
- .WaitAndRetryAsync(2, retryCount => TimeSpan.FromSeconds(retryCount))
- .ExecuteAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ async _ =>
{
if (sourcePosition >= 0)
{
@@ -68,6 +67,12 @@ public class FileSystemBlobProvider : BlobProviderBase, ITransientDependency
await fileStream.FlushAsync();
}
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 2,
+ DelayFactory = retryCount => TimeSpan.FromSeconds(retryCount),
+ ShouldRetryOnException = ex => ex is IOException && (sourcePosition >= 0 || !targetOpened)
});
}
@@ -92,9 +97,14 @@ public class FileSystemBlobProvider : BlobProviderBase, ITransientDependency
return null;
}
- return await Policy.Handle()
- .WaitAndRetryAsync(2, retryCount => TimeSpan.FromSeconds(retryCount))
- .ExecuteAsync(() => Task.FromResult(File.OpenRead(filePath)));
+ return await RetryHelper.ExecuteAsync(
+ _ => Task.FromResult(File.OpenRead(filePath)),
+ new RetryOptions
+ {
+ MaxRetryCount = 2,
+ DelayFactory = retryCount => TimeSpan.FromSeconds(retryCount),
+ ShouldRetryOnException = ex => ex is IOException
+ });
}
protected virtual Stream OpenFileStream(string filePath, FileMode fileMode)
diff --git a/framework/src/Volo.Abp.Cli.Core/Volo.Abp.Cli.Core.csproj b/framework/src/Volo.Abp.Cli.Core/Volo.Abp.Cli.Core.csproj
index 23cb5c2b33..d73bda8303 100644
--- a/framework/src/Volo.Abp.Cli.Core/Volo.Abp.Cli.Core.csproj
+++ b/framework/src/Volo.Abp.Cli.Core/Volo.Abp.Cli.Core.csproj
@@ -19,8 +19,6 @@
-
-
diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs
index f6da2e46e4..fa9411c83e 100644
--- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs
+++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs
@@ -1,14 +1,14 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Duende.IdentityModel.Client;
-using Polly;
-using Polly.Extensions.Http;
using Volo.Abp.Cli.Auth;
+using Volo.Abp.Threading;
using Microsoft.Extensions.Logging;
namespace Volo.Abp.Cli.Http;
@@ -55,29 +55,32 @@ public static class CliHttpClientExtensions
cancellationToken = cancellationTokenSource.Token;
}
- return await HttpPolicyExtensions
- .HandleTransientHttpError()
- .OrResult(msg => !msg.IsSuccessStatusCode)
- .WaitAndRetryAsync(sleepDurations,
- (responseMessage, timeSpan, retryCount, context) =>
+ var delays = sleepDurations.ToArray();
+
+ return await RetryHelper.ExecuteAsync(
+ _ => httpClient.GetAsync(url, cancellationToken.Value),
+ new RetryOptions
+ {
+ MaxRetryCount = delays.Length,
+ DelayFactory = retryCount => delays[retryCount - 1],
+ ShouldRetryOnException = exception => exception is HttpRequestException,
+ ShouldRetryOnResult = response => !response.IsSuccessStatusCode,
+ OnRetry = attempt =>
{
- if (responseMessage.Exception != null)
+ if (attempt.Exception != null)
{
- string httpErrorCode = responseMessage.Result == null ?
- httpErrorCode = string.Empty :
- "HTTP-" + (int)responseMessage.Result.StatusCode + ", ";
-
logger?.LogWarning(
- $"{retryCount}. HTTP request attempt failed to {url} with an error: {httpErrorCode}{responseMessage.Exception.Message}. " +
- $"Waiting {timeSpan.TotalSeconds} secs for the next try...");
+ $"{attempt.RetryCount}. HTTP request attempt failed to {url} with an error: {attempt.Exception.Message}. " +
+ $"Waiting {attempt.RetryDelay.TotalSeconds} secs for the next try...");
}
- else if (responseMessage.Result != null)
+ else if (attempt.Result != null)
{
logger?.LogWarning(
- $"{retryCount}. HTTP request attempt failed to {url} with an error: {(int)responseMessage.Result.StatusCode}-{responseMessage.Result.ReasonPhrase}. " +
- $"Waiting {timeSpan.TotalSeconds} secs for the next try...");
+ $"{attempt.RetryCount}. HTTP request attempt failed to {url} with an error: {(int)attempt.Result.StatusCode}-{attempt.Result.ReasonPhrase}. " +
+ $"Waiting {attempt.RetryDelay.TotalSeconds} secs for the next try...");
}
- })
- .ExecuteAsync(async () => await httpClient.GetAsync(url, cancellationToken.Value));
+ return Task.CompletedTask;
+ }
+ });
}
}
diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryAttempt.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryAttempt.cs
new file mode 100644
index 0000000000..32afaad23b
--- /dev/null
+++ b/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryAttempt.cs
@@ -0,0 +1,49 @@
+using System;
+
+namespace Volo.Abp.Threading;
+
+///
+/// A failed attempt that is about to retry.
+///
+public class RetryAttempt
+{
+ ///
+ /// Number of the retry that is about to be performed, starting from 1.
+ ///
+ public int RetryCount { get; }
+
+ ///
+ /// How long to wait before the retry.
+ ///
+ public TimeSpan RetryDelay { get; }
+
+ ///
+ /// The exception that caused the retry. Null if the attempt is retried because of its result.
+ ///
+ public Exception? Exception { get; }
+
+ public RetryAttempt(int retryCount, TimeSpan retryDelay, Exception? exception)
+ {
+ RetryCount = retryCount;
+ RetryDelay = retryDelay;
+ Exception = exception;
+ }
+}
+
+///
+/// A failed attempt that is about to retry.
+///
+/// Type of the value returned by the retried action.
+public class RetryAttempt : RetryAttempt
+{
+ ///
+ /// The result that caused the retry. Default if the attempt is retried because of an exception.
+ ///
+ public TResult? Result { get; }
+
+ public RetryAttempt(int retryCount, TimeSpan retryDelay, Exception? exception, TResult? result)
+ : base(retryCount, retryDelay, exception)
+ {
+ Result = result;
+ }
+}
diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryHelper.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryHelper.cs
new file mode 100644
index 0000000000..e6e6747d0c
--- /dev/null
+++ b/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryHelper.cs
@@ -0,0 +1,232 @@
+using System;
+using System.Runtime.ExceptionServices;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Volo.Abp.Threading;
+
+///
+/// Runs an action and retries it while it keeps failing, waiting between the attempts.
+/// See to control the retry count, the delay and which failures are retried.
+///
+public static class RetryHelper
+{
+ // Task.Delay rejects a longer delay on the netstandard targets.
+ private static readonly TimeSpan MaxDelay = TimeSpan.FromMilliseconds(int.MaxValue);
+
+ ///
+ /// Runs the given action and retries it while it throws a retryable exception.
+ /// Rethrows the last exception when the retries are exhausted.
+ ///
+ public static async Task ExecuteAsync(
+ Func action,
+ RetryOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ Check.NotNull(action, nameof(action));
+
+ options ??= new RetryOptions();
+
+ // Read once, so that changing a shared instance cannot affect a running execution.
+ var maxRetryCount = options.MaxRetryCount;
+ var delayFactory = options.DelayFactory;
+ var shouldRetryOnException = options.ShouldRetryOnException;
+ var onRetry = options.OnRetry;
+
+ Validate(maxRetryCount, delayFactory, shouldRetryOnException);
+
+ var retryCount = 0;
+
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Exception? caught = null;
+
+ try
+ {
+ await action(cancellationToken);
+ return;
+ }
+ catch (Exception ex)
+ {
+ caught = ex;
+ }
+
+ var exception = caught!;
+
+ // Asked on every attempt, including the last one, which is not retried.
+ var isHandled = shouldRetryOnException(exception);
+
+ if (!isHandled || IsLastRetry(retryCount, maxRetryCount))
+ {
+ ExceptionDispatchInfo.Capture(exception).Throw();
+ }
+
+ retryCount = NextRetryCount(retryCount);
+
+ var delay = GetDelay(delayFactory, retryCount);
+ if (onRetry != null)
+ {
+ await onRetry(new RetryAttempt(retryCount, delay, exception));
+ }
+
+ await WaitAsync(delay, cancellationToken);
+ }
+ }
+
+ ///
+ /// Runs the given action and retries it while it throws a retryable exception or returns a retryable result.
+ /// Rethrows the last exception when the retries are exhausted, or returns the result of the last attempt
+ /// if it failed because of its result. A retried result is disposed if it is disposable.
+ ///
+ public static async Task ExecuteAsync(
+ Func> action,
+ RetryOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ Check.NotNull(action, nameof(action));
+
+ options ??= new RetryOptions();
+
+ // Read once, so that changing a shared instance cannot affect a running execution.
+ var maxRetryCount = options.MaxRetryCount;
+ var delayFactory = options.DelayFactory;
+ var shouldRetryOnException = options.ShouldRetryOnException;
+ var shouldRetryOnResult = options.ShouldRetryOnResult;
+ var onRetry = options.OnRetry;
+
+ Validate(maxRetryCount, delayFactory, shouldRetryOnException);
+ Check.NotNull(shouldRetryOnResult, nameof(RetryOptions.ShouldRetryOnResult));
+
+ var retryCount = 0;
+
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Exception? exception = null;
+ var result = default(TResult)!;
+ var hasResult = false;
+
+ try
+ {
+ result = await action(cancellationToken);
+ hasResult = true;
+
+ if (!shouldRetryOnResult(result))
+ {
+ return result;
+ }
+ }
+ catch (Exception ex)
+ {
+ exception = ex;
+ }
+
+ // Asked on every attempt, including the last one, which is not retried.
+ var isUnhandledException = exception != null && !shouldRetryOnException(exception);
+
+ if (isUnhandledException || IsLastRetry(retryCount, maxRetryCount))
+ {
+ if (exception != null)
+ {
+ // The caller never sees this result, so it must not leak.
+ if (hasResult)
+ {
+ await TryDisposeAsync(result);
+ }
+
+ ExceptionDispatchInfo.Capture(exception).Throw();
+ }
+
+ return result;
+ }
+
+ retryCount = NextRetryCount(retryCount);
+
+ var delay = GetDelay(delayFactory, retryCount);
+ if (onRetry != null)
+ {
+ await onRetry(new RetryAttempt(retryCount, delay, exception, exception == null ? result : default));
+ }
+
+ if (hasResult)
+ {
+ await TryDisposeAsync(result);
+ }
+
+ await WaitAsync(delay, cancellationToken);
+ }
+ }
+
+ private static void Validate(
+ int maxRetryCount,
+ Func delayFactory,
+ Func shouldRetryOnException)
+ {
+ if (maxRetryCount < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(RetryOptions.MaxRetryCount), maxRetryCount, "Must not be negative.");
+ }
+
+ Check.NotNull(delayFactory, nameof(RetryOptions.DelayFactory));
+ Check.NotNull(shouldRetryOnException, nameof(RetryOptions.ShouldRetryOnException));
+ }
+
+ // int.MaxValue means "retry forever": the counter stops there instead of overflowing.
+ private static bool IsLastRetry(int retryCount, int maxRetryCount)
+ {
+ return maxRetryCount != int.MaxValue && retryCount >= maxRetryCount;
+ }
+
+ private static TimeSpan GetDelay(Func delayFactory, int retryCount)
+ {
+ var delay = delayFactory(retryCount);
+
+ // Clamped before it is reported, so that the reported delay is the one that is waited for.
+ return delay > MaxDelay ? MaxDelay : delay;
+ }
+
+ internal static TimeSpan GetExponentialDelay(int retryCount)
+ {
+ var seconds = Math.Pow(2, retryCount);
+
+ // Stops growing instead of overflowing when the retry count gets high.
+ return seconds >= MaxDelay.TotalSeconds ? MaxDelay : TimeSpan.FromSeconds(seconds);
+ }
+
+ private static int NextRetryCount(int retryCount)
+ {
+ return retryCount == int.MaxValue ? retryCount : retryCount + 1;
+ }
+
+ private static async Task TryDisposeAsync(TResult result)
+ {
+ try
+ {
+ if (result is IAsyncDisposable asyncDisposable)
+ {
+ await asyncDisposable.DisposeAsync();
+ }
+ else if (result is IDisposable disposable)
+ {
+ disposable.Dispose();
+ }
+ }
+ catch
+ {
+ // A result that is being thrown away should not fail the retry.
+ }
+ }
+
+ private static async Task WaitAsync(TimeSpan delay, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (delay > TimeSpan.Zero)
+ {
+ await Task.Delay(delay, cancellationToken);
+ }
+ }
+}
diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryOptions.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryOptions.cs
new file mode 100644
index 0000000000..f3462b75aa
--- /dev/null
+++ b/framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryOptions.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Threading.Tasks;
+
+namespace Volo.Abp.Threading;
+
+///
+/// Options to control how retries a failing action.
+///
+public class RetryOptions
+{
+ ///
+ /// How many times to retry after the initial attempt fails. Default: 3.
+ /// Set to to retry forever.
+ ///
+ public int MaxRetryCount { get; set; } = 3;
+
+ ///
+ /// Returns how long to wait before the given retry.
+ /// Default: 2^retryCount seconds, up to the longest delay that can be waited for.
+ ///
+ public Func DelayFactory { get; set; } = RetryHelper.GetExponentialDelay;
+
+ ///
+ /// Decides if the action should be retried after the given exception.
+ /// Default: retries any exception except .
+ ///
+ public Func ShouldRetryOnException { get; set; } = exception => exception is not OperationCanceledException;
+
+ ///
+ /// Called once per retry, before waiting.
+ ///
+ public Func? OnRetry { get; set; }
+}
+
+///
+/// Options to control how retries a failing action that returns a value.
+/// The action can also be retried because of the value it returned.
+///
+/// Type of the value returned by the retried action.
+public class RetryOptions
+{
+ ///
+ /// How many times to retry after the initial attempt fails. Default: 3.
+ /// Set to to retry forever.
+ ///
+ public int MaxRetryCount { get; set; } = 3;
+
+ ///
+ /// Returns how long to wait before the given retry.
+ /// Default: 2^retryCount seconds, up to the longest delay that can be waited for.
+ ///
+ public Func DelayFactory { get; set; } = RetryHelper.GetExponentialDelay;
+
+ ///
+ /// Decides if the action should be retried after the given exception.
+ /// Default: retries any exception except .
+ ///
+ public Func ShouldRetryOnException { get; set; } = exception => exception is not OperationCanceledException;
+
+ ///
+ /// Decides if the action should be retried because of the value it returned. Default: no result is retried.
+ ///
+ public Func ShouldRetryOnResult { get; set; } = _ => false;
+
+ ///
+ /// Called once per retry, before the retried result is disposed and before waiting.
+ ///
+ public Func, Task>? OnRetry { get; set; }
+}
diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Threading/RetryHelper_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Threading/RetryHelper_Tests.cs
new file mode 100644
index 0000000000..45b8e5879d
--- /dev/null
+++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Threading/RetryHelper_Tests.cs
@@ -0,0 +1,1027 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Shouldly;
+using Xunit;
+
+namespace Volo.Abp.Threading;
+
+public class RetryHelper_Tests
+{
+ private static RetryOptions NoDelay(
+ int maxRetryCount = 3,
+ Func? shouldRetryOnException = null,
+ Func? onRetry = null)
+ {
+ var options = new RetryOptions
+ {
+ MaxRetryCount = maxRetryCount,
+ DelayFactory = _ => TimeSpan.Zero,
+ OnRetry = onRetry
+ };
+
+ if (shouldRetryOnException != null)
+ {
+ options.ShouldRetryOnException = shouldRetryOnException;
+ }
+
+ return options;
+ }
+
+ private static RetryOptions NoDelay(
+ int maxRetryCount = 3,
+ Func? shouldRetryOnResult = null,
+ Func? shouldRetryOnException = null,
+ Func, Task>? onRetry = null)
+ {
+ var options = new RetryOptions
+ {
+ MaxRetryCount = maxRetryCount,
+ DelayFactory = _ => TimeSpan.Zero,
+ OnRetry = onRetry
+ };
+
+ if (shouldRetryOnResult != null)
+ {
+ options.ShouldRetryOnResult = shouldRetryOnResult;
+ }
+
+ if (shouldRetryOnException != null)
+ {
+ options.ShouldRetryOnException = shouldRetryOnException;
+ }
+
+ return options;
+ }
+
+ private static async Task ThrowFromHelperAsync()
+ {
+ await Task.Yield();
+ throw new InvalidOperationException("thrown-by-helper");
+ }
+
+ #region Defaults
+
+ [Fact]
+ public void RetryOptions_Should_Have_Expected_Defaults()
+ {
+ var options = new RetryOptions();
+
+ options.MaxRetryCount.ShouldBe(3);
+ options.OnRetry.ShouldBeNull();
+ options.ShouldRetryOnException(new Exception()).ShouldBeTrue();
+ options.ShouldRetryOnException(new OperationCanceledException()).ShouldBeFalse();
+
+ options.DelayFactory(1).ShouldBe(TimeSpan.FromSeconds(2));
+ options.DelayFactory(2).ShouldBe(TimeSpan.FromSeconds(4));
+ options.DelayFactory(3).ShouldBe(TimeSpan.FromSeconds(8));
+
+ options.DelayFactory(21).ShouldBe(TimeSpan.FromSeconds(2097152));
+ options.DelayFactory(22).ShouldBe(TimeSpan.FromMilliseconds(int.MaxValue));
+ options.DelayFactory(int.MaxValue).ShouldBe(TimeSpan.FromMilliseconds(int.MaxValue));
+ }
+
+ [Fact]
+ public void RetryOptions_Of_TResult_Should_Have_Expected_Defaults()
+ {
+ var options = new RetryOptions();
+
+ options.MaxRetryCount.ShouldBe(3);
+ options.OnRetry.ShouldBeNull();
+ options.ShouldRetryOnException(new Exception()).ShouldBeTrue();
+ options.ShouldRetryOnException(new OperationCanceledException()).ShouldBeFalse();
+ options.ShouldRetryOnResult(42).ShouldBeFalse();
+
+ options.DelayFactory(1).ShouldBe(TimeSpan.FromSeconds(2));
+ options.DelayFactory(2).ShouldBe(TimeSpan.FromSeconds(4));
+ options.DelayFactory(3).ShouldBe(TimeSpan.FromSeconds(8));
+
+ options.DelayFactory(21).ShouldBe(TimeSpan.FromSeconds(2097152));
+ options.DelayFactory(22).ShouldBe(TimeSpan.FromMilliseconds(int.MaxValue));
+ options.DelayFactory(int.MaxValue).ShouldBe(TimeSpan.FromMilliseconds(int.MaxValue));
+ }
+
+ #endregion
+
+ #region ExecuteAsync
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Not_Retry_When_The_Action_Succeeds()
+ {
+ var attempts = 0;
+ var retries = 0;
+
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.CompletedTask;
+ },
+ NoDelay(onRetry: _ => { retries++; return Task.CompletedTask; }));
+
+ attempts.ShouldBe(1);
+ retries.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Retry_Until_The_Action_Succeeds()
+ {
+ var attempts = 0;
+
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts < 3)
+ {
+ throw new InvalidOperationException("not yet");
+ }
+
+ return Task.CompletedTask;
+ },
+ NoDelay());
+
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Rethrow_The_Last_Exception_When_The_Retries_Are_Exhausted()
+ {
+ var attempts = 0;
+
+ var exception = await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException($"attempt-{attempts}");
+ },
+ NoDelay(maxRetryCount: 3)));
+
+ attempts.ShouldBe(4); // the initial attempt + 3 retries
+ exception.Message.ShouldBe("attempt-4");
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Preserve_The_Stack_Trace_Of_The_Rethrown_Exception()
+ {
+ var exception = await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => ThrowFromHelperAsync(),
+ NoDelay(maxRetryCount: 1)));
+
+ exception.Message.ShouldBe("thrown-by-helper");
+ exception.StackTrace.ShouldNotBeNull();
+ exception.StackTrace.ShouldContain(nameof(ThrowFromHelperAsync));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Not_Retry_When_ShouldRetryOnException_Returns_False()
+ {
+ var attempts = 0;
+ var retries = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException();
+ },
+ NoDelay(shouldRetryOnException: _ => false, onRetry: _ => { retries++; return Task.CompletedTask; })));
+
+ attempts.ShouldBe(1);
+ retries.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Only_Retry_The_Handled_Exception_Types()
+ {
+ var attempts = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts < 3)
+ {
+ throw new IOException();
+ }
+
+ throw new UnauthorizedAccessException();
+ },
+ NoDelay(maxRetryCount: 10, shouldRetryOnException: ex => ex is IOException)));
+
+ attempts.ShouldBe(3); // 2 retried IOExceptions, then the unhandled one stops it
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Not_Retry_When_MaxRetryCount_Is_Zero()
+ {
+ var attempts = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException();
+ },
+ NoDelay(maxRetryCount: 0)));
+
+ attempts.ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Ask_The_DelayFactory_With_An_Increasing_One_Based_RetryCount()
+ {
+ var requestedRetryCounts = new List();
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => throw new InvalidOperationException(),
+ new RetryOptions
+ {
+ MaxRetryCount = 3,
+ DelayFactory = retryCount =>
+ {
+ requestedRetryCounts.Add(retryCount);
+ return TimeSpan.Zero;
+ }
+ }));
+
+ requestedRetryCounts.ShouldBe(new[] { 1, 2, 3 });
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Report_Every_Retry_To_OnRetry()
+ {
+ var attempts = 0;
+ var reported = new List();
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException($"attempt-{attempts}");
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 2,
+ DelayFactory = retryCount => TimeSpan.FromMilliseconds(retryCount),
+ OnRetry = attempt => { reported.Add(attempt); return Task.CompletedTask; }
+ }));
+
+ reported.Count.ShouldBe(2);
+
+ reported[0].RetryCount.ShouldBe(1);
+ reported[0].RetryDelay.ShouldBe(TimeSpan.FromMilliseconds(1));
+ reported[0].Exception.ShouldNotBeNull();
+ reported[0].Exception!.Message.ShouldBe("attempt-1");
+
+ reported[1].RetryCount.ShouldBe(2);
+ reported[1].RetryDelay.ShouldBe(TimeSpan.FromMilliseconds(2));
+ reported[1].Exception!.Message.ShouldBe("attempt-2");
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Pass_The_CancellationToken_To_The_Action()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var received = CancellationToken.None;
+
+ await RetryHelper.ExecuteAsync(
+ cancellationToken =>
+ {
+ received = cancellationToken;
+ return Task.CompletedTask;
+ },
+ NoDelay(),
+ cancellationTokenSource.Token);
+
+ received.ShouldBe(cancellationTokenSource.Token);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Stop_Waiting_When_The_CancellationToken_Is_Cancelled()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var attempts = 0;
+
+ // Cancelled while Task.Delay is running, not before it starts.
+ cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(50));
+
+ await Assert.ThrowsAnyAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException();
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 5,
+ DelayFactory = _ => TimeSpan.FromMinutes(1)
+ },
+ cancellationTokenSource.Token));
+
+ attempts.ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Not_Report_A_Retry_When_The_Action_Was_Cancelled()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var attempts = 0;
+ var retries = 0;
+
+ await Assert.ThrowsAnyAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ cancellationToken =>
+ {
+ attempts++;
+ cancellationTokenSource.Cancel();
+ cancellationToken.ThrowIfCancellationRequested();
+ return Task.CompletedTask;
+ },
+ NoDelay(maxRetryCount: 5, onRetry: _ => { retries++; return Task.CompletedTask; }),
+ cancellationTokenSource.Token));
+
+ attempts.ShouldBe(1);
+ retries.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Not_Report_A_Retry_When_The_Action_Was_Cancelled()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var attempts = 0;
+ var retries = 0;
+
+ await Assert.ThrowsAnyAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ cancellationToken =>
+ {
+ attempts++;
+ cancellationTokenSource.Cancel();
+ cancellationToken.ThrowIfCancellationRequested();
+ return Task.FromResult(1);
+ },
+ NoDelay(maxRetryCount: 5, onRetry: _ => { retries++; return Task.CompletedTask; }),
+ cancellationTokenSource.Token));
+
+ attempts.ShouldBe(1);
+ retries.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Retry_A_Cancellation_Exception_When_The_Predicate_Allows_It()
+ {
+ var attempts = 0;
+
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts < 3)
+ {
+ throw new OperationCanceledException();
+ }
+
+ return Task.CompletedTask;
+ },
+ NoDelay(maxRetryCount: 5, shouldRetryOnException: _ => true));
+
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Await_OnRetry_Before_The_Next_Attempt()
+ {
+ var attempts = 0;
+ var onRetryFinished = 0;
+ var onRetryFinishedBeforeNextAttempt = true;
+
+ await RetryHelper.ExecuteAsync(
+ async _ =>
+ {
+ attempts++;
+ if (attempts > 1 && onRetryFinished != attempts - 1)
+ {
+ onRetryFinishedBeforeNextAttempt = false;
+ }
+
+ if (attempts < 3)
+ {
+ await Task.Yield();
+ throw new InvalidOperationException();
+ }
+ },
+ NoDelay(
+ maxRetryCount: 5,
+ onRetry: async _ =>
+ {
+ await Task.Delay(10);
+ onRetryFinished++;
+ }));
+
+ attempts.ShouldBe(3);
+ onRetryFinished.ShouldBe(2);
+ onRetryFinishedBeforeNextAttempt.ShouldBeTrue();
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Not_Run_The_Action_When_The_CancellationToken_Is_Already_Cancelled()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ cancellationTokenSource.Cancel();
+
+ var attempts = 0;
+
+ await Assert.ThrowsAnyAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.CompletedTask;
+ },
+ NoDelay(),
+ cancellationTokenSource.Token));
+
+ attempts.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Not_Run_The_Action_When_The_CancellationToken_Is_Already_Cancelled()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ cancellationTokenSource.Cancel();
+
+ var attempts = 0;
+
+ await Assert.ThrowsAnyAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(1);
+ },
+ NoDelay(),
+ cancellationTokenSource.Token));
+
+ attempts.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Throw_When_The_DelayFactory_Throws()
+ {
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => throw new InvalidOperationException(),
+ new RetryOptions
+ {
+ MaxRetryCount = 5,
+ DelayFactory = _ => TimeSpan.FromSeconds(double.MaxValue)
+ }));
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => throw new InvalidOperationException(),
+ new RetryOptions
+ {
+ MaxRetryCount = 5,
+ DelayFactory = _ => throw new FormatException()
+ }));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Report_The_Delay_It_Waits_For()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var reported = TimeSpan.Zero;
+
+ await Assert.ThrowsAnyAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => throw new InvalidOperationException(),
+ new RetryOptions
+ {
+ MaxRetryCount = 5,
+ DelayFactory = _ => TimeSpan.FromDays(100),
+ OnRetry = attempt =>
+ {
+ reported = attempt.RetryDelay;
+ cancellationTokenSource.Cancel();
+ return Task.CompletedTask;
+ }
+ },
+ cancellationTokenSource.Token));
+
+ reported.ShouldBe(TimeSpan.FromMilliseconds(int.MaxValue));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Use_The_Options_As_They_Were_When_It_Started()
+ {
+ var attempts = 0;
+ var options = new RetryOptions
+ {
+ MaxRetryCount = 2,
+ DelayFactory = _ => TimeSpan.Zero
+ };
+
+ options.OnRetry = _ =>
+ {
+ options.MaxRetryCount = 0;
+ options.DelayFactory = null!;
+ options.ShouldRetryOnException = null!;
+ return Task.CompletedTask;
+ };
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException();
+ },
+ options));
+
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Not_Wait_For_A_Negative_Delay()
+ {
+ var attempts = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException();
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 2,
+ DelayFactory = _ => TimeSpan.FromSeconds(-1)
+ }));
+
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Ask_The_Exception_Predicate_On_Every_Attempt()
+ {
+ var asked = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => throw new InvalidOperationException(),
+ NoDelay(maxRetryCount: 2, shouldRetryOnException: _ => { asked++; return true; })));
+
+ asked.ShouldBe(3); // including the last attempt, which is not retried
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Throw_When_MaxRetryCount_Is_Negative()
+ {
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(_ => Task.CompletedTask, new RetryOptions { MaxRetryCount = -1 }));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Throw_When_A_Delegate_Option_Is_Null()
+ {
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(_ => Task.CompletedTask, new RetryOptions { DelayFactory = null! }));
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(_ => Task.CompletedTask, new RetryOptions { ShouldRetryOnException = null! }));
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(_ => Task.FromResult(1), new RetryOptions { ShouldRetryOnResult = null! }));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Throw_When_The_Action_Is_Null()
+ {
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(null!, NoDelay()));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Work_Without_Options()
+ {
+ var attempts = 0;
+
+ await RetryHelper.ExecuteAsync(_ =>
+ {
+ attempts++;
+ return Task.CompletedTask;
+ });
+
+ attempts.ShouldBe(1);
+ }
+
+ #endregion
+
+ #region ExecuteAsync
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Return_The_Result_Without_Retrying_By_Default()
+ {
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult("ok");
+ },
+ NoDelay());
+
+ result.ShouldBe("ok");
+ attempts.ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Retry_While_The_Result_Is_Not_Accepted()
+ {
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(attempts);
+ },
+ NoDelay(maxRetryCount: 5, shouldRetryOnResult: value => value < 3));
+
+ result.ShouldBe(3);
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Return_The_Last_Result_When_The_Retries_Are_Exhausted()
+ {
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(attempts);
+ },
+ NoDelay(maxRetryCount: 2, shouldRetryOnResult: _ => true));
+
+ result.ShouldBe(3); // the initial attempt + 2 retries, returned instead of throwing
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Retry_On_Exception_And_Return_The_Result()
+ {
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts < 3)
+ {
+ throw new IOException();
+ }
+
+ return Task.FromResult("ok");
+ },
+ NoDelay());
+
+ result.ShouldBe("ok");
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Rethrow_The_Last_Exception_When_The_Retries_Are_Exhausted()
+ {
+ var attempts = 0;
+
+ var exception = await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new InvalidOperationException($"attempt-{attempts}");
+ },
+ NoDelay(maxRetryCount: 2)));
+
+ attempts.ShouldBe(3);
+ exception.Message.ShouldBe("attempt-3");
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Not_Retry_When_ShouldRetryOnException_Returns_False()
+ {
+ var attempts = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ throw new IOException();
+ },
+ NoDelay(maxRetryCount: 5, shouldRetryOnException: _ => false)));
+
+ attempts.ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Stop_On_An_Unhandled_Exception_After_Retrying_The_Result()
+ {
+ var attempts = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts == 1)
+ {
+ return Task.FromResult(0);
+ }
+
+ throw new UnauthorizedAccessException();
+ },
+ NoDelay(
+ maxRetryCount: 5,
+ shouldRetryOnResult: value => value == 0,
+ shouldRetryOnException: _ => false)));
+
+ attempts.ShouldBe(2);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Report_The_Result_To_OnRetry_When_Retried_Because_Of_The_Result()
+ {
+ var reported = new List>();
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ => Task.FromResult("bad"),
+ NoDelay(maxRetryCount: 1, shouldRetryOnResult: value => value == "bad", onRetry: attempt => { reported.Add(attempt); return Task.CompletedTask; }));
+
+ result.ShouldBe("bad");
+ reported.Count.ShouldBe(1);
+ reported[0].RetryCount.ShouldBe(1);
+ reported[0].Result.ShouldBe("bad");
+ reported[0].Exception.ShouldBeNull();
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Report_The_Exception_To_OnRetry_When_Retried_Because_Of_An_Exception()
+ {
+ var reported = new List>();
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts == 1)
+ {
+ throw new IOException("io-failed");
+ }
+
+ return Task.FromResult("ok");
+ },
+ NoDelay(maxRetryCount: 1, onRetry: attempt => { reported.Add(attempt); return Task.CompletedTask; }));
+
+ result.ShouldBe("ok");
+ reported.Count.ShouldBe(1);
+ reported[0].RetryCount.ShouldBe(1);
+ reported[0].Exception.ShouldBeOfType();
+ reported[0].Result.ShouldBeNull();
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Pass_The_CancellationToken_To_The_Action()
+ {
+ using var cancellationTokenSource = new CancellationTokenSource();
+ var received = CancellationToken.None;
+
+ await RetryHelper.ExecuteAsync(
+ cancellationToken =>
+ {
+ received = cancellationToken;
+ return Task.FromResult(1);
+ },
+ NoDelay(),
+ cancellationTokenSource.Token);
+
+ received.ShouldBe(cancellationTokenSource.Token);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Throw_When_The_Action_Is_Null()
+ {
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(null!, NoDelay()));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Work_Without_Options()
+ {
+ var result = await RetryHelper.ExecuteAsync(_ => Task.FromResult("ok"));
+
+ result.ShouldBe("ok");
+ }
+
+ #endregion
+
+ #region Disposing and unlimited retries
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Dispose_A_Retried_Result()
+ {
+ var disposed = new List();
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(new DisposableResult(attempts, disposed));
+ },
+ NoDelay(maxRetryCount: 5, shouldRetryOnResult: value => value.Id < 3));
+
+ result.Id.ShouldBe(3);
+ disposed.ShouldBe(new[] { 1, 2 }); // the returned one is not disposed
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Not_Dispose_A_Result_That_Is_Not_Retried()
+ {
+ var disposed = new List();
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ => Task.FromResult(new DisposableResult(1, disposed)),
+ NoDelay());
+
+ result.Id.ShouldBe(1);
+ disposed.ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Not_Fail_When_Disposing_The_Retried_Result_Throws()
+ {
+ var attempts = 0;
+
+ var result = await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(new ThrowingDisposableResult(attempts));
+ },
+ NoDelay(maxRetryCount: 5, shouldRetryOnResult: value => value.Id < 3));
+
+ result.Id.ShouldBe(3);
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Dispose_The_Result_When_ShouldRetryOnResult_Throws()
+ {
+ var disposed = new List();
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ => Task.FromResult(new DisposableResult(1, disposed)),
+ NoDelay(
+ maxRetryCount: 1,
+ shouldRetryOnResult: _ => throw new InvalidOperationException("predicate failed"),
+ shouldRetryOnException: _ => false)));
+
+ disposed.ShouldBe(new[] { 1 });
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Retry_The_Action_When_ShouldRetryOnResult_Throws()
+ {
+ var attempts = 0;
+
+ await Assert.ThrowsAsync(async () =>
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(1);
+ },
+ NoDelay(
+ maxRetryCount: 2,
+ shouldRetryOnResult: _ => throw new InvalidOperationException("predicate failed"))));
+
+ // A throwing result predicate counts as a failed attempt.
+ attempts.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Of_TResult_Should_Prefer_IAsyncDisposable_Over_IDisposable()
+ {
+ var log = new List();
+ var attempts = 0;
+
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ return Task.FromResult(new BothDisposableResult(attempts, log));
+ },
+ NoDelay(maxRetryCount: 3, shouldRetryOnResult: value => value.Id < 2));
+
+ log.ShouldBe(new[] { "async:1" });
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_Should_Keep_Retrying_When_MaxRetryCount_Is_The_Maximum()
+ {
+ var attempts = 0;
+
+ await RetryHelper.ExecuteAsync(
+ _ =>
+ {
+ attempts++;
+ if (attempts < 5)
+ {
+ throw new InvalidOperationException();
+ }
+
+ return Task.CompletedTask;
+ },
+ NoDelay(maxRetryCount: int.MaxValue));
+
+ attempts.ShouldBe(5);
+ }
+
+ private class DisposableResult : IDisposable
+ {
+ public int Id { get; }
+
+ private readonly List _disposed;
+
+ public DisposableResult(int id, List disposed)
+ {
+ Id = id;
+ _disposed = disposed;
+ }
+
+ public void Dispose()
+ {
+ _disposed.Add(Id);
+ }
+ }
+
+ private class BothDisposableResult : IDisposable, IAsyncDisposable
+ {
+ public int Id { get; }
+
+ private readonly List _log;
+
+ public BothDisposableResult(int id, List log)
+ {
+ Id = id;
+ _log = log;
+ }
+
+ public void Dispose()
+ {
+ _log.Add($"sync:{Id}");
+ }
+
+ public ValueTask DisposeAsync()
+ {
+ _log.Add($"async:{Id}");
+ return default;
+ }
+ }
+
+ private class ThrowingDisposableResult : IDisposable
+ {
+ public int Id { get; }
+
+ public ThrowingDisposableResult(int id)
+ {
+ Id = id;
+ }
+
+ public void Dispose()
+ {
+ throw new InvalidOperationException("dispose failed");
+ }
+ }
+
+ #endregion
+}
diff --git a/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo.Abp.FeatureManagement.Domain.csproj b/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo.Abp.FeatureManagement.Domain.csproj
index bbb2419515..5044a067b1 100644
--- a/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo.Abp.FeatureManagement.Domain.csproj
+++ b/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo.Abp.FeatureManagement.Domain.csproj
@@ -18,8 +18,4 @@
-
-
-
-
diff --git a/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/AbpFeatureManagementDomainModule.cs b/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/AbpFeatureManagementDomainModule.cs
index 1c465817f2..21bd522145 100644
--- a/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/AbpFeatureManagementDomainModule.cs
+++ b/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/AbpFeatureManagementDomainModule.cs
@@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
-using Polly;
using Volo.Abp.Caching;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
diff --git a/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/FeatureDynamicInitializer.cs b/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/FeatureDynamicInitializer.cs
index d96b7b3800..0a209cbded 100644
--- a/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/FeatureDynamicInitializer.cs
+++ b/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/FeatureDynamicInitializer.cs
@@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
-using Polly;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Features;
using Volo.Abp.Threading;
@@ -95,17 +94,8 @@ public class FeatureDynamicInitializer : ITransientDependency
var staticFeatureSaver = ServiceProvider.GetRequiredService();
- await Policy
- .Handle()
- .WaitAndRetryAsync(
- 8,
- retryAttempt => TimeSpan.FromSeconds(
- Volo.Abp.RandomHelper.GetRandom(
- (int)Math.Pow(2, retryAttempt) * 8,
- (int)Math.Pow(2, retryAttempt) * 12)
- )
- )
- .ExecuteAsync(async _ =>
+ await RetryHelper.ExecuteAsync(
+ async _ =>
{
try
{
@@ -114,9 +104,20 @@ public class FeatureDynamicInitializer : ITransientDependency
catch (Exception ex)
{
Logger.LogException(ex);
- throw; // Polly will catch it
+ throw; // RetryHelper will catch it
}
- }, cancellationToken);
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 8,
+ DelayFactory = retryAttempt => TimeSpan.FromSeconds(
+ Volo.Abp.RandomHelper.GetRandom(
+ (int)Math.Pow(2, retryAttempt) * 8,
+ (int)Math.Pow(2, retryAttempt) * 12)
+ ),
+ ShouldRetryOnException = _ => true
+ },
+ cancellationToken);
}
protected virtual async Task PreCacheDynamicFeaturesAsync(
diff --git a/modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/EfCoreFeatureValueRepository.cs b/modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/EfCoreFeatureValueRepository.cs
index 555682d56d..0c70e798cc 100644
--- a/modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/EfCoreFeatureValueRepository.cs
+++ b/modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/EfCoreFeatureValueRepository.cs
@@ -4,7 +4,6 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
-using Polly;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
diff --git a/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo.Abp.PermissionManagement.Domain.csproj b/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo.Abp.PermissionManagement.Domain.csproj
index ea6d7ea44a..d66cc859cf 100644
--- a/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo.Abp.PermissionManagement.Domain.csproj
+++ b/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo.Abp.PermissionManagement.Domain.csproj
@@ -23,8 +23,4 @@
-
-
-
-
diff --git a/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/AbpPermissionManagementDomainModule.cs b/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/AbpPermissionManagementDomainModule.cs
index 1f7eb88bd8..2f65a89994 100644
--- a/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/AbpPermissionManagementDomainModule.cs
+++ b/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/AbpPermissionManagementDomainModule.cs
@@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
-using Polly;
using Volo.Abp.Authorization;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Caching;
diff --git a/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/PermissionDynamicInitializer.cs b/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/PermissionDynamicInitializer.cs
index ef3cf355bb..4b4d4686e8 100644
--- a/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/PermissionDynamicInitializer.cs
+++ b/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/PermissionDynamicInitializer.cs
@@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
-using Polly;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Threading;
@@ -95,17 +94,8 @@ public class PermissionDynamicInitializer : ITransientDependency
var staticPermissionSaver = ServiceProvider.GetRequiredService();
- await Policy
- .Handle()
- .WaitAndRetryAsync(
- 8,
- retryAttempt => TimeSpan.FromSeconds(
- Volo.Abp.RandomHelper.GetRandom(
- (int)Math.Pow(2, retryAttempt) * 8,
- (int)Math.Pow(2, retryAttempt) * 12)
- )
- )
- .ExecuteAsync(async _ =>
+ await RetryHelper.ExecuteAsync(
+ async _ =>
{
try
{
@@ -115,9 +105,20 @@ public class PermissionDynamicInitializer : ITransientDependency
{
Logger.LogException(ex);
- throw; // Polly will catch it
+ throw; // RetryHelper will catch it
}
- }, cancellationToken);
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 8,
+ DelayFactory = retryAttempt => TimeSpan.FromSeconds(
+ Volo.Abp.RandomHelper.GetRandom(
+ (int)Math.Pow(2, retryAttempt) * 8,
+ (int)Math.Pow(2, retryAttempt) * 12)
+ ),
+ ShouldRetryOnException = _ => true
+ },
+ cancellationToken);
}
protected virtual async Task PreCacheDynamicPermissionsAsync(
diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo.Abp.SettingManagement.Domain.csproj b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo.Abp.SettingManagement.Domain.csproj
index 9c781497c2..d3f6b15980 100644
--- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo.Abp.SettingManagement.Domain.csproj
+++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo.Abp.SettingManagement.Domain.csproj
@@ -22,8 +22,4 @@
-
-
-
-
diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/AbpSettingManagementDomainModule.cs b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/AbpSettingManagementDomainModule.cs
index a5d2ba832e..84e7a24e8a 100644
--- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/AbpSettingManagementDomainModule.cs
+++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/AbpSettingManagementDomainModule.cs
@@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
-using Polly;
using Volo.Abp.Caching;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/SettingDynamicInitializer.cs b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/SettingDynamicInitializer.cs
index af9858353c..438ba2332d 100644
--- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/SettingDynamicInitializer.cs
+++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/SettingDynamicInitializer.cs
@@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
-using Polly;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Settings;
using Volo.Abp.Threading;
@@ -96,17 +95,8 @@ public class SettingDynamicInitializer : ITransientDependency
var staticSettingSaver = ServiceProvider.GetRequiredService();
- await Policy
- .Handle()
- .WaitAndRetryAsync(
- 8,
- retryAttempt => TimeSpan.FromSeconds(
- Volo.Abp.RandomHelper.GetRandom(
- (int)Math.Pow(2, retryAttempt) * 8,
- (int)Math.Pow(2, retryAttempt) * 12)
- )
- )
- .ExecuteAsync(async _ =>
+ await RetryHelper.ExecuteAsync(
+ async _ =>
{
try
{
@@ -115,9 +105,20 @@ public class SettingDynamicInitializer : ITransientDependency
catch (Exception ex)
{
Logger.LogException(ex);
- throw; // Polly will catch it
+ throw; // RetryHelper will catch it
}
- }, cancellationToken);
+ },
+ new RetryOptions
+ {
+ MaxRetryCount = 8,
+ DelayFactory = retryAttempt => TimeSpan.FromSeconds(
+ Volo.Abp.RandomHelper.GetRandom(
+ (int)Math.Pow(2, retryAttempt) * 8,
+ (int)Math.Pow(2, retryAttempt) * 12)
+ ),
+ ShouldRetryOnException = _ => true
+ },
+ cancellationToken);
}
protected virtual async Task PreCacheDynamicSettingsAsync(