Giter VIP home page Giter VIP logo

microsoft / featuremanagement-dotnet Goto Github PK

View Code? Open in Web Editor NEW
1.0K 36.0 112.0 2.41 MB

Microsoft.FeatureManagement provides standardized APIs for enabling feature flags within applications. Utilize this library to secure a consistent experience when developing applications that use patterns such as beta access, rollout, dark deployments, and more.

License: MIT License

Batchfile 0.01% PowerShell 0.97% C# 98.95% HTML 0.07%

featuremanagement-dotnet's Introduction

.NET Feature Management

Microsoft.FeatureManagement Microsoft.FeatureManagement.AspNetCore

Feature management provides a way to develop and expose application functionality based on features. Many applications have special requirements when a new feature is developed such as when the feature should be enabled and under what conditions. This library provides a way to define these relationships, and also integrates into common .NET code patterns to make exposing these features possible.

Get started

Quickstart: A quickstart guide is available to learn how to integrate feature flags from Azure App Configuration into your .NET applications.

Feature Reference: This document provides a full feature rundown.

API reference: This API reference details the API surface of the libraries contained within this repository.

Examples

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

featuremanagement-dotnet's People

Contributors

abhilasharora avatar amerjusupovic avatar andreytretyak avatar antmdvs avatar avanigupta avatar brental avatar davkean avatar jason-roberts avatar jimmyca15 avatar josephwoodward avatar kimsey0 avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar msftgits avatar neiljohari avatar rossgrambo avatar thompson-tomo avatar weihanli avatar zhiyuanliang-ms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

featuremanagement-dotnet's Issues

Any plans on creating an abstraction package?

Many of the Microsoft.Extensions packages comes with an abstraction package containing the fundamental interfaces for a component. This can be a lifesaver when trying to untangle dependency graphs/verison constraints in larger projects.

With this in mind - and in the light of the dependencies that the feature toggle package have taken - are there any plans to extract IFeatureManager, IFeatureFilter et. al. into a abstraction package?

Add a result filter for razor pages

Right now, there's no nice declarative way (that I could find) to add a feature flag to a razor page.

[FeatureGate(FeatureFlags.FeatureA)]
public class IndexModel : PageModel {...}

Doesn't work because FeatureGateAttribute only overrides OnActionExecutionAsync. I haven't tested this myself, but I believe if you also implement OnResultExecutingAsync you'll cover Razor pages. At least according to the docs Filter methods for Razor Pages in ASP.NET Core

Dynamic change a Feature and apply it at runtime without restarting the application

Hi,

I can't find any answer on all docs I've read so far, so here is my point :

The context :
I feed the IConfiguration object using the IConfigurationBuilder with an external ressource (Hashicorp Vault here), I don't work with the Appsettings file but with a Inmemory configuration provider (builder.AddInMemoryCollection) feed by my Json from Hashicorp .
It works well, and the services.AddFeatureManagement() allows me to use the IFeatureManager as expected for example.

My point :
I would like to dynamically change some feature toogle:
for example enable FeatureA which was previously disabled, or disable FeatureB which was previously enabled. It's easy to change my Json in HaschiCorp and implement a kind of polling to Hashicorp to get keep my features activation up to date. But I don't want to have to restart the application to get the new changes.

Is there any way to achieve this ? ie force the FeatureManagement lib to "update its information" during runtime ?
Or could we update the IConfiguration at runtime ? If yes the FeatureManagement will be updated as expected ?

Thank you for your help.

Guidance for Azure Functions

Hi,

We are currently interested in using the Feature Management services in our Azure Functions. We've figured out how to register the service and can connect to the App Configuration instance to resolve the state of the FeatureFlag, however, we weren't sure how the 'refresh' of the feature flag is supposed to work?

My current tests show that toggling the feature flag from enabled/disabled doesn't affect the result of
await _featureManager.IsEnabledAsync("TestFlag") and only seems to take effect upon function restart.

cheers

Configure services depending on the enabled feature

Hi,

What's the correct way to checking whether feature enabled from Startup.ConfigureServices?

I'd expect something like
services.AddForFeature(MyFeatures.RedisCache, x => x.Decorate<IMyService, MyCachedService>());

or
if (configuration.IsFeatureEnabled(MyFeatures.RedisCache)) { services.Decorate<IMyService, MyCachedService>(); }

but have not found a nice way of doing it. Have I missed something existing for this? Or such usage breaks design somehow?

An exception should be thrown if a configured feature filter has not been registered.

If a feature is configured to be enabled for a certain feature filter, the feature management pipeline should throw if that feature is being evaluated and the feature filter can not be found. Without this behavior it is very hard to track down the fact that a feature filter has been excluded from being registered. For those who intend for this behavior and depend on an exception not being thrown, this could be configurable via feature management options.

Settings for different environment don't transform correctly

I have a Development and Staging setup. For some business reasons, I'd like to disable certain features entirely, while enable them with predefined criteria for other environments.

For example, my appsettings.json file may have something like this

"FeatureManagement": {
    "FeatureA": {
      "EnabledFor": [
        {
          "Name": "ProductPlan",
          "Parameters": {
            "AllowedPlans": [
              "Developer",
              "Production",
              "Enterprise"
            ]
          }
        }
      ]
    }
  }

However, I'd like entirely disable this for my Staging configuration.
In my appsettings.Staging.json I would like to completely disable the feature

"FeatureManagement": {
    "FeatureA": false
  }

It appears that this is not possible. I also tried specifying different subset in the AllowedPlans, but that didn't work either - the environment specific settings file was never processed.
Other settings in it work fine.

Is this an expected behavior? Any help would be appreciated. Thanks

Why Microsoft.FeatureManagement.FeatureFilters project is empty?

I guess, it would be nice if filters are moved into the Microsoft.FeatureManagement.FeatureFilters.

Any specific reason for that?

And also any guidance or ideas to have some base filter? I am using Time Window approach for all my other filters as all feature flags have time based life-time.

It would be nice to have these because I don't want to use modified version of this project any more...

Maybe I'll send some PR ๐Ÿ™ƒ

Is it possible to exclude non active features from auto generated Swagger definition?

Is it possible to hide non activated features(actions or controllers in an API) from the swagger defintion generated by the swashbuckle package?

If I set an action as not activated, it still getยดs generated in the documentation site myapplication/swagger, but when trying to call the action I get a 404 response(which is what I expect)

How to combine FeatureFlags settings from multiple providers / sources?

Cross-post from Azure/AppConfiguration#228 since it is relevant to both Microsoft.FeatureManagement and Azure App Configuration.

Suppose that I want to do the following:

  • use Azure App Configuration to set Feature Flags
    • for the production environment
    • as a baseline for the development environment
  • have a way for locally overriding the Feature Flags in the development environment, e.g. using cookies

The usecase for this is e.g. for testers / product owners to switch on/off Features when checking their behavior or presenting them, without needing access to Azure and without impacting others members of the development team.
Another use case could be for users opting in to preview features.

The documentation explains how to add Azure App Configuration as a source for FeatureManagement. I assume I would need to implement an IFeatureFilter or an ISessionManager to provide the values from the cookies, but I don't see this documented.

I believe an IFeatureFilter should be able to independently provide a Feature value, so how can we set what source gets preference over the other? The comparison cannot be done inside the IFeatureFilter I believe.

The logic I want to achieve is this:

Azure App Configuration feature state Local (cookie-based?) feature value Calculated feature result
false null false
true null true
false false false
true false false
false true true
true true true

featurebits.core

There is any relation with the development of the package featurebits.core, nuget, github.
Both packages seems to have related goals, they work both on netcore.
It would be better, IMHO, to have a unified approach to feature flags.

Feature filters are combined with a logical OR

Hello,

While experimenting with the sdk, we noticed that when evaluating the filters and the contextual filters, the FeatureManager internal loop will break and return true for the first filter that returns true.

We are planning to use heavily the sdk, but we feel that our needs are mainly steering towards a logical AND.

For example, we will want to enable a feature for one specific country (contextual filter), but only for a defined percentage of them (filter). This would look like this in the app configuration store :

"conditions": {
    "client_filters": [
        {
            "name": "CountryContextual",
            "parameters": {
                "Country": [
                    "FR",
                    "IT"
                ]
            }
        },
        {
            "name": "Microsoft.Percentage",
            "parameters": {
                "Value": "50"
            }
        }
    ]
}

We imagine we might be able to create "meta" filters that would contain a logical operator and a list of sub filters, which can also be recursive. This would solve pretty much any use case we could imagine, but it seems to be a little over-complicated.

We could also create our own implementation of IFeatureManager, but the required dependency IFeatureSettingsProvider is currently internal.

In our opinion, the most sensible default combination operator should be an AND.

What's your opinion on that? Do you think of any built-in or alternative way of reaching our goals?

Enable dynamic configuration values to be retrieved based on a feature.

Sometimes the addition of a new feature within an application might require altered/new configuration. This configuration is scoped to the feature itself and should not pollute the overall configuration of the application. A method should be established to allow applications to pull settings from the configuration system that may be altered based on a specific feature and whether it is enabled/disabled.

E.g. something like


{
  "MaxRequests": "100",
  "MaxRetries": "10",
  "FeatureManagement": {
    "Beta": {
      "EnabledFor": [
        {
          "Name": "Percentage",
          "Parameters": {
            "Value": "50"
          }
        }
      ],
      "Configuration': {
        "MaxRequests:" 500
      }
    }
}

Getting configuration normally would yield expected results

IConfiguration config;
config["MaxRequests"] // 100
config["MaxRetries"] // 10

Getting configuration with respect to the Beta feature would yield something like
IConfiguration betaAwareConfig
config["Maxrequests"] // 500
config["MaxRetries"] // 10

Demo app failed with internal server error

I am trying to run the demo locally but with App Configure service using regular endpoint connection string instead of managed identity. Got an error below (screenshot attached):
An unhandled exception occurred while processing the request.
MissingMethodException: Method not found: 'Boolean Roslyn.Utilities.IObjectWritable.get_ShouldReuseInSerialization()'.
Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(string assemblyName, CSharpCompilationOptions options, IEnumerable syntaxTrees,
IEnumerable references, CSharpCompilation previousSubmission, Type returnType, Type hostObjectType, bool isSubmission)

Stack trace:
MissingMethodException: Method not found: 'Boolean Roslyn.Utilities.IObjectWritable.get_ShouldReuseInSerialization()'.
Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(string assemblyName, CSharpCompilationOptions options, IEnumerable syntaxTrees, IEnumerable references, CSharpCompilation previousSubmission, Type returnType, Type hostObjectType, bool isSubmission)
Microsoft.CodeAnalysis.Razor.CompilationTagHelperFeature.GetDescriptors()
Microsoft.AspNetCore.Razor.Language.DefaultRazorTagHelperBinderPhase.ExecuteCore(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.DefaultRazorEngine.Process(RazorCodeDocument document)
Microsoft.AspNetCore.Razor.Language.RazorProjectEngine.Process(RazorProjectItem projectItem)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(string relativePath)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.OnCacheMiss(string normalizedPath)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.DefaultPageLoader.Load(PageActionDescriptor actionDescriptor)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
Microsoft.AspNetCore.Mvc.Internal.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
Microsoft.AspNetCore.Mvc.Internal.MvcAttributeRouteHandler+<>c__DisplayClass12_0.b__0(HttpContext c)
Microsoft.AspNetCore.Builder.RouterMiddleware+d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.Azure.AppConfiguration.AspNetCore.AzureAppConfigurationRefreshMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()
appconfigsettings
appconfigError

Permanent caching?

Hi,

I have an issue where feature flags appear to be permanently cached throughout the lifetime of the ASP.NET Core session.

WebApi.cs file has:

 return new WebHostBuilder()
                                    .UseKestrel()
                                    .ConfigureAppConfiguration((builderContext, config) =>
                                    {
                                        config.AddJsonFile(environment, serviceContext);
                                        var settings = config.Build();
                                        AppConfigExists = !string.IsNullOrWhiteSpace(settings["VDSSettings:AppConfig"]);
                                        if (AppConfigExists)
                                        {
                                            config.AddAzureAppConfiguration(options => {
                                               options.Connect(settings["VDSSettings:AppConfig"])
                                                      .UseFeatureFlags();
                                            });
                                        }
                                    })

UseFeatureFlags had CacheExpirationTime set at one point (not above) but it didn't seem to make a difference.

The ASP.NET core web API is hosted in Service Fabric on Azure.

To reproduce:

  1. Make a request
  2. Feature flags are set as expected (in the App Configuration on Azure) - can see from a log in App Insights
  3. Change the flag
  4. Wait 30 seconds (or an age)
  5. Make a request
  6. Feature flag has not changed

From my machine (running Service Fabric locally), it's as above. However, I can get different behavior if I follow the steps below:

  1. Change the flag
  2. Stop debugging
  3. Start debugging again
  4. Make a request
  5. The flag will have the updated value

In the controller files I'm using IFeatureManagerSnapshot. I get a flag by using something like:

_enable = await _featureManagerSnapshot.IsEnabledAsync(FeatureFlagConstants.Enable);

So it appears as though the cache isn't getting released as I'd expect it to, but holds the values for the lifetime of the software being in memory.

Version info:

FeatureManagement 2.0.0
FeatureManagement.AspNetCore 2.0.0

Provide for Distributed Systems

Feature Request:
Based on documentation and blog articles I've read and from poking around some of the source code, the FeatureManagement system appears to be a wrapper on top of the Configuration System. The Configuration System doesn't easily provide for setting up a configuration source that is distributed - e.g. Database, Distributed Cache, etc.

Question:
Is there a recommendation for accomplishing this? I would expect this to be something that is easily configurable thru the Feature Management API but I must be missing something.

IFeatureManagerSnapshot one flag, many contexts.

Probably it's more a question than an issue (I hope), but is this expected behavior?

Context:

I'm evaluating one flag for two different contexts:

  • 123
  • 456

The flag should only return true for context 123.

var featureVFor123 = await _featureManagerSnapshot.IsEnabledAsync("FeatureV", "123");
var featureVFor456 = await _featureManagerSnapshot.IsEnabledAsync("FeatureV", "456");

return $"FeatureVFor123: {await featureVFor123}. FeatureVFor456: {await featureVFor456}.";

(where _featureManagerSnapshot is of type IFeatureManagerSnapshot)

returns:

FeatureVFor123: true. FeatureVFor456: true.

Which I would not expect (it's a different set of conditions for the flag). I would expect:

FeatureVFor123: true. FeatureVFor456: false.

It looks like the evaluated flag is getting cached and subsequent evaluations are ignoring different contexts. It does work correctly when I use IFeatureManager _featureManager.

Is this by design?

Turning off the internal cache within UseFeatureFlags(), or overarching AddAzureAppConfiguration method

Hello,

We're currently in the process of wrapping our feature flag code into an API, which surfaces the values stored in AAC out in an easy to read way for our clients/ui's to consume. We have written some Specflow API tests that covers all the scenarios that we may find our API's being used for, but we have come across a situation that seems to have us stumped.

What we do in said tests, is that we clear the AAC (Azure App Configuration) down, to remove any existing feature flags from any past test runs to avoid any interference between runs.

For example:

We create the following features Feature1-1, Feature2-1 using the AAC SDK.
We then poll our API, which calls the GetFeatureNamesAsync method. This returns:

Feature1-1
Feature2-1 

We loop through the features returned above, and check to see if they're enabled or not, via use of a custom feature filter, which when complete, is then sent as a response from the API.
We assert based on the response given in the test, and check that the values retrieved are correct.

However, if we run these tests as a group, one after another, we're finding that some of the tests fail, as they're getting some of the old test run features within their response.

From what I can gather, the API is updating its AAC configuration provider every 30 seconds or so, as that is what the default cache expiration value is. However, is there perhaps a way that we can get the provider to be updated/refreshed PER REQUEST? Or per call to GetFeaturesNamesAsync?

I know that we can update the cache value to within a second, as that's the minimum value. But is there a way that we can perhaps turn off the caching provided by the packages? As we're relying on using our own caching layer within the API for limiting calls to AAC where possible.

Logging hook?

Hi, are there any hooks for logging?

It'd be super awesome if there was a to log all the features that are 'known about' and what they status is, including on a refresh.

Anyone know of a way?

Feature filters should match even if 'Filter' is included in the configuration.

Right now the current matching mechanism is a type named BrowserFilter would map to Browser in the configured feature filters for a feature. If the whole type name is specified including 'Filter', there is no match. We should enable this to match since there have been many cases where this behavior was expected.

Should not depend on MS.Bcl.Interfaces for .NET Core 3.0+

The MS.FeatureManagement package depends on the MS.Bcl.Interfaces package:

<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" />

For .NET Core 3.0+ this seems to duplicate the IAsyncEnumerable<> and other async interfaces and creates compiler errors regarding those types being defined in both System.Runtime as well as System.Interactive.Async.

Basically, it wrecks the developer experience for IAsyncEnumerable and friends, unless you work around it by forcefully throwing out the duplicate with a bit of assembly aliasing magic in each affected project that transitively pulls in the dependency:

<Target Name="AddAssemblyAliasToReactiveAsync" AfterTargets="ResolveAssemblyReferences">
  <ItemGroup>
    <ReferencePath Condition=" '%(FileName)' == 'System.Interactive.Async' ">
      <Aliases>reactive</Aliases>
    </ReferencePath>
  </ItemGroup>
</Target>

Custom Feature Settings Providers

We really like what we're seeing here - great work for bringing something like this to the community!

We'd like to propose that some of the interfaces be made public so we can switch out their implementations to interface either with legacy (in-house) feature management solutions or external vendors (LaunchDarkly, split.io et al) to provide a consistent abstraction layer across multiple different backends.

We're happy to contribute code if you're accepting PR's too.

Misconfigured Flags Should Error

I think that if a flag is used and that flag is not configured then the app should error and not just default the flag to false.

For example, if a configured flag is for some reason omitted in a production config (or mis-spelled) then the app will continue to run without error and the fault may not be noticed.

If a flag is being used programmability then this could cause data issues.

If a flag is being used to control UI elements such as some legal wording that needs to be shown, then by defaulting to false the company could be in breach of laws.

Recommended approach for automated testing of both code paths in ASP.NET Core?

Hi! I appreciate the work being done here.

One thing I haven't been able to find in the docs are examples of automated tests showing how to exercise both code paths (with a given feature both on & off).

Would the suggestion be to stub IFeatureManager or is there a more idiomatic approach the team recommends?

To illustrate what I'm asking with code, this is what I've got working so far:
(based on https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0#inject-mock-services)

[Fact]
public async Task FeatureA_ShouldBePresent_WhenConfiguredOn()
{
	// Arrange
	var client = _factory
		.WithWebHostBuilder(builder =>
		{
			builder.ConfigureServices(services =>
			{
				services.AddScoped<IFeatureManager, StubFeatureManagerWithFeatureAOn>();
			});
		})
		.CreateClient();

	// Act
	var response = await client.GetAsync("/Home/FeatureA");

	// Assert
	response.EnsureSuccessStatusCode(); // Status Code 200-299
	Assert.Equal("text/html; charset=utf-8",
			response.Content.Headers.ContentType.ToString());
}

[Fact]
public async Task FeatureA_ShouldNotBePresent_WhenConfiguredOff()
{
	// Arrange
	var client = _factory
		.WithWebHostBuilder(builder =>
		{
			builder.ConfigureServices(services =>
			{
				services.AddScoped<IFeatureManager, StubFeatureManagerWithFeatureAOff>();
			});
		})
		.CreateClient();

	// Act
	var response = await client.GetAsync("/Home/FeatureA");

	// Assert
	Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

The salient lines in this snippet are:

services.AddScoped<IFeatureManager, StubFeatureManagerWithFeatureAOn>();
services.AddScoped<IFeatureManager, StubFeatureManagerWithFeatureAOff>();

The actual stub code is not shown (could use hand-rolled or Moq, etc.).

Does the team have a different recommendation for toggling a feature on a per-test basis?

Should the single-value parameters (on Feature Filters) be serialized as arrays ?

In Azure App Configuration, when defining a feature with a feature filter that has one parameter then that parameter is serialized as single-value.

public class BrowserPreviewFeatureFilterParameters
{
        public IList<string> Allowed { get; set; } = new List<string>();
        public IList<string> Blocked { get; set; } = new List<string>();
}

In the below example if we use the above model for deserialization then the parameter "Allowed" is deserialized but "Blocked" is not.
image

Observations:

  • This means that if someone defines the same parameter twice in Azure portal then the developer must deserialize field as an array, if the parameter is defined only once then the developer needs to deserialize the value using a completely different model:
public class BrowserPreviewFeatureFilterParameters
{
        public IList<string> Allowed { get; set; } = new List<string>();
        public string Blocked { get; set; } ;
}

ISSUE: The developer has to implement a JSONConverter to handle both scenarios, which is not nice.
Is this something that can be improved from Azure App Configuration portal UI ?

async implementation of TryGetAsync on ISessionManager not possible?

The ISessionManager interface switched to using an async approach, which is good in itself.

However the TryGetAsync function uses an out parameter which forbids declaring the function as async - so you cannot await Tasks in the function body.

This feels a bit awkward - do you have any example on how to best tackle that?

Asp.net Core web app doesn't throw any exception when feature flag free quota limit is reached

This is something that we faced in production recently.
Accidentlally we were using Free tier of App Configuration in production workload for our web app.
We were deploying the new changes in the production environment and we were getting 500.30 service unavailable error, when we were trying to access the API's
We tried running the command *dotnet .dll from kudu using dotnet .dll command and it just hangs doesn't show any error in console.
At last we tested on local env and found it was due to feature flag free quota limit is reached application was not running and no exception was shown in console, making it hard to understand what is the root cause of the issue.

below is our code for program.cs

`{

                 var builtConfig = builder.Build();

                 var azureServiceTokenProvider = new AzureServiceTokenProvider();

                 var keyVaultClient = new KeyVaultClient(
                     new KeyVaultClient.AuthenticationCallback(
                         azureServiceTokenProvider.KeyVaultTokenCallback));

                 builder.AddAzureKeyVault(
                     $"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",
                     keyVaultClient,
                     new DefaultKeyVaultSecretManager());

             })

            .ConfigureAppConfiguration((ctx, builder) =>
            {
                var builtConfig = builder.Build();
                builder.AddAzureAppConfiguration(options => {
                    options.Connect(builtConfig["feature-flag-connection-string"])
                        .UseFeatureFlags();
                });
            })`

Custom FeatureDefinitionProvider still depends on IConfiguration

I've been look at the latest pre-release of this package (2.2.0-preview) - it is a great improvement in terms of migration from other feature management system ๐Ÿ‘

However, when implementing a custom IFeatureDefinitionProvider I noticed that FeatureFilterConfiguration still expects its data to be modeled as IConfiguration. There are a few reasons why I think this is problematic:

  • Non-transparent API. It is not transparent what settings are mandatory or even expected, IConfiguration is very broad.
  • Cumbersome API. In my case, I have loaded feature toggle data that I want to map to percentage filter, groups etc. The best way I have found is to look at the source code for the filter classes and mimic the expected configuration in an in-memory configuration collection.
  • Surprising API. Configuration is a concept that is tied to application startup. Whenever code is reliant on configuration, the first step is usually to map it the configuration to a strongly typed class and let downstream classes rely on it.

It would be great if the API for implementing a custom data source/adapter for the feature management system would be strongly typed and not reliant on IConfiguration.

Feature names with colon in name are not parsed correctly

Given the following configuration:

"FeatureManagement": {
    "Feature1": true,
    "Prefix:Feature2": true
}

Querying the features was a bit surprising at first:

featureManager.IsEnabledAsync("Feature1") //returns true
featureManager.IsEnabledAsync("Prefix:Feature2") //returns false

Listing the feature names is also quite misleading:

featureManager.GetFeatureNamesAsync(); //returns "Feature1", "Prefix"

By taking a closer look, the colon is of course not only a gimmick, but more like a common separator for config sections. So when using the JSON file provider, the abovementioned configuration could also be semantically identical rephrased as

"FeatureManagement": {
    "Feature1": true,
    "Prefix": {
        "Feature2": true
    }
}

And that explains the weird behavior.

To solve that, would it be a possible to tokenize given feature names by : , treating them as config-sections and only the last segment as the name? Imho that would fix the "Prefix":Feature" : true case, as well as enable feature grouping (see above).

Authorization/authentication errors thrown before feature flag is checked

If you have a ASP.Net Core app with a controller with the following method:

[HttpGet]
[FeatureGate(FeatureFlags.Foo)]
[Authorize]
public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

Currently if:

  1. A request is made with correct scopes and the feature is turned on -> 200 returned (expected)
  2. A request is made with incorrect scopes and the feature is turned on -> 401 returned (expected)
  3. A request is made with correct scopes and the feature is turned off -> 404 returned (expected)
  4. A request is made with incorrect scopes and the feature is turned off -> 401 returned (unexpected)

In scenario 4 (or any scenario when the feature is turned off) I would have imagined that it would always return a 404 so that a client wouldn't be made aware of new features it doesn't have access to.

Unable to inject Scoped/Transient services into FeatureFilter

In.NET Core 3.0 DI scope validation is enabled by default.
Application throws an exception that it is not possible to resolve service that is Scoped/Transient .

Cannot consume scoped service 'Common.Services.IRequestDataProvider' from singleton 'Microsoft.FeatureManagement.IFeatureFilter'

Feature request: Set of IFeatureFilters applied to all features

Request

I have a custom IFeatureFilter I would like to apply automatically to all features in my application. I don't see a way to do this, short of building a custom IFeatureDefinitionProvider. No problem building an IFeatureDefinitionProvider, it's just unfortunate because the ConfigurationFeatureDefinitionProvider has everything I need besides that. Would it make sense to expose such a feature?

Proposal

Via configuration:

"FeatureManagement": {
   "Default": {
        "EnabledFor": [
            { "Name": "CustomFilter" },
            { "Name": "CustomFilterWithParameters", "Parameters": { "Param1": "Value1" } }
        ]
   }
}

IFeatureManager.GetFeatureNamesAsync returning all configuration keys

I dont have a 'FeatureManagement' section in my appsettings.json, but when I call GetFeatureNamesAsync, it is returning key in IConfiguration.

I'd also try adding 'FeatureManagement' section without any feature set, but the result was the same.

the following are some of the names return from GetFeatureNamesAsync()

"AllowedHosts"
"ALLUSERSPROFILE"
"APPDATA"
"applicationName"
"APP_POOL_CONFIG"
"APP_POOL_ID"
"ASPNETCORE_ENVIRONMENT"
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES"
"ASPNETCORE_IIS_HTTPAUTH"
"ASPNETCORE_IIS_PHYSICAL_PATH"

Using Label prevents cache expiration

I never see updates reflected if I try to apply a Label filter. Simply commenting out the setting of Label in the code below restores cache expiration and I see updates again but any time Label is set I only get the initial value.

var env = hostingContext.HostingEnvironment.EnvironmentName; config.AddAzureAppConfiguration(options => options .Connect(connectionString) .Select(KeyFilter.Any, LabelFilter.Null) .Select(KeyFilter.Any, env) .UseFeatureFlags(options => { options.CacheExpirationTime = TimeSpan.FromSeconds(5); options.Label = env; }) );

Forcing a toggle to be false in the middle of the `EnabledFor`

Hi,

I have the necessity to force a toggle to false in the middle of the EnabledFor for a particular filter.

For example
My feature flags

"FeatureManagement": {
    "FeatureA": {
      "EnabledFor": [
        {
          "Name": "QueryString",
        },
       {
          "Name": "AppSettings",
        }
      ]
    }
  }

In my Appsettings file the feature is enable but i need force disable feature by query string(https://www.microsoft.com/?FeatureA=false).

Proposed Snippet

on IFeatureFilter.cs Line 18

Task<bool?> EvaluateAsync(FeatureFilterEvaluationContext context);

on FeatureManager.cs Line 108

if (filter is IFeatureFilter featureFilter)
 {
    var result = await featureFilter.EvaluateAsync(context).ConfigureAwait(false);
    if(result.hasValue){
          enabled = result.Value;
           break;
    }
 }

Or you think it's better throw a exception from the filter?

What do you think about this?

create sample for Blazor WASM usage

I'm trying to use the feature management within BlazorWASM, however have been unable to get this to work; I'm unable to see any exceptions of why this is the case; please consider providing support/examples of how to use this library from a BlazorWASM application

Consider moving to Microsoft.Extensions.FeatureManagement

Consider changing the namespaces and the assembly name to be Microsoft.Extensions.FeatureManagement. IMO, this makes the library look more like the rest of .NET Core "standard" libraries than a stand-alone thing.

Besides, it has the same "spirit" that other Microsoft.Extensions.* libraries have.

Unwanted feature values retrieved when no feature flags set within Azure App Configuration

I've been working with your library for some time now, and have got it working so that a list of feature flags is passed through an API of my own creation, via Azure App Configuration and the use of this package. However, is there a way to limit what feature store featureManager.GetFeatureNamesAsync() has access to? I only want to poll my AAC connection with this method, but currently, if no features are found within my instance of Azure App Configuration, it will fall back to using what appears to be environment variables of some kind?

TL:DR - Is there a way to limit the featureManager to access only one store/provider?

Enable data to be passed to feature filters in console apps and frameworks that do not have a context.

At the moment console apps do not have a way to pass data to the feature management system to evaluate feature state based on contextual data. As an example, imagine I am processing notifications in a console app from a file. Part of the processing might trigger some additional functionality based off of criteria within the notification. We could assume that data is notificationId. We need to be able to propagate this data to feature filters to check if a feature is enabled.

This is available to frameworks like ASP.NET and ASP.NET Core by utilizing the HTTP Context which flows ambiently through the application. During the request, assorted items can be added to the context and accessed in feature filters.

To keep design and usage consistent across all types of applications I believe the best approach here would be to add a way to flow contextual data into the feature management pipeline to be utilized during evaluation.

Consider making IFeatureSettingsProvider public

There are many system in the wild that uses other feature toggling frameworks that does not load its data from IConfiguration, nor has a data source that can be used as a ConfigurationProvider. The idea behind making IFeatureSettingsProvider public is that these systems could use a custom implementation as part of their migration story over to this toggle framework.

Enable applications to report what features are being used, what were the states during a request, etc...

Currently feature management can be used to gate application functionality behind features. An important part of this flow is measuring how often these features are being used, and whether these features are healthy. The feature management interfaces lack the ability to extrapolate data such as what features were accessed during their request and what are their states. This should be added.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.