From cb0248f79aba371bee6348671cba9ef8471d6b98 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Sat, 28 Nov 2026 11:37:21 +0000 Subject: [PATCH 1/2] feat: improve developer ergonomics - Add public ReflagEvaluationErrorCodes constants and use them internally. - Ship XML documentation and document the main client and option members. - Accept anonymous-object contexts in GetFlag, GetFlag, GetFlags and GetFlagsForBootstrap, matching BindClient. - Default the logger to the host ILoggerFactory when registered with AddReflag. - Rate-limit the not-initialized error and say how to fix it. - Log evaluation diagnostics with the flag key and readable messages. - Explain how to provide a missing or invalid secret key. - Shorten the testing docs, note failed evaluations, and say remote config is not supported. --- README.md | 131 ++++-------------- .../Internal/FlagCollectionEvaluator.cs | 8 +- src/Reflag/Reflag.csproj | 4 +- src/Reflag/ReflagClient.cs | 94 +++++++++++-- src/Reflag/ReflagFlagModels.cs | 24 +++- src/Reflag/ReflagModels.cs | 12 ++ .../ReflagServiceCollectionExtensions.cs | 5 +- .../EvaluationDiagnosticsTelemetryTests.cs | 2 +- .../FeatureFlagCheckEventTests.cs | 4 +- tests/Reflag.Tests/ReflagClientTests.cs | 82 +++++++++++ 10 files changed, 240 insertions(+), 126 deletions(-) diff --git a/README.md b/README.md index a000f97..b2aba65 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ using Reflag; await using var client = new ReflagClient(); await client.InitializeAsync(); -var context = ReflagContext.From(new +var context = new { User = new { @@ -51,7 +51,7 @@ var context = ReflagContext.From(new { Device = "Desktop", }, -}); +}; var enabled = client.GetFlag("new-dashboard", context); @@ -61,7 +61,7 @@ if (enabled) } ``` -`ReflagContext.From(...)` accepts anonymous objects or nested dictionaries. Well-known fields like `Id`, `Name`, `Email`, and `Avatar` are mapped directly; additional fields become attributes. +Flag reads and `BindClient(...)` accept a typed `ReflagContext`, an anonymous object, or nested dictionaries. Well-known fields like `Id`, `Name`, `Email`, and `Avatar` are mapped directly; additional fields become attributes. `ReflagContext.From(...)` does the same conversion if you need a `ReflagContext`. If you evaluate multiple flags for the same context, for example in middleware or request-scoped helpers, bind that context once and reuse the bound client: @@ -134,6 +134,10 @@ Primitive elements are normalized to strings (null becomes `""`); composite elem Numeric, date, boolean, percentage-rollout, and percentage-distribution operators do not support arrays. +### Failed evaluations + +If a targeting rule can't be evaluated, for example because a required context field is missing or has the wrong type, the SDK treats that rule as not matching, logs a warning, and reports the failure to Reflag. You can view failed evaluations in the Reflag app. + ## Fallback provider `FlagsFallbackProvider` is a reliability feature for startup fallback and outage recovery. @@ -143,7 +147,7 @@ If you do not configure a fallback provider, the SDK still uses live definitions Reflag remains the source of truth. In the normal case, the SDK fetches live definitions and then saves an updated snapshot through the fallback provider. The fallback copy is only used when that initial live fetch is unavailable. -Built-in providers currently available in the .NET package: +Built-in providers: - `ReflagFallbackProviders.Static(...)` - `ReflagFallbackProviders.File(...)` @@ -220,7 +224,7 @@ var bootstrapped = bound.GetFlagsForBootstrap(); ## Configuring -The .NET SDK currently supports configuration through: +The .NET SDK is configured through: 1. constructor options 2. environment variables @@ -246,13 +250,13 @@ export REFLAG_FLAGS_ENABLED=demo-flag export REFLAG_FLAGS_DISABLED=new-dashboard ``` -Constructor options currently available: +Constructor options: | Option | Type | Notes | Env var | | --- | --- | --- | --- | | `SecretKey` | `string?` | Required unless `Offline == true` | `REFLAG_SECRET_KEY` | | `ApiBaseUrl` | `Uri?` | Absolute URI | `REFLAG_API_BASE_URL` | -| `Logger` | `ILogger?` | Defaults to `NullLogger.Instance` | - | +| `Logger` | `ILogger?` | Defaults to the host's `ILoggerFactory` with `AddReflag(...)`, otherwise no logging | - | | `HttpClient` | `HttpClient?` | Customize the built-in HTTP transport used for requests and push sync | - | | `FlagsFallbackProvider` | `IFlagsFallbackProvider?` | Ignored in offline mode | - | | `FetchTimeout` | `TimeSpan?` | Default `10s` | - | @@ -268,120 +272,40 @@ Constructor options currently available: Specify at most one of `FlagOverrides`, `FlagOverridesFactory`, `JsonFlagOverrides`, or `JsonFlagOverridesFactory`. -## Testing with flag overrides - -The SDK has first-class override APIs for tests and local development. -In tests, you will often want to run the client in offline mode: - -```csharp -await using var client = new ReflagClient(new ReflagClientOptions -{ - Offline = true, -}); -``` - -### Base overrides - -Set base overrides in the constructor, replace them later with `SetFlagOverrides(...)`, and clear them with `ClearFlagOverrides()`: - -```csharp -await using var client = new ReflagClient(new ReflagClientOptions -{ - Offline = true, - FlagOverrides = new Dictionary - { - ["demo-flag"] = true, - }, -}); - -client.SetFlagOverrides(new Dictionary -{ - ["demo-flag"] = false, -}); - -client.ClearFlagOverrides(); -``` - -### Layering overrides - -`PushFlagOverrides(...)` adds a temporary layer on top of the base overrides and returns an `IDisposable` scope. -The override is active until that scope is disposed. +## Overrides and tests ```csharp await using var client = new ReflagClient(new ReflagClientOptions { Offline = true, + FlagOverrides = new Dictionary { ["new-editor"] = true }, }); +await client.InitializeAsync(); -Assert.False(client.GetFlag("new-dashboard", new ReflagContext())); +client.SetFlagOverrides(new Dictionary { ["new-dashboard"] = true }); -using (client.PushFlagOverrides(new Dictionary +using (client.PushFlagOverrides(context => new Dictionary { - ["new-dashboard"] = true, + ["smart-summaries"] = context.Company?.Id == "qa", })) { - Assert.True(client.GetFlag("new-dashboard", new ReflagContext())); + // the pushed layer applies until it is disposed } -Assert.False(client.GetFlag("new-dashboard", new ReflagContext())); +client.ClearFlagOverrides(); ``` -The precedence is: - -1. base overrides from the constructor or `SetFlagOverrides(...)` -2. temporary layers added by `PushFlagOverrides(...)` - -### Context dependent overrides - -`SetFlagOverrides(...)` and `PushFlagOverrides(...)` also accept a function: +Multivariate flags take JSON values through `JsonFlagOverrides` or the `Dictionary` overloads: ```csharp -using (client.PushFlagOverrides(context => new Dictionary -{ - ["smart-summaries"] = context.User?.Id == "qa-user", -})) +client.SetFlagOverrides(new Dictionary { - Assert.True(client.GetFlag( - "smart-summaries", - new ReflagContext - { - User = new ReflagUserContext { Id = "qa-user" }, - })); -} -``` - -### JSON overrides for multivariate flags - -Set JSON-valued overrides at construction with `JsonFlagOverrides`, including when registering the client with dependency injection: - -```csharp -builder.Services.AddReflag(new ReflagClientOptions -{ - JsonFlagOverrides = new Dictionary - { - ["model"] = new { name = "large", maxTokens = 8000 }, - ["demo-flag"] = true, - }, + ["model"] = "quick", + ["limits"] = new { maxItems = 5 }, }); ``` -Use `JsonFlagOverridesFactory` for context-dependent startup values. `SetFlagOverrides(...)` and `PushFlagOverrides(...)` accept the same dictionary shape or a context-dependent function. - -Overriding a flag does not change the results of other flags that depend on it. - -### Additional ways to provide flag overrides - -You can also provide overrides through environment variables: - -```bash -export REFLAG_FLAGS_ENABLED=flag-a,flag-b -export REFLAG_FLAGS_DISABLED=flag-c -``` - -The example app tests in this repository also use `PushFlagOverrides(...)` to toggle flags through the real minimal API endpoints. -See: - -- `examples/Reflag.MinimalApiExample.Tests/ExampleAppTests.cs` +Pushed layers win over base overrides and are removed independently by disposing them. Overrides apply **after evaluation**, so overriding a flag does not change the results of other flags that depend on it. `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` also set base overrides. Offline mode does not fetch, load a fallback provider, or send tracking events. In ASP.NET Core tests, get `ReflagClient` from the test host's services; see `examples/Reflag.MinimalApiExample.Tests/ExampleAppTests.cs`. ## Using with ASP.NET Core @@ -392,10 +316,9 @@ using Reflag; var builder = WebApplication.CreateBuilder(args); -builder.Services.AddReflag(sp => new ReflagClientOptions +builder.Services.AddReflag(new ReflagClientOptions { SecretKey = builder.Configuration["REFLAG_SECRET_KEY"], - Logger = sp.GetRequiredService().CreateLogger("Reflag"), }); var app = builder.Build(); @@ -607,6 +530,10 @@ var bound = client.BindClient( }); ``` +## Remote config + +Remote config is not supported by this SDK. Use [multivariate flags](#multivariate-flags) for configuration values instead. + ## Upgrading from 0.2.x to 0.3.0 - **Definitions:** `GetFlagDefinitions()` now returns a collection with `.Flags` and `.Segments`. Definitions use variants and rules instead of `Targeting`; `FlagTargetingDefinition` and `FlagTargetingRuleDefinition` are removed. diff --git a/src/Reflag/Internal/FlagCollectionEvaluator.cs b/src/Reflag/Internal/FlagCollectionEvaluator.cs index a5a6466..e8a31ba 100644 --- a/src/Reflag/Internal/FlagCollectionEvaluator.cs +++ b/src/Reflag/Internal/FlagCollectionEvaluator.cs @@ -11,10 +11,10 @@ namespace Reflag.Internal; /// internal sealed class FlagCollectionEvaluator { - private const string MissingContextField = "MISSING_CONTEXT_FIELD"; - private const string UnsupportedArrayOperator = "UNSUPPORTED_ARRAY_OPERATOR"; - private const string InvalidComparison = "INVALID_COMPARISON"; - private const string InvalidFlagDefinition = "INVALID_FLAG_DEFINITION"; + private const string MissingContextField = ReflagEvaluationErrorCodes.MissingContextField; + private const string UnsupportedArrayOperator = ReflagEvaluationErrorCodes.UnsupportedArrayOperator; + private const string InvalidComparison = ReflagEvaluationErrorCodes.InvalidComparison; + private const string InvalidFlagDefinition = ReflagEvaluationErrorCodes.InvalidFlagDefinition; private const string InvalidKey = "invalid"; private readonly Dictionary _flags = new(StringComparer.Ordinal); diff --git a/src/Reflag/Reflag.csproj b/src/Reflag/Reflag.csproj index 5561d88..233de63 100644 --- a/src/Reflag/Reflag.csproj +++ b/src/Reflag/Reflag.csproj @@ -3,7 +3,9 @@ net10.0;netstandard2.0 enable enable - false + true + + $(NoWarn);CS1591 Reflag.RuntimeSDK Reflag Reflag diff --git a/src/Reflag/ReflagClient.cs b/src/Reflag/ReflagClient.cs index 37f7384..a5c6c22 100644 --- a/src/Reflag/ReflagClient.cs +++ b/src/Reflag/ReflagClient.cs @@ -6,11 +6,15 @@ namespace Reflag; +/// +/// The Reflag server SDK client. Create one long-lived instance, call once, +/// and reuse it for flag evaluation and tracking. +/// public sealed class ReflagClient : IAsyncDisposable { private static readonly ReflagEvaluationError ClientNotInitializedError = new() { - Code = "CLIENT_NOT_INITIALIZED", + Code = ReflagEvaluationErrorCodes.ClientNotInitialized, Field = string.Empty, Message = "ReflagClient was not initialized before this flag was evaluated. Call InitializeAsync() before evaluating flags.", }; @@ -43,7 +47,14 @@ public sealed class ReflagClient : IAsyncDisposable private bool _shutdownFlushCompleted; private bool _canLoadFlagsFallbackProvider = true; + /// Creates a client. Options not set here fall back to REFLAG_* environment variables. + /// No secret key was found and is not set, or an option is invalid. public ReflagClient(ReflagClientOptions? options = null) + : this(options, defaultLogger: null) + { + } + + internal ReflagClient(ReflagClientOptions? options, ILogger? defaultLogger) { options ??= new ReflagClientOptions(); ValidateOptions(options); @@ -55,12 +66,16 @@ public ReflagClient(ReflagClientOptions? options = null) { if (secretKey is null) { - throw new ArgumentNullException(nameof(options), "options.SecretKey must be provided unless offline is true."); + throw new ArgumentException( + "No Reflag secret key was found. Set ReflagClientOptions.SecretKey or the REFLAG_SECRET_KEY environment variable, or set Offline = true to run without one (for example in tests).", + nameof(options)); } if (secretKey.Length <= 22) { - throw new ArgumentException("invalid options.SecretKey specified", nameof(options)); + throw new ArgumentException( + "The Reflag secret key is too short to be valid. Copy the secret key from your environment's settings in the Reflag app.", + nameof(options)); } } @@ -82,7 +97,7 @@ public ReflagClient(ReflagClientOptions? options = null) var secretKeyHash = secretKey is null ? string.Empty : Hashing.HashString(secretKey); var flagsPushUrl = ResolveFlagsPushUrl(options.FlagsPushUrl); - _logger = options.Logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + _logger = options.Logger ?? defaultLogger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; // Normalize startup values before creating owned transport resources; serialization can fail. _baseFlagOverrides = BuildBaseFlagOverrides(envConfig.FlagOverrides, options); @@ -132,6 +147,10 @@ public ReflagClient(ReflagClientOptions? options = null) }; } + /// + /// Fetches flag definitions and starts background sync. Call once before evaluating flags. + /// Concurrent and repeated calls share the same initialization. + /// public Task InitializeAsync(CancellationToken cancellationToken = default) { EnsureNotDisposed(); @@ -140,12 +159,16 @@ public Task InitializeAsync(CancellationToken cancellationToken = default) return AsyncHelpers.WaitAsync(initializeTask, cancellationToken); } + /// Sends any buffered tracking events now. public Task FlushAsync(CancellationToken cancellationToken = default) { EnsureNotDisposed(); return FlushCoreAsync(cancellationToken); } + /// Fetches the latest flag definitions. + /// If set, keeps refreshing until at least this flag state version is available. + /// Cancels the refresh. public async Task RefreshFlagsAsync(int? waitForVersion = null, CancellationToken cancellationToken = default) { EnsureNotDisposed(); @@ -304,6 +327,46 @@ public ReflagBootstrappedFlags GetFlagsForBootstrap( }; } + /// Reads a Boolean flag for an anonymous-object or dictionary context. See . + public bool GetFlag( + string key, + object context, + ReflagTelemetryOptions? telemetryOptions = null) + { + EnsureNotDisposed(); + return GetFlag(key, ReflagContextNormalizer.NormalizeLooseContext(context), telemetryOptions); + } + + /// Reads a flag value for an anonymous-object or dictionary context. See . + public T GetFlag( + string key, + object context, + T defaultValue, + ReflagTelemetryOptions? telemetryOptions = null) + { + EnsureNotDisposed(); + return GetFlag(key, ReflagContextNormalizer.NormalizeLooseContext(context), defaultValue, telemetryOptions); + } + + /// Evaluates all flags for an anonymous-object or dictionary context. See . + public IReadOnlyDictionary GetFlags( + object context, + ReflagTelemetryOptions? telemetryOptions = null) + { + EnsureNotDisposed(); + return GetFlags(ReflagContextNormalizer.NormalizeLooseContext(context), telemetryOptions); + } + + /// Builds a bootstrap payload for an anonymous-object or dictionary context. See . + public ReflagBootstrappedFlags GetFlagsForBootstrap( + object context, + ReflagTelemetryOptions? telemetryOptions = null) + { + EnsureNotDisposed(); + return GetFlagsForBootstrap(ReflagContextNormalizer.NormalizeLooseContext(context), telemetryOptions); + } + + /// Returns a client bound to a context, so later calls do not need to pass it. public ReflagBoundClient BindClient( ReflagContext context, ReflagTelemetryOptions? telemetryOptions = null) @@ -314,6 +377,7 @@ public ReflagBoundClient BindClient( return CreateBoundClient(normalizedContext, normalizedTelemetry); } + /// Returns a client bound to an anonymous-object or dictionary context. See . public ReflagBoundClient BindClient( object context, ReflagTelemetryOptions? telemetryOptions = null) @@ -324,6 +388,7 @@ public ReflagBoundClient BindClient( return CreateBoundClient(normalizedContext, normalizedTelemetry); } + /// Sends user attributes to Reflag. public async Task UpdateUserAsync( string userId, ReflagTrackOptions? options = null, @@ -361,6 +426,7 @@ await _batchBuffer.AddAsync( cancellationToken).ConfigureAwait(false); } + /// Sends company attributes to Reflag, optionally associating a user with the company. public async Task UpdateCompanyAsync( string companyId, ReflagCompanyTrackOptions? options = null, @@ -404,6 +470,7 @@ await _batchBuffer.AddAsync( cancellationToken).ConfigureAwait(false); } + /// Tracks a custom event for a user. public async Task TrackAsync( string userId, string eventName, @@ -437,6 +504,7 @@ await _batchBuffer.AddAsync( cancellationToken).ConfigureAwait(false); } + /// Replaces the base flag overrides with Boolean values. public void SetFlagOverrides(IReadOnlyDictionary overrides) { EnsureNotDisposed(); @@ -454,6 +522,7 @@ public void SetFlagOverrides(IReadOnlyDictionary overrides) SetFlagOverridesCore(_ => normalized); } + /// Replaces the base flag overrides with Boolean values computed per context. public void SetFlagOverrides(Func> overridesFactory) { EnsureNotDisposed(); @@ -469,6 +538,7 @@ public void SetFlagOverrides(FuncAdds a temporary layer of Boolean overrides on top of the base overrides. Dispose the result to remove it. public IDisposable PushFlagOverrides(IReadOnlyDictionary overrides) { EnsureNotDisposed(); @@ -486,6 +556,7 @@ public IDisposable PushFlagOverrides(IReadOnlyDictionary overri return PushFlagOverridesCore(_ => normalized); } + /// Adds a temporary layer of Boolean overrides computed per context. Dispose the result to remove it. public IDisposable PushFlagOverrides(Func> overridesFactory) { EnsureNotDisposed(); @@ -501,6 +572,7 @@ public IDisposable PushFlagOverrides(FuncClears the base overrides. Pushed layers are not affected. public void ClearFlagOverrides() { EnsureNotDisposed(); @@ -511,6 +583,7 @@ public void ClearFlagOverrides() } } + /// Stops background sync and, unless disabled with , flushes buffered events. public async ValueTask DisposeAsync() { if (_disposed) @@ -727,9 +800,9 @@ private FlagsEvaluation EvaluateFlags( string? key) { var evaluatedBeforeInitialization = !_initializationFinished && !_config.Offline; - if (evaluatedBeforeInitialization) + if (evaluatedBeforeInitialization && _rateLimiter.IsAllowed("client-not-initialized-warning")) { - _logger.LogError("flag access: ReflagClient is not initialized yet."); + _logger.LogError("flag access: ReflagClient is not initialized yet. Call InitializeAsync() before evaluating flags."); } _ = SyncContextAsync(context, telemetryOptions); @@ -1103,11 +1176,9 @@ private void WarnFlagEvaluationDiagnostics(RawReflagFlag flag) } _logger.LogWarning( - "flag targeting rules could not be fully evaluated. {EvaluationErrors}", - new Dictionary> - { - [flag.FlagKey] = flag.Errors, - }); + "flag \"{FlagKey}\": targeting rules could not be fully evaluated: {EvaluationErrors}", + flag.FlagKey, + string.Join("; ", flag.Errors.Select(error => error.Message))); } private void TryQueueCheckEvent( @@ -1808,6 +1879,7 @@ private async Task RefreshAsync(int? waitForVersion) } +/// A client bound to a context. Create one with . public sealed class ReflagBoundClient { private readonly ReflagClient _rootClient; diff --git a/src/Reflag/ReflagFlagModels.cs b/src/Reflag/ReflagFlagModels.cs index 186e129..543c8c7 100644 --- a/src/Reflag/ReflagFlagModels.cs +++ b/src/Reflag/ReflagFlagModels.cs @@ -15,13 +15,29 @@ public sealed class ReflagEvaluationErrorSource public string Key { get; init; } = string.Empty; } +/// The values of . +public static class ReflagEvaluationErrorCodes +{ + /// A context field required by a targeting rule was missing. + public const string MissingContextField = "MISSING_CONTEXT_FIELD"; + + /// An operator that does not support arrays was applied to an array-valued context field. + public const string UnsupportedArrayOperator = "UNSUPPORTED_ARRAY_OPERATOR"; + + /// A context value or targeting comparison value could not be compared with the rule's operator. + public const string InvalidComparison = "INVALID_COMPARISON"; + + /// The flag definition is invalid or uses something this SDK version does not support. + public const string InvalidFlagDefinition = "INVALID_FLAG_DEFINITION"; + + /// The flag was evaluated before InitializeAsync() completed. + public const string ClientNotInitialized = "CLIENT_NOT_INITIALIZED"; +} + /// A non-fatal flag evaluation diagnostic. public sealed class ReflagEvaluationError { - /// - /// MISSING_CONTEXT_FIELD, UNSUPPORTED_ARRAY_OPERATOR, INVALID_COMPARISON, - /// INVALID_FLAG_DEFINITION or CLIENT_NOT_INITIALIZED. - /// + /// One of the values. [JsonPropertyName("code")] public string Code { get; init; } = string.Empty; diff --git a/src/Reflag/ReflagModels.cs b/src/Reflag/ReflagModels.cs index 15dc951..ed7c4ce 100644 --- a/src/Reflag/ReflagModels.cs +++ b/src/Reflag/ReflagModels.cs @@ -27,22 +27,31 @@ public sealed class ReflagBatchOptions public bool? FlushOnExit { get; init; } } +/// Options for . Unset options fall back to environment variables, then defaults. public sealed class ReflagClientOptions { + /// The environment secret key. Defaults to REFLAG_SECRET_KEY. Required unless is set. public string? SecretKey { get; init; } + /// The Reflag API base URL. Defaults to REFLAG_API_BASE_URL, then https://front.reflag.com. public Uri? ApiBaseUrl { get; init; } + /// The logger. Defaults to the host's ILoggerFactory when registered with AddReflag, otherwise no logging. public ILogger? Logger { get; init; } + /// The HTTP client used for API requests and push sync. public HttpClient? HttpClient { get; init; } + /// Durable storage for the last fetched flag definitions, used if Reflag is unavailable at startup. Ignored in offline mode. public IFlagsFallbackProvider? FlagsFallbackProvider { get; init; } + /// Timeout for flag definition requests. Defaults to 10 seconds. public TimeSpan? FetchTimeout { get; init; } + /// Retries for flag definition requests. Defaults to 3. public int? FlagsFetchRetries { get; init; } + /// Tracking event batching options. public ReflagBatchOptions? Batch { get; init; } /// Base Boolean overrides. Specify at most one of the four override options. @@ -65,10 +74,13 @@ public sealed class ReflagClientOptions /// public Func>? JsonFlagOverridesFactory { get; init; } + /// Disables all network I/O. Defaults to REFLAG_OFFLINE. Useful in tests. public bool? Offline { get; init; } + /// How flag definitions are kept fresh. Defaults to . public ReflagFlagsSyncMode? FlagsSyncMode { get; init; } + /// Overrides the push sync endpoint. public Uri? FlagsPushUrl { get; init; } } diff --git a/src/Reflag/ReflagServiceCollectionExtensions.cs b/src/Reflag/ReflagServiceCollectionExtensions.cs index ee44e6e..6ba1e47 100644 --- a/src/Reflag/ReflagServiceCollectionExtensions.cs +++ b/src/Reflag/ReflagServiceCollectionExtensions.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Reflag.Internal; namespace Reflag; @@ -23,7 +24,9 @@ public static IServiceCollection AddReflag( ThrowHelpers.ThrowIfNull(services, nameof(services)); ThrowHelpers.ThrowIfNull(configure, nameof(configure)); - services.AddSingleton(sp => new ReflagClient(configure(sp))); + services.AddSingleton(sp => new ReflagClient( + configure(sp), + sp.GetService()?.CreateLogger("Reflag"))); services.AddSingleton(); return services; } diff --git a/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs b/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs index bc1cf12..347c07b 100644 --- a/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs +++ b/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs @@ -52,7 +52,7 @@ public async Task Scalar_diagnostics_reach_checks_bootstrap_and_rate_limited_war var healthy = payload.RootElement.EnumerateArray().Single(item => item.GetProperty("key").GetString() == "healthy"); Assert.False(healthy.TryGetProperty("evalErrors", out _)); - Assert.Single(logger.Entries, entry => entry.Level == LogLevel.Warning && entry.Message.Contains("flag targeting rules")); + Assert.Single(logger.Entries, entry => entry.Level == LogLevel.Warning && entry.Message.Contains("targeting rules could not be fully evaluated")); } [Theory] diff --git a/tests/Reflag.Tests/FeatureFlagCheckEventTests.cs b/tests/Reflag.Tests/FeatureFlagCheckEventTests.cs index d404958..6b1e5f3 100644 --- a/tests/Reflag.Tests/FeatureFlagCheckEventTests.cs +++ b/tests/Reflag.Tests/FeatureFlagCheckEventTests.cs @@ -270,7 +270,7 @@ public async Task GetFlag_rate_limits_missing_context_field_warnings() }, new ReflagTelemetryOptions { EnableTelemetry = false })); var warningEntries = logger.Entries - .Where(entry => entry.Level == LogLevel.Warning && entry.Message.Contains("flag targeting rules could not be fully evaluated.")) + .Where(entry => entry.Level == LogLevel.Warning && entry.Message.Contains("targeting rules could not be fully evaluated")) .ToList(); Assert.Single(warningEntries); @@ -329,7 +329,7 @@ public async Task Diagnostics_are_in_checks_and_bootstrap_and_warnings_are_rate_ } Assert.False(item.TryGetProperty("evalMissingFields", out _)); - Assert.Single(logger.Entries, entry => entry.Level == LogLevel.Warning && entry.Message.Contains("flag targeting rules")); + Assert.Single(logger.Entries, entry => entry.Level == LogLevel.Warning && entry.Message.Contains("targeting rules could not be fully evaluated")); } private static List ToJsonArray(string body) diff --git a/tests/Reflag.Tests/ReflagClientTests.cs b/tests/Reflag.Tests/ReflagClientTests.cs index 0a7d24c..41e2691 100644 --- a/tests/Reflag.Tests/ReflagClientTests.cs +++ b/tests/Reflag.Tests/ReflagClientTests.cs @@ -386,4 +386,86 @@ private static Task AssertDisposedAsync(Func action) { return Assert.ThrowsAsync(action); } + + [Fact] + public async Task AddReflag_uses_the_host_logger_factory_when_no_logger_is_configured() + { + var logger = new TestLogger(); + var services = new ServiceCollection(); + services.AddSingleton(new SingleLoggerFactory(logger)); + services.AddReflag(new ReflagClientOptions { Offline = true }); + + await using var provider = services.BuildServiceProvider(); + var client = provider.GetRequiredService(); + await client.InitializeAsync(); + + Assert.NotEmpty(logger.Entries); + } + + [Fact] + public void Evaluating_before_initialize_logs_the_error_once_per_window() + { + var logger = new TestLogger(); + var client = new ReflagClient(new ReflagClientOptions + { + SecretKey = "validSecretKeyWithMoreThan22Chars", + Logger = logger, + }); + + client.GetFlag("a", new ReflagContext()); + client.GetFlag("b", new ReflagContext()); + client.GetFlagsForBootstrap(new ReflagContext()); + + Assert.Single(logger.Entries, entry => entry.Level == LogLevel.Error && entry.Message.Contains("not initialized yet")); + } + + [Fact] + public void Flag_reads_accept_loose_contexts() + { + var client = new ReflagClient(new ReflagClientOptions + { + Offline = true, + FlagOverridesFactory = context => new Dictionary + { + ["qa-flag"] = context.User?.Id == "qa-user", + }, + }); + + var context = new { User = new { Id = "qa-user", Plan = "pro" } }; + + Assert.True(client.GetFlag("qa-flag", context)); + Assert.True(client.GetFlag("qa-flag", context, false)); + Assert.True(client.GetFlags(context)["qa-flag"]?.GetBoolean()); + Assert.Equal("pro", client.GetFlagsForBootstrap(context).Context.User?.Attributes["Plan"]?.ToString()); + } + + [Fact] + public void Constructor_explains_how_to_provide_a_missing_secret_key() + { + var previous = Environment.GetEnvironmentVariable("REFLAG_SECRET_KEY"); + Environment.SetEnvironmentVariable("REFLAG_SECRET_KEY", null); + try + { + var error = Assert.Throws(() => new ReflagClient(new ReflagClientOptions())); + Assert.Contains("REFLAG_SECRET_KEY", error.Message); + Assert.Contains("Offline", error.Message); + } + finally + { + Environment.SetEnvironmentVariable("REFLAG_SECRET_KEY", previous); + } + } + + private sealed class SingleLoggerFactory(ILogger logger) : ILoggerFactory + { + public ILogger CreateLogger(string categoryName) => logger; + + public void AddProvider(ILoggerProvider provider) + { + } + + public void Dispose() + { + } + } } From 0586ff1ddb913b3cd48e839292f50f502b71baf1 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Sat, 28 Nov 2026 11:39:52 +0000 Subject: [PATCH 2/2] test: cover check telemetry across initialization Port the regression test from #18. Current main already keeps a pre-initialization check from suppressing the matching check after initialization, because the dedupe key includes evalErrors and flagStateVersion. --- .../EvaluationDiagnosticsTelemetryTests.cs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs b/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs index 347c07b..fb5d67b 100644 --- a/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs +++ b/tests/Reflag.Tests/EvaluationDiagnosticsTelemetryTests.cs @@ -84,6 +84,34 @@ public async Task Checks_before_initialization_include_a_diagnostic_even_for_ove Assert.Contains(logger.Entries, entry => entry.Level == LogLevel.Error && entry.Message.Contains("not initialized")); } + [Fact] + public async Task Initialization_state_is_part_of_check_event_deduplication() + { + var transport = new TestTransport(); + transport.EnqueueGetJson("{\"success\":true,\"protocolVersion\":2,\"flagStateVersion\":1,\"flags\":[],\"segments\":[]}"); + await using var client = new ReflagClient(new ReflagClientOptions + { + SecretKey = "validSecretKeyWithMoreThan22Chars", + HttpClient = transport.CreateHttpClient(), + FlagsSyncMode = ReflagFlagsSyncMode.Polling, + FlagsFetchRetries = 0, + FlagOverrides = new Dictionary { ["flag"] = true }, + }); + + Assert.True(client.GetFlag("flag", new ReflagContext())); + await client.InitializeAsync(); + Assert.True(client.GetFlag("flag", new ReflagContext())); + await client.FlushAsync(); + + using var payload = JsonDocument.Parse(Assert.Single(transport.PostCalls).Body); + var checks = payload.RootElement.EnumerateArray().ToArray(); + Assert.Equal(2, checks.Length); + Assert.Equal( + ReflagEvaluationErrorCodes.ClientNotInitialized, + Assert.Single(checks[0].GetProperty("evalErrors").EnumerateArray()).GetProperty("code").GetString()); + Assert.False(checks[1].TryGetProperty("evalErrors", out _)); + } + [Fact] public async Task Initialization_diagnostic_is_appended_to_check_errors_but_not_bootstrap_errors() {