-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
ChaosStrategy.cs
46 lines (39 loc) · 2.06 KB
/
ChaosStrategy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using Polly.Simmy.Utils;
namespace Polly.Simmy;
/// <summary>
/// Base class for chaos strategies.
/// </summary>
public abstract class ChaosStrategy : ResilienceStrategy
{
private readonly Func<double> _randomizer;
/// <summary>
/// Initializes a new instance of the <see cref="ChaosStrategy"/> class.
/// </summary>
/// <param name="options">The chaos strategy options.</param>
protected ChaosStrategy(ChaosStrategyOptions options)
{
Guard.NotNull(options);
Guard.NotNull(options.Randomizer);
_randomizer = options.Randomizer;
InjectionRateGenerator = options.InjectionRateGenerator is not null ? options.InjectionRateGenerator : (_) => new(options.InjectionRate);
EnabledGenerator = options.EnabledGenerator is not null ? options.EnabledGenerator : (_) => new(options.Enabled);
}
/// <summary>
/// Gets the injection rate for a given execution, which the value should be between [0, 1] (inclusive).
/// </summary>
internal Func<InjectionRateGeneratorArguments, ValueTask<double>> InjectionRateGenerator { get; }
/// <summary>
/// Gets a value that indicates whether or not the chaos strategy is enabled for a given execution.
/// </summary>
internal Func<EnabledGeneratorArguments, ValueTask<bool>> EnabledGenerator { get; }
/// <summary>
/// Determines whether or not the chaos strategy should be injected based on the injection rate and enabled flag.
/// </summary>
/// <param name="context">The <see cref="ResilienceContext"/> instance.</param>
/// <returns>A boolean value that indicates whether or not the chaos strategy should be injected.</returns>
/// <remarks>Use this method before injecting any chaos strategy to evaluate whether a given chaos strategy needs to be injected during the execution.</remarks>
protected async ValueTask<bool> ShouldInjectAsync(ResilienceContext context) =>
await ChaosStrategyHelper
.ShouldInjectAsync(context, InjectionRateGenerator, EnabledGenerator, _randomizer)
.ConfigureAwait(false);
}