Skip to content

Allow a feature flag to require all registered feature filters be enabled. #192

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

Closed
Closed
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
Expand Up @@ -22,6 +22,7 @@ sealed class ConfigurationFeatureFlagDefinitionProvider : IFeatureFlagDefinition
private const string FeatureManagementSectionName = "FeatureManagement";
private const string FeatureFlagDefinitionsSectionName = "FeatureFlags";
private const string FeatureFiltersSectionName = "EnabledFor";
private const string RequirementTypeKeyword = "RequirementType";
private readonly IConfiguration _configuration;
private readonly ConcurrentDictionary<string, FeatureFlagDefinition> _featureFlagDefinitions;
private IDisposable _changeSubscription;
Expand Down Expand Up @@ -125,6 +126,8 @@ We support

Debug.Assert(configurationSection != null);

RequirementType requirementType = RequirementType.Any;

var enabledFor = new List<FeatureFilterConfiguration>();

string val = configurationSection.Value; // configuration[$"{featureName}"];
Expand All @@ -149,6 +152,20 @@ We support
}
else
{
string rawRequirementType = configurationSection[RequirementTypeKeyword];

if (!string.IsNullOrEmpty(rawRequirementType))
{
if (!Enum.TryParse(rawRequirementType, true, out RequirementType r))
{
throw new FeatureManagementException(
FeatureManagementError.InvalidConfiguration,
$"Invalid requirement type value for feature {configurationSection.Key}.");
}

requirementType = r;
}

IEnumerable<IConfigurationSection> filterSections = configurationSection.GetSection(FeatureFiltersSectionName).GetChildren();

foreach (IConfigurationSection section in filterSections)
Expand All @@ -171,6 +188,7 @@ We support
{
Name = configurationSection.Key,
EnabledFor = enabledFor,
RequirementType = requirementType
};
}

Expand Down
6 changes: 6 additions & 0 deletions src/Microsoft.FeatureManagement/FeatureFlagDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,11 @@ public class FeatureFlagDefinition
/// The feature filters that the feature flag can be enabled for.
/// </summary>
public IEnumerable<FeatureFilterConfiguration> EnabledFor { get; set; } = Enumerable.Empty<FeatureFilterConfiguration>();

/// <summary>
/// Determines whether any or all registered feature filters must be enabled for the feature to be considered enabled
/// The default value is <see cref="RequirementType.Any"/>.
/// </summary>
public RequirementType RequirementType { get; set; } = RequirementType.Any;
}
}
81 changes: 48 additions & 33 deletions src/Microsoft.FeatureManagement/FeatureManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private async Task<bool> IsEnabledAsync<TContext>(string feature, TContext appCo
}
}

bool enabled = false;
bool flagEnabled = false;

FeatureFlagDefinition featureDefinition = await _featureDefinitionProvider.GetFeatureFlagDefinitionAsync(feature, cancellationToken).ConfigureAwait(false);

Expand All @@ -94,7 +94,7 @@ private async Task<bool> IsEnabledAsync<TContext>(string feature, TContext appCo

if (featureDefinition.EnabledFor.Any(featureFilter => string.Equals(featureFilter.Name, "AlwaysOn", StringComparison.OrdinalIgnoreCase)))
{
enabled = true;
flagEnabled = true;
}
else
{
Expand All @@ -104,6 +104,8 @@ private async Task<bool> IsEnabledAsync<TContext>(string feature, TContext appCo

foreach (FeatureFilterConfiguration featureFilterConfiguration in featureDefinition.EnabledFor)
{
bool filterEnabled = false;

if (string.IsNullOrEmpty(featureFilterConfiguration.Name))
{
throw new FeatureManagementException(
Expand All @@ -125,48 +127,61 @@ private async Task<bool> IsEnabledAsync<TContext>(string feature, TContext appCo
{
_logger.LogWarning(errorMessage);
}

continue;
}

var context = new FeatureFilterEvaluationContext()
{
FeatureFlagName = featureDefinition.Name,
Parameters = featureFilterConfiguration.Parameters
};

//
// IFeatureFilter
if (filter is IFeatureFilter featureFilter)
else
{
if (await featureFilter.EvaluateAsync(context, cancellationToken).ConfigureAwait(false))
var context = new FeatureFilterEvaluationContext()
{
enabled = true;
FeatureFlagName = featureDefinition.Name,
Parameters = featureFilterConfiguration.Parameters
};

break;
//
// IFeatureFilter
if (filter is IFeatureFilter featureFilter)
{
filterEnabled = await featureFilter.EvaluateAsync(context, cancellationToken).ConfigureAwait(false);
}
//
// IContextualFeatureFilter
else if (useAppContext &&
TryGetContextualFeatureFilter(featureFilterConfiguration.Name, typeof(TContext), out ContextualFeatureFilterEvaluator contextualFilter))
{
filterEnabled = await contextualFilter.EvaluateAsync(context, appContext, cancellationToken).ConfigureAwait(false);
}
//
// The filter doesn't implement a feature filter interface capable of performing the evaluation
else
{
throw new FeatureManagementException(
FeatureManagementError.InvalidFeatureFilter,
useAppContext ?
$"The feature filter '{featureFilterConfiguration.Name}' specified for the feature '{feature}' is not capable of evaluating the requested feature with the provided context." :
$"The feature filter '{featureFilterConfiguration.Name}' specified for the feature '{feature}' is not capable of evaluating the requested feature.");
}
}
//
// IContextualFeatureFilter
else if (useAppContext &&
TryGetContextualFeatureFilter(featureFilterConfiguration.Name, typeof(TContext), out ContextualFeatureFilterEvaluator contextualFilter))

if (featureDefinition.RequirementType == RequirementType.Any)
{
if (await contextualFilter.EvaluateAsync(context, appContext, cancellationToken).ConfigureAwait(false))
if (filterEnabled)
{
enabled = true;
flagEnabled = true;

break;
}
}
//
// The filter doesn't implement a feature filter interface capable of performing the evaluation
else
else /* require all filters */
{
throw new FeatureManagementException(
FeatureManagementError.InvalidFeatureFilter,
useAppContext ?
$"The feature filter '{featureFilterConfiguration.Name}' specified for the feature '{feature}' is not capable of evaluating the requested feature with the provided context." :
$"The feature filter '{featureFilterConfiguration.Name}' specified for the feature '{feature}' is not capable of evaluating the requested feature.");
if (!filterEnabled)
{
flagEnabled = false;

break;
}

//
// True unless short-circuited as false
flagEnabled = true;
}
}
}
Expand All @@ -187,10 +202,10 @@ private async Task<bool> IsEnabledAsync<TContext>(string feature, TContext appCo

foreach (ISessionManager sessionManager in _sessionManagers)
{
await sessionManager.SetAsync(feature, enabled, cancellationToken).ConfigureAwait(false);
await sessionManager.SetAsync(feature, flagEnabled, cancellationToken).ConfigureAwait(false);
}

return enabled;
return flagEnabled;
}

private IFeatureFilterMetadata GetFeatureFilterMetadata(string filterName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
namespace Microsoft.FeatureManagement
{
/// <summary>
/// Describes whether any or all features in a given set should be required to be considered enabled.
/// Describes whether any or all conditions in a set should be required to be true.
/// </summary>
public enum RequirementType
{
/// <summary>
/// The enabled state will be attained if any feature in the set is enabled.
/// The set of conditions will be evaluated as true if any condition in the set is true.
/// </summary>
Any,
/// <summary>
/// The enabled state will be attained if all features in the set are enabled.
/// The set of conditions will be evaluated as true if all the conditions in the set are true.
/// </summary>
All
}
Expand Down
44 changes: 44 additions & 0 deletions tests/Tests.FeatureManagement/FeatureManagement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public class FeatureManagement
private const string ContextualFeature = "ContextualFeature";
private const string WithSuffixFeature = "WithSuffixFeature";
private const string WithoutSuffixFeature = "WithoutSuffixFeature";
private const string AnyFilterFeature = "AnyFilterFeature";
private const string AllFiltersFeature = "AllFiltersFeature";

[Fact]
public async Task ReadsConfiguration()
Expand Down Expand Up @@ -209,6 +211,48 @@ public async Task AllowsSuffix()
Assert.True(called);
}

[Fact]
public async Task UsesRequirementType()
{
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

var services = new ServiceCollection();

services
.AddSingleton(config)
.AddFeatureManagement()
.AddFeatureFilter<TestFilter>()
.AddFeatureFilter<Test2Filter>();

ServiceProvider serviceProvider = services.BuildServiceProvider();

IFeatureManager featureManager = serviceProvider.GetRequiredService<IFeatureManager>();

IEnumerable<IFeatureFilterMetadata> featureFilters = serviceProvider.GetRequiredService<IEnumerable<IFeatureFilterMetadata>>();

TestFilter testFeatureFilter = (TestFilter)featureFilters.First(f => f is TestFilter && !(f is Test2Filter));

Test2Filter testFeatureFilter2 = (Test2Filter)featureFilters.First(f => f is Test2Filter);

testFeatureFilter.Callback = testFeatureFilter2.Callback = (evaluationContext) => Task.FromResult(false);

Assert.False(await featureManager.IsEnabledAsync(AnyFilterFeature, CancellationToken.None));

Assert.False(await featureManager.IsEnabledAsync(AllFiltersFeature, CancellationToken.None));

testFeatureFilter.Callback = testFeatureFilter2.Callback = (evaluationContext) => Task.FromResult(true);

Assert.True(await featureManager.IsEnabledAsync(AnyFilterFeature, CancellationToken.None));

Assert.True(await featureManager.IsEnabledAsync(AllFiltersFeature, CancellationToken.None));

testFeatureFilter2.Callback = (evaluationContext) => Task.FromResult(false);

Assert.True(await featureManager.IsEnabledAsync(AnyFilterFeature, CancellationToken.None));

Assert.False(await featureManager.IsEnabledAsync(AllFiltersFeature, CancellationToken.None));
}

[Fact]
public async Task Integrates()
{
Expand Down
6 changes: 6 additions & 0 deletions tests/Tests.FeatureManagement/TestFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,10 @@ public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context, Cancella
return Callback?.Invoke(context) ?? Task.FromResult(false);
}
}

//
// Offers the same functionality as TestFilter, but allows a feature used in tests to reference two different filters
class Test2Filter : TestFilter
{
}
}
Loading