Browse Source

Add RetryHelper and replace Polly usages with it

pull/26169/head
maliming 2 months ago
parent
commit
91df40d2f0
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 2
      Directory.Packages.props
  2. 75
      docs/en/release-info/migration-guides/abp-11-0.md
  3. 1
      docs/en/release-info/migration-guides/index.md
  4. 1
      framework/src/Volo.Abp.BlobStoring.FileSystem/Volo.Abp.BlobStoring.FileSystem.csproj
  5. 24
      framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobProvider.cs
  6. 2
      framework/src/Volo.Abp.Cli.Core/Volo.Abp.Cli.Core.csproj
  7. 41
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs
  8. 49
      framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryAttempt.cs
  9. 232
      framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryHelper.cs
  10. 69
      framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryOptions.cs
  11. 1027
      framework/test/Volo.Abp.Core.Tests/Volo/Abp/Threading/RetryHelper_Tests.cs
  12. 4
      modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo.Abp.FeatureManagement.Domain.csproj
  13. 1
      modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/AbpFeatureManagementDomainModule.cs
  14. 29
      modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/FeatureDynamicInitializer.cs
  15. 1
      modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/EfCoreFeatureValueRepository.cs
  16. 4
      modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo.Abp.PermissionManagement.Domain.csproj
  17. 1
      modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/AbpPermissionManagementDomainModule.cs
  18. 29
      modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo/Abp/PermissionManagement/PermissionDynamicInitializer.cs
  19. 4
      modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo.Abp.SettingManagement.Domain.csproj
  20. 1
      modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/AbpSettingManagementDomainModule.cs
  21. 29
      modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/SettingDynamicInitializer.cs

2
Directory.Packages.props

@ -140,8 +140,6 @@
<PackageVersion Include="OpenIddict.Validation.AspNetCore" Version="7.7.0" /> <PackageVersion Include="OpenIddict.Validation.AspNetCore" Version="7.7.0" />
<PackageVersion Include="OpenIddict.Validation.ServerIntegration" Version="7.7.0" /> <PackageVersion Include="OpenIddict.Validation.ServerIntegration" Version="7.7.0" />
<PackageVersion Include="Oracle.EntityFrameworkCore" Version="10.23.26000" /> <PackageVersion Include="Oracle.EntityFrameworkCore" Version="10.23.26000" />
<PackageVersion Include="Polly" Version="8.6.3" />
<PackageVersion Include="Polly.Extensions.Http" Version="3.0.0" />
<PackageVersion Include="Pomelo.EntityFrameworkCore.MySql" Version="9.0.0" /> <PackageVersion Include="Pomelo.EntityFrameworkCore.MySql" Version="9.0.0" />
<PackageVersion Include="MySql.EntityFrameworkCore" Version="10.0.9" /> <PackageVersion Include="MySql.EntityFrameworkCore" Version="10.0.9" />
<PackageVersion Include="Quartz" Version="3.15.0" /> <PackageVersion Include="Quartz" Version="3.15.0" />

75
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
<PackageReference Include="Polly" Version="8.6.3" />
```
`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<HttpResponseMessage>
{
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.

1
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). 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.6 to 10.7](abp-10-7.md)
- [10.5 to 10.6](abp-10-6.md) - [10.5 to 10.6](abp-10-6.md)
- [10.4 to 10.5](abp-10-5.md) - [10.4 to 10.5](abp-10-5.md)

1
framework/src/Volo.Abp.BlobStoring.FileSystem/Volo.Abp.BlobStoring.FileSystem.csproj

@ -18,7 +18,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Volo.Abp.BlobStoring\Volo.Abp.BlobStoring.csproj" /> <ProjectReference Include="..\Volo.Abp.BlobStoring\Volo.Abp.BlobStoring.csproj" />
<PackageReference Include="Polly" />
</ItemGroup> </ItemGroup>
</Project> </Project>

24
framework/src/Volo.Abp.BlobStoring.FileSystem/Volo/Abp/BlobStoring/FileSystem/FileSystemBlobProvider.cs

@ -1,9 +1,9 @@
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using Polly;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.IO; using Volo.Abp.IO;
using Volo.Abp.Threading;
namespace Volo.Abp.BlobStoring.FileSystem; namespace Volo.Abp.BlobStoring.FileSystem;
@ -48,9 +48,8 @@ public class FileSystemBlobProvider : BlobProviderBase, ITransientDependency
var targetOpened = false; var targetOpened = false;
await Policy.Handle<IOException>(_ => sourcePosition >= 0 || !targetOpened) await RetryHelper.ExecuteAsync(
.WaitAndRetryAsync(2, retryCount => TimeSpan.FromSeconds(retryCount)) async _ =>
.ExecuteAsync(async () =>
{ {
if (sourcePosition >= 0) if (sourcePosition >= 0)
{ {
@ -68,6 +67,12 @@ public class FileSystemBlobProvider : BlobProviderBase, ITransientDependency
await fileStream.FlushAsync(); 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 null;
} }
return await Policy.Handle<IOException>() return await RetryHelper.ExecuteAsync(
.WaitAndRetryAsync(2, retryCount => TimeSpan.FromSeconds(retryCount)) _ => Task.FromResult(File.OpenRead(filePath)),
.ExecuteAsync(() => Task.FromResult(File.OpenRead(filePath))); new RetryOptions<FileStream>
{
MaxRetryCount = 2,
DelayFactory = retryCount => TimeSpan.FromSeconds(retryCount),
ShouldRetryOnException = ex => ex is IOException
});
} }
protected virtual Stream OpenFileStream(string filePath, FileMode fileMode) protected virtual Stream OpenFileStream(string filePath, FileMode fileMode)

2
framework/src/Volo.Abp.Cli.Core/Volo.Abp.Cli.Core.csproj

@ -19,8 +19,6 @@
<PackageReference Include="NuGet.Versioning" /> <PackageReference Include="NuGet.Versioning" />
<PackageReference Include="System.Security.Permissions" /> <PackageReference Include="System.Security.Permissions" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" />
<PackageReference Include="Polly" />
<PackageReference Include="Polly.Extensions.Http" />
<PackageReference Include="LibGit2Sharp" /> <PackageReference Include="LibGit2Sharp" />
<PackageReference Include="Newtonsoft.Json" /> <PackageReference Include="Newtonsoft.Json" />
<PackageReference Include="StackExchange.Redis" /> <PackageReference Include="StackExchange.Redis" />

41
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs

@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Duende.IdentityModel.Client; using Duende.IdentityModel.Client;
using Polly;
using Polly.Extensions.Http;
using Volo.Abp.Cli.Auth; using Volo.Abp.Cli.Auth;
using Volo.Abp.Threading;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Volo.Abp.Cli.Http; namespace Volo.Abp.Cli.Http;
@ -55,29 +55,32 @@ public static class CliHttpClientExtensions
cancellationToken = cancellationTokenSource.Token; cancellationToken = cancellationTokenSource.Token;
} }
return await HttpPolicyExtensions var delays = sleepDurations.ToArray();
.HandleTransientHttpError()
.OrResult(msg => !msg.IsSuccessStatusCode) return await RetryHelper.ExecuteAsync(
.WaitAndRetryAsync(sleepDurations, _ => httpClient.GetAsync(url, cancellationToken.Value),
(responseMessage, timeSpan, retryCount, context) => new RetryOptions<HttpResponseMessage>
{
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( logger?.LogWarning(
$"{retryCount}. HTTP request attempt failed to {url} with an error: {httpErrorCode}{responseMessage.Exception.Message}. " + $"{attempt.RetryCount}. HTTP request attempt failed to {url} with an error: {attempt.Exception.Message}. " +
$"Waiting {timeSpan.TotalSeconds} secs for the next try..."); $"Waiting {attempt.RetryDelay.TotalSeconds} secs for the next try...");
} }
else if (responseMessage.Result != null) else if (attempt.Result != null)
{ {
logger?.LogWarning( logger?.LogWarning(
$"{retryCount}. HTTP request attempt failed to {url} with an error: {(int)responseMessage.Result.StatusCode}-{responseMessage.Result.ReasonPhrase}. " + $"{attempt.RetryCount}. HTTP request attempt failed to {url} with an error: {(int)attempt.Result.StatusCode}-{attempt.Result.ReasonPhrase}. " +
$"Waiting {timeSpan.TotalSeconds} secs for the next try..."); $"Waiting {attempt.RetryDelay.TotalSeconds} secs for the next try...");
} }
}) return Task.CompletedTask;
.ExecuteAsync(async () => await httpClient.GetAsync(url, cancellationToken.Value)); }
});
} }
} }

49
framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryAttempt.cs

@ -0,0 +1,49 @@
using System;
namespace Volo.Abp.Threading;
/// <summary>
/// A failed attempt that <see cref="RetryHelper"/> is about to retry.
/// </summary>
public class RetryAttempt
{
/// <summary>
/// Number of the retry that is about to be performed, starting from 1.
/// </summary>
public int RetryCount { get; }
/// <summary>
/// How long to wait before the retry.
/// </summary>
public TimeSpan RetryDelay { get; }
/// <summary>
/// The exception that caused the retry. Null if the attempt is retried because of its result.
/// </summary>
public Exception? Exception { get; }
public RetryAttempt(int retryCount, TimeSpan retryDelay, Exception? exception)
{
RetryCount = retryCount;
RetryDelay = retryDelay;
Exception = exception;
}
}
/// <summary>
/// A failed attempt that <see cref="RetryHelper"/> is about to retry.
/// </summary>
/// <typeparam name="TResult">Type of the value returned by the retried action.</typeparam>
public class RetryAttempt<TResult> : RetryAttempt
{
/// <summary>
/// The result that caused the retry. Default if the attempt is retried because of an exception.
/// </summary>
public TResult? Result { get; }
public RetryAttempt(int retryCount, TimeSpan retryDelay, Exception? exception, TResult? result)
: base(retryCount, retryDelay, exception)
{
Result = result;
}
}

232
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;
/// <summary>
/// Runs an action and retries it while it keeps failing, waiting between the attempts.
/// See <see cref="RetryOptions"/> to control the retry count, the delay and which failures are retried.
/// </summary>
public static class RetryHelper
{
// Task.Delay rejects a longer delay on the netstandard targets.
private static readonly TimeSpan MaxDelay = TimeSpan.FromMilliseconds(int.MaxValue);
/// <summary>
/// Runs the given action and retries it while it throws a retryable exception.
/// Rethrows the last exception when the retries are exhausted.
/// </summary>
public static async Task ExecuteAsync(
Func<CancellationToken, Task> 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);
}
}
/// <summary>
/// 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.
/// </summary>
public static async Task<TResult> ExecuteAsync<TResult>(
Func<CancellationToken, Task<TResult>> action,
RetryOptions<TResult>? options = null,
CancellationToken cancellationToken = default)
{
Check.NotNull(action, nameof(action));
options ??= new RetryOptions<TResult>();
// 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<TResult>.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<TResult>(retryCount, delay, exception, exception == null ? result : default));
}
if (hasResult)
{
await TryDisposeAsync(result);
}
await WaitAsync(delay, cancellationToken);
}
}
private static void Validate(
int maxRetryCount,
Func<int, TimeSpan> delayFactory,
Func<Exception, bool> 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<int, TimeSpan> 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>(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);
}
}
}

69
framework/src/Volo.Abp.Core/Volo/Abp/Threading/RetryOptions.cs

@ -0,0 +1,69 @@
using System;
using System.Threading.Tasks;
namespace Volo.Abp.Threading;
/// <summary>
/// Options to control how <see cref="RetryHelper"/> retries a failing action.
/// </summary>
public class RetryOptions
{
/// <summary>
/// How many times to retry after the initial attempt fails. Default: 3.
/// Set to <see cref="int.MaxValue"/> to retry forever.
/// </summary>
public int MaxRetryCount { get; set; } = 3;
/// <summary>
/// Returns how long to wait before the given retry.
/// Default: 2^retryCount seconds, up to the longest delay that can be waited for.
/// </summary>
public Func<int, TimeSpan> DelayFactory { get; set; } = RetryHelper.GetExponentialDelay;
/// <summary>
/// Decides if the action should be retried after the given exception.
/// Default: retries any exception except <see cref="OperationCanceledException"/>.
/// </summary>
public Func<Exception, bool> ShouldRetryOnException { get; set; } = exception => exception is not OperationCanceledException;
/// <summary>
/// Called once per retry, before waiting.
/// </summary>
public Func<RetryAttempt, Task>? OnRetry { get; set; }
}
/// <summary>
/// Options to control how <see cref="RetryHelper"/> retries a failing action that returns a value.
/// The action can also be retried because of the value it returned.
/// </summary>
/// <typeparam name="TResult">Type of the value returned by the retried action.</typeparam>
public class RetryOptions<TResult>
{
/// <summary>
/// How many times to retry after the initial attempt fails. Default: 3.
/// Set to <see cref="int.MaxValue"/> to retry forever.
/// </summary>
public int MaxRetryCount { get; set; } = 3;
/// <summary>
/// Returns how long to wait before the given retry.
/// Default: 2^retryCount seconds, up to the longest delay that can be waited for.
/// </summary>
public Func<int, TimeSpan> DelayFactory { get; set; } = RetryHelper.GetExponentialDelay;
/// <summary>
/// Decides if the action should be retried after the given exception.
/// Default: retries any exception except <see cref="OperationCanceledException"/>.
/// </summary>
public Func<Exception, bool> ShouldRetryOnException { get; set; } = exception => exception is not OperationCanceledException;
/// <summary>
/// Decides if the action should be retried because of the value it returned. Default: no result is retried.
/// </summary>
public Func<TResult, bool> ShouldRetryOnResult { get; set; } = _ => false;
/// <summary>
/// Called once per retry, before the retried result is disposed and before waiting.
/// </summary>
public Func<RetryAttempt<TResult>, Task>? OnRetry { get; set; }
}

1027
framework/test/Volo.Abp.Core.Tests/Volo/Abp/Threading/RetryHelper_Tests.cs

File diff suppressed because it is too large

4
modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo.Abp.FeatureManagement.Domain.csproj

@ -18,8 +18,4 @@
<ProjectReference Include="..\Volo.Abp.FeatureManagement.Domain.Shared\Volo.Abp.FeatureManagement.Domain.Shared.csproj" /> <ProjectReference Include="..\Volo.Abp.FeatureManagement.Domain.Shared\Volo.Abp.FeatureManagement.Domain.Shared.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Polly" />
</ItemGroup>
</Project> </Project>

1
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.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Polly;
using Volo.Abp.Caching; using Volo.Abp.Caching;
using Volo.Abp.Data; using Volo.Abp.Data;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;

29
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;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Polly;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.Features; using Volo.Abp.Features;
using Volo.Abp.Threading; using Volo.Abp.Threading;
@ -95,17 +94,8 @@ public class FeatureDynamicInitializer : ITransientDependency
var staticFeatureSaver = ServiceProvider.GetRequiredService<IStaticFeatureSaver>(); var staticFeatureSaver = ServiceProvider.GetRequiredService<IStaticFeatureSaver>();
await Policy await RetryHelper.ExecuteAsync(
.Handle<Exception>() async _ =>
.WaitAndRetryAsync(
8,
retryAttempt => TimeSpan.FromSeconds(
Volo.Abp.RandomHelper.GetRandom(
(int)Math.Pow(2, retryAttempt) * 8,
(int)Math.Pow(2, retryAttempt) * 12)
)
)
.ExecuteAsync(async _ =>
{ {
try try
{ {
@ -114,9 +104,20 @@ public class FeatureDynamicInitializer : ITransientDependency
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogException(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( protected virtual async Task PreCacheDynamicFeaturesAsync(

1
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;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Polly;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore;

4
modules/permission-management/src/Volo.Abp.PermissionManagement.Domain/Volo.Abp.PermissionManagement.Domain.csproj

@ -23,8 +23,4 @@
<ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.Json\Volo.Abp.Json.csproj" /> <ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.Json\Volo.Abp.Json.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Polly" />
</ItemGroup>
</Project> </Project>

1
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.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Polly;
using Volo.Abp.Authorization; using Volo.Abp.Authorization;
using Volo.Abp.Authorization.Permissions; using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Caching; using Volo.Abp.Caching;

29
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;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Polly;
using Volo.Abp.Authorization.Permissions; using Volo.Abp.Authorization.Permissions;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.Threading; using Volo.Abp.Threading;
@ -95,17 +94,8 @@ public class PermissionDynamicInitializer : ITransientDependency
var staticPermissionSaver = ServiceProvider.GetRequiredService<IStaticPermissionSaver>(); var staticPermissionSaver = ServiceProvider.GetRequiredService<IStaticPermissionSaver>();
await Policy await RetryHelper.ExecuteAsync(
.Handle<Exception>() async _ =>
.WaitAndRetryAsync(
8,
retryAttempt => TimeSpan.FromSeconds(
Volo.Abp.RandomHelper.GetRandom(
(int)Math.Pow(2, retryAttempt) * 8,
(int)Math.Pow(2, retryAttempt) * 12)
)
)
.ExecuteAsync(async _ =>
{ {
try try
{ {
@ -115,9 +105,20 @@ public class PermissionDynamicInitializer : ITransientDependency
{ {
Logger.LogException(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 PreCacheDynamicPermissionsAsync( protected virtual async Task PreCacheDynamicPermissionsAsync(

4
modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo.Abp.SettingManagement.Domain.csproj

@ -22,8 +22,4 @@
<ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.Caching\Volo.Abp.Caching.csproj" /> <ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.Caching\Volo.Abp.Caching.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Polly" />
</ItemGroup>
</Project> </Project>

1
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.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Polly;
using Volo.Abp.Caching; using Volo.Abp.Caching;
using Volo.Abp.Data; using Volo.Abp.Data;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;

29
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;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Polly;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.Settings; using Volo.Abp.Settings;
using Volo.Abp.Threading; using Volo.Abp.Threading;
@ -96,17 +95,8 @@ public class SettingDynamicInitializer : ITransientDependency
var staticSettingSaver = ServiceProvider.GetRequiredService<IStaticSettingSaver>(); var staticSettingSaver = ServiceProvider.GetRequiredService<IStaticSettingSaver>();
await Policy await RetryHelper.ExecuteAsync(
.Handle<Exception>() async _ =>
.WaitAndRetryAsync(
8,
retryAttempt => TimeSpan.FromSeconds(
Volo.Abp.RandomHelper.GetRandom(
(int)Math.Pow(2, retryAttempt) * 8,
(int)Math.Pow(2, retryAttempt) * 12)
)
)
.ExecuteAsync(async _ =>
{ {
try try
{ {
@ -115,9 +105,20 @@ public class SettingDynamicInitializer : ITransientDependency
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogException(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( protected virtual async Task PreCacheDynamicSettingsAsync(

Loading…
Cancel
Save