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

Introduce Polly.Extensions project #1088

Merged
merged 12 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions build.cake
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ Task("__RunMutationTests")
.Does(() =>
{
TestProject(File("./src/Polly.Core/Polly.Core.csproj"), File("./src/Polly.Core.Tests/Polly.Core.Tests.csproj"), "Polly.Core.csproj");
TestProject(File("./src/Polly.Hosting/Polly.Hosting.csproj"), File("./src/Polly.Hosting.Tests/Polly.Hosting.Tests.csproj"), "Polly.Hosting.csproj");
TestProject(File("./src/Polly/Polly.csproj"), File("./src/Polly.Specs/Polly.Specs.csproj"), "Polly.csproj");

void TestProject(FilePath proj, FilePath testProj, string project)
Expand Down
3 changes: 1 addition & 2 deletions eng/Common.targets
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
</ItemGroup>

<ItemGroup Condition="'$(LegacySupport)' == 'true' AND !$([MSBuild]::IsTargetFrameworkCompatible($(TargetFramework), 'netcoreapp3.1'))">
<Compile Include="$(MSBuildThisFileDirectory)\..\src\LegacySupport\*.cs" LinkBase="LegacySupport" />
<Compile Include="$(MSBuildThisFileDirectory)..\src\LegacySupport\*.cs" LinkBase="LegacySupport" />
</ItemGroup>

</Project>
16 changes: 15 additions & 1 deletion src/Directory.Packages.props
martincostello marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,30 @@
<PackageVersion Include="GitHubActionsTestLogger" Version="2.0.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
<PackageVersion Include="Moq" Version="4.18.4" />
<PackageVersion Include="ReportGenerator" Version="5.1.19" />
<PackageVersion Include="SonarAnalyzer.CSharp" Version="8.51.0.59060" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.435" />
<PackageVersion Include="System.ComponentModel.Annotations" Version="4.5.0" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="7.0.0" />
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
<PackageVersion Include="System.ValueTuple" Version="4.5.0" />
<PackageVersion Include="xunit" Version="2.4.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.4.5" />
</ItemGroup>
</Project>
<ItemGroup Condition="$(TargetFramework) == 'net7.0'">
<PackageVersion Include="Microsoft.Extensions.Options" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
</ItemGroup>
<ItemGroup Condition="$(TargetFramework) == 'net6.0'">
<PackageVersion Include="Microsoft.Extensions.Options" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
</ItemGroup>
<ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible($(TargetFramework), 'netcoreapp3.1'))">
<PackageVersion Include="Microsoft.Extensions.Options" Version="2.2.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="2.2.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Moq;
using Polly.Builder;
using Polly.Telemetry;
using Polly.Utils;
Expand All @@ -16,4 +17,25 @@ public void Ctor_EnsureDefaults()
options.TimeProvider.Should().Be(TimeProvider.System);
options.TelemetryFactory.Should().Be(NullResilienceTelemetryFactory.Instance);
}

[Fact]
public void Ctor_Copy_EnsureCopied()
{
var options = new ResilienceStrategyBuilderOptions
{
BuilderName = "test",
TelemetryFactory = Mock.Of<ResilienceTelemetryFactory>(),
TimeProvider = new FakeTimeProvider().Object
};

options.Properties.Set(new ResiliencePropertyKey<int>("A"), 1);
options.Properties.Set(new ResiliencePropertyKey<int>("B"), 2);

var other = new ResilienceStrategyBuilderOptions(options);

other.BuilderName.Should().Be("test");
other.TelemetryFactory.Should().BeSameAs(options.TelemetryFactory);
other.TimeProvider.Should().BeSameAs(options.TimeProvider);
other.Properties.Should().BeEquivalentTo(options.Properties);
}
}
29 changes: 29 additions & 0 deletions src/Polly.Core/Builder/ResilienceStrategyBuilderOptions.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Polly.Telemetry;

Expand All @@ -8,6 +9,34 @@ namespace Polly.Builder;
/// </summary>
public class ResilienceStrategyBuilderOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="ResilienceStrategyBuilderOptions"/> class.
/// </summary>
public ResilienceStrategyBuilderOptions()
{
}

/// <summary>
/// Initializes a new instance of the <see cref="ResilienceStrategyBuilderOptions"/> class.
/// </summary>
/// <param name="other">The options to copy the values from.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public ResilienceStrategyBuilderOptions(ResilienceStrategyBuilderOptions other)
{
Guard.NotNull(other);

BuilderName = other.BuilderName;
TelemetryFactory = other.TelemetryFactory;
TimeProvider = other.TimeProvider;

IDictionary<string, object?> props = Properties;

foreach (KeyValuePair<string, object?> pair in other.Properties)
{
props.Add(pair.Key, pair.Value);
}
}

/// <summary>
/// Gets or sets the name of the builder.
/// </summary>
Expand Down
3 changes: 2 additions & 1 deletion src/Polly.Core/Polly.Core.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net7.0;net6.0;netstandard2.0;net472;net461</TargetFrameworks>
<TargetFrameworks>net7.0;net6.0;netstandard2.0;net472;net462</TargetFrameworks>
<AssemblyTitle>Polly.Core</AssemblyTitle>
<RootNamespace>Polly</RootNamespace>
<Nullable>enable</Nullable>
Expand All @@ -11,6 +11,7 @@
<SkipPollyUsings>true</SkipPollyUsings>
<MutationScore>100</MutationScore>
<LegacySupport>true</LegacySupport>
<InjectSharedSources>true</InjectSharedSources>
</PropertyGroup>

<ItemGroup>
Expand Down
20 changes: 20 additions & 0 deletions src/Polly.Hosting.Tests/Polly.Hosting.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net7.0;net6.0</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('Windows'))">$(TargetFrameworks);net481</TargetFrameworks>
<ProjectType>Test</ProjectType>
<UseDefaultAnalyzers>true</UseDefaultAnalyzers>
<Nullable>enable</Nullable>
<SkipPollyUsings>true</SkipPollyUsings>
<Threshold>100</Threshold>
<NoWarn>$(NoWarn);SA1600;SA1204</NoWarn>
<Include>[Polly.Hosting]*</Include>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Polly.Hosting\Polly.Hosting.csproj" />
</ItemGroup>
</Project>
12 changes: 12 additions & 0 deletions src/Polly.Hosting.Tests/PollyDependencyInjectionKeysTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Polly.DependencyInjection;

namespace Polly.Hosting.Tests;

public class PollyDependencyInjectionKeysTests
{
[Fact]
public void ServiceProvider_Ok()
{
PollyDependencyInjectionKeys.ServiceProvider.Key.Should().Be("Polly.DependencyInjection.ServiceProvider");
}
}
208 changes: 208 additions & 0 deletions src/Polly.Hosting.Tests/PollyServiceCollectionExtensionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Polly.Builder;
using Polly.DependencyInjection;
using Polly.Registry;
using Polly.Telemetry;

namespace Polly.Hosting.Tests;

public class PollyServiceCollectionExtensionTests
{
private const string Key = "my-strategy";
private ServiceCollection _services;

public PollyServiceCollectionExtensionTests() => _services = new ServiceCollection();

[Fact]
public void AddResilienceStrategy_ArgValidation()
{
_services = null!;
Assert.Throws<ArgumentNullException>(() => AddResilienceStrategy(Key));

_services = new ServiceCollection();
Assert.Throws<ArgumentNullException>(() => _services.AddResilienceStrategy(Key, null!));
}

[Fact]
public void AddResilienceStrategy_EnsureRegisteredServices()
{
AddResilienceStrategy(Key);

var serviceProvider = _services.BuildServiceProvider();

serviceProvider.GetServices<ResilienceStrategyBuilder>().Should().NotBeNull();
serviceProvider.GetServices<ResilienceStrategyRegistry<string>>().Should().NotBeNull();
serviceProvider.GetServices<ResilienceStrategyProvider<string>>().Should().NotBeNull();
serviceProvider.GetServices<ResilienceStrategyBuilder>().Should().NotBeSameAs(serviceProvider.GetServices<ResilienceStrategyBuilder>());
}

[Fact]
public void AddResilienceStrategy_MultipleRegistries_Ok()
{
AddResilienceStrategy(Key);
_services.AddResilienceStrategy(10, context => context.Builder.AddStrategy(new TestStrategy()));

var serviceProvider = _services.BuildServiceProvider();

serviceProvider.GetRequiredService<ResilienceStrategyRegistry<string>>().Get(Key).Should().NotBeNull();
serviceProvider.GetRequiredService<ResilienceStrategyRegistry<int>>().Get(10).Should().NotBeNull();
}

[Fact]
public void AddResilienceStrategy_EnsureContextFilled()
{
bool asserted = false;

_services.AddResilienceStrategy(Key, context =>
{
context.Key.Should().Be(Key);
context.Builder.Should().NotBeNull();
context.ServiceProvider.Should().NotBeNull();
context.Builder.AddStrategy(new TestStrategy());
asserted = true;
});

CreateProvider().Get(Key);

asserted.Should().BeTrue();
}

[Fact]
public void AddResilienceStrategy_EnsureResilienceStrategyBuilderOptionsApplied()
{
var telemetry = Mock.Of<ResilienceTelemetry>();
var telemetryFactory = Mock.Of<ResilienceTelemetryFactory>(v => v.Create(It.IsAny<ResilienceTelemetryFactoryContext>()) == telemetry);
var asserted = false;
var key = new ResiliencePropertyKey<int>("A");
ResilienceStrategyBuilderOptions? globalOptions = null;

_services.Configure<ResilienceStrategyBuilderOptions>(options =>
{
options.BuilderName = "dummy";
options.TelemetryFactory = telemetryFactory;
options.Properties.Set(key, 123);
globalOptions = options;
});

AddResilienceStrategy(Key, context =>
{
context.BuilderProperties.Should().NotBeSameAs(globalOptions!.Properties);
context.BuilderName.Should().Be("dummy");
context.Telemetry.Should().Be(telemetry);
context.BuilderProperties.TryGetValue(key, out var val).Should().BeTrue();
val.Should().Be(123);
asserted = true;
});

CreateProvider().Get(Key);

asserted.Should().BeTrue();
}

[Fact]
public void AddResilienceStrategy_EnsureServicesNotAddedTwice()
{
AddResilienceStrategy(Key);
var count = _services.Count;

AddResilienceStrategy(Key);

_services.Count.Should().Be(count + 1);
}

[Fact]
public void AddResilienceStrategy_Single_Ok()
{
AddResilienceStrategy(Key);

var provider = CreateProvider();

var strategy = provider.Get(Key);
strategy.Should().BeOfType<TestStrategy>();
provider.Get("my-strategy").Should().BeSameAs(provider.Get("my-strategy"));
}

[Fact]
public void AddResilienceStrategy_Twice_LastOneWins()
{
bool firstCalled = false;
bool secondCalled = false;

AddResilienceStrategy(Key, _ => firstCalled = true);
AddResilienceStrategy(Key, _ => secondCalled = true);

CreateProvider().Get(Key);

firstCalled.Should().BeFalse();
secondCalled.Should().BeTrue();
}

[Fact]
public void AddResilienceStrategy_Multiple_Ok()
{
for (int i = 0; i < 10; i++)
{
AddResilienceStrategy(i.ToString(CultureInfo.InvariantCulture));
}

var provider = CreateProvider();

Enumerable.Range(0, 10).Select(i => i.ToString(CultureInfo.InvariantCulture)).Distinct().Should().HaveCount(10);
}

[Fact]
public void AddResilienceStrategy_CustomTelemetryFactory_EnsureUsed()
{
var telemetry = new Mock<ResilienceTelemetry>(MockBehavior.Strict);
var factory = new Mock<ResilienceTelemetryFactory>(MockBehavior.Strict);
factory.Setup(v => v.Create(It.IsAny<ResilienceTelemetryFactoryContext>())).Returns(telemetry.Object);

var asserted = false;

_services.AddSingleton<ResilienceTelemetryFactory>(factory.Object);
_services.AddResilienceStrategy(
Key,
context =>
{
context.Builder.Options.TelemetryFactory.Should().Be(factory.Object);
context.Builder.AddStrategy(context =>
{
context.Telemetry.Should().Be(telemetry.Object);

asserted = true;
return new TestStrategy();
});
});

CreateProvider().Get(Key);

asserted.Should().BeTrue();
}

private void AddResilienceStrategy(string key, Action<ResilienceStrategyBuilderContext>? onBuilding = null)
{
_services.AddResilienceStrategy(key, context =>
{
context.Builder.AddStrategy(context =>
{
onBuilding?.Invoke(context);
return new TestStrategy();
});
});
}

private ResilienceStrategyProvider<string> CreateProvider()
{
return _services.BuildServiceProvider().GetRequiredService<ResilienceStrategyProvider<string>>();
}

private class TestStrategy : ResilienceStrategy
{
protected override ValueTask<TResult> ExecuteCoreAsync<TResult, TState>(
Func<ResilienceContext, TState, ValueTask<TResult>> callback,
ResilienceContext context,
TState state) => throw new NotSupportedException();
}
}
Loading