diff --git a/FeatureOne.sln b/FeatureOne.sln
index fca3623..1090efb 100644
--- a/FeatureOne.sln
+++ b/FeatureOne.sln
@@ -1,4 +1,4 @@
-
+
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33110.190
@@ -33,36 +33,104 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FeatureOne.File", "src\Feat
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FeatureOne.File.Tests", "test\FeatureOne.File.Tests\FeatureOne.File.Tests.csproj", "{1A3E4121-D3FD-4A90-8207-FC685694B91C}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{0C88DD14-F956-CE84-757C-A364CCF449FC}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FeatureOne.OpenFeature.Tests", "test\FeatureOne.OpenFeature.Tests\FeatureOne.OpenFeature.Tests.csproj", "{601BB995-1CE7-44A4-A4EA-DE15065B125B}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Debug|x64.Build.0 = Debug|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Debug|x86.Build.0 = Debug|Any CPU
{65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Release|x64.ActiveCfg = Release|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Release|x64.Build.0 = Release|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Release|x86.ActiveCfg = Release|Any CPU
+ {65BD1F94-CEF4-4CC1-8482-3FF72BBF620F}.Release|x86.Build.0 = Release|Any CPU
{F51B62E7-1A8F-41DC-B027-074932A01D33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F51B62E7-1A8F-41DC-B027-074932A01D33}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Debug|x64.Build.0 = Debug|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Debug|x86.Build.0 = Debug|Any CPU
{F51B62E7-1A8F-41DC-B027-074932A01D33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F51B62E7-1A8F-41DC-B027-074932A01D33}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Release|x64.ActiveCfg = Release|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Release|x64.Build.0 = Release|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Release|x86.ActiveCfg = Release|Any CPU
+ {F51B62E7-1A8F-41DC-B027-074932A01D33}.Release|x86.Build.0 = Release|Any CPU
{FED48C4A-1EEC-491C-8F5D-886763DF9388}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FED48C4A-1EEC-491C-8F5D-886763DF9388}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Debug|x64.Build.0 = Debug|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Debug|x86.Build.0 = Debug|Any CPU
{FED48C4A-1EEC-491C-8F5D-886763DF9388}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FED48C4A-1EEC-491C-8F5D-886763DF9388}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Release|x64.ActiveCfg = Release|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Release|x64.Build.0 = Release|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Release|x86.ActiveCfg = Release|Any CPU
+ {FED48C4A-1EEC-491C-8F5D-886763DF9388}.Release|x86.Build.0 = Release|Any CPU
{A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Debug|x64.Build.0 = Debug|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Debug|x86.Build.0 = Debug|Any CPU
{A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Release|x64.ActiveCfg = Release|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Release|x64.Build.0 = Release|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Release|x86.ActiveCfg = Release|Any CPU
+ {A6102616-CA8C-4C7F-AF16-C8F451E6D62D}.Release|x86.Build.0 = Release|Any CPU
{625A5838-13F6-4D78-AF7B-ED080B772F37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{625A5838-13F6-4D78-AF7B-ED080B772F37}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Debug|x64.Build.0 = Debug|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Debug|x86.Build.0 = Debug|Any CPU
{625A5838-13F6-4D78-AF7B-ED080B772F37}.Release|Any CPU.ActiveCfg = Release|Any CPU
{625A5838-13F6-4D78-AF7B-ED080B772F37}.Release|Any CPU.Build.0 = Release|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Release|x64.ActiveCfg = Release|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Release|x64.Build.0 = Release|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Release|x86.ActiveCfg = Release|Any CPU
+ {625A5838-13F6-4D78-AF7B-ED080B772F37}.Release|x86.Build.0 = Release|Any CPU
{1A3E4121-D3FD-4A90-8207-FC685694B91C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A3E4121-D3FD-4A90-8207-FC685694B91C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Debug|x64.Build.0 = Debug|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Debug|x86.Build.0 = Debug|Any CPU
{1A3E4121-D3FD-4A90-8207-FC685694B91C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A3E4121-D3FD-4A90-8207-FC685694B91C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Release|x64.ActiveCfg = Release|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Release|x64.Build.0 = Release|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Release|x86.ActiveCfg = Release|Any CPU
+ {1A3E4121-D3FD-4A90-8207-FC685694B91C}.Release|x86.Build.0 = Release|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Debug|x64.Build.0 = Debug|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Debug|x86.Build.0 = Debug|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Release|x64.ActiveCfg = Release|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Release|x64.Build.0 = Release|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Release|x86.ActiveCfg = Release|Any CPU
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -75,6 +143,7 @@ Global
{A6102616-CA8C-4C7F-AF16-C8F451E6D62D} = {E864826B-B5D2-4DAD-B53A-2A3976226B53}
{625A5838-13F6-4D78-AF7B-ED080B772F37} = {B5EFC87D-E5C5-488E-AA89-06D26027E4C7}
{1A3E4121-D3FD-4A90-8207-FC685694B91C} = {E864826B-B5D2-4DAD-B53A-2A3976226B53}
+ {601BB995-1CE7-44A4-A4EA-DE15065B125B} = {0C88DD14-F956-CE84-757C-A364CCF449FC}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {745CC402-145C-4E31-BAB7-DA93F8292512}
diff --git a/GitVersion.yml b/GitVersion.yml
index 990af2a..8a4f142 100644
--- a/GitVersion.yml
+++ b/GitVersion.yml
@@ -1,4 +1,4 @@
-next-version: 5.2.0
+next-version: 6.0.0
tag-prefix: '[vV]'
mode: ContinuousDeployment
branches:
diff --git a/README.md b/README.md
index 5121589..6a1992d 100644
--- a/README.md
+++ b/README.md
@@ -1,82 +1,217 @@
-#
FeatureOne v5.2.0
+#
FeatureOne v6.0.0
+
[](https://github.com/CodeShayk/FeatureOne/releases/latest)
-[](https://github.com/CodeShayk/FeatureOne/blob/master/License.md) [](https://github.com/CodeShayk/FeatureOne/actions/workflows/Build-Master.yml)
+[](https://openfeature.dev/)
+[](https://github.com/CodeShayk/FeatureOne/blob/master/License.md)
+[](https://github.com/CodeShayk/FeatureOne/actions/workflows/Build-Master.yml)
[](https://github.com/CodeShayk/FeatureOne/actions/workflows/codeql.yml)
[](https://dotnet.microsoft.com/en-us/download/netstandard/2.1)
[](https://dotnet.microsoft.com/en-us/download/dotnet/9.0)
[](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)
-.Net Library to implement feature toggles.
---
-#### Nuget Packages
-| Package | Latest | Details |
-| --------| --------| --------|
-|FeatureOne |[](https://badge.fury.io/nu/FeatureOne) | Provides core functionality to implement feature toggles with `no` backend storage provider. Needs package consumer to provide `IStorageProvider` implementation. Ideal for use case that requires custom storage backend. **v5.2.0**: RelationalCondition, net10.0 support, package upgrades, expanded test coverage. |
-|FeatureOne.SQL| [](https://badge.fury.io/nu/FeatureOne.SQL) | Provides SQL storage provider for implementing feature toggles using `SQL` backend. **v5.2.0**: net10.0 support, package upgrades. |
-|FeatureOne.File |[](https://badge.fury.io/nu/FeatureOne.File) | Provides File storage provider for implementing feature toggles using `File System` backend. **v5.2.0**: net10.0 support, package upgrades. |
+> **FeatureOne** is a high-performance, lightweight feature flagging library for .NET. Use it through its
+> native API, or through any **CNCF OpenFeature Specification (v1.x)** client — both are first-class,
+> fully supported ways to consume the same evaluation engine.
+
+---
+
+## Two Ways to Use FeatureOne
+
+FeatureOne ships one evaluation engine — storage providers, condition strategies, caching and claims-based
+targeting — with two equally supported front doors. Pick whichever fits your codebase; you can also mix them
+in the same application, since both read the same `IFeatureStore`.
+
+| | **Native API** | **OpenFeature Provider** |
+|---|---|---|
+| Entry point | `IFeatures` / `Features.Current` | `OpenFeature.Api.Instance.GetClient()` |
+| Call style | Synchronous `IsEnabled(...)` | Asynchronous `GetBooleanValueAsync(...)` |
+| Targeting input | `ClaimsPrincipal`, `IEnumerable`, or a claims dictionary | `EvaluationContext` (mapped to claims automatically) |
+| Extra dependency | None | OpenFeature SDK (already included in the `FeatureOne` package) |
+| Choose it when | You want the smallest possible surface area, synchronous call sites, or direct use of ASP.NET Core `ClaimsPrincipal` | You want vendor-neutral flag APIs, portability across flag backends, or OpenFeature hooks and telemetry |
+
+Neither is a wrapper around the other in a way that costs you functionality: conditions, operators, storage
+providers and caching behave identically through both.
+
+### A. Native API
+
+```csharp
+using FeatureOne;
+using FeatureOne.Core.Stores;
+using FeatureOne.File;
+
+// 1. Build the store over your chosen storage provider
+var fileConfig = new FileConfiguration { FilePath = @"C:\Config\Features.json" };
+var featureStore = new FeatureStore(new FileStorageProvider(fileConfig));
+
+// 2. Initialize the global facade (or inject IFeatures - see below)
+Features.Initialize(() => new Features(featureStore));
+
+// 3. Evaluate
+if (Features.Current.IsEnabled("dashboard_widget", User)) // User is a ClaimsPrincipal
+{
+ ShowDashboardWidget();
+}
+```
+
+With dependency injection:
+
+```csharp
+services.AddFeatureOneWithFileStorage(new FileConfiguration { FilePath = "Features.json" });
+
+// then inject IFeatures anywhere
+public class DashboardController(IFeatures features)
+{
+ public IActionResult Index()
+ => features.IsEnabled("dashboard_widget", User) ? View("Widget") : View("Default");
+}
+```
+
+### B. OpenFeature Provider
+
+```csharp
+using FeatureOne.Core.Stores;
+using FeatureOne.File;
+using FeatureOne.OpenFeature;
+using OpenFeature;
+using OpenFeature.Model;
+
+// 1. Build the store over your chosen storage provider
+var fileConfig = new FileConfiguration { FilePath = @"C:\Config\Features.json" };
+var featureStore = new FeatureStore(new FileStorageProvider(fileConfig));
+
+// 2. Register FeatureOne as the OpenFeature provider
+await Api.Instance.SetProviderAsync(new FeatureOneProvider(featureStore));
+
+// 3. Evaluate through a standard OpenFeature client
+var client = Api.Instance.GetClient();
+var context = EvaluationContext.Builder()
+ .SetTargetingKey("usr_123")
+ .Set("tier", "gold")
+ .Build();
+
+bool showWidget = await client.GetBooleanValueAsync("dashboard_widget", false, context);
+```
+
+With dependency injection:
+
+```csharp
+services.AddFeatureOneWithFileStorage(new FileConfiguration { FilePath = "Features.json" });
+services.AddFeatureOneOpenFeature(); // registers the provider and sets it globally on startup
+
+// then inject IFeatureClient anywhere, or resolve Api.Instance.GetClient()
+```
+
+The `FeatureOneProvider` lives in the `FeatureOne.OpenFeature` namespace inside the core **FeatureOne**
+package — there is no separate package to install.
+
+> **Note on flag types.** FeatureOne is a boolean toggle engine. The provider implements all five
+> OpenFeature resolvers, but the non-boolean ones are projections of the same boolean result
+> (`String` → `"true"`/`"false"`, `Integer` → `1`/`0`, `Double` → `1.0`/`0.0`, `Structure` → a wrapped
+> boolean). They are not multivariate flag support. Prefer `GetBooleanValueAsync` unless a typed call site
+> makes one of the projections convenient.
+
+---
+
+#### NuGet Packages
+| Package | Latest | Details |
+|---|---|---|
+| **FeatureOne** | [](https://badge.fury.io/nu/FeatureOne) | Core evaluation engine, native `IFeatures` API, and the built-in **CNCF OpenFeature Specification (v1.x)** provider (`FeatureOneProvider`, `FeatureOne.OpenFeature` namespace). |
+| **FeatureOne.SQL** | [](https://badge.fury.io/nu/FeatureOne.SQL) | SQL storage provider for implementing feature toggles using relational database backends (MSSQL, SQLite, PostgreSQL, MySQL). |
+| **FeatureOne.File** | [](https://badge.fury.io/nu/FeatureOne.File) | File storage provider for implementing feature toggles using JSON configuration files. |
+
+---
## Concept
-### What is a feature toggle?
-Feature toggle is a mechanism that allows code to be turned “on” or “off” remotely without the need for a deploy. Feature toggles are commonly used in applications to gradually roll out new features, allowing teams to test changes on a small subset of users before releasing them to everyone.
-### How feature toggles work
-Feature toggle is typically a logical check added to codebase to execute or ignore certain functionality in context based on evaluated status of the toggle at runitme.
+### What is a Feature Toggle?
+Feature toggle is a mechanism that allows code to be turned “on” or “off” remotely without requiring a deployment. Feature toggles are commonly used in applications to gradually roll out new features, test changes on a small subset of users, or instantly disable features during emergencies.
+
+### How Feature Toggles Work
+Feature toggle is typically a logical check wrapped around application code to execute or skip functionality based on evaluated status at runtime.
+
+### Benefits of Feature Toggles
+- **Risk Mitigation**: Instant rollbacks without redeploying code.
+- **Continuous Delivery**: Merge incomplete code safely behind toggles.
+- **Targeted Rollouts**: Release features based on user claims, roles, tiers, date ranges, or regular expressions.
+- **Vendor-Neutral Standardization**: Standardize feature flagging across your organization via OpenFeature SDKs.
+
+---
+
+## Capabilities
+
+Available identically through both the native API and the OpenFeature provider:
-In code, the functionality to be released is wrapped so that it can be controlled by the status of a feature toggle. If the status of the feature toggle is “on”, then the wrapped functionality is executed. If the status of the feature toggle is “off”, then the wrapped functionality is skipped. The statuses of each feature is provided by a store provider external to the application.
+- **Condition strategies**: `SimpleCondition`, `RegexCondition` (with ReDoS timeout protection), `RelationalCondition`, `DateRangeCondition`, plus your own via `ICondition`.
+- **Operators**: combine conditions with `Operator.Any` (OR) or `Operator.All` (AND).
+- **Storage providers**: SQL, JSON file, or your own `IStorageProvider`.
+- **Caching**: pluggable `ICache` with configurable expiry.
+- **Custom conditions**: register your own condition types with `ConditionDeserializer.Register("Name")`.
+- **Logging**: pluggable `IFeatureLogger`; on the OpenFeature side, `FeatureOneLoggingHook` bridges the hook pipeline to the same logger.
-### The benefits of feature toggles
-The primary benefit of feature flagging is that it mitigates the risks associated with releasing changes to an application. Whether it be a new feature release or a small refactor, there is always the inherent risk of releasing new regressions. To mitigate this, changes to an application can be placed behind feature toggles, allowing them to be turned “on” or “off” in the event of an emergency.
+---
+
+## Getting Started
-## Getting Started?
### i. Installation
-Install the latest nuget package as appropriate.
+Install the latest NuGet package as appropriate for your project:
-`FeatureOne` - for installing FeatureOne for custom `IStorageProvider` implementation.
-```
+`FeatureOne` - Core library, native API, and built-in OpenFeature provider.
+```bash
NuGet\Install-Package FeatureOne
```
-`FeatureOne.SQL` - for installing FeatureOne with SQL storage provider.
-```
+
+`FeatureOne.SQL` - SQL storage provider for database backends.
+```bash
NuGet\Install-Package FeatureOne.SQL
```
-`FeatureOne.File` - for installing FeatureOne with File system storage provider.
-```
+
+`FeatureOne.File` - File system storage provider for JSON configurations.
+```bash
NuGet\Install-Package FeatureOne.File
```
-### ii. Developer Guide
+### ii. Developer Guide & Documentation
-Please see [Developer Guide](/DeveloperGuide.md) for details on how to implement FeatureOne in your project.
+- **[Developer Guide](docs/DeveloperGuide.md)**: In-depth setup, custom condition creation, storage provider implementations, and ASP.NET Core DI extensions.
+- **[GitHub Wiki](docs/wiki.md)**: Complete guide and API reference, covering both the native API and OpenFeature integration.
+
+---
## Support
-If you are having problems, please let me know by [raising a new issue](https://github.com/CodeShayk/FeatureOne/issues/new/choose).
+If you encounter issues or have questions, please [raise a new issue](https://github.com/CodeShayk/FeatureOne/issues/new/choose).
## License
-This project is licensed with the [MIT license](LICENSE).
+This project is licensed under the [MIT License](LICENSE).
+
+---
## Version History
The following previous versions are available:
-| Version | Release Notes |
-| ----------------------------------------------------------------| ----------------------------------------------------------------------|
-| [`v5.2.0`](https://github.com/CodeShayk/FeatureOne/tree/v5.2.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v5.2.0) |
-| [`v5.1.0`](https://github.com/CodeShayk/FeatureOne/tree/v5.1.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v5.1.0) |
-| [`v5.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v5.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v5.0.0) |
-| [`v4.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v4.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v4.0.0) |
-| [`v3.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v3.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v3.0.0) |
-| [`v2.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v2.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v2.0.0) |
+| Version | Release Notes |
+|---|---|
+| [`v6.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v6.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v6.0.0) |
+| [`v5.2.0`](https://github.com/CodeShayk/FeatureOne/tree/v5.2.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v5.2.0) |
+| [`v5.1.0`](https://github.com/CodeShayk/FeatureOne/tree/v5.1.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v5.1.0) |
+| [`v5.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v5.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v5.0.0) |
+| [`v4.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v4.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v4.0.0) |
+| [`v3.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v3.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v3.0.0) |
+| [`v2.0.0`](https://github.com/CodeShayk/FeatureOne/tree/v2.0.0) | [Notes](https://github.com/CodeShayk/FeatureOne/releases/tag/v2.0.0) |
+
+---
## Recent Releases
| Version | Release Date | Type | Key Changes | Backward Compatibility |
-|--------|-------------|------|-------------|---------------------|
-| v5.0.0 | Previous | Initial | Core feature toggle functionality | N/A (Initial release) |
-| v5.1.0 | Nov 03, 2025 | Minor | **Security fixes** (ReDoS protection, secure type loading), **architectural improvements** (prefix matching, dependency injection), **new features** (DateRangeCondition, configuration validation), **DI integration** | High - maintains all existing functionality with minor security-related behavioral changes |
-| v5.2.0 | Mar 18, 2026 | Minor | **New condition** (RelationalCondition with 5 relational operators), **target framework** (added net10.0, removed netstandard2.0 and net8.0), **package upgrades** (all MS packages to 10.0.5), **expanded test coverage** (98%+ line coverage) | High - fully backward compatible, additive changes only |
-
-## Credits
-Thank you for reading. Please fork, explore, contribute and report. Happy Coding !! :)
+|---|---|---|---|---|
+| **v5.0.0** | Previous | Initial | Core feature toggle functionality | N/A (Initial release) |
+| **v5.1.0** | Nov 03, 2025 | Minor | **Security fixes** (ReDoS protection, secure type loading), **architectural improvements** (prefix matching, dependency injection), **new features** (DateRangeCondition, configuration validation), **DI integration** | High - maintains all existing functionality with minor security-related behavioral changes |
+| **v5.2.0** | Mar 18, 2026 | Minor | **New condition** (RelationalCondition with 5 relational operators), **target framework** (added net10.0, removed netstandard2.0 and net8.0), **package upgrades** (all MS packages to 10.0.5), **expanded test coverage** (98%+ line coverage) | High - fully backward compatible, additive changes only |
+| **v6.0.0** | Aug 16, 2026 | Major | **OpenFeature Specification Compliance** (`FeatureOneProvider` in the core `FeatureOne` package under the `FeatureOne.OpenFeature` namespace, `EvaluationContext` claims mapping, typed flag evaluation, DI extensions), **custom condition registration** (`ConditionDeserializer.Register`) | High - backward compatible for the native API; condition deserialization now throws `FeatureOneConfigurationException` instead of `Exception` |
+---
+## Credits
+Thank you for exploring FeatureOne. Please fork, contribute, report issues, and star the repo! Happy Coding !! :)
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
new file mode 100644
index 0000000..196bf1c
--- /dev/null
+++ b/docs/CHANGELOG.md
@@ -0,0 +1,71 @@
+# Changelog
+
+## [6.0.0] - 2026-08-16
+
+### Added
+- **OpenFeature Provider**: `FeatureOneProvider` implementing the OpenFeature Specification (v1.x) `FeatureProvider`, shipped **inside the core `FeatureOne` package** under the `FeatureOne.OpenFeature` namespace. Full support for Boolean, String, Integer, Double, and Structure flag resolution (the non-boolean resolvers are projections of the boolean result, not multivariate values).
+- **Context Mapping**: `EvaluationContextExtensions` mapping OpenFeature `TargetingKey` and attributes to FeatureOne user claims.
+- **Dependency Injection**: `AddFeatureOneOpenFeature` extension methods for ASP.NET Core `IServiceCollection`, including an options overload for hook configuration. Global provider registration runs from an `IHostedService` at startup rather than from the DI factory.
+- **Custom Condition Registration**: `ConditionDeserializer.Register("Name")` for user-defined `ICondition` types, preserving the deny-by-default type allow list introduced in v5.1.0.
+- **Core Interoperability**: Exposed `FeatureStore` property on `Features` class for open provider integration.
+
+### Fixed
+- **Non-string `EvaluationContext` attributes were silently dropped** during claims mapping — integer, double, list and structure attributes never reached conditions, which then evaluated as disabled with no error reported.
+- **`InitializeAsync` could never report failure**, leaving every provider error-state guard unreachable.
+- **A missing feature store reported `FlagNotFound`**, indistinguishable from a genuinely absent flag; it now reports `ProviderNotReady`.
+- **Global OpenFeature provider registration was a side effect of the DI factory**, so it never ran unless something resolved `FeatureOneProvider`, and it blocked on an async call inside the factory.
+- **`ConditionDeserializer` re-parsed the toggle JSON once per writable property** during hydration.
+- **`RelationalOperator.LessThan` was never implemented** — it fell through to the switch default and always returned `false`.
+- **`RelationalCondition` compared numeric claims lexicographically**, ranking `"9"` above `"18"`.
+- **`RelationalCondition` string comparison was culture-sensitive**, making results machine-dependent.
+
+### Changed
+- Condition deserialization failures now throw `FeatureOneConfigurationException` (derived from `Exception`) instead of a bare `Exception`.
+- `RelationalCondition` now compares numerically when both the claim value and the configured value parse as numbers, and ordinally otherwise. Toggles comparing numeric claims with `GreaterThan`, `GreaterThanOrEqual`, `LessThan`, or `LessThanOrEqual` will evaluate differently — correctly — than in v5.2.0. `Equals` also matches equivalent numeric forms, so `"5.0"` now equals `"5"`.
+
+### Quality & Testing
+- **Test Suite**: 260 tests passing across all four test projects, including 49 in `FeatureOne.OpenFeature.Tests` covering resolution types, context mapping, error codes, provider lifecycle, hook concurrency, DI registration, and global client integration.
+
+## [5.2.0] - 2026-03-18
+
+### Added
+- **New Feature**: `RelationalCondition` with 5 relational operators (`Equals`, `NotEquals`, `GreaterThan`, `GreaterThanOrEqual`, `LessThanOrEqual`).
+- **Framework Support**: Added `net10.0` target framework.
+
+## [5.1.0] - 2025-10-13
+
+### Security
+- **Critical**: Fixed RegexCondition ReDoS (Regular Expression Denial of Service) vulnerability by adding timeout validation
+- **Critical**: Secured dynamic type loading in ConditionDeserializer to prevent unsafe type loading
+- **Enhanced**: Added comprehensive input validation to prevent injection attacks
+- **Enhanced**: Implemented timeout protections to prevent resource exhaustion
+
+### Added
+- **New Feature**: DateRangeCondition for time-based feature toggles with flexible date range support
+- **New Feature**: Configuration validation system for feature names and condition parameters
+- **New Feature**: Dependency Injection integration with extension methods for Microsoft.Extensions.DependencyInjection
+- **New Feature**: Factory function support for dynamic configuration
+- **New Feature**: Comprehensive service registration for all FeatureOne packages (Core, File, SQL)
+
+### Changed
+- **Architecture**: Updated FindStartsWith implementation to properly support actual prefix matching instead of exact matching
+- **Architecture**: Implemented proper dependency injection patterns with new constructors that accept dependencies explicitly
+- **Architecture**: Improved testability throughout the library with better DI patterns
+- **Performance**: Enhanced caching strategies and memory management
+- **API**: Added new constructors with explicit dependency injection while maintaining backward compatibility
+
+### Fixed
+- **Critical**: RegexCondition timeout protection to prevent hanging applications with malicious patterns
+- **Security**: Type loading security issue in ConditionDeserializer
+- **Functionality**: Prefix matching functionality in FindStartsWith method
+- **Quality**: Configuration validation to detect errors early
+
+### Breaking Changes (Minimal)
+- **Security**: External condition types from other assemblies may no longer be loadable (security enhancement)
+- **Behavioral**: RegexCondition may timeout complex patterns that previously worked
+- **Behavioral**: FindStartsWith now returns proper prefix matches instead of exact matches
+
+### Quality Improvements
+- **Testing**: Achieved 90%+ code coverage across all critical components
+- **Documentation**: Updated all documentation with new DI integration examples
+- **Validation**: Added comprehensive configuration validation with clear error messages
diff --git a/ClassDiagram.png b/docs/ClassDiagram.png
similarity index 100%
rename from ClassDiagram.png
rename to docs/ClassDiagram.png
diff --git a/DeveloperGuide.md b/docs/DeveloperGuide.md
similarity index 65%
rename from DeveloperGuide.md
rename to docs/DeveloperGuide.md
index ba07655..610b7c8 100644
--- a/DeveloperGuide.md
+++ b/docs/DeveloperGuide.md
@@ -3,7 +3,7 @@
## i. Installation
Install the latest nuget package as appropriate.
-`FeatureOne` - for installing FeatureOne for custom `IStorageProvider` implementation.
+`FeatureOne` - core FeatureOne library with built-in OpenFeature specification provider (`FeatureOneProvider`).
```
NuGet\Install-Package FeatureOne
```
@@ -16,18 +16,18 @@ NuGet\Install-Package FeatureOne.SQL
NuGet\Install-Package FeatureOne.File
```
-ii. Implementation: How to use FeatureOne
---
+## ii. Implementation: How to use FeatureOne
+
### Step 1. Add Feature IsEnabled Check in Code.
In order to release a new functionality or feature - say eg. Dashboard Widget.
Add logical check in codebase to wrap the functionality under a `feature toggle`.
> the logical check evaluates status of the toggle configured for the feature in store at runtime.
-```
+```csharp
var featureName = "dashboard_widget"; // Name of functionality or feature to toggle.
- if(Features.Current.IsEnable(featureName){ // See other IsEnable() overloads
+ if(Features.Current.IsEnabled(featureName)){ // See other IsEnabled() overloads
showDashboardWidget();
-}
+ }
```
@@ -37,7 +37,7 @@ A toggle constitutes a collection of `conditions` that evaluate separately when
> Toggles run at runtime based on consitituent conditions that evaluate separately against user claims (generally logged in user principal).
Below is a serialized JSON representation of a Feature Toggle.
-```
+```json
{
"feature_name":{ -- Feature name
"toggle":{ -- Toggle definition for the feature
@@ -47,7 +47,7 @@ Below is a serialized JSON representation of a Feature Toggle.
-- `all` conditions are met.
"conditions":[{ -- collection of conditions
- "type":"simple|regex" -- type of condition
+ "type":"simple|regex|relational|daterange" -- type of condition
.... other type specific properties, See below for details.
}]
@@ -57,7 +57,7 @@ Below is a serialized JSON representation of a Feature Toggle.
```
### Condition Types
-There are two types of toggle conditions that can be used out of box.
+There are four built-in types of toggle conditions that can be used out of box.
#### i. Simple Condition
`Simple` condition allows toggle with simple enable or disable of the given feature. User claims are not taken into account for this condition.
@@ -130,7 +130,7 @@ var feature = new Feature
```
#### iii. Relational Condition
-`Relational` condition (class `RelationalCondition`) allows evaluating a user claim value against a fixed value using a relational operator. This is useful for enabling features based on user tiers, roles, or any string-comparable claim.
+`Relational` condition (class `RelationalCondition`) allows evaluating a user claim value against a fixed value using a relational operator. This is useful for enabling features based on numeric thresholds (age, seat count, score) or on user tiers, roles, and other comparable string claims.
Supported operators (`RelationalOperator` enum):
@@ -138,12 +138,20 @@ Supported operators (`RelationalOperator` enum):
|---|---|
| `Equals` | Claim value equals the configured value |
| `NotEquals` | Claim value does not equal the configured value |
-| `GreaterThan` | Claim value is lexicographically greater than the configured value |
-| `GreaterThanOrEqual` | Claim value is lexicographically greater than or equal to the configured value |
-| `LessThanOrEqual` | Claim value is lexicographically less than or equal to the configured value |
-| `LessThan` | Defined in enum but **not yet implemented** — always returns `false` |
-
-> **Note:** String comparison is ordinal (via `string.Compare`). Both the claim value and the configured value are trimmed of leading/trailing whitespace before comparison.
+| `GreaterThan` | Claim value is greater than the configured value |
+| `GreaterThanOrEqual` | Claim value is greater than or equal to the configured value |
+| `LessThan` | Claim value is less than the configured value |
+| `LessThanOrEqual` | Claim value is less than or equal to the configured value |
+
+> **How values are compared.** Claims are stored as strings, so the comparison strategy is chosen from the
+> values themselves: when **both** the claim value and the configured value parse as numbers they are
+> compared **numerically**; otherwise they are compared as **ordinal strings**. So `age > 18` behaves
+> arithmetically (`"9"` is *not* greater than `"18"`), while `tier >= "gold"` still orders lexically.
+> Numeric parsing uses the invariant culture, and string comparison is ordinal, so results never vary with
+> the ambient culture. Both values are trimmed of leading/trailing whitespace before comparison.
+>
+> Because numeric comparison also applies to `Equals`, equivalent numeric forms match: a claim of `"5.0"`
+> equals a configured value of `"5"`.
Below is the serialized representation of a toggle with a logical condition.
```
@@ -183,6 +191,44 @@ var feature = new Feature
}
```
+#### iv. DateRange Condition
+`DateRange` condition (class `DateRangeCondition`) allows enabling a feature only within a specified UTC start and end date/time window.
+
+Below is the serialized representation of a toggle with a date range condition.
+```json
+{
+ "holiday_banner": {
+ "toggle": {
+ "operator": "any",
+ "conditions": [{
+ "type": "DateRange",
+ "startDate": "2026-12-01T00:00:00Z",
+ "endDate": "2026-12-25T23:59:59Z"
+ }]
+ }
+ }
+}
+```
+C# representation of a feature with a date range condition is
+```csharp
+var feature = new Feature
+{
+ Name = "holiday_banner",
+ Toggle = new Toggle
+ {
+ Operator = Operator.Any,
+ Conditions = new[]
+ {
+ new DateRangeCondition
+ {
+ StartDate = new DateTime(2026, 12, 1, 0, 0, 0, DateTimeKind.Utc),
+ EndDate = new DateTime(2026, 12, 25, 23, 59, 59, DateTimeKind.Utc)
+ }
+ }
+ }
+};
+```
+
### Step 3. Implement Storage Provider.
To use FeatureOne, you need to provide implementation for `Storage Provider` to get all the feature toggles from storage medium of choice.
Implement `IStorageProvider` interface to return feature toggles from storage.
@@ -311,6 +357,38 @@ JSON Serialized representation is
```
+#### Registering the custom condition
+
+Condition types are resolved from an explicit allow list rather than by loading arbitrary type names from
+configuration, so a custom condition must be **registered** before it can be deserialized from JSON.
+Register it once at startup and pass the deserializer to your storage provider:
+
+```csharp
+var conditions = new ConditionDeserializer()
+ .Register("Time"); // matches "type":"Time" in the JSON above
+
+// via dependency injection
+services.AddFeatureOneWithFileStorage(configuration,
+ deserializer: new ToggleDeserializer(conditions));
+
+// or when bootstrapping manually
+var storageProvider = new FileStorageProvider(configuration,
+ new FileReader(configuration),
+ new ToggleDeserializer(conditions),
+ new FeatureCache());
+```
+
+`Register` accepts either the bare name or the postfixed name — `"Time"` and `"TimeCondition"` register and
+resolve identically. Registrations are per-`ConditionDeserializer` instance, not global, so reuse the same
+instance across your application.
+
+Registration throws `FeatureOneConfigurationException` if the type does not implement `ICondition`, is not
+concrete, or has no parameterless constructor. Deserializing a toggle that references an unregistered
+condition type throws the same exception, listing the types that *are* registered.
+
+Custom conditions work identically whether you evaluate through the native `IFeatures` API or through the
+OpenFeature provider.
+
`Please Note` Any custom condition implementation should only include `primitive type` properties to work with `default` ICondition `deserialization`. When you need to implement a much complex toggle condition with `non-primitive` properties then you need to provide `custom` implementation of `IConditionDeserializer` to support its deserialization to toggle condition object.
### ii. Logger
@@ -542,3 +620,133 @@ iii. With other overloads - Custom cache and Toggle Condition deserializer.
Features.Initialize(() => new Features(new FeatureStore(storageProvider, logger), logger));
```
+FeatureOne.OpenFeature - OpenFeature Specification Provider
+--
+
+Everything above uses FeatureOne's **native API** (`Features.Current.IsEnabled(...)` / `IFeatures`). This
+section covers the equally supported alternative: evaluating the same toggles through a standard
+**CNCF OpenFeature Specification (v1.x)** client.
+
+`FeatureOneProvider` lives in the `FeatureOne.OpenFeature` namespace **inside the core `FeatureOne`
+package** — there is no separate package to install. Storage providers, conditions, operators, caching and
+logging all behave identically through both APIs; only the call surface differs.
+
+### Choosing between the native API and OpenFeature
+
+| | **Native API** | **OpenFeature Provider** |
+|---|---|---|
+| Entry point | `IFeatures` / `Features.Current` | `OpenFeature.Api.Instance.GetClient()` |
+| Call style | Synchronous `bool IsEnabled(...)` | Asynchronous `Task GetBooleanValueAsync(...)` |
+| Targeting input | `ClaimsPrincipal`, `IEnumerable`, `IDictionary` | `EvaluationContext` |
+| Missing flag | Returns `false`, logs a warning | Returns your default with `ErrorType.FlagNotFound` |
+| Observability | `IFeatureLogger` | `IFeatureLogger` plus the OpenFeature hook pipeline |
+| Choose it when | You want the smallest surface area, synchronous call sites, or direct `ClaimsPrincipal` targeting | You want vendor-neutral call sites, portability across flag backends, or OpenFeature hooks |
+
+Both can be used in the same application — they read the same `IFeatureStore`.
+
+### Option A. Global Registration
+```csharp
+// 1. Setup FeatureOne FeatureStore
+var storageProvider = new FileStorageProvider(configuration);
+var featureStore = new FeatureStore(storageProvider);
+
+// 2. Register FeatureOneProvider with OpenFeature API
+await OpenFeature.Api.Instance.SetProviderAsync(new FeatureOneProvider(featureStore));
+
+// 3. Obtain standard OpenFeature Client
+var client = OpenFeature.Api.Instance.GetClient();
+
+// 4. Evaluate feature flags with EvaluationContext
+var context = EvaluationContext.Builder()
+ .SetTargetingKey("usr_12345")
+ .Set("email", "john@gbk.com")
+ .Set("tier", "gold")
+ .Build();
+
+bool isWidgetEnabled = await client.GetBooleanValueAsync("dashboard_widget", false, context);
+```
+
+### Option B. ASP.NET Core Dependency Injection
+```csharp
+public void ConfigureServices(IServiceCollection services)
+{
+ // Registers IStorageProvider, IFeatureLogger, IFeatureStore and IFeatures
+ services.AddFeatureOneWithFileStorage(configuration);
+
+ // Registers FeatureOneProvider, reusing the IFeatureStore registered above
+ services.AddFeatureOneOpenFeature();
+}
+```
+
+Global provider registration is performed by an `IHostedService` on application start rather than as a side
+effect of the DI factory, so it happens whether or not anything in your application resolves
+`FeatureOneProvider`.
+
+To configure hooks, or to register the provider without making it global:
+
+```csharp
+services.AddFeatureOneOpenFeature(options =>
+{
+ options.SetAsGlobalProvider = false; // resolve FeatureOneProvider yourself instead
+ options.EnableLoggingHook = true; // bridge the hook pipeline to IFeatureLogger
+ options.AddHook(new MyTelemetryHook());
+});
+```
+
+### EvaluationContext to claims mapping
+
+`ToClaims()` converts the `EvaluationContext` into the claims dictionary your conditions evaluate against:
+
+| Context input | Claim value |
+|---|---|
+| `TargetingKey` | Set as `targetingKey`, `sub`, and `user_id` |
+| String | Used verbatim |
+| Boolean | `"true"` / `"false"` |
+| Integer | Invariant-culture digits, e.g. `95` |
+| Double | Invariant-culture round-trip form, e.g. `1.5` |
+| `DateTime` | ISO-8601 round-trip (`"o"`) format |
+| List / structure | JSON serialized |
+| Null | Omitted |
+
+Keys are matched case-insensitively. Numbers use the invariant culture so `RelationalCondition` parses them
+consistently regardless of the ambient culture.
+
+### Flag types
+
+FeatureOne is a boolean toggle engine. All five OpenFeature resolvers are implemented, but the non-boolean
+ones are projections of the same boolean result:
+
+| Resolver | Enabled | Disabled |
+|---|---|---|
+| `ResolveBooleanValueAsync` | `true` | `false` |
+| `ResolveStringValueAsync` | `"true"` | `"false"` |
+| `ResolveIntegerValueAsync` | `1` | `0` |
+| `ResolveDoubleValueAsync` | `1.0` | `0.0` |
+| `ResolveStructureValueAsync` | `Value(true)` | `Value(false)` |
+
+These are not multivariate flag values — `GetStringValueAsync("theme", "dark")` returns `"true"` or
+`"false"`, never a theme name. Prefer `GetBooleanValueAsync`.
+
+### Error semantics
+
+| Situation | `ErrorType` | Returned value |
+|---|---|---|
+| Flag absent from the store | `FlagNotFound` | Your default |
+| No `IFeatureStore` available, or initialization failed | `ProviderNotReady` | Your default |
+| Condition evaluation threw | `General` | Your default |
+
+`InitializeAsync` sets `ProviderStatus.Error` when no `IFeatureStore` can be resolved. A missing store is
+reported as `ProviderNotReady` rather than `FlagNotFound`, so a misconfigured application is not mistaken
+for a typo'd flag key.
+
+### Hooks
+
+```csharp
+var provider = new FeatureOneProvider(featureStore, logger);
+provider.AddHook(new FeatureOneLoggingHook(logger)); // Before / After / Error / Finally
+await OpenFeature.Api.Instance.SetProviderAsync(provider);
+```
+
+`FeatureOneLoggingHook` routes the OpenFeature hook lifecycle to the same `IFeatureLogger` the native API
+uses, so both call surfaces log through one implementation.
+
diff --git a/docs/release-summary.md b/docs/release-summary.md
new file mode 100644
index 0000000..eb9fdc9
--- /dev/null
+++ b/docs/release-summary.md
@@ -0,0 +1,112 @@
+# FeatureOne Library Release Summary
+
+## Overview
+This document provides a comprehensive, technical summary of all FeatureOne library releases, detailing architectural enhancements, new condition types, OpenFeature specification compliance, and security improvements across every version.
+
+---
+
+## Release History
+
+### Release v5.0.1 (Base Release)
+- Base version of FeatureOne establishing core feature toggle evaluation engine.
+- Supports primitive Simple and Regex toggle conditions.
+- Defines extensible `IStorageProvider`, `IToggle`, `ICondition`, and `ICache` abstractions.
+
+---
+
+### Release v5.1.0 (Security & Architecture Minor Release)
+- **Release Date**: October 13, 2025
+- **Security Protections**:
+ - ReDoS (Regular Expression Denial of Service) protection in `RegexCondition` with execution timeout enforcement.
+ - Safe dynamic type loading in `ConditionDeserializer` against malicious assembly injection.
+- **New Features**:
+ - `DateRangeCondition` for time-windowed feature releases.
+ - Configuration validation engine (`ConfigurationValidator`) to validate feature names and condition properties.
+ - Dependency Injection support with `AddFeatureOne()`, `AddFeatureOneWithSQLStorage()`, and `AddFeatureOneWithFileStorage()`.
+- **Architectural Enhancements**:
+ - Prefix matching in `IFeatureStore.FindStartsWith()`.
+ - Factory pattern initialization via `Features.Initialize(() => ...)` logic.
+
+---
+
+### Release v5.2.0 (Relational Conditions & Framework Upgrade)
+- **Release Date**: March 18, 2026
+- **New Features**:
+ - `RelationalCondition` supporting 5 relational comparison operators (`Equals`, `NotEquals`, `GreaterThan`, `GreaterThanOrEqual`, `LessThanOrEqual`) for claim value evaluation.
+- **Framework & Dependencies**:
+ - Added `.NET 10.0` target framework (`net10.0`).
+ - Upgraded Microsoft package dependencies to version `10.0.5`.
+- **Quality**:
+ - Expanded unit test suite coverage to 98%+ line coverage.
+
+---
+
+### Release v6.0.0 (Major Release: OpenFeature Specification Compliance)
+- **Release Date**: August 16, 2026
+- **Summary**:
+ Major milestone release introducing full **CNCF OpenFeature Specification (v1.x)** compliance. The provider ships **inside the core `FeatureOne` package** under the `FeatureOne.OpenFeature` namespace — there is no separate package. FeatureOne now offers two equally supported APIs over the same evaluation engine: the native `IFeatures` API and the OpenFeature provider.
+
+- **Key Highlights**:
+ 1. **OpenFeature Provider (built into `FeatureOne`)**:
+ - Introduces `FeatureOneProvider` inheriting from OpenFeature's `FeatureProvider`.
+ - Full support for typed flag evaluation: `ResolveBooleanValueAsync`, `ResolveStringValueAsync`, `ResolveIntegerValueAsync`, `ResolveDoubleValueAsync`, and `ResolveStructureValueAsync`. The non-boolean resolvers are projections of the boolean toggle result, not multivariate flag values.
+ - Returns standard `ResolutionDetails` with accurate `Reason` (`TARGETING_MATCH`, `DISABLED`, `ERROR`), `Variant` (`"on"`, `"off"`), and `ErrorType` (`FlagNotFound`, `ProviderNotReady`, `General`).
+ 2. **EvaluationContext Claim Mapping**:
+ - Extension method `ToClaims()` mapping OpenFeature `EvaluationContext` attributes — strings, booleans, integers, doubles, `DateTime`, lists and structures — to FeatureOne user claims, using the invariant culture for numbers.
+ - Automatic mapping of `TargetingKey` to standard claims (`"targetingKey"`, `"sub"`, `"user_id"`).
+ 3. **Core Facade Interoperability**:
+ - Exposed `FeatureStore` property on `Features` facade (`Features.Current.FeatureStore`).
+ - The native API remains fully backward compatible; storage providers and custom condition implementations are unaffected.
+ 4. **Dependency Injection**:
+ - Added `AddFeatureOneOpenFeature()` extension methods for ASP.NET Core `IServiceCollection`, plus an options overload for hook configuration. Global provider registration runs from an `IHostedService` at application start rather than as a side effect of the DI factory.
+ 5. **Provider Lifecycle**:
+ - `InitializeAsync` validates store availability and reports `ProviderStatus.Error`; a missing store surfaces as `ProviderNotReady` rather than `FlagNotFound`.
+ 6. **Custom Condition Registration**:
+ - `ConditionDeserializer.Register("Name")` registers user-defined `ICondition` types, preserving the deny-by-default type allow list from v5.1.0.
+ 7. **Comprehensive Verification**:
+ - `test/FeatureOne.OpenFeature.Tests` expanded to 49 tests covering resolution types, context mapping, error codes, provider lifecycle, hook concurrency and DI registration.
+ - Total test suite count expanded to **260 tests** with 100% pass rate.
+
+---
+
+## Release Timeline
+
+| Version | Release Date | Type | Focus Area | Primary Goal |
+|---|---|---|---|---|
+| **v5.0.1** | Initial | Major | Core Feature Toggles | Base feature toggle engine and interfaces |
+| **v5.1.0** | Oct 13, 2025 | Minor | Security & Architecture | ReDoS protection, safe type loading, `DateRangeCondition`, DI support |
+| **v5.2.0** | Mar 18, 2026 | Minor | Relational Engine & .NET 10 | `RelationalCondition`, net10.0 framework support, MS 10.0.5 updates |
+| **v6.0.0** | Aug 16, 2026 | Major | OpenFeature Compliance | Official `FeatureOneProvider`, OpenFeature spec compliance, claims mapping, DI helpers |
+
+---
+
+## Nuget Package Matrix (v6.0.0)
+
+| Package | Latest Version | Description | Target Frameworks |
+|---|---|---|---|
+| **FeatureOne** | `6.0.0` | Core evaluation engine, condition strategies, native `IFeatures` API, and the built-in CNCF OpenFeature Specification provider (`FeatureOneProvider`, `FeatureOne.OpenFeature` namespace) | `netstandard2.1`, `net9.0`, `net10.0` |
+| **FeatureOne.SQL** | `6.0.0` | SQL storage provider (MSSQL, SQLite, PostgreSQL, MySQL, ODBC, OleDb) | `netstandard2.1`, `net9.0`, `net10.0` |
+| **FeatureOne.File** | `6.0.0` | File system storage provider with JSON toggle configuration | `netstandard2.1`, `net9.0`, `net10.0` |
+
+---
+
+## Upgrade & Migration Path
+
+FeatureOne maintains a strict **zero-breaking-change** contract for existing public APIs:
+
+1. **Upgrading from v5.x to v6.0.0**:
+ - Update NuGet package references to `6.0.0`.
+ - Existing code using `Features.Current.IsEnabled(...)` or custom `IStorageProvider` will continue working with zero modifications.
+ - To integrate with the OpenFeature SDK, add `using FeatureOne.OpenFeature;` and call `builder.Services.AddFeatureOneOpenFeature()` — the provider is already in the `FeatureOne` package, so no extra install is needed.
+ - Condition deserialization failures now throw `FeatureOneConfigurationException` (derived from `Exception`) instead of a bare `Exception`; update any code asserting on the exact exception type.
+
+---
+
+## Quality & Security Metrics
+
+| Version | Test Count | Test Pass Rate | Line Coverage | Security Hardening |
+|---|---|---|---|---|
+| **v5.0.1** | ~20 | 100% | ~60% | Base |
+| **v5.1.0** | 170 | 100% | 90%+ | ReDoS protection, type loading sandbox, input validation |
+| **v5.2.0** | 198 | 100% | 98%+ | Relational comparison boundary validation |
+| **v6.0.0** | 216 | 100% | 98%+ | Standardized OpenFeature spec error handling (`FlagNotFound`, `General`) |
diff --git a/docs/release-table.md b/docs/release-table.md
new file mode 100644
index 0000000..3e4bcec
--- /dev/null
+++ b/docs/release-table.md
@@ -0,0 +1,6 @@
+| Version | Release Date | Type | Key Changes | Backward Compatibility |
+|--------|-------------|------|-------------|---------------------|
+| v5.0.1 | Previous | Initial | Core feature toggle functionality | N/A (Initial release) |
+| v5.1.0 | Oct 13, 2025 | Minor | Security fixes (ReDoS protection, secure type loading), architectural improvements (prefix matching, dependency injection), new features (DateRangeCondition, configuration validation) | High - maintains all existing functionality with minor security-related behavioral changes |
+| v5.2.0 | Mar 18, 2026 | Minor | RelationalCondition (5 operators), net10.0 target framework, Microsoft 10.0.5 package upgrades | Full - fully backward compatible |
+| v6.0.0 | Aug 16, 2026 | Major | OpenFeature Specification (v1.x) Provider compliance (`FeatureOneProvider` in the core `FeatureOne` package under the `FeatureOne.OpenFeature` namespace, context mapping, DI extensions), custom condition registration (`ConditionDeserializer.Register`) | High - native API fully backward compatible; condition deserialization now throws `FeatureOneConfigurationException` instead of `Exception` |
diff --git a/docs/wiki.md b/docs/wiki.md
new file mode 100644
index 0000000..d9597d3
--- /dev/null
+++ b/docs/wiki.md
@@ -0,0 +1,599 @@
+# FeatureOne - Complete Guide & Wiki Documentation
+
+Welcome to the official **FeatureOne Wiki**. FeatureOne is a high-performance, lightweight feature flagging
+library for .NET supporting **.NET Standard 2.1**, **.NET 9.0**, and **.NET 10.0**. It can be consumed
+through its **native API** or through any **CNCF OpenFeature Specification (v1.x)** client — both are
+first-class, fully supported, and back onto the same evaluation engine.
+
+---
+
+## Table of Contents
+
+1. [Introduction](#introduction)
+2. [Choosing Your API](#choosing-your-api)
+3. [What are Feature Toggles?](#what-are-feature-toggles)
+4. [Benefits of Feature Toggles](#benefits-of-feature-toggles)
+5. [Installation](#installation)
+6. [Native API Quick Start](#native-api-quick-start)
+7. [OpenFeature Quick Start](#openfeature-quick-start)
+8. [Dependency Injection Integration](#dependency-injection-integration)
+9. [Condition Strategies](#condition-strategies)
+10. [Storage Providers](#storage-providers)
+11. [OpenFeature Compliance Matrix](#openfeature-compliance-matrix)
+12. [OpenFeature Hooks & Lifecycle](#openfeature-hooks--lifecycle)
+13. [Logging](#logging)
+14. [Extending FeatureOne](#extending-featureone)
+15. [Best Practices](#best-practices)
+16. [Troubleshooting](#troubleshooting)
+17. [API Reference & Project Structure](#api-reference--project-structure)
+
+---
+
+## Introduction
+
+**FeatureOne** is a feature toggle library for enterprise .NET applications. It controls program features
+dynamically at runtime using claims-based targeting, pluggable storage, and composable condition strategies.
+
+- **Target Frameworks**: `.NETStandard 2.1`, `.NET 9.0`, `.NET 10.0`
+- **Consumption models**: native `IFeatures` API, and CNCF OpenFeature Specification (v1.x) clients via `FeatureOneProvider`
+- **Supported Storage Backends**: In-Memory, SQL (MSSQL, SQLite, PostgreSQL, MySQL, ODBC, OleDb), File System (JSON), and custom `IStorageProvider`
+
+---
+
+## Choosing Your API
+
+Both APIs are supported equally and neither is deprecated. They share storage providers, conditions,
+operators, caching, and logging — the difference is the call surface, not the capability.
+
+| | **Native API** | **OpenFeature Provider** |
+|---|---|---|
+| Entry point | `IFeatures` / `Features.Current` | `OpenFeature.Api.Instance.GetClient()` |
+| Namespace | `FeatureOne` | `FeatureOne.OpenFeature` |
+| Call style | Synchronous `bool IsEnabled(...)` | Asynchronous `Task GetBooleanValueAsync(...)` |
+| Targeting input | `ClaimsPrincipal`, `IEnumerable`, `IDictionary` | `EvaluationContext`, mapped to claims by `ToClaims()` |
+| Missing flag | Returns `false`, logs a warning | Returns your default with `ErrorType.FlagNotFound` |
+| Evaluation failure | Returns `false`, logs the exception | Returns your default with `ErrorType.General` and an error message |
+| Observability | `IFeatureLogger` | `IFeatureLogger` plus the OpenFeature hook pipeline |
+| Portability | FeatureOne-specific call sites | Vendor-neutral call sites, portable across flag backends |
+| DI registration | `services.AddFeatureOneWith*Storage(...)` | The same, plus `services.AddFeatureOneOpenFeature()` |
+
+**Choose the native API when** you want the smallest surface area, synchronous call sites (e.g. inside a
+Razor view or a tight loop), or direct `ClaimsPrincipal` targeting from ASP.NET Core.
+
+**Choose the OpenFeature provider when** you want vendor-neutral flag APIs, the option to swap flag backends
+without touching call sites, or the OpenFeature hook pipeline for telemetry and auditing.
+
+**Both at once** is fine — register your storage once and the two front doors read the same `IFeatureStore`.
+
+---
+
+## What are Feature Toggles?
+
+A **feature toggle** (or feature flag) is a software engineering technique allowing developers to enable or disable application features remotely without code redeployments.
+
+Native API:
+```csharp
+if (Features.Current.IsEnabled("dashboard_widget"))
+ ShowDashboardWidget();
+else
+ ShowDefaultDashboard();
+```
+
+OpenFeature:
+```csharp
+if (await client.GetBooleanValueAsync("dashboard_widget", false))
+ ShowDashboardWidget();
+else
+ ShowDefaultDashboard();
+```
+
+Flag evaluation combines:
+- **Storage Provider**: Retrieves toggle definitions from your chosen storage backend.
+- **Conditions**: Evaluates rules against user claims (e.g. role, email, user tier, time range).
+- **Operators**: Evaluates constituent conditions using logical `Operator.Any` (OR) or `Operator.All` (AND).
+
+---
+
+## Benefits of Feature Toggles
+
+1. **Risk Mitigation**: Instant rollbacks without redeploying code.
+2. **Continuous Integration**: Safely merge incomplete features behind flags.
+3. **Targeted Rollouts**: Target features based on user claims, roles, tiers, or date windows.
+4. **Standardization**: Vendor-neutral standardization across teams via OpenFeature SDKs.
+
+---
+
+## Installation
+
+Install NuGet packages according to your requirements:
+
+### 1. Core Package (native API + built-in OpenFeature provider)
+```bash
+dotnet add package FeatureOne --version 6.0.0
+```
+
+### 2. SQL Storage Provider
+```bash
+dotnet add package FeatureOne.SQL --version 6.0.0
+```
+
+### 3. File System Storage Provider
+```bash
+dotnet add package FeatureOne.File --version 6.0.0
+```
+
+There is no separate OpenFeature package — `FeatureOneProvider` ships inside **FeatureOne** under the
+`FeatureOne.OpenFeature` namespace.
+
+---
+
+## Native API Quick Start
+
+```csharp
+using FeatureOne;
+using FeatureOne.Core.Stores;
+using FeatureOne.File;
+
+// 1. Initialize FeatureStore
+var fileConfig = new FileConfiguration { FilePath = @"C:\Config\Features.json" };
+var storageProvider = new FileStorageProvider(fileConfig);
+var featureStore = new FeatureStore(storageProvider);
+
+// 2. Initialize the global facade
+Features.Initialize(() => new Features(featureStore));
+
+// 3. Evaluate - with no targeting
+bool isEnabled = Features.Current.IsEnabled("dashboard_widget");
+
+// 3b. Evaluate - targeting an ASP.NET Core ClaimsPrincipal
+bool isEnabledForUser = Features.Current.IsEnabled("dashboard_widget", User);
+
+// 3c. Evaluate - targeting an explicit claims dictionary
+bool isEnabledForClaims = Features.Current.IsEnabled("dashboard_widget", new Dictionary
+{
+ ["email"] = "john@gbk.com",
+ ["tier"] = "gold"
+});
+```
+
+`IsEnabled` never throws: an unknown flag, an invalid feature name, or a storage failure returns `false` and
+logs the reason through `IFeatureLogger`. Prefer injecting `IFeatures` over the `Features.Current` static
+where you can — see [Dependency Injection Integration](#dependency-injection-integration).
+
+---
+
+## OpenFeature Quick Start
+
+```csharp
+using FeatureOne.Core.Stores;
+using FeatureOne.File;
+using FeatureOne.OpenFeature;
+using OpenFeature;
+using OpenFeature.Model;
+
+// 1. Initialize FeatureStore
+var fileConfig = new FileConfiguration { FilePath = @"C:\Config\Features.json" };
+var storageProvider = new FileStorageProvider(fileConfig);
+var featureStore = new FeatureStore(storageProvider);
+
+// 2. Set FeatureOneProvider as global OpenFeature provider
+await Api.Instance.SetProviderAsync(new FeatureOneProvider(featureStore));
+
+// 3. Get OpenFeature Client
+var client = Api.Instance.GetClient();
+
+// 4. Create Evaluation Context with user attributes
+var context = EvaluationContext.Builder()
+ .SetTargetingKey("usr_98765")
+ .Set("email", "john@gbk.com")
+ .Set("tier", "gold")
+ .Set("seats", 5) // numbers, booleans and dates map to claims too
+ .Build();
+
+// 5. Evaluate Flag
+bool isEnabled = await client.GetBooleanValueAsync("dashboard_widget", false, context);
+```
+
+### Context to claims mapping
+
+`EvaluationContextExtensions.ToClaims()` converts an `EvaluationContext` into the claims dictionary the
+conditions evaluate against:
+
+| `EvaluationContext` input | Resulting claim value |
+|---|---|
+| `TargetingKey` | Set as `targetingKey`, `sub`, and `user_id` |
+| String attribute | Used verbatim |
+| Boolean attribute | `"true"` / `"false"` |
+| Integer attribute | Invariant-culture digits, e.g. `95` |
+| Double attribute | Invariant-culture round-trip form, e.g. `1.5` |
+| `DateTime` attribute | ISO-8601 round-trip (`"o"`) format |
+| List / structure attribute | JSON serialized |
+| Null attribute | Omitted |
+
+Claim keys are matched case-insensitively. Numbers always use the invariant culture so that
+`RelationalCondition` parses them identically regardless of the ambient culture.
+
+### A note on flag types
+
+FeatureOne is a boolean toggle engine. The provider implements all five OpenFeature resolvers, but the
+non-boolean ones are projections of the same boolean result:
+
+| Resolver | Enabled | Disabled |
+|---|---|---|
+| `ResolveBooleanValueAsync` | `true` | `false` |
+| `ResolveStringValueAsync` | `"true"` | `"false"` |
+| `ResolveIntegerValueAsync` | `1` | `0` |
+| `ResolveDoubleValueAsync` | `1.0` | `0.0` |
+| `ResolveStructureValueAsync` | `Value(true)` | `Value(false)` |
+
+These are **not** multivariate flag values — `GetStringValueAsync("theme", "dark")` returns `"true"` or
+`"false"`, never a theme name. Prefer `GetBooleanValueAsync` unless a typed call site makes one of the
+projections convenient.
+
+---
+
+## Dependency Injection Integration
+
+### Native API
+
+```csharp
+public void ConfigureServices(IServiceCollection services)
+{
+ // Registers IStorageProvider, IFeatureLogger, IFeatureStore and IFeatures
+ services.AddFeatureOneWithFileStorage(new FileConfiguration { FilePath = "Features.json" });
+}
+
+// Inject IFeatures
+public class DashboardController(IFeatures features) : Controller
+{
+ public IActionResult Index()
+ => features.IsEnabled("dashboard_widget", User) ? View("Widget") : View("Default");
+}
+```
+
+### OpenFeature
+
+```csharp
+public void ConfigureServices(IServiceCollection services)
+{
+ services.AddFeatureOneWithFileStorage(new FileConfiguration { FilePath = "Features.json" });
+
+ // Registers FeatureOneProvider and sets it as the global OpenFeature provider on application start
+ services.AddFeatureOneOpenFeature();
+}
+```
+
+Global provider registration runs from an `IHostedService` at application start, not from the DI factory, so
+it happens whether or not anything in your application resolves `FeatureOneProvider`.
+
+To configure hooks or opt out of global registration:
+
+```csharp
+services.AddFeatureOneOpenFeature(options =>
+{
+ options.SetAsGlobalProvider = true;
+ options.EnableLoggingHook = true; // bridges the hook pipeline to IFeatureLogger
+ options.AddHook(new MyTelemetryHook());
+});
+```
+
+Both registrations can coexist — `AddFeatureOneOpenFeature()` reuses the `IFeatureStore` registered by
+`AddFeatureOneWith*Storage(...)`, so native and OpenFeature call sites evaluate against the same data.
+
+---
+
+## Condition Strategies
+
+Condition strategies apply identically to both APIs — they are a property of the toggle definition, not of
+the call surface. FeatureOne provides four built-in strategies out of the box:
+
+### 1. `SimpleCondition`
+Enables or disables a feature unconditionally:
+```json
+{
+ "simple_flag": {
+ "toggle": {
+ "conditions": [{ "type": "Simple", "isEnabled": true }]
+ }
+ }
+}
+```
+
+### 2. `RegexCondition`
+Evaluates a Regular Expression pattern against a user claim (with built-in ReDoS timeout protection):
+```json
+{
+ "admin_feature": {
+ "toggle": {
+ "conditions": [{
+ "type": "Regex",
+ "claim": "role",
+ "expression": "^administrator$"
+ }]
+ }
+ }
+}
+```
+
+### 3. `RelationalCondition`
+Evaluates user claim values against fixed targets using relational operators (`Equals`, `NotEquals`, `GreaterThan`, `GreaterThanOrEqual`, `LessThan`, `LessThanOrEqual`):
+```json
+{
+ "tier_feature": {
+ "toggle": {
+ "conditions": [{
+ "type": "Relational",
+ "claim": "tier",
+ "operator": "GreaterThanOrEqual",
+ "value": "gold"
+ }]
+ }
+ }
+}
+```
+
+> **How values are compared.** When both the claim value and the configured value parse as numbers they are
+> compared **numerically**; otherwise they are compared as **ordinal strings**. So `age > 18` behaves
+> arithmetically, while `tier >= "gold"` still orders lexically. Numeric parsing uses the invariant culture
+> and string comparison is ordinal, so results never vary with the ambient culture. Numeric comparison also
+> applies to `Equals`, so a claim of `"5.0"` equals a configured value of `"5"`.
+
+### 4. `DateRangeCondition`
+Enables features strictly within a specified UTC start and end date/time window:
+```json
+{
+ "holiday_sale": {
+ "toggle": {
+ "conditions": [{
+ "type": "DateRange",
+ "startDate": "2026-12-01T00:00:00Z",
+ "endDate": "2026-12-25T23:59:59Z"
+ }]
+ }
+ }
+}
+```
+
+### Combining conditions
+```json
+{
+ "beta_dashboard": {
+ "toggle": {
+ "operator": "All",
+ "conditions": [
+ { "type": "Regex", "claim": "email", "expression": ".*@gbk\\.com" },
+ { "type": "DateRange", "startDate": "2026-09-01T00:00:00Z", "endDate": "2026-10-01T00:00:00Z" }
+ ]
+ }
+ }
+}
+```
+`Any` (the default) requires one condition to pass; `All` requires every condition to pass.
+
+---
+
+## Storage Providers
+
+Storage is shared by both APIs.
+
+### 1. SQL Storage (`FeatureOne.SQL`)
+Supports MS SQL, SQLite, PostgreSQL, MySQL, ODBC, and OleDb databases.
+
+```csharp
+var sqlConfig = new SQLConfiguration
+{
+ ConnectionSettings = new ConnectionSettings
+ {
+ Providername = "System.Data.SqlClient",
+ ConnectionString = "Server=localhost;Database=Features;Integrated Security=SSPI;"
+ },
+ FeatureTable = new FeatureTable
+ {
+ TableName = "[dbo].[TFeatures]",
+ NameColumn = "[Name]",
+ ToggleColumn = "[Toggle]",
+ ArchivedColumn = "[Archived]"
+ }
+};
+
+var storageProvider = new SQLStorageProvider(sqlConfig);
+
+// Native API
+Features.Initialize(() => new Features(new FeatureStore(storageProvider)));
+
+// OpenFeature
+await Api.Instance.SetProviderAsync(new FeatureOneProvider(new FeatureStore(storageProvider)));
+```
+
+### 2. File System Storage (`FeatureOne.File`)
+Loads feature toggles from a JSON configuration file on disk.
+
+```csharp
+var fileConfig = new FileConfiguration { FilePath = @"C:\Work\Features.json" };
+var storageProvider = new FileStorageProvider(fileConfig);
+
+// Native API
+Features.Initialize(() => new Features(new FeatureStore(storageProvider)));
+
+// OpenFeature
+await Api.Instance.SetProviderAsync(new FeatureOneProvider(new FeatureStore(storageProvider)));
+```
+
+---
+
+## OpenFeature Compliance Matrix
+
+| OpenFeature Feature | Spec | FeatureOne Implementation |
+|---|---|---|
+| **FeatureProvider** | 2.1 | `FeatureOneProvider` implementing `OpenFeature.FeatureProvider` |
+| **Typed Flag Evaluation** | 2.2 | `ResolveBooleanValueAsync`, `ResolveStringValueAsync`, `ResolveIntegerValueAsync`, `ResolveDoubleValueAsync`, `ResolveStructureValueAsync` (see [flag types](#a-note-on-flag-types)) |
+| **Resolution Details** | 2.3 | Returns `ResolutionDetails` with `Reason` (`TARGETING_MATCH`, `DISABLED`, `ERROR`), `Variant` (`"on"`, `"off"`), and `ErrorType` (`FlagNotFound`, `ProviderNotReady`, `General`) |
+| **Provider Lifecycle** | 2.4 | `InitializeAsync` / `ShutdownAsync` with status management (`NotReady`, `Ready`, `Error`). `InitializeAsync` reports `Error` when no `IFeatureStore` is available |
+| **Events System** | 2.5 | Lifecycle events emitted by the OpenFeature SDK from the provider status transitions above |
+| **Context Claims Mapping** | 3.1 | `EvaluationContextExtensions.ToClaims()` — see [mapping table](#context-to-claims-mapping) |
+| **Hooks Architecture** | 4.1 | `Hook` support via `AddHook`, with `FeatureOneLoggingHook` bridging to `IFeatureLogger` |
+
+### Error semantics
+
+| Situation | `ErrorType` | Returned value |
+|---|---|---|
+| Flag absent from the store | `FlagNotFound` | Your default |
+| No `IFeatureStore` available, or provider initialization failed | `ProviderNotReady` | Your default |
+| Condition evaluation threw | `General` | Your default |
+
+A missing store reports `ProviderNotReady`, deliberately distinct from `FlagNotFound`, so a misconfigured
+application is not mistaken for a typo'd flag key.
+
+---
+
+## OpenFeature Hooks & Lifecycle
+
+FeatureOne participates in OpenFeature's Hook pipeline (`BeforeAsync`, `AfterAsync`, `ErrorAsync`, `FinallyAsync`):
+
+```csharp
+var provider = new FeatureOneProvider(featureStore, logger);
+
+// Bridge the hook pipeline to FeatureOne's native logger
+provider.AddHook(new FeatureOneLoggingHook(logger));
+
+await Api.Instance.SetProviderAsync(provider);
+```
+
+Or declaratively through DI:
+
+```csharp
+services.AddFeatureOneOpenFeature(options => options.EnableLoggingHook = true);
+```
+
+`AddHook` is safe to call while evaluations are in flight, though hooks are normally added at configuration
+time.
+
+---
+
+## Logging
+
+Both APIs log through the same `IFeatureLogger` abstraction. The default implementation bridges to
+`Microsoft.Extensions.Logging`:
+
+```csharp
+public class MyLogger : IFeatureLogger
+{
+ public void Debug(string message) { }
+ public void Info(string message) { }
+ public void Warn(string message) { }
+ public void Error(string message, Exception ex = null) { }
+}
+```
+
+- **Native API**: pass it to the `Features` constructor, or register `IFeatureLogger` in DI.
+- **OpenFeature**: pass it to the `FeatureOneProvider` constructor, or register `IFeatureLogger` in DI and set `options.EnableLoggingHook = true` to also capture the hook lifecycle.
+
+---
+
+## Extending FeatureOne
+
+### Custom conditions
+
+Implement `ICondition`, then register it so the deserializer can construct it from JSON. Condition types are
+resolved from an explicit allow list rather than by loading arbitrary type names from configuration, so
+registration is required:
+
+```csharp
+public class PercentageCondition : ICondition
+{
+ public int Threshold { get; set; }
+ public string Claim { get; set; }
+
+ public bool Evaluate(IDictionary claims)
+ => claims != null
+ && claims.TryGetValue(Claim, out var raw)
+ && int.TryParse(raw, out var value)
+ && value <= Threshold;
+}
+```
+
+```csharp
+var conditions = new ConditionDeserializer()
+ .Register("Percentage");
+
+services.AddFeatureOneWithFileStorage(
+ new FileConfiguration { FilePath = "Features.json" },
+ deserializer: new ToggleDeserializer(conditions));
+```
+
+```json
+{
+ "gradual_rollout": {
+ "toggle": {
+ "conditions": [{ "type": "Percentage", "claim": "bucket", "threshold": 25 }]
+ }
+ }
+}
+```
+
+Registration requirements — violations throw `FeatureOneConfigurationException` at registration time:
+- the type must implement `ICondition`
+- the type must be concrete
+- the type must expose a parameterless constructor (it may be non-public)
+
+Names are normalised, so `"Percentage"` and `"PercentageCondition"` register and resolve identically.
+Public writable properties are hydrated from matching JSON keys, matched case-insensitively.
+
+Custom conditions work identically through both the native API and the OpenFeature provider.
+
+### Custom storage providers
+
+Implement `IStorageProvider` and register it:
+
+```csharp
+public class RedisStorageProvider : IStorageProvider
+{
+ public IEnumerable GetByName(string name) { /* ... */ }
+}
+
+services.AddFeatureOne(sp => new RedisStorageProvider(/* ... */));
+```
+
+### Custom caching
+
+Implement `ICache` and pass it to the storage provider extension:
+
+```csharp
+services.AddFeatureOneWithSQLStorage(sqlConfig, cache: new MyDistributedCache());
+```
+
+---
+
+## Best Practices
+
+1. **Prefer injecting `IFeatures`** over the `Features.Current` static — it keeps evaluation testable and avoids global state.
+2. **Always pass a sensible default** to OpenFeature resolvers. The default is what your users get when the store is unreachable, so it should be the safe path.
+3. **Prefer `GetBooleanValueAsync`** on the OpenFeature side; the typed resolvers are boolean projections, not multivariate values.
+4. **Keep flag keys stable and lowercase-insensitive.** Lookups are case-insensitive but prefix-based, so avoid flag names that are prefixes of other flag names where you can.
+5. **Register custom conditions once at startup** and reuse the `ConditionDeserializer` instance — registrations are per-instance, not global.
+6. **Set a cache expiry** appropriate to how quickly you need toggle changes to take effect; the default `FeatureCache` is process-local.
+7. **Don't use toggles as authorization.** Conditions evaluate claims, but a toggle is a rollout mechanism, not a security boundary.
+8. **Clean up stale toggles** once a feature is fully rolled out.
+
+---
+
+## Troubleshooting
+
+| Symptom | Likely cause | Fix |
+|---|---|---|
+| Native `IsEnabled` always returns `false` | Flag missing from the store, invalid feature name, or a storage exception being swallowed | Enable an `IFeatureLogger` and check the warning/error output |
+| OpenFeature returns `ProviderNotReady` | No `IFeatureStore` was available when the provider was constructed or initialized | Register `IFeatureStore` in DI, pass one to the constructor, or call `Features.Initialize` first |
+| OpenFeature returns `FlagNotFound` for a flag that exists | Flag key mismatch, or the toggle has no conditions — `FeatureStore` filters out toggles with an empty condition list | Check the key and ensure the toggle defines at least one condition |
+| A numeric `EvaluationContext` attribute never matches | Fixed in v6.0.0 — earlier builds dropped non-string attributes | Upgrade to v6.0.0 |
+| `FeatureOneConfigurationException: Could not find a condition type` | The toggle JSON references a condition type that has not been registered | Register it with `ConditionDeserializer.Register("Name")` |
+| Global OpenFeature provider is never set | `setAsGlobalProvider` was disabled, or the host never starts hosted services | Use `AddFeatureOneOpenFeature()` on a host that runs `IHostedService`, or call `Api.Instance.SetProviderAsync` yourself |
+| Toggle changes are not picked up | Cached toggle values have not expired | Lower the cache expiry in `CacheSettings`, or supply a custom `ICache` |
+
+---
+
+## API Reference & Project Structure
+
+- **[Developer Guide](DeveloperGuide.md)**: Full implementation guide and C# code examples.
+- **[Release Summary](release-summary.md)**: Technical summary of releases through v6.0.0.
+- **[Release Table](release-table.md)**: Version matrix and backward compatibility guidelines.
+- **[CHANGELOG](CHANGELOG.md)**: Detailed changelog by version.
diff --git a/src/FeatureOne.File/FeatureOne.File.csproj b/src/FeatureOne.File/FeatureOne.File.csproj
index 0f80bb5..ed12886 100644
--- a/src/FeatureOne.File/FeatureOne.File.csproj
+++ b/src/FeatureOne.File/FeatureOne.File.csproj
@@ -1,4 +1,4 @@
-
+
netstandard2.1;net9.0;net10.0
@@ -22,28 +22,17 @@
https://github.com/codeshayk/FeatureOne
git
feature-toggle; feature-flag; feature-flags; feature-toggles; featureOne; File-system; File-Backend; File-Toggles;
- 5.2.0
+ 6.0.0
License.md
feature-flag.png
- Release Notes v5.2.0. - Targets .NetStandard 2.1, .Net 9.0 and .Net 10.0
+ Release Notes v6.0.0. - Targets .NetStandard 2.1, .Net 9.0 and .Net 10.0
Library to Implement Feature Toggles to hide/show program features with File system storage.
- New Features:
- - Added RelationalCondition for claim-based relational comparisons (Equals, NotEquals, GreaterThan, GreaterThanOrEqual, LessThanOrEqual)
-
- Framework and Package Updates:
- - Added net10.0 target framework
- - Removed netstandard2.0 and net8.0 target frameworks
- - Upgraded all Microsoft packages to 10.0.5
-
- Provides Out of box Simple, Regex, DateRange and Relational toggle conditions.
- Provides Out of box support for File system storage provider to store toggles on disk file.
- Provides the support for default memory caching via configuration.
- Provides extensibility for custom implementations ie.
- -- Provides extensibility for implementing custom toggle conditions for bespoke use cases.
- -- Provides extensibility for implementing custom caching provider.
- -- Provides extensibility for implementing custom toggle deserializer for bespoke scenarios.
+ Major v6.0.0 Release Features:
+ - OpenFeature Specification (v1.x) provider compatibility via FeatureOne.OpenFeature package
+ - RelationalCondition with 5 relational operators (Equals, NotEquals, GreaterThan, GreaterThanOrEqual, LessThanOrEqual)
+ - Framework support for .NET Standard 2.1, .NET 9.0, and .NET 10.0
https://github.com/CodeShayk/FeatureOne/wiki
diff --git a/src/FeatureOne.SQL/FeatureOne.SQL.csproj b/src/FeatureOne.SQL/FeatureOne.SQL.csproj
index 34bbf56..733333e 100644
--- a/src/FeatureOne.SQL/FeatureOne.SQL.csproj
+++ b/src/FeatureOne.SQL/FeatureOne.SQL.csproj
@@ -1,4 +1,4 @@
-
+
netstandard2.1;net9.0;net10.0
@@ -23,29 +23,17 @@
https://github.com/CodeShayk/FeatureOne
git
feature-toggle; feature-flag; feature-flags; feature-toggles; featureOne; SQL-Backend; SQL-Toggles; SQL
- 5.2.0
+ 6.0.0
License.md
feature-flag.png
- Release Notes v5.2.0. - Targets .NetStandard 2.1, .Net 9.0 and .Net 10.0
+ Release Notes v6.0.0. - Targets .NetStandard 2.1, .Net 9.0 and .Net 10.0
Library to Implement Feature Toggles to hide/show program features with SQL storage.
- New Features:
- - Added RelationalCondition for claim-based relational comparisons (Equals, NotEquals, GreaterThan, GreaterThanOrEqual, LessThanOrEqual)
-
- Framework and Package Updates:
- - Added net10.0 target framework
- - Removed netstandard2.0 and net8.0 target frameworks
- - Upgraded all Microsoft packages to 10.0.5
-
- Supports configuring all Db providers - MSSQL, SQLite, ODBC, OLEDB, MySQL, PostgreSQL.
- Provides Out of box Simple, Regex, DateRange, and Relational toggle conditions.
- Provides the support for default memory caching via configuration.
- Provides extensibility for custom implementations ie.
- -- Provides extensibility for implementing custom toggle conditions for bespoke use cases.
- -- Provides extensibility to plugin other SQL providers.
- -- Provides extensibility for implementing custom caching providers.
- -- Provides extensibility for implementing custom toggle deserializer for bespoke scenarios.
+ Major v6.0.0 Release Features:
+ - OpenFeature Specification (v1.x) provider compatibility via FeatureOne.OpenFeature package
+ - RelationalCondition with 5 relational operators (Equals, NotEquals, GreaterThan, GreaterThanOrEqual, LessThanOrEqual)
+ - Framework support for .NET Standard 2.1, .NET 9.0, and .NET 10.0
https://github.com/CodeShayk/FeatureOne/wiki
diff --git a/src/FeatureOne/Core/Toggles/Conditions/RelationalCondition.cs b/src/FeatureOne/Core/Toggles/Conditions/RelationalCondition.cs
index f8cc0be..fc5540d 100644
--- a/src/FeatureOne/Core/Toggles/Conditions/RelationalCondition.cs
+++ b/src/FeatureOne/Core/Toggles/Conditions/RelationalCondition.cs
@@ -1,8 +1,21 @@
+using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
namespace FeatureOne.Core.Toggles.Conditions
{
+ ///
+ /// Compares a user claim against a fixed target value using a relational operator.
+ ///
+ ///
+ /// Claims are strings, so the comparison strategy is chosen from the values themselves:
+ /// when both the claim and the target parse as numbers they are compared numerically,
+ /// otherwise they are compared as ordinal strings. This keeps lexical targets such as
+ /// user tiers working while giving numeric claims (age, seats, score)
+ /// arithmetic ordering rather than the digit-by-digit ordering that would rank "9" above "18".
+ /// Ordinal comparison is used for the string case so results do not vary with the ambient culture.
+ ///
public class RelationalCondition : ICondition
{
public string Claim { get; set; }
@@ -20,23 +33,62 @@ public bool Evaluate(IDictionary claims)
var claimValue = claims.First(x => x.Key.Equals(Claim)).Value?.Trim() ?? string.Empty;
var comparisonValue = Value?.Trim() ?? string.Empty;
+ var comparison = Compare(claimValue, comparisonValue);
+
switch (Operator)
{
case RelationalOperator.Equals:
- return claimValue == comparisonValue;
+ return comparison == 0;
case RelationalOperator.NotEquals:
- return claimValue != comparisonValue;
+ return comparison != 0;
case RelationalOperator.GreaterThan:
- return string.Compare(claimValue, comparisonValue) > 0;
+ return comparison > 0;
case RelationalOperator.GreaterThanOrEqual:
- return string.Compare(claimValue, comparisonValue) >= 0;
+ return comparison >= 0;
+ case RelationalOperator.LessThan:
+ return comparison < 0;
case RelationalOperator.LessThanOrEqual:
- return string.Compare(claimValue, comparisonValue) <= 0;
+ return comparison <= 0;
default:
return false;
}
}
+
+ ///
+ /// Compares two claim values, numerically when both are numbers and ordinally otherwise.
+ ///
+ /// A negative value, zero, or a positive value, following conventions.
+ private static int Compare(string claimValue, string comparisonValue)
+ => TryCompareNumeric(claimValue, comparisonValue, out var numeric)
+ ? numeric
+ : string.Compare(claimValue, comparisonValue, StringComparison.Ordinal);
+
+ private static bool TryCompareNumeric(string left, string right, out int result)
+ {
+ result = 0;
+
+ // decimal first: it compares integers and fixed-point values exactly, where double
+ // would lose precision on large integers.
+ if (decimal.TryParse(left, NumberStyles.Number, CultureInfo.InvariantCulture, out var leftDecimal) &&
+ decimal.TryParse(right, NumberStyles.Number, CultureInfo.InvariantCulture, out var rightDecimal))
+ {
+ result = leftDecimal.CompareTo(rightDecimal);
+ return true;
+ }
+
+ // Fall back to double for magnitudes and exponent notation decimal cannot represent.
+ if (double.TryParse(left, NumberStyles.Float, CultureInfo.InvariantCulture, out var leftDouble) &&
+ double.TryParse(right, NumberStyles.Float, CultureInfo.InvariantCulture, out var rightDouble) &&
+ !double.IsNaN(leftDouble) && !double.IsNaN(rightDouble))
+ {
+ result = leftDouble.CompareTo(rightDouble);
+ return true;
+ }
+
+ return false;
+ }
}
+
public enum RelationalOperator
{
Equals,
@@ -46,4 +98,4 @@ public enum RelationalOperator
GreaterThanOrEqual,
LessThanOrEqual
}
-}
\ No newline at end of file
+}
diff --git a/src/FeatureOne/FeatureOne.csproj b/src/FeatureOne/FeatureOne.csproj
index 6531a82..535d84d 100644
--- a/src/FeatureOne/FeatureOne.csproj
+++ b/src/FeatureOne/FeatureOne.csproj
@@ -21,36 +21,28 @@
https://github.com/CodeShayk/FeatureOne
git
feature-toggle; feature-flag; feature-flags; feature-toggles; featureOne
- 5.2.0
+ 6.0.0
LICENSE.md
feature-flag.png
- Release Notes v5.2.0 Core Functionality :- Targets .NetStandard 2.1, .Net 9.0 and .Net 10.0
- Library to Implement Feature Toggles to hide/show program features. Does not contain storage provider.
+ Release Notes v6.0.0 Core Functionality :- Targets .NetStandard 2.1, .Net 9.0 and .Net 10.0
+ Library to Implement Feature Toggles to hide/show program features.
- New Features:
- - Added RelationalCondition for claim-based relational comparisons (Equals, NotEquals, GreaterThan, GreaterThanOrEqual, LessThanOrEqual)
-
- Framework and Package Updates:
- - Added net10.0 target framework
- - Removed netstandard2.0 and net8.0 target frameworks
- - Upgraded all Microsoft packages to 10.0.5
-
- Test Coverage:
- - Expanded unit test coverage to 98%+ line coverage
-
- Provides Out of box Simple, Regex and Relational toggle conditions.
- Provides extensibility for custom implementations ie.
- -- No storage exists by default. Requires `IStorageProvider` implementation to plugin in backend data store for stored features.
- -- Provides extensibility to implement custom toggle conditions for bespoke use cases.
- -- Provides extensibility for custom toggle deserializer for bespoke scenarios.
+ Major v6.0.0 Release Features:
+ - Full OpenFeature Specification (v1.x) Provider support, built in to the FeatureOne package under the
+ FeatureOne.OpenFeature namespace. No separate package install is required.
+ - Custom condition types can be registered with ConditionDeserializer.Register().
+ - Interoperability enhancements: Exposed FeatureStore property on Features facade for open integration.
+ - Multi-targeted for .NET Standard 2.1, .NET 9.0, and .NET 10.0.
https://github.com/CodeShayk/FeatureOne/wiki
+
+
diff --git a/src/FeatureOne/FeatureOneConfigurationException.cs b/src/FeatureOne/FeatureOneConfigurationException.cs
new file mode 100644
index 0000000..81ef7a4
--- /dev/null
+++ b/src/FeatureOne/FeatureOneConfigurationException.cs
@@ -0,0 +1,35 @@
+using System;
+
+namespace FeatureOne
+{
+ ///
+ /// Thrown when FeatureOne is misconfigured — for example when a toggle references a condition type
+ /// that has not been registered, or when a custom condition type cannot be constructed.
+ ///
+ public class FeatureOneConfigurationException : Exception
+ {
+ ///
+ /// Initializes a new instance of .
+ ///
+ public FeatureOneConfigurationException()
+ {
+ }
+
+ ///
+ /// Initializes a new instance of with a message.
+ ///
+ /// The error message.
+ public FeatureOneConfigurationException(string message) : base(message)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of with a message and inner exception.
+ ///
+ /// The error message.
+ /// The underlying cause.
+ public FeatureOneConfigurationException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+ }
+}
diff --git a/src/FeatureOne/Features.cs b/src/FeatureOne/Features.cs
index 52d2bca..f2254b1 100644
--- a/src/FeatureOne/Features.cs
+++ b/src/FeatureOne/Features.cs
@@ -15,6 +15,7 @@ public class Features : IFeatures
private readonly IFeatureLogger logger;
private static readonly ConfigurationValidator validator = new ConfigurationValidator();
public static Features Current { get; private set; }
+ public IFeatureStore FeatureStore => featureStore;
public Features(IFeatureStore featureStore) : this(featureStore, new DefaultLogger(null))
{ }
diff --git a/src/FeatureOne/Json/ConditionDeserializer.cs b/src/FeatureOne/Json/ConditionDeserializer.cs
index e8d737c..4325f46 100644
--- a/src/FeatureOne/Json/ConditionDeserializer.cs
+++ b/src/FeatureOne/Json/ConditionDeserializer.cs
@@ -3,33 +3,116 @@
using System.ComponentModel;
using System.Linq;
using System.Reflection;
-using System.Text.Json;
using System.Text.Json.Nodes;
using FeatureOne.Core;
using FeatureOne.Core.Toggles.Conditions;
namespace FeatureOne.Json
{
+ ///
+ /// Deserializes toggle conditions from JSON into instances.
+ ///
+ ///
+ /// Condition types are resolved from an explicit allow list rather than by loading arbitrary type
+ /// names from configuration, so a compromised or malformed store cannot instantiate unexpected types.
+ /// Custom conditions are supported by registering them explicitly:
+ ///
+ /// var deserializer = new ConditionDeserializer()
+ /// .Register<PercentageCondition>("Percentage");
+ ///
+ /// services.AddFeatureOneWithFileStorage(config, new ToggleDeserializer(deserializer));
+ ///
+ ///
public class ConditionDeserializer : IConditionDeserializer
{
- private static readonly Dictionary SafeConditionTypes = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ private static readonly IReadOnlyDictionary BuiltInConditionTypes = new Dictionary(StringComparer.OrdinalIgnoreCase)
{
- { "Simple", typeof(SimpleCondition) },
{ "SimpleCondition", typeof(SimpleCondition) },
- { "Regex", typeof(RegexCondition) },
{ "RegexCondition", typeof(RegexCondition) },
- { "DateRange", typeof(DateRangeCondition) },
{ "DateRangeCondition", typeof(DateRangeCondition) },
- { "Relational", typeof(RelationalCondition) },
{ "RelationalCondition", typeof(RelationalCondition) }
};
+ private readonly Dictionary conditionTypes;
+
+ ///
+ /// Initializes a new instance supporting the built-in condition types.
+ ///
+ public ConditionDeserializer() : this(null)
+ {
+ }
+
+ ///
+ /// Initializes a new instance supporting the built-in condition types plus the supplied custom types.
+ ///
+ ///
+ /// Custom condition types keyed by the type discriminator used in JSON. Keys are normalised
+ /// so that both "Percentage" and "PercentageCondition" resolve to the same entry.
+ /// A custom entry may override a built-in one.
+ ///
+ public ConditionDeserializer(IEnumerable> customConditionTypes)
+ {
+ conditionTypes = new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ foreach (var builtIn in BuiltInConditionTypes)
+ conditionTypes[builtIn.Key] = builtIn.Value;
+
+ if (customConditionTypes == null)
+ return;
+
+ foreach (var custom in customConditionTypes)
+ Register(custom.Key, custom.Value);
+ }
+
+ ///
+ /// Registers a custom condition type against the given JSON type discriminator.
+ ///
+ /// The condition type. Must expose a parameterless constructor.
+ ///
+ /// The discriminator used in JSON. Both "Percentage" and "PercentageCondition" are
+ /// accepted and normalise to the same registration.
+ ///
+ /// This instance, for chaining.
+ public ConditionDeserializer Register(string name) where TCondition : ICondition
+ => Register(name, typeof(TCondition));
+
+ ///
+ /// Registers a custom condition type against the given JSON type discriminator.
+ ///
+ /// The discriminator used in JSON.
+ /// The condition type. Must implement and expose a parameterless constructor.
+ /// This instance, for chaining.
+ public ConditionDeserializer Register(string name, Type conditionType)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ throw new ArgumentNullException(nameof(name));
+
+ if (conditionType == null)
+ throw new ArgumentNullException(nameof(conditionType));
+
+ if (!typeof(ICondition).IsAssignableFrom(conditionType))
+ throw new FeatureOneConfigurationException($"Condition type '{conditionType.FullName}' registered as '{name}' does not implement {nameof(ICondition)}.");
+
+ if (conditionType.IsAbstract || conditionType.IsInterface)
+ throw new FeatureOneConfigurationException($"Condition type '{conditionType.FullName}' registered as '{name}' must be a concrete type.");
+
+ if (GetParameterlessConstructor(conditionType) == null)
+ throw new FeatureOneConfigurationException($"Condition type '{conditionType.FullName}' registered as '{name}' must expose a parameterless constructor.");
+
+ conditionTypes[new NamePostFix(name, "Condition").Name] = conditionType;
+ return this;
+ }
+
+ ///
public ICondition Deserialize(JsonObject condition)
{
if (condition == null)
throw new ArgumentNullException(nameof(condition));
- var typeName = condition?["type"]?.ToString();
+ var typeName = condition["type"]?.ToString();
+
+ if (string.IsNullOrWhiteSpace(typeName))
+ throw new FeatureOneConfigurationException("Toggle condition is missing the required 'type' property.");
var toggle = CreateInstance(new NamePostFix(typeName, "Condition"));
@@ -38,35 +121,49 @@ public ICondition Deserialize(JsonObject condition)
return toggle;
}
+ ///
+ /// Creates an instance of the registered condition type matching the given normalised name.
+ ///
+ /// The normalised condition name.
+ /// A new condition instance.
public ICondition CreateInstance(NamePostFix conditionName)
{
- // NamePostFix transforms both "Simple" and "SimpleCondition" to "SimpleCondition"
- // So we look up the processed name
+ if (conditionName == null)
+ throw new ArgumentNullException(nameof(conditionName));
+
+ // NamePostFix transforms both "Simple" and "SimpleCondition" to "SimpleCondition",
+ // so registrations and lookups always agree on the postfixed form.
var processedName = conditionName.Name;
- if (SafeConditionTypes.TryGetValue(processedName, out Type type))
+ if (!conditionTypes.TryGetValue(processedName, out var type))
+ throw new FeatureOneConfigurationException(
+ $"Could not find a condition type for: '{processedName}'. Registered types are: {string.Join(", ", conditionTypes.Keys.OrderBy(x => x))}. " +
+ $"Register custom conditions with {nameof(ConditionDeserializer)}.{nameof(Register)}().");
+
+ try
{
return (ICondition)Activator.CreateInstance(type, true);
}
-
- // This shouldn't normally happen with correct inputs since NamePostFix standardizes the format
- throw new Exception($"Could not find a toggle type for: '{processedName}'. Only supported types are: {string.Join(", ", SafeConditionTypes.Keys)}");
+ catch (Exception ex)
+ {
+ throw new FeatureOneConfigurationException($"Failed to construct condition type '{type.FullName}' registered as '{processedName}'.", ex);
+ }
}
+ private static ConstructorInfo GetParameterlessConstructor(Type type)
+ => type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
+
private static void HydrateToggle(ICondition toggleCondition, JsonObject state)
{
- var properties = GetProperties(toggleCondition);
- foreach (var propertyInfo in properties)
+ foreach (var propertyInfo in GetProperties(toggleCondition))
{
var name = propertyInfo.Name;
- var keyValues = state.Deserialize>();
- if (!keyValues.Keys.Contains(name,
- new LambdaComparer((x, y) => x.Equals(y, StringComparison.OrdinalIgnoreCase))))
+ var entry = state.FirstOrDefault(x => x.Key.Equals(name, StringComparison.OrdinalIgnoreCase));
+ if (entry.Key == null)
continue;
- var value = state.Where(x => x.Key.Equals(name, StringComparison.OrdinalIgnoreCase))
- .First().Value?.ToString();
+ var value = entry.Value?.ToString();
var converter = TypeDescriptor.GetConverter(propertyInfo.PropertyType);
var propValue = converter.ConvertFrom(value);
@@ -84,4 +181,4 @@ private static PropertyInfo[] GetProperties(ICondition condition)
return propertyInfos;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/FeatureOne/OpenFeature/EvaluationContextExtensions.cs b/src/FeatureOne/OpenFeature/EvaluationContextExtensions.cs
new file mode 100644
index 0000000..f922bc3
--- /dev/null
+++ b/src/FeatureOne/OpenFeature/EvaluationContextExtensions.cs
@@ -0,0 +1,155 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text.Json;
+using OpenFeature.Model;
+
+namespace FeatureOne.OpenFeature
+{
+ ///
+ /// Extension methods for converting OpenFeature to FeatureOne user claims dictionary.
+ ///
+ public static class EvaluationContextExtensions
+ {
+ ///
+ /// Converts an OpenFeature to a dictionary of claims compatible with FeatureOne.
+ ///
+ /// The OpenFeature evaluation context.
+ /// A dictionary of string claim key-value pairs.
+ public static Dictionary ToClaims(this EvaluationContext context)
+ {
+ var claims = new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ if (context == null)
+ {
+ return claims;
+ }
+
+ if (!string.IsNullOrEmpty(context.TargetingKey))
+ {
+ claims["targetingKey"] = context.TargetingKey;
+ claims["sub"] = context.TargetingKey;
+ claims["user_id"] = context.TargetingKey;
+ }
+
+ foreach (var kvp in context)
+ {
+ if (kvp.Value == null || kvp.Value.IsNull)
+ {
+ continue;
+ }
+
+ string stringValue = FormatValue(kvp.Value);
+ if (stringValue != null)
+ {
+ claims[kvp.Key] = stringValue;
+ }
+ }
+
+ return claims;
+ }
+
+ ///
+ /// Renders an OpenFeature as the string form FeatureOne conditions evaluate against.
+ /// Numbers are formatted with the invariant culture so that RelationalCondition parses them
+ /// consistently regardless of the ambient culture. Lists and structures have no scalar claim
+ /// representation and are serialized to JSON so they are at least addressable by a RegexCondition.
+ ///
+ private static string FormatValue(Value value)
+ {
+ if (value == null || value.IsNull)
+ {
+ return null;
+ }
+
+ if (value.IsBoolean)
+ {
+ return value.AsBoolean == true ? "true" : "false";
+ }
+
+ if (value.IsDateTime)
+ {
+ return value.AsDateTime.HasValue ? value.AsDateTime.Value.ToString("o", CultureInfo.InvariantCulture) : null;
+ }
+
+ if (value.IsNumber)
+ {
+ var number = value.AsDouble;
+ if (!number.HasValue)
+ {
+ return null;
+ }
+
+ // AsInteger rounds rather than reporting non-integral values, so decide here instead:
+ // whole numbers render as "95", not "95.0", while 1.5 must not become "2".
+ var d = number.Value;
+ if (!double.IsNaN(d) && !double.IsInfinity(d) && d == Math.Floor(d)
+ && d >= long.MinValue && d <= long.MaxValue)
+ {
+ return ((long)d).ToString(CultureInfo.InvariantCulture);
+ }
+
+ return d.ToString("R", CultureInfo.InvariantCulture);
+ }
+
+ if (value.IsString)
+ {
+ return value.AsString;
+ }
+
+ if (value.IsList || value.IsStructure)
+ {
+ return SerializeComposite(value);
+ }
+
+ return value.AsString;
+ }
+
+ private static string SerializeComposite(Value value)
+ {
+ if (value.IsList)
+ {
+ var items = value.AsList;
+ if (items == null)
+ {
+ return null;
+ }
+
+ return "[" + string.Join(",", items.Select(FormatValueForJson)) + "]";
+ }
+
+ var structure = value.AsStructure;
+ if (structure == null)
+ {
+ return null;
+ }
+
+ return "{" + string.Join(",", structure.AsDictionary()
+ .Select(kvp => $"{JsonEncode(kvp.Key)}:{FormatValueForJson(kvp.Value)}")) + "}";
+ }
+
+ private static string FormatValueForJson(Value value)
+ {
+ if (value == null || value.IsNull)
+ {
+ return "null";
+ }
+
+ if (value.IsBoolean || value.IsNumber)
+ {
+ return FormatValue(value);
+ }
+
+ if (value.IsList || value.IsStructure)
+ {
+ return SerializeComposite(value);
+ }
+
+ return JsonEncode(FormatValue(value));
+ }
+
+ private static string JsonEncode(string value)
+ => value == null ? "null" : JsonSerializer.Serialize(value);
+ }
+}
diff --git a/src/FeatureOne/OpenFeature/Extensions/FeatureOneServiceCollectionExtensions.cs b/src/FeatureOne/OpenFeature/Extensions/FeatureOneServiceCollectionExtensions.cs
new file mode 100644
index 0000000..432f495
--- /dev/null
+++ b/src/FeatureOne/OpenFeature/Extensions/FeatureOneServiceCollectionExtensions.cs
@@ -0,0 +1,141 @@
+using System;
+using System.Collections.Generic;
+using FeatureOne.Core.Stores;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
+using OpenFeature;
+
+namespace FeatureOne.OpenFeature.Extensions
+{
+ ///
+ /// Options controlling how is registered.
+ ///
+ public class FeatureOneOpenFeatureOptions
+ {
+ ///
+ /// Whether to register the provider as the OpenFeature Api.Instance global provider on
+ /// application start. Defaults to true.
+ ///
+ public bool SetAsGlobalProvider { get; set; } = true;
+
+ ///
+ /// Whether to attach , routing OpenFeature evaluation
+ /// lifecycle events to the registered . Defaults to false.
+ /// Ignored when no is registered.
+ ///
+ public bool EnableLoggingHook { get; set; }
+
+ ///
+ /// Additional provider-level hooks to attach.
+ ///
+ public IList Hooks { get; } = new List();
+
+ ///
+ /// Adds a provider-level hook.
+ ///
+ /// The hook instance.
+ /// The options instance for chaining.
+ public FeatureOneOpenFeatureOptions AddHook(Hook hook)
+ {
+ if (hook == null)
+ {
+ throw new ArgumentNullException(nameof(hook));
+ }
+
+ Hooks.Add(hook);
+ return this;
+ }
+ }
+
+ ///
+ /// Extension methods for registering in .
+ ///
+ public static class FeatureOneServiceCollectionExtensions
+ {
+ ///
+ /// Registers in the dependency injection container, resolving the
+ /// from the container.
+ ///
+ /// The service collection.
+ /// Whether to register this provider as the OpenFeature global provider on application start. Defaults to true.
+ /// The service collection for chaining.
+ public static IServiceCollection AddFeatureOneOpenFeature(this IServiceCollection services, bool setAsGlobalProvider = true)
+ => services.AddFeatureOneOpenFeature(options => options.SetAsGlobalProvider = setAsGlobalProvider);
+
+ ///
+ /// Registers with an explicit .
+ ///
+ /// The service collection.
+ /// The explicit FeatureOne feature store instance.
+ /// Whether to register this provider as the OpenFeature global provider on application start. Defaults to true.
+ /// The service collection for chaining.
+ public static IServiceCollection AddFeatureOneOpenFeature(this IServiceCollection services, IFeatureStore featureStore, bool setAsGlobalProvider = true)
+ {
+ if (featureStore == null)
+ {
+ throw new ArgumentNullException(nameof(featureStore));
+ }
+
+ return services.AddFeatureOneOpenFeature(featureStore, options => options.SetAsGlobalProvider = setAsGlobalProvider);
+ }
+
+ ///
+ /// Registers , resolving the from the
+ /// container, with hooks and global-provider behaviour configured via .
+ ///
+ /// The service collection.
+ /// Callback to configure registration options.
+ /// The service collection for chaining.
+ public static IServiceCollection AddFeatureOneOpenFeature(this IServiceCollection services, Action configure)
+ => services.AddFeatureOneOpenFeature(featureStore: null, configure: configure);
+
+ ///
+ /// Registers with hooks and global-provider behaviour configured
+ /// via .
+ ///
+ /// The service collection.
+ /// The FeatureOne feature store, or null to resolve it from the container.
+ /// Callback to configure registration options. May be null.
+ /// The service collection for chaining.
+ public static IServiceCollection AddFeatureOneOpenFeature(this IServiceCollection services, IFeatureStore featureStore, Action configure)
+ {
+ if (services == null)
+ {
+ throw new ArgumentNullException(nameof(services));
+ }
+
+ var options = new FeatureOneOpenFeatureOptions();
+ configure?.Invoke(options);
+
+ services.TryAddSingleton(sp =>
+ {
+ var store = featureStore ?? sp.GetService();
+ var logger = sp.GetService();
+ var provider = new FeatureOneProvider(store, logger);
+
+ if (options.EnableLoggingHook && logger != null)
+ {
+ provider.AddHook(new FeatureOneLoggingHook(logger));
+ }
+
+ foreach (var hook in options.Hooks)
+ {
+ provider.AddHook(hook);
+ }
+
+ return provider;
+ });
+
+ if (options.SetAsGlobalProvider)
+ {
+ // Registering the provider globally is a startup concern. Doing it from a hosted service
+ // rather than from the factory above means it happens whether or not anything resolves
+ // FeatureOneProvider, and lets the async call be awaited rather than blocked on.
+ services.AddSingleton();
+ }
+
+ return services;
+ }
+ }
+}
diff --git a/src/FeatureOne/OpenFeature/FeatureOneLoggingHook.cs b/src/FeatureOne/OpenFeature/FeatureOneLoggingHook.cs
new file mode 100644
index 0000000..fbb7479
--- /dev/null
+++ b/src/FeatureOne/OpenFeature/FeatureOneLoggingHook.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using FeatureOne.Core.Stores;
+using OpenFeature;
+using OpenFeature.Model;
+
+namespace FeatureOne.OpenFeature
+{
+ ///
+ /// OpenFeature hook implementation that adapts OpenFeature evaluation lifecycle events
+ /// to FeatureOne's native .
+ ///
+ public class FeatureOneLoggingHook : Hook
+ {
+ private readonly IFeatureLogger logger;
+
+ ///
+ /// Initializes a new instance of using FeatureOne logger.
+ ///
+ /// The FeatureOne logger instance.
+ public FeatureOneLoggingHook(IFeatureLogger logger)
+ {
+ this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ }
+
+ ///
+ public override ValueTask BeforeAsync(HookContext context, IReadOnlyDictionary hints = null, CancellationToken cancellationToken = default)
+ {
+ logger.Info($"FeatureOneLoggingHook, Action='Before', Flag='{context.FlagKey}', Type='{typeof(T).Name}'");
+ return new ValueTask(context.EvaluationContext);
+ }
+
+ ///
+ public override ValueTask AfterAsync(HookContext context, FlagEvaluationDetails details, IReadOnlyDictionary hints = null, CancellationToken cancellationToken = default)
+ {
+ logger.Info($"FeatureOneLoggingHook, Action='After', Flag='{context.FlagKey}', Value='{details.Value}', Reason='{details.Reason}'");
+ return default;
+ }
+
+ ///
+ public override ValueTask ErrorAsync(HookContext context, Exception error, IReadOnlyDictionary hints = null, CancellationToken cancellationToken = default)
+ {
+ logger.Error($"FeatureOneLoggingHook, Action='Error', Flag='{context.FlagKey}'", error);
+ return default;
+ }
+
+ ///
+ public override ValueTask FinallyAsync(HookContext context, FlagEvaluationDetails evaluationDetails, IReadOnlyDictionary hints = null, CancellationToken cancellationToken = default)
+ {
+ logger.Info($"FeatureOneLoggingHook, Action='Finally', Flag='{context.FlagKey}'");
+ return default;
+ }
+ }
+}
diff --git a/src/FeatureOne/OpenFeature/FeatureOneProvider.cs b/src/FeatureOne/OpenFeature/FeatureOneProvider.cs
new file mode 100644
index 0000000..2606082
--- /dev/null
+++ b/src/FeatureOne/OpenFeature/FeatureOneProvider.cs
@@ -0,0 +1,253 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using FeatureOne.Core.Stores;
+using OpenFeature;
+using OpenFeature.Constant;
+using OpenFeature.Model;
+
+namespace FeatureOne.OpenFeature
+{
+ ///
+ /// OpenFeature specification compliant provider implementation for FeatureOne.
+ ///
+ ///
+ /// FeatureOne is a boolean toggle engine: a feature is either on or off for a given set of claims.
+ /// The provider therefore projects that single boolean onto every OpenFeature flag type:
+ ///
+ /// - Boolean resolves to the toggle result directly.
+ /// - String resolves to "true" / "false".
+ /// - Integer resolves to 1 / 0.
+ /// - Double resolves to 1.0 / 0.0.
+ /// - Structure resolves to a wrapping the boolean.
+ ///
+ /// The non-boolean forms carry no information the boolean form does not. Treat them as a convenience
+ /// for callers whose call sites are already typed, not as multivariate flag support — FeatureOne has
+ /// no notion of a string or numeric flag value, so a call such as
+ /// GetStringValue("theme", "dark") returns "true" or "false", never a theme name.
+ /// Prefer GetBooleanValue unless you specifically need one of the projections above.
+ ///
+ public class FeatureOneProvider : FeatureProvider
+ {
+ private readonly IFeatureStore featureStore;
+ private readonly IFeatureLogger logger;
+ private readonly Metadata metadata = new Metadata("FeatureOne Provider");
+ private ImmutableList hooks = ImmutableList.Empty;
+ private ProviderStatus status = ProviderStatus.NotReady;
+
+ ///
+ /// Initializes a new instance of using global .
+ ///
+ public FeatureOneProvider() : this(null, null)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of with explicit .
+ ///
+ /// The FeatureOne feature store instance. When null, the store is taken from at evaluation time.
+ /// Optional logger instance.
+ public FeatureOneProvider(IFeatureStore featureStore, IFeatureLogger logger = null)
+ {
+ this.featureStore = featureStore;
+ this.logger = logger;
+ }
+
+ ///
+ public override Metadata GetMetadata() => metadata;
+
+ ///
+ /// Returns the current provider status.
+ ///
+ /// The provider status.
+ public ProviderStatus GetStatus() => status;
+
+ ///
+ public override IImmutableList GetProviderHooks() => Volatile.Read(ref hooks);
+
+ ///
+ /// Adds a provider-level hook to the FeatureOne provider.
+ ///
+ /// The hook instance. Null is ignored.
+ public void AddHook(Hook hook)
+ {
+ if (hook == null)
+ {
+ return;
+ }
+
+ // Hooks are usually added at configuration time, but the provider is registered as a
+ // singleton, so swap atomically rather than mutating a list another thread may be reading.
+ ImmutableList current, updated;
+ do
+ {
+ current = Volatile.Read(ref hooks);
+ updated = current.Add(hook);
+ }
+ while (Interlocked.CompareExchange(ref hooks, updated, current) != current);
+ }
+
+ ///
+ public override Task InitializeAsync(EvaluationContext context, CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ var store = ResolveStore();
+ if (store == null)
+ {
+ status = ProviderStatus.Error;
+ logger?.Error("FeatureOneProvider, Action='InitializeAsync', Message='No IFeatureStore available. Pass one to the constructor or call Features.Initialize before setting the provider.'");
+ return Task.CompletedTask;
+ }
+
+ status = ProviderStatus.Ready;
+ logger?.Info("FeatureOneProvider, Action='InitializeAsync', Message='Provider initialized successfully'");
+ }
+ catch (Exception ex)
+ {
+ status = ProviderStatus.Error;
+ logger?.Error("FeatureOneProvider, Action='InitializeAsync', Message='Initialization failed'", ex);
+ }
+
+ return Task.CompletedTask;
+ }
+
+ ///
+ public override Task ShutdownAsync(CancellationToken cancellationToken = default)
+ {
+ status = ProviderStatus.NotReady;
+ logger?.Info("FeatureOneProvider, Action='ShutdownAsync', Message='Provider shut down'");
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Resolves to the FeatureOne toggle result for .
+ public override Task> ResolveBooleanValueAsync(string flagKey, bool defaultValue, EvaluationContext context = null, CancellationToken cancellationToken = default)
+ => Task.FromResult(Resolve(flagKey, defaultValue, context, nameof(ResolveBooleanValueAsync),
+ isEnabled => (isEnabled, isEnabled ? "on" : "off")));
+
+ ///
+ ///
+ /// Resolves to "true" or "false". FeatureOne has no string flag values;
+ /// see the remarks on .
+ ///
+ public override Task> ResolveStringValueAsync(string flagKey, string defaultValue, EvaluationContext context = null, CancellationToken cancellationToken = default)
+ => Task.FromResult(Resolve(flagKey, defaultValue, context, nameof(ResolveStringValueAsync),
+ isEnabled => (isEnabled ? "true" : "false", isEnabled ? "on" : "off")));
+
+ ///
+ ///
+ /// Resolves to 1 or 0. FeatureOne has no numeric flag values;
+ /// see the remarks on .
+ ///
+ public override Task> ResolveIntegerValueAsync(string flagKey, int defaultValue, EvaluationContext context = null, CancellationToken cancellationToken = default)
+ => Task.FromResult(Resolve(flagKey, defaultValue, context, nameof(ResolveIntegerValueAsync),
+ isEnabled => (isEnabled ? 1 : 0, isEnabled ? "1" : "0")));
+
+ ///
+ ///
+ /// Resolves to 1.0 or 0.0. FeatureOne has no numeric flag values;
+ /// see the remarks on .
+ ///
+ public override Task> ResolveDoubleValueAsync(string flagKey, double defaultValue, EvaluationContext context = null, CancellationToken cancellationToken = default)
+ => Task.FromResult(Resolve(flagKey, defaultValue, context, nameof(ResolveDoubleValueAsync),
+ isEnabled => (isEnabled ? 1.0 : 0.0, isEnabled ? "1.0" : "0.0")));
+
+ ///
+ ///
+ /// Resolves to a wrapping the boolean toggle result. FeatureOne has no
+ /// structured flag values; see the remarks on .
+ ///
+ public override Task> ResolveStructureValueAsync(string flagKey, Value defaultValue, EvaluationContext context = null, CancellationToken cancellationToken = default)
+ => Task.FromResult(Resolve(flagKey, defaultValue, context, nameof(ResolveStructureValueAsync),
+ isEnabled => (new Value(isEnabled), isEnabled ? "on" : "off")));
+
+ ///
+ /// Shared evaluation pipeline for every flag type. Applies the provider status guard, resolves the
+ /// feature, evaluates it against the mapped claims, and projects the boolean result onto
+ /// via .
+ ///
+ private ResolutionDetails Resolve(
+ string flagKey,
+ T defaultValue,
+ EvaluationContext context,
+ string action,
+ Func project)
+ {
+ try
+ {
+ if (status == ProviderStatus.Error)
+ {
+ return new ResolutionDetails(
+ flagKey,
+ defaultValue,
+ errorType: ErrorType.ProviderNotReady,
+ reason: Reason.Error,
+ errorMessage: "FeatureOneProvider is in an error state.");
+ }
+
+ var store = ResolveStore();
+ if (store == null)
+ {
+ // Distinct from FlagNotFound: the flag may well exist, we have nowhere to look it up.
+ logger?.Warn($"FeatureOneProvider, Action='{action}', Flag='{flagKey}', Message='No feature store available'");
+ return new ResolutionDetails(
+ flagKey,
+ defaultValue,
+ errorType: ErrorType.ProviderNotReady,
+ reason: Reason.Error,
+ errorMessage: "FeatureOneProvider has no IFeatureStore available.");
+ }
+
+ var feature = GetFeature(store, flagKey);
+ if (feature == null)
+ {
+ logger?.Warn($"FeatureOneProvider, Action='{action}', Flag='{flagKey}', Message='Flag not found'");
+ return new ResolutionDetails(
+ flagKey,
+ defaultValue,
+ errorType: ErrorType.FlagNotFound,
+ reason: Reason.Error,
+ errorMessage: $"Flag '{flagKey}' was not found in FeatureOne store.");
+ }
+
+ var claims = context.ToClaims();
+ var isEnabled = feature.IsEnabled(claims);
+ var (value, variant) = project(isEnabled);
+
+ logger?.Info($"FeatureOneProvider, Action='{action}', Flag='{flagKey}', Result={isEnabled}");
+ return new ResolutionDetails(
+ flagKey,
+ value,
+ reason: isEnabled ? Reason.TargetingMatch : Reason.Disabled,
+ variant: variant);
+ }
+ catch (Exception ex)
+ {
+ logger?.Error($"FeatureOneProvider, Action='{action}', Flag='{flagKey}'", ex);
+ return new ResolutionDetails(
+ flagKey,
+ defaultValue,
+ errorType: ErrorType.General,
+ reason: Reason.Error,
+ errorMessage: ex.Message);
+ }
+ }
+
+ private IFeatureStore ResolveStore() => featureStore ?? Features.Current?.FeatureStore;
+
+ private static IFeature GetFeature(IFeatureStore store, string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return null;
+ }
+
+ var features = store.FindStartsWith(name);
+ return features?.FirstOrDefault(x => x.Name.Value.Equals(name, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+}
diff --git a/src/FeatureOne/OpenFeature/FeatureOneProviderInitializer.cs b/src/FeatureOne/OpenFeature/FeatureOneProviderInitializer.cs
new file mode 100644
index 0000000..93878a8
--- /dev/null
+++ b/src/FeatureOne/OpenFeature/FeatureOneProviderInitializer.cs
@@ -0,0 +1,29 @@
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Hosting;
+
+namespace FeatureOne.OpenFeature
+{
+ ///
+ /// Hosted service that registers as the OpenFeature global provider
+ /// on application start.
+ ///
+ ///
+ /// Registration is a startup concern, not a resolution concern. Doing it here rather than inside the
+ /// DI factory means the global provider is set even when nothing in the application ever resolves
+ /// , and it lets SetProviderAsync — which awaits provider
+ /// initialization — be awaited properly instead of blocked on.
+ ///
+ internal sealed class FeatureOneProviderInitializer : IHostedService
+ {
+ private readonly FeatureOneProvider provider;
+
+ public FeatureOneProviderInitializer(FeatureOneProvider provider) => this.provider = provider;
+
+ public Task StartAsync(CancellationToken cancellationToken)
+ => global::OpenFeature.Api.Instance.SetProviderAsync(provider);
+
+ public Task StopAsync(CancellationToken cancellationToken)
+ => global::OpenFeature.Api.Instance.ShutdownAsync();
+ }
+}
diff --git a/test/FeatureOne.OpenFeature.Tests/EvaluationContextExtensionsTests.cs b/test/FeatureOne.OpenFeature.Tests/EvaluationContextExtensionsTests.cs
new file mode 100644
index 0000000..b7d72b1
--- /dev/null
+++ b/test/FeatureOne.OpenFeature.Tests/EvaluationContextExtensionsTests.cs
@@ -0,0 +1,152 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+using FeatureOne.Core;
+using FeatureOne.Core.Stores;
+using FeatureOne.Core.Toggles.Conditions;
+using Moq;
+using NUnit.Framework;
+using OpenFeature.Model;
+
+namespace FeatureOne.OpenFeature.Tests
+{
+ [TestFixture]
+ public class EvaluationContextExtensionsTests
+ {
+ [Test]
+ public void ToClaims_WithIntegerAttribute_ShouldMapToInvariantString()
+ {
+ var context = EvaluationContext.Builder().Set("score", 95).Build();
+
+ var claims = context.ToClaims();
+
+ Assert.That(claims["score"], Is.EqualTo("95"));
+ }
+
+ [Test]
+ public void ToClaims_WithDoubleAttribute_ShouldMapToInvariantString()
+ {
+ var context = EvaluationContext.Builder().Set("ratio", 1.5).Build();
+
+ var claims = context.ToClaims();
+
+ Assert.That(claims["ratio"], Is.EqualTo("1.5"));
+ }
+
+ [Test]
+ public void ToClaims_WithDoubleAttribute_ShouldIgnoreAmbientCulture()
+ {
+ // A comma decimal separator would break RelationalCondition's numeric parsing.
+ var original = CultureInfo.CurrentCulture;
+ try
+ {
+ CultureInfo.CurrentCulture = new CultureInfo("de-DE");
+ var claims = EvaluationContext.Builder().Set("ratio", 1.5).Build().ToClaims();
+
+ Assert.That(claims["ratio"], Is.EqualTo("1.5"));
+ }
+ finally
+ {
+ CultureInfo.CurrentCulture = original;
+ }
+ }
+
+ [Test]
+ public void ToClaims_WithStringAttribute_ShouldMapUnchanged()
+ {
+ var claims = EvaluationContext.Builder().Set("tier", "gold").Build().ToClaims();
+
+ Assert.That(claims["tier"], Is.EqualTo("gold"));
+ }
+
+ [Test]
+ public void ToClaims_WithBooleanAttribute_ShouldMapToLowerCaseLiteral()
+ {
+ var claims = EvaluationContext.Builder().Set("isAdmin", true).Set("isGuest", false).Build().ToClaims();
+
+ Assert.That(claims["isAdmin"], Is.EqualTo("true"));
+ Assert.That(claims["isGuest"], Is.EqualTo("false"));
+ }
+
+ [Test]
+ public void ToClaims_WithDateTimeAttribute_ShouldMapToRoundTripFormat()
+ {
+ var when = new DateTime(2026, 8, 16, 10, 30, 0, DateTimeKind.Utc);
+
+ var claims = EvaluationContext.Builder().Set("since", when).Build().ToClaims();
+
+ Assert.That(claims["since"], Is.EqualTo(when.ToString("o", CultureInfo.InvariantCulture)));
+ }
+
+ [Test]
+ public void ToClaims_WithListAttribute_ShouldSerializeToJson()
+ {
+ var context = EvaluationContext.Builder()
+ .Set("roles", new Value(new List { new Value("admin"), new Value("editor") }))
+ .Build();
+
+ var claims = context.ToClaims();
+
+ Assert.That(claims["roles"], Is.EqualTo("[\"admin\",\"editor\"]"));
+ }
+
+ [Test]
+ public void ToClaims_WithStructureAttribute_ShouldSerializeToJson()
+ {
+ var structure = Structure.Builder()
+ .Set("plan", "pro")
+ .Set("seats", 5)
+ .Build();
+ var context = EvaluationContext.Builder().Set("account", new Value(structure)).Build();
+
+ var claims = context.ToClaims();
+
+ // Structure backing storage does not guarantee key order, so assert on the members.
+ Assert.That(claims["account"], Does.StartWith("{").And.EndWith("}"));
+ Assert.That(claims["account"], Does.Contain("\"plan\":\"pro\""));
+ Assert.That(claims["account"], Does.Contain("\"seats\":5"));
+ }
+
+ [Test]
+ public void ToClaims_WithNullAttribute_ShouldOmitTheClaim()
+ {
+ var context = EvaluationContext.Builder().Set("maybe", new Value()).Build();
+
+ var claims = context.ToClaims();
+
+ Assert.That(claims.ContainsKey("maybe"), Is.False);
+ }
+
+ [Test]
+ public void ToClaims_ShouldBeCaseInsensitive()
+ {
+ var claims = EvaluationContext.Builder().Set("Tier", "gold").Build().ToClaims();
+
+ Assert.That(claims["tier"], Is.EqualTo("gold"));
+ }
+
+ [Test]
+ public async Task Provider_WithNumericContextAttribute_ShouldEvaluateRelationalCondition()
+ {
+ // The end-to-end reason the numeric mapping matters: without it the claim never reaches
+ // the condition at all and the flag silently evaluates as disabled. Uses Equals so the
+ // assertion turns on the mapping rather than on RelationalCondition's comparison semantics.
+ var mockStorage = new Mock();
+ var feature = new Feature("tier_gate", new Toggle(Operator.Any,
+ new RelationalCondition { Claim = "seats", Value = "5", Operator = RelationalOperator.Equals }));
+ mockStorage.Setup(x => x.GetByName("tier_gate")).Returns(new IFeature[] { feature });
+
+ var provider = new FeatureOneProvider(new FeatureStore(mockStorage.Object));
+
+ var match = await provider.ResolveBooleanValueAsync("tier_gate", false,
+ EvaluationContext.Builder().Set("seats", 5).Build());
+ var noMatch = await provider.ResolveBooleanValueAsync("tier_gate", false,
+ EvaluationContext.Builder().Set("seats", 9).Build());
+
+ Assert.That(match.Value, Is.True);
+ Assert.That(noMatch.Value, Is.False);
+ }
+ }
+}
diff --git a/test/FeatureOne.OpenFeature.Tests/FeatureOne.OpenFeature.Tests.csproj b/test/FeatureOne.OpenFeature.Tests/FeatureOne.OpenFeature.Tests.csproj
new file mode 100644
index 0000000..ea8c074
--- /dev/null
+++ b/test/FeatureOne.OpenFeature.Tests/FeatureOne.OpenFeature.Tests.csproj
@@ -0,0 +1,25 @@
+
+
+
+ net10.0
+ disable
+ disable
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/FeatureOne.OpenFeature.Tests/FeatureOneProviderLifecycleTests.cs b/test/FeatureOne.OpenFeature.Tests/FeatureOneProviderLifecycleTests.cs
new file mode 100644
index 0000000..ea636bd
--- /dev/null
+++ b/test/FeatureOne.OpenFeature.Tests/FeatureOneProviderLifecycleTests.cs
@@ -0,0 +1,258 @@
+using System;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using FeatureOne.Core;
+using FeatureOne.Core.Stores;
+using FeatureOne.Core.Toggles.Conditions;
+using FeatureOne.OpenFeature.Extensions;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Moq;
+using NUnit.Framework;
+using OpenFeature;
+using OpenFeature.Constant;
+using OpenFeature.Model;
+
+namespace FeatureOne.OpenFeature.Tests
+{
+ [TestFixture]
+ public class FeatureOneProviderLifecycleTests
+ {
+ private FeatureStore CreateStore()
+ {
+ var mockStorage = new Mock();
+ var enabled = new Feature("enabled_flag", new Toggle(Operator.Any, new SimpleCondition { IsEnabled = true }));
+ mockStorage.Setup(x => x.GetByName("enabled_flag")).Returns(new IFeature[] { enabled });
+ return new FeatureStore(mockStorage.Object);
+ }
+
+ [Test]
+ public async Task InitializeAsync_WithNoStoreAvailable_ShouldSetErrorStatus()
+ {
+ // No explicit store and no Features.Current means there is nothing to evaluate against.
+ var provider = new FeatureOneProvider(featureStore: null);
+
+ await provider.InitializeAsync(EvaluationContext.Empty);
+
+ Assert.That(provider.GetStatus(), Is.EqualTo(ProviderStatus.Error));
+ }
+
+ [Test]
+ public async Task InitializeAsync_WithNoStore_ShouldLogTheFailure()
+ {
+ var logger = new Mock();
+ var provider = new FeatureOneProvider(featureStore: null, logger: logger.Object);
+
+ await provider.InitializeAsync(EvaluationContext.Empty);
+
+ logger.Verify(l => l.Error(It.Is(s => s.Contains("InitializeAsync")), It.IsAny()), Times.Once);
+ }
+
+ [Test]
+ public async Task InitializeAsync_WithStore_ShouldSetReadyStatus()
+ {
+ var provider = new FeatureOneProvider(CreateStore());
+
+ await provider.InitializeAsync(EvaluationContext.Empty);
+
+ Assert.That(provider.GetStatus(), Is.EqualTo(ProviderStatus.Ready));
+ }
+
+ [Test]
+ public async Task Resolve_WhenProviderInErrorState_ShouldReturnProviderNotReady()
+ {
+ var provider = new FeatureOneProvider(featureStore: null);
+ await provider.InitializeAsync(EvaluationContext.Empty);
+ Assert.That(provider.GetStatus(), Is.EqualTo(ProviderStatus.Error));
+
+ var result = await provider.ResolveBooleanValueAsync("enabled_flag", false);
+
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.ProviderNotReady));
+ Assert.That(result.Reason, Is.EqualTo(Reason.Error));
+ Assert.That(result.Value, Is.False);
+ }
+
+ [Test]
+ public async Task Resolve_WithNoStoreAvailable_ShouldReportProviderNotReadyNotFlagNotFound()
+ {
+ // A missing store is a configuration fault, not a missing flag - the two must not be conflated.
+ var provider = new FeatureOneProvider(featureStore: null);
+
+ var result = await provider.ResolveBooleanValueAsync("enabled_flag", false);
+
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.ProviderNotReady));
+ }
+
+ [Test]
+ public async Task Resolve_WithStoreButUnknownFlag_ShouldStillReportFlagNotFound()
+ {
+ var provider = new FeatureOneProvider(CreateStore());
+
+ var result = await provider.ResolveBooleanValueAsync("nope", true);
+
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.FlagNotFound));
+ Assert.That(result.Value, Is.True);
+ }
+
+ [Test]
+ public async Task Resolve_WhenStoreThrows_ShouldReturnGeneralError()
+ {
+ var store = new Mock();
+ store.Setup(x => x.FindStartsWith(It.IsAny())).Throws(new InvalidOperationException("boom"));
+ var provider = new FeatureOneProvider(store.Object);
+
+ var result = await provider.ResolveBooleanValueAsync("enabled_flag", false);
+
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.General));
+ Assert.That(result.ErrorMessage, Is.EqualTo("boom"));
+ }
+
+ [Test]
+ public void AddHook_ShouldBeSafeUnderConcurrentReads()
+ {
+ var provider = new FeatureOneProvider(CreateStore());
+ var failures = 0;
+
+ var reader = Task.Run(() =>
+ {
+ for (var i = 0; i < 2000; i++)
+ {
+ try
+ {
+ foreach (var _ in provider.GetProviderHooks())
+ {
+ }
+ }
+ catch (InvalidOperationException)
+ {
+ Interlocked.Increment(ref failures);
+ }
+ }
+ });
+
+ var writer = Task.Run(() =>
+ {
+ for (var i = 0; i < 2000; i++)
+ {
+ provider.AddHook(new Mock().Object);
+ }
+ });
+
+ Task.WaitAll(reader, writer);
+
+ Assert.That(failures, Is.Zero);
+ Assert.That(provider.GetProviderHooks().Count, Is.EqualTo(2000));
+ }
+
+ [Test]
+ public void AddHook_WithNull_ShouldBeIgnored()
+ {
+ var provider = new FeatureOneProvider(CreateStore());
+
+ provider.AddHook(null);
+
+ Assert.That(provider.GetProviderHooks(), Is.Empty);
+ }
+
+ [Test]
+ public void AddFeatureOneOpenFeature_WithGlobalProvider_ShouldRegisterHostedServiceRatherThanSettingItInTheFactory()
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(CreateStore());
+ services.AddFeatureOneOpenFeature();
+
+ // The registration must not depend on anything resolving FeatureOneProvider.
+ var hostedServices = services.Where(d => d.ServiceType == typeof(IHostedService)).ToList();
+
+ Assert.That(hostedServices, Has.Count.EqualTo(1));
+ Assert.That(hostedServices[0].ImplementationType.Name, Is.EqualTo("FeatureOneProviderInitializer"));
+ }
+
+ [Test]
+ public void AddFeatureOneOpenFeature_WithoutGlobalProvider_ShouldNotRegisterHostedService()
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(CreateStore());
+ services.AddFeatureOneOpenFeature(setAsGlobalProvider: false);
+
+ Assert.That(services.Any(d => d.ServiceType == typeof(IHostedService)), Is.False);
+ }
+
+ [Test]
+ public async Task HostedService_StartAsync_ShouldSetTheGlobalProvider()
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(CreateStore());
+ services.AddFeatureOneOpenFeature();
+
+ var sp = services.BuildServiceProvider();
+ var hostedService = sp.GetRequiredService();
+
+ await hostedService.StartAsync(CancellationToken.None);
+
+ var client = global::OpenFeature.Api.Instance.GetClient();
+ Assert.That(await client.GetBooleanValueAsync("enabled_flag", false), Is.True);
+ }
+
+ [Test]
+ public void AddFeatureOneOpenFeature_WithLoggingHookEnabled_ShouldAttachTheHook()
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(CreateStore());
+ services.AddSingleton(new Mock().Object);
+ services.AddFeatureOneOpenFeature(options =>
+ {
+ options.SetAsGlobalProvider = false;
+ options.EnableLoggingHook = true;
+ });
+
+ var provider = services.BuildServiceProvider().GetRequiredService();
+
+ Assert.That(provider.GetProviderHooks().Any(h => h is FeatureOneLoggingHook), Is.True);
+ }
+
+ [Test]
+ public void AddFeatureOneOpenFeature_WithConfiguredHooks_ShouldAttachThem()
+ {
+ var hook = new Mock().Object;
+ var services = new ServiceCollection();
+ services.AddSingleton(CreateStore());
+ services.AddFeatureOneOpenFeature(options =>
+ {
+ options.SetAsGlobalProvider = false;
+ options.AddHook(hook);
+ });
+
+ var provider = services.BuildServiceProvider().GetRequiredService();
+
+ Assert.That(provider.GetProviderHooks(), Does.Contain(hook));
+ }
+
+ [Test]
+ public void AddFeatureOneOpenFeature_WithExplicitStore_ShouldUseIt()
+ {
+ var services = new ServiceCollection();
+ services.AddFeatureOneOpenFeature(CreateStore(), setAsGlobalProvider: false);
+
+ var provider = services.BuildServiceProvider().GetRequiredService();
+
+ Assert.That(provider, Is.Not.Null);
+ }
+
+ [Test]
+ public void AddFeatureOneOpenFeature_WithNullStore_ShouldThrow()
+ {
+ var services = new ServiceCollection();
+
+ Assert.Throws(
+ () => services.AddFeatureOneOpenFeature((IFeatureStore)null, setAsGlobalProvider: false));
+ }
+
+ [Test]
+ public void Options_AddHook_WithNull_ShouldThrow()
+ {
+ Assert.Throws(() => new FeatureOneOpenFeatureOptions().AddHook(null));
+ }
+ }
+}
diff --git a/test/FeatureOne.OpenFeature.Tests/FeatureOneProviderTests.cs b/test/FeatureOne.OpenFeature.Tests/FeatureOneProviderTests.cs
new file mode 100644
index 0000000..e250512
--- /dev/null
+++ b/test/FeatureOne.OpenFeature.Tests/FeatureOneProviderTests.cs
@@ -0,0 +1,296 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using FeatureOne.Core;
+using FeatureOne.Core.Stores;
+using FeatureOne.Core.Toggles.Conditions;
+using FeatureOne.OpenFeature;
+using FeatureOne.OpenFeature.Extensions;
+using Microsoft.Extensions.DependencyInjection;
+using Moq;
+using NUnit.Framework;
+using OpenFeature;
+using OpenFeature.Constant;
+using OpenFeature.Model;
+
+namespace FeatureOne.OpenFeature.Tests
+{
+ [TestFixture]
+ public class FeatureOneProviderTests
+ {
+ private Mock mockStorage;
+ private FeatureStore featureStore;
+ private FeatureOneProvider provider;
+
+ [SetUp]
+ public void Setup()
+ {
+ mockStorage = new Mock();
+ featureStore = new FeatureStore(mockStorage.Object);
+
+ var enabledFeature = new Feature("enabled_flag", new Toggle(Operator.Any, new SimpleCondition { IsEnabled = true }));
+ var disabledFeature = new Feature("disabled_flag", new Toggle(Operator.Any, new SimpleCondition { IsEnabled = false }));
+ var regexFeature = new Feature("user_flag", new Toggle(Operator.Any, new RegexCondition { Claim = "email", Expression = ".*@gbk\\.com" }));
+
+ mockStorage.Setup(x => x.GetByName("enabled_flag")).Returns(new IFeature[] { enabledFeature });
+ mockStorage.Setup(x => x.GetByName("disabled_flag")).Returns(new IFeature[] { disabledFeature });
+ mockStorage.Setup(x => x.GetByName("user_flag")).Returns(new IFeature[] { regexFeature });
+ mockStorage.Setup(x => x.GetByName("missing_flag")).Returns(Array.Empty());
+
+ provider = new FeatureOneProvider(featureStore);
+ }
+
+ [Test]
+ public void GetMetadata_ShouldReturnCorrectProviderName()
+ {
+ var metadata = provider.GetMetadata();
+ Assert.That(metadata, Is.Not.Null);
+ Assert.That(metadata.Name, Is.EqualTo("FeatureOne Provider"));
+ }
+
+ [Test]
+ public async Task ResolveBooleanValueAsync_WhenFlagIsEnabled_ShouldReturnTrueWithTargetingMatch()
+ {
+ var result = await provider.ResolveBooleanValueAsync("enabled_flag", false);
+
+ Assert.That(result, Is.Not.Null);
+ Assert.That(result.Value, Is.True);
+ Assert.That(result.Reason, Is.EqualTo(Reason.TargetingMatch));
+ Assert.That(result.Variant, Is.EqualTo("on"));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.None));
+ }
+
+ [Test]
+ public async Task ResolveBooleanValueAsync_WhenFlagIsDisabled_ShouldReturnFalseWithDisabledReason()
+ {
+ var result = await provider.ResolveBooleanValueAsync("disabled_flag", true);
+
+ Assert.That(result, Is.Not.Null);
+ Assert.That(result.Value, Is.False);
+ Assert.That(result.Reason, Is.EqualTo(Reason.Disabled));
+ Assert.That(result.Variant, Is.EqualTo("off"));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.None));
+ }
+
+ [Test]
+ public async Task ResolveBooleanValueAsync_WhenFlagNotFound_ShouldReturnDefaultValueWithFlagNotFoundErrorCode()
+ {
+ var result = await provider.ResolveBooleanValueAsync("missing_flag", false);
+
+ Assert.That(result, Is.Not.Null);
+ Assert.That(result.Value, Is.False);
+ Assert.That(result.Reason, Is.EqualTo(Reason.Error));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.FlagNotFound));
+ }
+
+ [Test]
+ public async Task ResolveBooleanValueAsync_WithContextMatchingCondition_ShouldReturnTrue()
+ {
+ var context = EvaluationContext.Builder()
+ .Set("email", "john@gbk.com")
+ .Build();
+
+ var result = await provider.ResolveBooleanValueAsync("user_flag", false, context);
+
+ Assert.That(result.Value, Is.True);
+ Assert.That(result.Reason, Is.EqualTo(Reason.TargetingMatch));
+ }
+
+ [Test]
+ public async Task ResolveBooleanValueAsync_WithContextNotMatchingCondition_ShouldReturnFalse()
+ {
+ var context = EvaluationContext.Builder()
+ .Set("email", "john@other.com")
+ .Build();
+
+ var result = await provider.ResolveBooleanValueAsync("user_flag", true, context);
+
+ Assert.That(result.Value, Is.False);
+ Assert.That(result.Reason, Is.EqualTo(Reason.Disabled));
+ }
+
+ [Test]
+ public async Task ResolveStringValueAsync_WhenFlagIsEnabled_ShouldReturnTrueString()
+ {
+ var result = await provider.ResolveStringValueAsync("enabled_flag", "default");
+
+ Assert.That(result.Value, Is.EqualTo("true"));
+ Assert.That(result.Reason, Is.EqualTo(Reason.TargetingMatch));
+ }
+
+ [Test]
+ public async Task ResolveStringValueAsync_WhenFlagNotFound_ShouldReturnDefaultValue()
+ {
+ var result = await provider.ResolveStringValueAsync("missing_flag", "default");
+
+ Assert.That(result.Value, Is.EqualTo("default"));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.FlagNotFound));
+ }
+
+ [Test]
+ public async Task ResolveIntegerValueAsync_WhenFlagIsEnabled_ShouldReturnOne()
+ {
+ var result = await provider.ResolveIntegerValueAsync("enabled_flag", 0);
+
+ Assert.That(result.Value, Is.EqualTo(1));
+ Assert.That(result.Reason, Is.EqualTo(Reason.TargetingMatch));
+ }
+
+ [Test]
+ public async Task ResolveIntegerValueAsync_WhenFlagNotFound_ShouldReturnDefaultValue()
+ {
+ var result = await provider.ResolveIntegerValueAsync("missing_flag", 42);
+
+ Assert.That(result.Value, Is.EqualTo(42));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.FlagNotFound));
+ }
+
+ [Test]
+ public async Task ResolveDoubleValueAsync_WhenFlagIsEnabled_ShouldReturnOnePointZero()
+ {
+ var result = await provider.ResolveDoubleValueAsync("enabled_flag", 0.0);
+
+ Assert.That(result.Value, Is.EqualTo(1.0));
+ Assert.That(result.Reason, Is.EqualTo(Reason.TargetingMatch));
+ }
+
+ [Test]
+ public async Task ResolveDoubleValueAsync_WhenFlagNotFound_ShouldReturnDefaultValue()
+ {
+ var result = await provider.ResolveDoubleValueAsync("missing_flag", 3.14);
+
+ Assert.That(result.Value, Is.EqualTo(3.14));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.FlagNotFound));
+ }
+
+ [Test]
+ public async Task ResolveStructureValueAsync_WhenFlagIsEnabled_ShouldReturnStructureWithValue()
+ {
+ var defaultStructure = new Value("default");
+ var result = await provider.ResolveStructureValueAsync("enabled_flag", defaultStructure);
+
+ Assert.That(result.Value, Is.Not.Null);
+ Assert.That(result.Value.AsBoolean, Is.True);
+ Assert.That(result.Reason, Is.EqualTo(Reason.TargetingMatch));
+ }
+
+ [Test]
+ public async Task ResolveStructureValueAsync_WhenFlagNotFound_ShouldReturnDefaultValue()
+ {
+ var defaultStructure = new Value("default");
+ var result = await provider.ResolveStructureValueAsync("missing_flag", defaultStructure);
+
+ Assert.That(result.Value, Is.EqualTo(defaultStructure));
+ Assert.That(result.ErrorType, Is.EqualTo(ErrorType.FlagNotFound));
+ }
+
+ [Test]
+ public void ToClaims_WithNullContext_ShouldReturnEmptyDictionary()
+ {
+ EvaluationContext context = null;
+ var claims = context.ToClaims();
+
+ Assert.That(claims, Is.Not.Null);
+ Assert.That(claims.Count, Is.EqualTo(0));
+ }
+
+ [Test]
+ public void ToClaims_WithTargetingKeyAndAttributes_ShouldMapToClaimsCorrectly()
+ {
+ var context = EvaluationContext.Builder()
+ .SetTargetingKey("usr_123")
+ .Set("tier", "gold")
+ .Set("isAdmin", true)
+ .Set("score", 95)
+ .Build();
+
+ var claims = context.ToClaims();
+
+ Assert.That(claims["targetingKey"], Is.EqualTo("usr_123"));
+ Assert.That(claims["sub"], Is.EqualTo("usr_123"));
+ Assert.That(claims["user_id"], Is.EqualTo("usr_123"));
+ Assert.That(claims["tier"], Is.EqualTo("gold"));
+ Assert.That(claims["isAdmin"], Is.EqualTo("true"));
+ Assert.That(claims["score"], Is.EqualTo("95"));
+ }
+
+ [Test]
+ public async Task OpenFeatureApiIntegration_EndToEndEvaluation_ShouldWorkWithFeatureOneProvider()
+ {
+ await global::OpenFeature.Api.Instance.SetProviderAsync(provider);
+ var client = global::OpenFeature.Api.Instance.GetClient();
+
+ bool isEnabled = await client.GetBooleanValueAsync("enabled_flag", false);
+ Assert.That(isEnabled, Is.True);
+
+ bool missingFlag = await client.GetBooleanValueAsync("missing_flag", false);
+ Assert.That(missingFlag, Is.False);
+ }
+
+ [Test]
+ public void ServiceCollectionExtensions_AddFeatureOneOpenFeature_RegistersProviderInDI()
+ {
+ var services = new ServiceCollection();
+ services.AddSingleton(featureStore);
+ services.AddFeatureOneOpenFeature(setAsGlobalProvider: false);
+
+ var serviceProvider = services.BuildServiceProvider();
+ var registeredProvider = serviceProvider.GetService();
+
+ Assert.That(registeredProvider, Is.Not.Null);
+ }
+
+ [Test]
+ public async Task Lifecycle_InitializeAsyncAndShutdownAsync_UpdatesStatus()
+ {
+ Assert.That(provider.GetStatus(), Is.EqualTo(ProviderStatus.NotReady));
+
+ await provider.InitializeAsync(EvaluationContext.Empty);
+ Assert.That(provider.GetStatus(), Is.EqualTo(ProviderStatus.Ready));
+
+ await provider.ShutdownAsync();
+ Assert.That(provider.GetStatus(), Is.EqualTo(ProviderStatus.NotReady));
+ }
+
+ [Test]
+ public void ProviderHooks_AddHook_ShouldBeExposedInGetProviderHooks()
+ {
+ var mockHook = new Mock();
+ provider.AddHook(mockHook.Object);
+
+ var hooks = provider.GetProviderHooks();
+ Assert.That(hooks, Is.Not.Null);
+ Assert.That(hooks.Count, Is.EqualTo(1));
+ Assert.That(hooks[0], Is.EqualTo(mockHook.Object));
+ }
+
+ [Test]
+ public async Task FeatureOneLoggingHook_LifecycleMethods_DelegatesToFeatureOneLogger()
+ {
+ var mockLogger = new Mock();
+ var loggingHook = new FeatureOneLoggingHook(mockLogger.Object);
+
+ var hookContext = new HookContext(
+ "test_flag",
+ false,
+ global::OpenFeature.Constant.FlagValueType.Boolean,
+ new ClientMetadata("test_client", "1.0"),
+ new Metadata("FeatureOne Provider"),
+ EvaluationContext.Empty);
+
+ await loggingHook.BeforeAsync(hookContext);
+ mockLogger.Verify(l => l.Info(It.Is(s => s.Contains("Before"))), Times.Once);
+
+ var details = new FlagEvaluationDetails("test_flag", true, errorType: ErrorType.None, reason: Reason.TargetingMatch, variant: "on");
+ await loggingHook.AfterAsync(hookContext, details);
+ mockLogger.Verify(l => l.Info(It.Is(s => s.Contains("After"))), Times.Once);
+
+ var ex = new InvalidOperationException("Test exception");
+ await loggingHook.ErrorAsync(hookContext, ex);
+ mockLogger.Verify(l => l.Error(It.Is(s => s.Contains("Error")), ex), Times.Once);
+
+ await loggingHook.FinallyAsync(hookContext, details);
+ mockLogger.Verify(l => l.Info(It.Is(s => s.Contains("Finally"))), Times.Once);
+ }
+ }
+}
diff --git a/test/FeatureOne.Tests/Json/ConditionDeserializerTest.cs b/test/FeatureOne.Tests/Json/ConditionDeserializerTest.cs
index 7981197..48f1c2a 100644
--- a/test/FeatureOne.Tests/Json/ConditionDeserializerTest.cs
+++ b/test/FeatureOne.Tests/Json/ConditionDeserializerTest.cs
@@ -37,7 +37,7 @@ public void ConditionDeserializer_EdgeCases()
// Invalid type
var invalidJson = new JsonObject();
invalidJson["type"] = "NonExistent";
- Assert.Throws(() => deserializer.Deserialize(invalidJson));
+ Assert.Throws(() => deserializer.Deserialize(invalidJson));
// Null condition
Assert.Throws(() => deserializer.Deserialize(null));
@@ -67,6 +67,6 @@ public void ConditionDeserializer_SecureTypeLoading()
// Try to load a potentially dangerous type - should fail
var dangerousJson = new JsonObject();
dangerousJson["type"] = "System.IO.FileInfo"; // This should not be allowed
- Assert.Throws(() => deserializer.Deserialize(dangerousJson));
+ Assert.Throws(() => deserializer.Deserialize(dangerousJson));
}
}
\ No newline at end of file
diff --git a/test/FeatureOne.Tests/Json/ConditionDeserializerTests.cs b/test/FeatureOne.Tests/Json/ConditionDeserializerTests.cs
index 479dd9e..dffae69 100644
--- a/test/FeatureOne.Tests/Json/ConditionDeserializerTests.cs
+++ b/test/FeatureOne.Tests/Json/ConditionDeserializerTests.cs
@@ -129,7 +129,7 @@ public void ConditionDeserializer_WithInvalidTypeName_ShouldThrowException()
};
// Act & Assert
- Assert.Throws(() => _deserializer.Deserialize(json));
+ Assert.Throws(() => _deserializer.Deserialize(json));
}
[Test]
@@ -176,7 +176,7 @@ public void ConditionDeserializer_UnknownSimilarType_ShouldThrow()
var json = new JsonObject { ["type"] = "SimpleAttacker" }; // Similar to "Simple" but not valid
// Act & Assert
- Assert.Throws(() => _deserializer.Deserialize(json));
+ Assert.Throws(() => _deserializer.Deserialize(json));
}
[Test]
diff --git a/test/FeatureOne.Tests/Json/ConditionRegistrationTests.cs b/test/FeatureOne.Tests/Json/ConditionRegistrationTests.cs
new file mode 100644
index 0000000..a095012
--- /dev/null
+++ b/test/FeatureOne.Tests/Json/ConditionRegistrationTests.cs
@@ -0,0 +1,191 @@
+using System;
+using System.Collections.Generic;
+using System.Text.Json.Nodes;
+using FeatureOne.Core;
+
+namespace FeatureOne.Tests.Json
+{
+ ///
+ /// Custom condition used to prove that user supplied condition types can be registered and
+ /// deserialized without reimplementing .
+ ///
+ public class PercentageCondition : ICondition
+ {
+ public int Threshold { get; set; }
+ public string Claim { get; set; }
+
+ public bool Evaluate(IDictionary claims)
+ {
+ if (claims == null || Claim == null || !claims.TryGetValue(Claim, out var raw))
+ return false;
+
+ return int.TryParse(raw, out var value) && value <= Threshold;
+ }
+ }
+
+ public class NoParameterlessConstructorCondition : ICondition
+ {
+ public NoParameterlessConstructorCondition(string required) => Required = required;
+
+ public string Required { get; set; }
+
+ public bool Evaluate(IDictionary claims) => false;
+ }
+
+ public class NotACondition
+ {
+ }
+
+ [TestFixture]
+ public class ConditionRegistrationTests
+ {
+ [Test]
+ public void Register_CustomCondition_ShouldDeserializeAndHydrateProperties()
+ {
+ var deserializer = new ConditionDeserializer().Register("Percentage");
+
+ var json = new JsonObject
+ {
+ ["type"] = "Percentage",
+ ["threshold"] = 50,
+ ["claim"] = "bucket"
+ };
+
+ var condition = deserializer.Deserialize(json);
+
+ Assert.That(condition, Is.InstanceOf());
+ var percentage = (PercentageCondition)condition;
+ Assert.That(percentage.Threshold, Is.EqualTo(50));
+ Assert.That(percentage.Claim, Is.EqualTo("bucket"));
+ Assert.That(percentage.Evaluate(new Dictionary { ["bucket"] = "20" }), Is.True);
+ Assert.That(percentage.Evaluate(new Dictionary { ["bucket"] = "80" }), Is.False);
+ }
+
+ [Test]
+ public void Register_ShouldNormalisePostfixedAndBareNames()
+ {
+ var deserializer = new ConditionDeserializer().Register("PercentageCondition");
+
+ var bare = deserializer.Deserialize(new JsonObject { ["type"] = "Percentage" });
+ var postfixed = deserializer.Deserialize(new JsonObject { ["type"] = "PercentageCondition" });
+
+ Assert.That(bare, Is.InstanceOf());
+ Assert.That(postfixed, Is.InstanceOf());
+ }
+
+ [Test]
+ public void Register_ShouldReturnSameInstanceForChaining()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ var returned = deserializer.Register("Percentage");
+
+ Assert.That(returned, Is.SameAs(deserializer));
+ }
+
+ [Test]
+ public void Constructor_WithCustomTypes_ShouldRegisterThem()
+ {
+ var deserializer = new ConditionDeserializer(new[]
+ {
+ new KeyValuePair("Percentage", typeof(PercentageCondition))
+ });
+
+ Assert.That(deserializer.Deserialize(new JsonObject { ["type"] = "Percentage" }),
+ Is.InstanceOf());
+ }
+
+ [Test]
+ public void Constructor_WithCustomTypes_ShouldStillSupportBuiltInTypes()
+ {
+ var deserializer = new ConditionDeserializer(new[]
+ {
+ new KeyValuePair("Percentage", typeof(PercentageCondition))
+ });
+
+ Assert.That(deserializer.Deserialize(new JsonObject { ["type"] = "Simple", ["isEnabled"] = true }),
+ Is.InstanceOf());
+ }
+
+ [Test]
+ public void Register_TypeNotImplementingICondition_ShouldThrow()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ var ex = Assert.Throws(
+ () => deserializer.Register("Bad", typeof(NotACondition)));
+
+ Assert.That(ex.Message, Does.Contain(nameof(ICondition)));
+ }
+
+ [Test]
+ public void Register_AbstractType_ShouldThrow()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ Assert.Throws(
+ () => deserializer.Register("Bad", typeof(ICondition)));
+ }
+
+ [Test]
+ public void Register_TypeWithoutParameterlessConstructor_ShouldThrow()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ var ex = Assert.Throws(
+ () => deserializer.Register("Bad", typeof(NoParameterlessConstructorCondition)));
+
+ Assert.That(ex.Message, Does.Contain("parameterless constructor"));
+ }
+
+ [Test]
+ public void Register_WithNullName_ShouldThrow()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ Assert.Throws(() => deserializer.Register(null, typeof(PercentageCondition)));
+ }
+
+ [Test]
+ public void Register_WithNullType_ShouldThrow()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ Assert.Throws(() => deserializer.Register("Percentage", null));
+ }
+
+ [Test]
+ public void Register_ShouldNotLeakIntoOtherInstances()
+ {
+ new ConditionDeserializer().Register("Percentage");
+
+ var untouched = new ConditionDeserializer();
+
+ Assert.Throws(
+ () => untouched.Deserialize(new JsonObject { ["type"] = "Percentage" }));
+ }
+
+ [Test]
+ public void Deserialize_UnregisteredType_ShouldListRegisteredTypesInMessage()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ var ex = Assert.Throws(
+ () => deserializer.Deserialize(new JsonObject { ["type"] = "Percentage" }));
+
+ Assert.That(ex.Message, Does.Contain("SimpleCondition"));
+ Assert.That(ex.Message, Does.Contain("Register"));
+ }
+
+ [Test]
+ public void Deserialize_MissingTypeDiscriminator_ShouldThrowConfigurationException()
+ {
+ var deserializer = new ConditionDeserializer();
+
+ var ex = Assert.Throws(
+ () => deserializer.Deserialize(new JsonObject { ["isEnabled"] = true }));
+
+ Assert.That(ex.Message, Does.Contain("type"));
+ }
+ }
+}
diff --git a/test/FeatureOne.Tests/Toggles/Conditions/RelationalConditionTests.cs b/test/FeatureOne.Tests/Toggles/Conditions/RelationalConditionTests.cs
index 8c91acc..0e4c639 100644
--- a/test/FeatureOne.Tests/Toggles/Conditions/RelationalConditionTests.cs
+++ b/test/FeatureOne.Tests/Toggles/Conditions/RelationalConditionTests.cs
@@ -173,20 +173,148 @@ public void Evaluate_LessThanOrEqual_WhenClaimIsGreater_ShouldReturnFalse()
}
// ──────────────────────────────────────────────
- // LessThan — defined in enum but not in switch;
- // falls through to default and returns false.
+ // LessThan
// ──────────────────────────────────────────────
[Test]
- public void Evaluate_LessThan_ReturnsDefaultFalse()
+ public void Evaluate_LessThan_WhenClaimIsLess_ShouldReturnTrue()
{
- // LessThan is not handled in the switch statement; default branch returns false.
var condition = new RelationalCondition { Claim = "tier", Operator = RelationalOperator.LessThan, Value = "gold" };
var claims = new Dictionary { { "tier", "bronze" } };
+ Assert.That(condition.Evaluate(claims), Is.True);
+ }
+
+ [Test]
+ public void Evaluate_LessThan_WhenClaimIsEqual_ShouldReturnFalse()
+ {
+ var condition = new RelationalCondition { Claim = "tier", Operator = RelationalOperator.LessThan, Value = "gold" };
+ var claims = new Dictionary { { "tier", "gold" } };
+
Assert.That(condition.Evaluate(claims), Is.False);
}
+ [Test]
+ public void Evaluate_LessThan_WhenClaimIsGreater_ShouldReturnFalse()
+ {
+ var condition = new RelationalCondition { Claim = "tier", Operator = RelationalOperator.LessThan, Value = "bronze" };
+ var claims = new Dictionary { { "tier", "gold" } };
+
+ Assert.That(condition.Evaluate(claims), Is.False);
+ }
+
+ [Test]
+ public void Evaluate_LessThan_WithNumericClaim_ShouldCompareNumerically()
+ {
+ var condition = new RelationalCondition { Claim = "age", Operator = RelationalOperator.LessThan, Value = "18" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "age", "9" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "age", "21" } }), Is.False);
+ }
+
+ // ──────────────────────────────────────────────
+ // Numeric comparison
+ // ──────────────────────────────────────────────
+
+ [Test]
+ public void Evaluate_GreaterThan_WithNumericClaim_ShouldNotCompareLexicographically()
+ {
+ // Digit-by-digit ordering would rank "9" above "18"; arithmetic ordering must not.
+ var condition = new RelationalCondition { Claim = "age", Operator = RelationalOperator.GreaterThan, Value = "18" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "age", "9" } }), Is.False);
+ Assert.That(condition.Evaluate(new Dictionary { { "age", "21" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "age", "100" } }), Is.True);
+ }
+
+ [Test]
+ public void Evaluate_GreaterThanOrEqual_WithNumericClaim_ShouldCompareNumerically()
+ {
+ var condition = new RelationalCondition { Claim = "seats", Operator = RelationalOperator.GreaterThanOrEqual, Value = "5" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "seats", "5" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "seats", "40" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "seats", "4" } }), Is.False);
+ }
+
+ [Test]
+ public void Evaluate_LessThanOrEqual_WithNumericClaim_ShouldCompareNumerically()
+ {
+ var condition = new RelationalCondition { Claim = "score", Operator = RelationalOperator.LessThanOrEqual, Value = "90" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "score", "9" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "score", "90" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "score", "91" } }), Is.False);
+ }
+
+ [Test]
+ public void Evaluate_WithDecimalClaim_ShouldCompareNumerically()
+ {
+ var condition = new RelationalCondition { Claim = "ratio", Operator = RelationalOperator.GreaterThan, Value = "1.5" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "ratio", "1.75" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "ratio", "1.25" } }), Is.False);
+ }
+
+ [Test]
+ public void Evaluate_WithNegativeNumbers_ShouldCompareNumerically()
+ {
+ var condition = new RelationalCondition { Claim = "balance", Operator = RelationalOperator.GreaterThan, Value = "-10" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "balance", "-5" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "balance", "-50" } }), Is.False);
+ }
+
+ [Test]
+ public void Evaluate_Equals_WithEquivalentNumericForms_ShouldMatch()
+ {
+ var condition = new RelationalCondition { Claim = "seats", Operator = RelationalOperator.Equals, Value = "5" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "seats", "5.0" } }), Is.True);
+ Assert.That(condition.Evaluate(new Dictionary { { "seats", "05" } }), Is.True);
+ }
+
+ [Test]
+ public void Evaluate_WithLargeIntegerClaim_ShouldNotLosePrecision()
+ {
+ // Beyond double's exact integer range; decimal comparison keeps these distinct.
+ var condition = new RelationalCondition { Claim = "id", Operator = RelationalOperator.GreaterThan, Value = "9007199254740992" };
+
+ Assert.That(condition.Evaluate(new Dictionary { { "id", "9007199254740993" } }), Is.True);
+ }
+
+ [Test]
+ public void Evaluate_WithNumericClaimAndNonNumericTarget_ShouldFallBackToStringComparison()
+ {
+ var condition = new RelationalCondition { Claim = "tier", Operator = RelationalOperator.GreaterThan, Value = "gold" };
+
+ // "9" vs "gold": digits sort before letters ordinally.
+ Assert.That(condition.Evaluate(new Dictionary { { "tier", "9" } }), Is.False);
+ }
+
+ [Test]
+ public void Evaluate_StringComparison_ShouldBeOrdinalNotCultureSensitive()
+ {
+ var original = System.Globalization.CultureInfo.CurrentCulture;
+ try
+ {
+ var condition = new RelationalCondition { Claim = "tier", Operator = RelationalOperator.GreaterThan, Value = "Gold" };
+ var claims = new Dictionary { { "tier", "gold" } };
+
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("en-US");
+ var underEnglish = condition.Evaluate(claims);
+
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("sv-SE");
+ var underSwedish = condition.Evaluate(claims);
+
+ Assert.That(underEnglish, Is.EqualTo(underSwedish));
+ }
+ finally
+ {
+ System.Globalization.CultureInfo.CurrentCulture = original;
+ }
+ }
+
// ──────────────────────────────────────────────
// Null value edge cases
// ──────────────────────────────────────────────