Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify AddStrategy method #1203

Merged
merged 3 commits into from
May 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Polly;
using Polly.Strategy;

namespace Polly.Core.Benchmarks;

Expand All @@ -13,14 +12,9 @@ internal static partial class Helper
{
for (var i = 0; i < count; i++)
{
builder.AddStrategy(new EmptyResilienceStrategy(), new BenchmarkResilienceStrategyOptions());
builder.AddStrategy(new EmptyResilienceStrategy());
}
}),
_ => throw new NotSupportedException()
};

private class BenchmarkResilienceStrategyOptions : ResilienceStrategyOptions
{
public override string StrategyType => "Benchmark";
}
}
10 changes: 5 additions & 5 deletions src/Polly.Core.Tests/Registry/ResilienceStrategyRegistryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public void Clear_Ok()
{
var registry = new ResilienceStrategyRegistry<string>();

registry.TryAddBuilder("C", (_, b) => b.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions()));
registry.TryAddBuilder("C", (_, b) => b.AddStrategy(new TestResilienceStrategy()));

registry.TryAdd("A", new TestResilienceStrategy());
registry.TryAdd("B", new TestResilienceStrategy());
Expand Down Expand Up @@ -74,7 +74,7 @@ public void Remove_Ok()
public void RemoveBuilder_Ok()
{
var registry = new ResilienceStrategyRegistry<string>();
registry.TryAddBuilder("A", (_, b) => b.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions()));
registry.TryAddBuilder("A", (_, b) => b.AddStrategy(new TestResilienceStrategy()));

registry.RemoveBuilder("A").Should().BeTrue();
registry.RemoveBuilder("A").Should().BeFalse();
Expand All @@ -88,7 +88,7 @@ public void GetStrategy_BuilderMultiInstance_EnsureMultipleInstances()
var builderName = "A";
var registry = CreateRegistry();
var strategies = new HashSet<ResilienceStrategy>();
registry.TryAddBuilder(StrategyId.Create(builderName), (_, builder) => builder.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions()));
registry.TryAddBuilder(StrategyId.Create(builderName), (_, builder) => builder.AddStrategy(new TestResilienceStrategy()));

for (int i = 0; i < 100; i++)
{
Expand All @@ -112,7 +112,7 @@ public void AddBuilder_GetStrategy_EnsureCalled()
var called = 0;
registry.TryAddBuilder(StrategyId.Create("A"), (key, builder) =>
{
builder.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions());
builder.AddStrategy(new TestResilienceStrategy());
builder.Properties.Set(StrategyId.ResilienceKey, key);
called++;
});
Expand Down Expand Up @@ -142,7 +142,7 @@ public void AddBuilder_EnsureStrategyKey()
var registry = CreateRegistry();
registry.TryAddBuilder(StrategyId.Create("A"), (_, builder) =>
{
builder.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions());
builder.AddStrategy(new TestResilienceStrategy());
builder.BuilderName.Should().Be("A");
builder.Properties.TryGetValue(TelemetryUtil.StrategyKey, out var val).Should().BeTrue();
val.Should().Be("Instance1");
Expand Down
38 changes: 22 additions & 16 deletions src/Polly.Core.Tests/ResilienceStrategyBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void AddStrategy_Single_Ok()
After = (_, _) => executions.Add(3),
};

builder.AddStrategy(first, new TestResilienceStrategyOptions());
builder.AddStrategy(first);

// act
var strategy = builder.Build();
Expand Down Expand Up @@ -63,9 +63,9 @@ public void AddStrategy_Multiple_Ok()
After = (_, _) => executions.Add(5),
};

builder.AddStrategy(first, new TestResilienceStrategyOptions());
builder.AddStrategy(second, new TestResilienceStrategyOptions());
builder.AddStrategy(third, new TestResilienceStrategyOptions());
builder.AddStrategy(first);
builder.AddStrategy(second);
builder.AddStrategy(third);

// act
var strategy = builder.Build();
Expand All @@ -88,8 +88,8 @@ public void AddStrategy_Duplicate_Throws()
// arrange
var executions = new List<int>();
var builder = new ResilienceStrategyBuilder()
.AddStrategy(NullResilienceStrategy.Instance, new TestResilienceStrategyOptions())
.AddStrategy(NullResilienceStrategy.Instance, new TestResilienceStrategyOptions());
.AddStrategy(NullResilienceStrategy.Instance)
.AddStrategy(NullResilienceStrategy.Instance);

builder.Invoking(b => b.Build())
.Should()
Expand Down Expand Up @@ -119,9 +119,9 @@ public void AddStrategy_MultipleNonDelegating_Ok()
After = () => executions.Add(5),
};

builder.AddStrategy(first, new TestResilienceStrategyOptions());
builder.AddStrategy(second, new TestResilienceStrategyOptions());
builder.AddStrategy(third, new TestResilienceStrategyOptions());
builder.AddStrategy(first);
builder.AddStrategy(second);
builder.AddStrategy(third);

// act
var strategy = builder.Build();
Expand All @@ -147,7 +147,7 @@ public void AddStrategy_AfterUsed_Throws()
builder.Build();

builder
.Invoking(b => b.AddStrategy(NullResilienceStrategy.Instance, new TestResilienceStrategyOptions()))
.Invoking(b => b.AddStrategy(NullResilienceStrategy.Instance))
.Should()
.Throw<InvalidOperationException>()
.WithMessage("Cannot add any more resilience strategies to the builder after it has been used to build a strategy once.");
Expand Down Expand Up @@ -179,7 +179,7 @@ public void AddStrategy_InvalidOptions_Throws()
var builder = new ResilienceStrategyBuilder();

builder
.Invoking(b => b.AddStrategy(NullResilienceStrategy.Instance, new TestResilienceStrategyOptions { StrategyName = null! }))
.Invoking(b => b.AddStrategy(_ => NullResilienceStrategy.Instance, new TestResilienceStrategyOptions { StrategyName = null! }))
.Should()
.Throw<ValidationException>()
.WithMessage(
Expand All @@ -197,7 +197,7 @@ public void AddStrategy_NullFactory_Throws()
var builder = new ResilienceStrategyBuilder();

builder
.Invoking(b => b.AddStrategy((Func<ResilienceStrategyBuilderContext, ResilienceStrategy>)null!, new TestResilienceStrategyOptions()))
.Invoking(b => b.AddStrategy(null!, new TestResilienceStrategyOptions()))
.Should()
.Throw<ArgumentNullException>()
.And.ParamName
Expand All @@ -221,17 +221,17 @@ public void AddStrategy_CombinePipelines_Ok()
After = (_, _) => executions.Add(6),
};

var pipeline1 = new ResilienceStrategyBuilder().AddStrategy(first, new TestResilienceStrategyOptions()).AddStrategy(second, new TestResilienceStrategyOptions()).Build();
var pipeline1 = new ResilienceStrategyBuilder().AddStrategy(first).AddStrategy(second).Build();

var third = new TestResilienceStrategy
{
Before = (_, _) => executions.Add(3),
After = (_, _) => executions.Add(5),
};
var pipeline2 = new ResilienceStrategyBuilder().AddStrategy(third, new TestResilienceStrategyOptions()).Build();
var pipeline2 = new ResilienceStrategyBuilder().AddStrategy(third).Build();

// act
var strategy = new ResilienceStrategyBuilder().AddStrategy(pipeline1, new TestResilienceStrategyOptions()).AddStrategy(pipeline2, new TestResilienceStrategyOptions()).Build();
var strategy = new ResilienceStrategyBuilder().AddStrategy(pipeline1).AddStrategy(pipeline2).Build();

// assert
strategy.Execute(_ => executions.Add(4));
Expand Down Expand Up @@ -305,7 +305,7 @@ public void Build_OnCreatingStrategy_EnsureRespected()
}
};

builder.AddStrategy(strategy, new TestResilienceStrategyOptions());
builder.AddStrategy(strategy);

// act
var finalStrategy = builder.Build();
Expand All @@ -314,6 +314,12 @@ public void Build_OnCreatingStrategy_EnsureRespected()
finalStrategy.Should().BeOfType<ResilienceStrategyPipeline>();
}

[Fact]
public void EmptyOptions_Ok()
{
ResilienceStrategyBuilder.EmptyOptions.Instance.StrategyType.Should().Be("Empty");
}

private class Strategy : ResilienceStrategy
{
public Action? Before { get; set; }
Expand Down
16 changes: 12 additions & 4 deletions src/Polly.Core/ResilienceStrategyBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,14 @@ public class ResilienceStrategyBuilder
/// Adds an already created strategy instance to the builder.
/// </summary>
/// <param name="strategy">The strategy instance.</param>
/// <param name="options">The options associated with the strategy. If none are provided the default instance of <see cref="ResilienceStrategyOptions"/> is created.</param>
/// <returns>The same builder instance.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="strategy"/> is null.</exception>
public ResilienceStrategyBuilder AddStrategy(ResilienceStrategy strategy, ResilienceStrategyOptions options)
/// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a strategy. The builder cannot be modified after it has been used.</exception>
public ResilienceStrategyBuilder AddStrategy(ResilienceStrategy strategy)
{
Guard.NotNull(strategy);
Guard.NotNull(options);

return AddStrategy(_ => strategy, options);
return AddStrategy(_ => strategy, EmptyOptions.Instance);
}

/// <summary>
Expand All @@ -64,6 +63,8 @@ public ResilienceStrategyBuilder AddStrategy(ResilienceStrategy strategy, Resili
/// <param name="options">The options associated with the strategy. If none are provided the default instance of <see cref="ResilienceStrategyOptions"/> is created.</param>
/// <returns>The same builder instance.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="factory"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a strategy. The builder cannot be modified after it has been used.</exception>
/// <exception cref="ValidationException">Thrown when the <paramref name="options"/> are invalid.</exception>
public ResilienceStrategyBuilder AddStrategy(Func<ResilienceStrategyBuilderContext, ResilienceStrategy> factory, ResilienceStrategyOptions options)
{
Guard.NotNull(factory);
Expand Down Expand Up @@ -121,4 +122,11 @@ private ResilienceStrategy CreateResilienceStrategy(Entry entry)
}

private sealed record Entry(Func<ResilienceStrategyBuilderContext, ResilienceStrategy> Factory, ResilienceStrategyOptions Properties);

internal sealed class EmptyOptions : ResilienceStrategyOptions
{
public static readonly EmptyOptions Instance = new();

public override string StrategyType => "Empty";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void AddResilienceStrategy_EnsureRegisteredServices()
public void AddResilienceStrategy_MultipleRegistries_Ok()
{
AddResilienceStrategy(Key);
_services.AddResilienceStrategy(10, context => context.AddStrategy(new TestStrategy(), new TestResilienceStrategyOptions()));
_services.AddResilienceStrategy(10, context => context.AddStrategy(new TestStrategy()));

var serviceProvider = _services.BuildServiceProvider();

Expand All @@ -67,7 +67,7 @@ public void AddResilienceStrategy_EnsureContextFilled()
context.Key.Should().Be(Key);
builder.Should().NotBeNull();
context.ServiceProvider.Should().NotBeNull();
builder.AddStrategy(new TestStrategy(), new TestResilienceStrategyOptions());
builder.AddStrategy(new TestStrategy());
asserted = true;
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task OnCircuitBreakWithServiceProvider_796()
var serviceCollection = new ServiceCollection().AddResilienceStrategy("my-strategy", (builder, context) =>
{
builder
.AddStrategy(new ServiceProviderStrategy(context.ServiceProvider), new TestResilienceStrategyOptions())
.AddStrategy(new ServiceProviderStrategy(context.ServiceProvider))
.AddAdvancedCircuitBreaker(options);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ public void EnableTelemetry_EnsureDiagnosticSourceUpdated()
{
_builder.EnableTelemetry(NullLoggerFactory.Instance);
_builder.Properties.GetValue(new ResiliencePropertyKey<DiagnosticSource?>("DiagnosticSource"), null).Should().BeOfType<ResilienceTelemetryDiagnosticSource>();
_builder.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions()).Build().Should().NotBeOfType<TestResilienceStrategy>();
_builder.AddStrategy(new TestResilienceStrategy()).Build().Should().NotBeOfType<TestResilienceStrategy>();
}

[Fact]
public void EnableTelemetry_EnsureLogging()
{
using var factory = TestUtilities.CreateLoggerFactory(out var fakeLogger);
_builder.EnableTelemetry(factory);
_builder.AddStrategy(new TestResilienceStrategy(), new TestResilienceStrategyOptions()).Build().Execute(_ => { });
_builder.AddStrategy(new TestResilienceStrategy()).Build().Execute(_ => { });

fakeLogger.GetRecords().Should().NotBeEmpty();
fakeLogger.GetRecords().Should().HaveCount(2);
Expand Down