From 62797922f44c633fd67fa754c044379835869530 Mon Sep 17 00:00:00 2001 From: Aghogho Bernard Date: Sat, 19 Sep 2026 16:19:43 -0230 Subject: [PATCH 1/4] fix: fail fast on unreachable Redis instead of queueing every command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AddCacheWeaveRedis set AbortOnConnectFail = false but left BacklogPolicy at its default, which queues commands while disconnected. With no reachable Redis, a cache-decorated request paid a StringGetAsync on the way in and a StringSetAsync on the way out, each blocking for the full SyncTimeout — ~10-12s of added latency per request, indefinitely, not a one-time connect cost. CacheWeave already converts any cache failure to a miss, so the request returned correct data with a 200 and the degradation was invisible in logs and metrics. Set BacklogPolicy.FailFast alongside AbortOnConnectFail: both settings express one policy — never throw on connect, and never block a request waiting for a connection that isn't there. FailFast is not consulted on the success path, so behaviour against a reachable Redis is unchanged. Evictions are the one case where a dropped command matters: a [CacheWeaveEvict] delete lost during a failover leaves a stale entry served until it expires. RemoveAsync and RemoveByPrefixAsync therefore wait up to 1.5s for the multiplexer to reconnect and retry once; deleting an already-deleted key is a no-op, so replaying a partially applied eviction is safe. Reads and writes stay fail-fast. Also: - Add an Action overload, as a separate overload so existing calls still bind. It runs after the defaults, so callers can override them — including back to BacklogPolicy.Default — and reach settings no connection string can express (TLS certs, Sentinel, Azure token auth). - Use TryAddSingleton for IConnectionMultiplexer, matching CacheWeave.Legacy. A multiplexer registered after the call still wins, so the existing re-registration workaround keeps working. - Apply the same fixes to CacheWeave.Legacy (net48), which had the same defect. - Document connection behaviour and the eviction trade-off in the README. Warrants a minor version bump: an app relying on the backlog to ride out a brief blip now takes a cache miss instead of up to SyncTimeout of latency. --- README.md | 37 ++++++ .../CacheWeave.Legacy.csproj | 4 + .../Extensions/ServiceCollectionExtensions.cs | 34 ++++- .../Providers/RedisCacheProvider.cs | 60 ++++++++- src/CacheWeave.Redis/CacheWeave.Redis.csproj | 4 + .../Extensions/ServiceCollectionExtensions.cs | 44 ++++++- src/CacheWeave.Redis/RedisCacheProvider.cs | 64 ++++++++- .../RedisServiceCollectionExtensionsTests.cs | 101 ++++++++++++++ .../Providers/RedisCacheProviderTests.cs | 104 +++++++++++++++ .../RedisServiceCollectionExtensionsTests.cs | 123 ++++++++++++++++++ .../Providers/RedisCacheProviderTests.cs | 75 +++++++++++ 11 files changed, 635 insertions(+), 15 deletions(-) create mode 100644 tests/CacheWeave.Legacy.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs create mode 100644 tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs create mode 100644 tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs diff --git a/README.md b/README.md index 8da6a4f..92c6454 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,43 @@ Multiple `[CacheWeaveEvict]` attributes are allowed on a single action. | `CacheWeave.Faster` | Microsoft FASTER KV | No | net8/9/10 | | `CacheWeave.Legacy` | Redis, InMemory, SQLite, DynamoDB, NCache | Depends on provider | **net48** | +### Redis connection behaviour + +Redis is treated as optional. `AddCacheWeaveRedis(connectionString)` parses the connection string and then sets: + +| Setting | Value | Effect | +|---|---|---| +| `AbortOnConnectFail` | `false` | Startup never fails because Redis is down; the multiplexer keeps reconnecting in the background | +| `BacklogPolicy` | `FailFast` | While disconnected, cache commands fail immediately and the request proceeds as a cache miss, instead of each command queueing for up to `syncTimeout` | + +All other settings (`connectTimeout`, `connectRetry`, `syncTimeout`, `asyncTimeout`, `ssl`, `password`, …) come from the connection string. For anything a connection string can't express, pass a `configure` callback — it runs after the defaults above and can override them: + +```csharp +builder.Services.AddCacheWeaveRedis("my-redis:6380,ssl=true", redis => +{ + redis.ConnectTimeout = 1000; + redis.BacklogPolicy = BacklogPolicy.Default; // opt back in to queueing during brief disconnects +}); + +// Or bring your own multiplexer (Sentinel, Azure token auth, shared with the rest of your app) +builder.Services.AddCacheWeaveRedis(existingMultiplexer); +``` + +If an `IConnectionMultiplexer` is already registered when `AddCacheWeaveRedis(connectionString)` is called, CacheWeave uses it rather than creating its own. + +#### Evictions during a brief outage + +Fail-fast is the right trade for reads and writes — a dropped one is just a cache miss. Evictions are +different: a `[CacheWeaveEvict]` delete that never reaches Redis leaves the old entry being served +until it expires. So evictions, and only evictions, wait up to **1.5s** for the multiplexer to +reconnect and then retry once. A failover or short network blip therefore still invalidates, while a +genuine outage costs a write request 1.5s at most, once per eviction, instead of `syncTimeout` on +every operation. + +If the retry doesn't get through, `CacheWeaveEvictFilter` logs a warning (`eviction failed … cache +may be stale`) and the request still succeeds. Watch for that warning if you need to know when the +cache and your data have diverged. + --- ## .NET Framework 4.8 Support (`CacheWeave.Legacy`) diff --git a/src/CacheWeave.Legacy/CacheWeave.Legacy.csproj b/src/CacheWeave.Legacy/CacheWeave.Legacy.csproj index 20bcfae..6e7ef90 100644 --- a/src/CacheWeave.Legacy/CacheWeave.Legacy.csproj +++ b/src/CacheWeave.Legacy/CacheWeave.Legacy.csproj @@ -15,6 +15,10 @@ + + + + diff --git a/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs b/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs index 3b2e958..894fbcd 100644 --- a/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs +++ b/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs @@ -77,15 +77,45 @@ public static IServiceCollection AddCacheWeave( public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string connectionString) + => services.AddCacheWeaveRedis(connectionString, configure: null); + + /// + /// Registers the Redis provider using a connection string, allowing the parsed + /// to be customised. + /// + /// + /// Redis is treated as optional: is false + /// and is , so an + /// unreachable Redis degrades to an immediate cache miss instead of blocking every command for + /// syncTimeout. runs after these defaults and can override them. + /// + public static IServiceCollection AddCacheWeaveRedis( + this IServiceCollection services, + string connectionString, + Action? configure) { - var configOpts = ConfigurationOptions.Parse(connectionString); - configOpts.AbortOnConnectFail = false; + var configOpts = BuildRedisConfigurationOptions(connectionString, configure); services.TryAddSingleton(_ => ConnectionMultiplexer.Connect(configOpts)); services.TryAddSingleton(); return services; } + internal static ConfigurationOptions BuildRedisConfigurationOptions( + string connectionString, + Action? configure) + { + var configOpts = ConfigurationOptions.Parse(connectionString); + + // The cache is optional — CacheWeave already treats any cache failure as a miss. Never throw + // on connect, and never queue commands waiting for a connection that isn't there. + configOpts.AbortOnConnectFail = false; + configOpts.BacklogPolicy = BacklogPolicy.FailFast; + + configure?.Invoke(configOpts); + return configOpts; + } + /// Registers the Redis provider using an existing . public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, diff --git a/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs b/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs index cbbb767..41d61fb 100644 --- a/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs +++ b/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using CacheWeave.Legacy.Abstractions; @@ -9,11 +10,27 @@ namespace CacheWeave.Legacy.Providers { public sealed class RedisCacheProvider : ICacheProviderInner { + /// + /// How long an eviction waits for the multiplexer to reconnect before giving up. Reads and writes + /// fail fast — a dropped one is just a cache miss — but a dropped eviction leaves a stale entry + /// being served until it expires, so evictions ride out a brief failover instead. + /// + private static readonly TimeSpan DefaultEvictionRetryWindow = TimeSpan.FromSeconds(1.5); + + private static readonly TimeSpan ReconnectPollInterval = TimeSpan.FromMilliseconds(50); + private readonly IConnectionMultiplexer _multiplexer; + private readonly TimeSpan _evictionRetryWindow; public RedisCacheProvider(IConnectionMultiplexer multiplexer) + : this(multiplexer, DefaultEvictionRetryWindow) + { + } + + internal RedisCacheProvider(IConnectionMultiplexer multiplexer, TimeSpan evictionRetryWindow) { _multiplexer = multiplexer; + _evictionRetryWindow = evictionRetryWindow; } private IDatabase Db => _multiplexer.GetDatabase(); @@ -28,9 +45,12 @@ public Task SetAsync(string key, string value, TimeSpan? expiry = null, Cancella Db.StringSetAsync(key, value, expiry); public Task RemoveAsync(string key, CancellationToken cancellationToken = default) => - Db.KeyDeleteAsync(key); + EvictAsync(() => Db.KeyDeleteAsync(key), cancellationToken); + + public Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) => + EvictAsync(() => ScanAndDeleteAsync(prefix), cancellationToken); - public async Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + private async Task ScanAndDeleteAsync(string prefix) { var db = Db; foreach (var server in _multiplexer.GetServers()) @@ -53,5 +73,41 @@ public async Task RemoveByPrefixAsync(string prefix, CancellationToken cancellat await db.KeyDeleteAsync(batch.ToArray()).ConfigureAwait(false); } } + + /// + /// Runs an eviction, retrying once if the connection was unavailable but comes back within + /// . Deleting an already-deleted key is a no-op, so replaying + /// a partially applied eviction is safe. + /// + private async Task EvictAsync(Func evict, CancellationToken cancellationToken) + { + try + { + await evict().ConfigureAwait(false); + return; + } + catch (RedisConnectionException) + { + if (!await WaitForReconnectAsync(cancellationToken).ConfigureAwait(false)) + throw; + } + + await evict().ConfigureAwait(false); + } + + private async Task WaitForReconnectAsync(CancellationToken cancellationToken) + { + var stopwatch = Stopwatch.StartNew(); + + while (!_multiplexer.IsConnected) + { + if (stopwatch.Elapsed >= _evictionRetryWindow || cancellationToken.IsCancellationRequested) + return false; + + await Task.Delay(ReconnectPollInterval, cancellationToken).ConfigureAwait(false); + } + + return true; + } } } diff --git a/src/CacheWeave.Redis/CacheWeave.Redis.csproj b/src/CacheWeave.Redis/CacheWeave.Redis.csproj index 8d44720..fb1a5ef 100644 --- a/src/CacheWeave.Redis/CacheWeave.Redis.csproj +++ b/src/CacheWeave.Redis/CacheWeave.Redis.csproj @@ -16,6 +16,10 @@ + + + + diff --git a/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs b/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs index 166ef67..9d430ba 100644 --- a/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs +++ b/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs @@ -1,6 +1,7 @@ using CacheWeave.Core.Abstractions; using CacheWeave.Core.Extensions; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using StackExchange.Redis; namespace CacheWeave.Redis.Extensions; @@ -15,22 +16,53 @@ public static class ServiceCollectionExtensions public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string redisConnectionString) + => services.AddCacheWeaveRedis(redisConnectionString, configure: null); + + /// + /// Registers CacheWeave with a Redis backing store via , + /// allowing the parsed to be customised. + /// + /// + /// Redis is treated as optional: is false + /// and is , so an + /// unreachable Redis degrades to an immediate cache miss instead of blocking every command for + /// syncTimeout. runs after these defaults and can override them. + /// If an is already registered, it is used as-is. + /// + /// The service collection. + /// Redis connection string (e.g. "localhost:6379"). + /// Optional callback to adjust the connection options (TLS, auth, timeouts, etc.). + public static IServiceCollection AddCacheWeaveRedis( + this IServiceCollection services, + string redisConnectionString, + Action? configure) { services.AddCacheWeave(); if (string.IsNullOrWhiteSpace(redisConnectionString)) return services; - services.AddSingleton(_ => - { - var options = ConfigurationOptions.Parse(redisConnectionString); - options.AbortOnConnectFail = false; - return ConnectionMultiplexer.Connect(options); - }); + services.TryAddSingleton(_ => + ConnectionMultiplexer.Connect(BuildConfigurationOptions(redisConnectionString, configure))); services.AddSingleton(); return services; } + internal static ConfigurationOptions BuildConfigurationOptions( + string redisConnectionString, + Action? configure) + { + var options = ConfigurationOptions.Parse(redisConnectionString); + + // The cache is optional — CacheWeave already treats any cache failure as a miss. Never throw + // on connect, and never queue commands waiting for a connection that isn't there. + options.AbortOnConnectFail = false; + options.BacklogPolicy = BacklogPolicy.FailFast; + + configure?.Invoke(options); + return options; + } + /// /// Registers CacheWeave with an existing instance. /// Use this overload if your app already registers Redis separately. diff --git a/src/CacheWeave.Redis/RedisCacheProvider.cs b/src/CacheWeave.Redis/RedisCacheProvider.cs index 0e9b83a..d9fa282 100644 --- a/src/CacheWeave.Redis/RedisCacheProvider.cs +++ b/src/CacheWeave.Redis/RedisCacheProvider.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using CacheWeave.Core.Abstractions; using StackExchange.Redis; @@ -10,11 +11,27 @@ namespace CacheWeave.Redis; /// public sealed class RedisCacheProvider : ICacheProviderInner { + /// + /// How long an eviction waits for the multiplexer to reconnect before giving up. Reads and writes + /// fail fast — a dropped one is just a cache miss — but a dropped eviction leaves a stale entry + /// being served until it expires, so evictions ride out a brief failover instead. + /// + private static readonly TimeSpan DefaultEvictionRetryWindow = TimeSpan.FromSeconds(1.5); + + private static readonly TimeSpan ReconnectPollInterval = TimeSpan.FromMilliseconds(50); + private readonly IConnectionMultiplexer _multiplexer; + private readonly TimeSpan _evictionRetryWindow; public RedisCacheProvider(IConnectionMultiplexer multiplexer) + : this(multiplexer, DefaultEvictionRetryWindow) + { + } + + internal RedisCacheProvider(IConnectionMultiplexer multiplexer, TimeSpan evictionRetryWindow) { _multiplexer = multiplexer; + _evictionRetryWindow = evictionRetryWindow; } private IDatabase Db => _multiplexer.GetDatabase(); @@ -30,12 +47,13 @@ public async Task SetAsync(string key, string value, TimeSpan? expiry = null, Ca await Db.StringSetAsync(key, value, expiry); } - public async Task RemoveAsync(string key, CancellationToken cancellationToken = default) - { - await Db.KeyDeleteAsync(key); - } + public Task RemoveAsync(string key, CancellationToken cancellationToken = default) + => EvictAsync(() => Db.KeyDeleteAsync(key), cancellationToken); + + public Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + => EvictAsync(() => ScanAndDeleteAsync(prefix, cancellationToken), cancellationToken); - public async Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + private async Task ScanAndDeleteAsync(string prefix, CancellationToken cancellationToken) { const int batchSize = 250; var pattern = $"{prefix}*"; @@ -65,4 +83,40 @@ public async Task RemoveByPrefixAsync(string prefix, CancellationToken cancellat } } } + + /// + /// Runs an eviction, retrying once if the connection was unavailable but comes back within + /// . Deleting an already-deleted key is a no-op, so replaying + /// a partially applied eviction is safe. + /// + private async Task EvictAsync(Func evict, CancellationToken cancellationToken) + { + try + { + await evict(); + return; + } + catch (RedisConnectionException) + { + if (!await WaitForReconnectAsync(cancellationToken)) + throw; + } + + await evict(); + } + + private async Task WaitForReconnectAsync(CancellationToken cancellationToken) + { + var stopwatch = Stopwatch.StartNew(); + + while (!_multiplexer.IsConnected) + { + if (stopwatch.Elapsed >= _evictionRetryWindow || cancellationToken.IsCancellationRequested) + return false; + + await Task.Delay(ReconnectPollInterval, cancellationToken); + } + + return true; + } } diff --git a/tests/CacheWeave.Legacy.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs b/tests/CacheWeave.Legacy.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..46d6944 --- /dev/null +++ b/tests/CacheWeave.Legacy.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs @@ -0,0 +1,101 @@ +using System; +using System.Threading.Tasks; +using CacheWeave.Legacy.Extensions; +using CacheWeave.Legacy.Providers; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using StackExchange.Redis; +using Xunit; + +namespace CacheWeave.Legacy.Tests.Extensions +{ + public class RedisServiceCollectionExtensionsTests + { + // Nothing listens on port 1, so connections are refused immediately. The long command timeouts + // mean a backlogged command would sit for a full minute before failing. + private const string UnreachableRedis = + "127.0.0.1:1,connectTimeout=200,connectRetry=1,syncTimeout=60000,asyncTimeout=60000"; + + // ------------------------------------------------------------------------- + // BuildRedisConfigurationOptions — connection defaults + // ------------------------------------------------------------------------- + + [Fact] + public void BuildRedisConfigurationOptions_DoesNotAbortOnConnectFail() + { + var options = ServiceCollectionExtensions.BuildRedisConfigurationOptions("localhost:6379", null); + + options.AbortOnConnectFail.Should().BeFalse(); + } + + [Fact] + public void BuildRedisConfigurationOptions_UsesFailFastBacklogPolicy() + { + var options = ServiceCollectionExtensions.BuildRedisConfigurationOptions("localhost:6379", null); + + options.BacklogPolicy.Should().BeSameAs(BacklogPolicy.FailFast); + } + + [Fact] + public void BuildRedisConfigurationOptions_PreservesTimeoutsFromConnectionString() + { + var options = ServiceCollectionExtensions.BuildRedisConfigurationOptions( + "localhost:6379,connectTimeout=250,connectRetry=1,syncTimeout=300,asyncTimeout=400", + null); + + options.ConnectTimeout.Should().Be(250); + options.ConnectRetry.Should().Be(1); + options.SyncTimeout.Should().Be(300); + options.AsyncTimeout.Should().Be(400); + } + + [Fact] + public void BuildRedisConfigurationOptions_ConfigureRunsAfterDefaults_AndCanOverrideThem() + { + var options = ServiceCollectionExtensions.BuildRedisConfigurationOptions("localhost:6379", o => + { + o.BacklogPolicy = BacklogPolicy.Default; + o.AbortOnConnectFail = true; + }); + + options.BacklogPolicy.Should().BeSameAs(BacklogPolicy.Default); + options.AbortOnConnectFail.Should().BeTrue(); + } + + // ------------------------------------------------------------------------- + // AddCacheWeaveRedis(string) — registrations + // ------------------------------------------------------------------------- + + [Fact] + public void AddCacheWeaveRedis_KeepsMultiplexerRegisteredBeforeIt() + { + var existing = new Mock().Object; + + var services = new ServiceCollection() + .AddSingleton(existing) + .AddCacheWeaveRedis("localhost:6379"); + + services.Should().ContainSingle(d => d.ServiceType == typeof(IConnectionMultiplexer)) + .Which.ImplementationInstance.Should().BeSameAs(existing); + } + + // ------------------------------------------------------------------------- + // Behaviour against an unreachable Redis + // ------------------------------------------------------------------------- + + [Fact] + public async Task BuildRedisConfigurationOptions_UnreachableRedis_CommandsFailFastInsteadOfQueueing() + { + using var multiplexer = ConnectionMultiplexer.Connect( + ServiceCollectionExtensions.BuildRedisConfigurationOptions(UnreachableRedis, null)); + + var provider = new RedisCacheProvider(multiplexer); + + // Both policies end in RedisConnectionException; the difference is whether the command waits + // out asyncTimeout in the backlog first. FailFast rejects it immediately. + await provider.Invoking(p => p.GetAsync("k")) + .Should().ThrowWithinAsync(TimeSpan.FromSeconds(10)); + } + } +} diff --git a/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs b/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs new file mode 100644 index 0000000..0cf8956 --- /dev/null +++ b/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs @@ -0,0 +1,104 @@ +using System; +using System.Threading.Tasks; +using CacheWeave.Legacy.Providers; +using FluentAssertions; +using Moq; +using StackExchange.Redis; +using Xunit; + +namespace CacheWeave.Legacy.Tests.Providers +{ + /// + /// Tests for using a mocked . + /// No live Redis instance required. + /// + public class RedisCacheProviderTests + { + private readonly Mock _multiplexer = new Mock(); + private readonly Mock _db = new Mock(); + + // Zero window when the connection never returns, so the test doesn't wait for it + private RedisCacheProvider MakeSut(bool reconnects) + { + _multiplexer.Setup(m => m.GetDatabase(It.IsAny(), It.IsAny())).Returns(_db.Object); + _multiplexer.Setup(m => m.IsConnected).Returns(reconnects); + + return new RedisCacheProvider( + _multiplexer.Object, + reconnects ? TimeSpan.FromSeconds(1) : TimeSpan.Zero); + } + + private static RedisConnectionException Disconnected() + => new RedisConnectionException(ConnectionFailureType.UnableToConnect, "No connection is active/available"); + + // ------------------------------------------------------------------------- + // Eviction retry — a dropped delete leaves a stale entry, so it rides out a blip + // ------------------------------------------------------------------------- + + [Fact] + public async Task RemoveAsync_RetriesOnce_WhenConnectionReturnsWithinWindow() + { + _db.SetupSequence(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()) + .ReturnsAsync(true); + + var sut = MakeSut(reconnects: true); + await sut.RemoveAsync("k"); + + _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Exactly(2)); + } + + [Fact] + public async Task RemoveAsync_Throws_WhenConnectionDoesNotReturnWithinWindow() + { + _db.Setup(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()); + + var sut = MakeSut(reconnects: false); + + await sut.Invoking(s => s.RemoveAsync("k")) + .Should().ThrowAsync(); + _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Once); + } + + [Fact] + public async Task GetAsync_DoesNotRetry_WhenConnectionFails() + { + _db.Setup(d => d.StringGetAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()); + + var sut = MakeSut(reconnects: true); + + // Reads stay fail-fast — a dropped read is just a cache miss + await sut.Invoking(s => s.GetAsync("k")) + .Should().ThrowAsync(); + _db.Verify(d => d.StringGetAsync((RedisKey)"k", It.IsAny()), Times.Once); + } + + // ------------------------------------------------------------------------- + // Get / Set pass-through + // ------------------------------------------------------------------------- + + [Fact] + public async Task GetAsync_ReturnsValue_WhenKeyExists() + { + _db.Setup(d => d.StringGetAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new RedisValue("hello")); + + var result = await MakeSut(reconnects: true).GetAsync("k"); + + result.Should().Be("hello"); + } + + [Fact] + public async Task GetAsync_ReturnsNull_WhenKeyMissing() + { + _db.Setup(d => d.StringGetAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(RedisValue.Null); + + var result = await MakeSut(reconnects: true).GetAsync("k"); + + result.Should().BeNull(); + } + } +} diff --git a/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs b/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..21e7bd0 --- /dev/null +++ b/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs @@ -0,0 +1,123 @@ +using CacheWeave.Redis; +using CacheWeave.Redis.Extensions; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using StackExchange.Redis; +using Xunit; + +namespace CacheWeave.Tests.Extensions; + +public class RedisServiceCollectionExtensionsTests +{ + // Nothing listens on port 1, so connections are refused immediately. The long command timeouts + // mean a backlogged command would sit for a full minute before failing. + private const string UnreachableRedis = + "127.0.0.1:1,connectTimeout=200,connectRetry=1,syncTimeout=60000,asyncTimeout=60000"; + + // ------------------------------------------------------------------------- + // BuildConfigurationOptions — connection defaults + // ------------------------------------------------------------------------- + + [Fact] + public void BuildConfigurationOptions_DoesNotAbortOnConnectFail() + { + var options = ServiceCollectionExtensions.BuildConfigurationOptions("localhost:6379", configure: null); + + options.AbortOnConnectFail.Should().BeFalse(); + } + + [Fact] + public void BuildConfigurationOptions_UsesFailFastBacklogPolicy() + { + var options = ServiceCollectionExtensions.BuildConfigurationOptions("localhost:6379", configure: null); + + options.BacklogPolicy.Should().BeSameAs(BacklogPolicy.FailFast); + } + + [Fact] + public void BuildConfigurationOptions_PreservesTimeoutsFromConnectionString() + { + var options = ServiceCollectionExtensions.BuildConfigurationOptions( + "localhost:6379,connectTimeout=250,connectRetry=1,syncTimeout=300,asyncTimeout=400", + configure: null); + + options.ConnectTimeout.Should().Be(250); + options.ConnectRetry.Should().Be(1); + options.SyncTimeout.Should().Be(300); + options.AsyncTimeout.Should().Be(400); + } + + [Fact] + public void BuildConfigurationOptions_ConfigureRunsAfterDefaults_AndCanOverrideThem() + { + var options = ServiceCollectionExtensions.BuildConfigurationOptions("localhost:6379", o => + { + o.BacklogPolicy = BacklogPolicy.Default; + o.AbortOnConnectFail = true; + }); + + options.BacklogPolicy.Should().BeSameAs(BacklogPolicy.Default); + options.AbortOnConnectFail.Should().BeTrue(); + } + + // ------------------------------------------------------------------------- + // AddCacheWeaveRedis(string) — registrations + // ------------------------------------------------------------------------- + + [Fact] + public void AddCacheWeaveRedis_KeepsMultiplexerRegisteredBeforeIt() + { + var existing = new Mock().Object; + + var sp = new ServiceCollection() + .AddLogging() + .AddSingleton(existing) + .AddCacheWeaveRedis("localhost:6379") + .BuildServiceProvider(); + + sp.GetRequiredService().Should().BeSameAs(existing); + } + + [Fact] + public void AddCacheWeaveRedis_MultiplexerRegisteredAfterIt_StillWins() + { + var replacement = new Mock().Object; + + var sp = new ServiceCollection() + .AddLogging() + .AddCacheWeaveRedis("localhost:6379") + .AddSingleton(replacement) + .BuildServiceProvider(); + + sp.GetRequiredService().Should().BeSameAs(replacement); + } + + [Fact] + public void AddCacheWeaveRedis_BlankConnectionString_RegistersNoMultiplexer() + { + var services = new ServiceCollection().AddCacheWeaveRedis(" "); + + services.Should().NotContain(d => d.ServiceType == typeof(IConnectionMultiplexer)); + } + + // ------------------------------------------------------------------------- + // Behaviour against an unreachable Redis + // ------------------------------------------------------------------------- + + [Fact] + public async Task AddCacheWeaveRedis_UnreachableRedis_CommandsFailFastInsteadOfQueueing() + { + await using var sp = new ServiceCollection() + .AddLogging() + .AddCacheWeaveRedis(UnreachableRedis) + .BuildServiceProvider(); + + var provider = new RedisCacheProvider(sp.GetRequiredService()); + + // Both policies end in RedisConnectionException; the difference is whether the command waits + // out asyncTimeout in the backlog first. FailFast rejects it immediately. + await provider.Invoking(p => p.GetAsync("k")) + .Should().ThrowWithinAsync(TimeSpan.FromSeconds(10)); + } +} diff --git a/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs b/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs index 21ee2f0..ccabb4a 100644 --- a/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs +++ b/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs @@ -178,6 +178,81 @@ public async Task RemoveByPrefixAsync_BatchesCorrectly_WhenKeysExceedBatchSize() It.Is(k => k.Length == 10), It.IsAny()), Times.Once); } + + // ------------------------------------------------------------------------- + // Eviction retry — a dropped delete leaves a stale entry, so it rides out a blip + // ------------------------------------------------------------------------- + + private RedisCacheProvider MakeSutForEviction(bool reconnects) + { + _multiplexer.Setup(m => m.GetDatabase(It.IsAny(), It.IsAny())).Returns(_db.Object); + _multiplexer.Setup(m => m.GetServers()).Returns([_server.Object]); + _multiplexer.Setup(m => m.IsConnected).Returns(reconnects); + + // Zero window when the connection never returns, so the test doesn't wait for it + return new RedisCacheProvider( + _multiplexer.Object, + reconnects ? TimeSpan.FromSeconds(1) : TimeSpan.Zero); + } + + private static RedisConnectionException Disconnected() + => new(ConnectionFailureType.UnableToConnect, "No connection is active/available"); + + [Fact] + public async Task RemoveAsync_RetriesOnce_WhenConnectionReturnsWithinWindow() + { + _db.SetupSequence(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()) + .ReturnsAsync(true); + + var sut = MakeSutForEviction(reconnects: true); + await sut.RemoveAsync("k"); + + _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Exactly(2)); + } + + [Fact] + public async Task RemoveAsync_Throws_WhenConnectionDoesNotReturnWithinWindow() + { + _db.Setup(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()); + + var sut = MakeSutForEviction(reconnects: false); + + await sut.Invoking(s => s.RemoveAsync("k")) + .Should().ThrowAsync(); + _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Once); + } + + [Fact] + public async Task RemoveByPrefixAsync_RetriesOnce_WhenConnectionReturnsWithinWindow() + { + _server.Setup(s => s.KeysAsync(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(() => new RedisKey[] { "products:1" }.ToAsyncEnumerable()); + _db.SetupSequence(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()) + .ReturnsAsync(1); + + var sut = MakeSutForEviction(reconnects: true); + await sut.RemoveByPrefixAsync("products:"); + + _db.Verify(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny()), Times.Exactly(2)); + } + + [Fact] + public async Task GetAsync_DoesNotRetry_WhenConnectionFails() + { + _db.Setup(d => d.StringGetAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()); + + var sut = MakeSutForEviction(reconnects: true); + + // Reads stay fail-fast — a dropped read is just a cache miss + await sut.Invoking(s => s.GetAsync("k")) + .Should().ThrowAsync(); + _db.Verify(d => d.StringGetAsync((RedisKey)"k", It.IsAny()), Times.Once); + } } // Helper to convert IEnumerable to IAsyncEnumerable From 951ce353be7b031d7224ea2ef10e027fe3880d8d Mon Sep 17 00:00:00 2001 From: Aghogho Bernard Date: Sat, 19 Sep 2026 16:21:07 -0230 Subject: [PATCH 2/4] test: cover the reconnect poll path in the eviction retry --- .../Providers/RedisCacheProviderTests.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs b/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs index ccabb4a..4308f30 100644 --- a/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs +++ b/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs @@ -240,6 +240,22 @@ public async Task RemoveByPrefixAsync_RetriesOnce_WhenConnectionReturnsWithinWin _db.Verify(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny()), Times.Exactly(2)); } + + [Fact] + public async Task RemoveAsync_RetriesOnce_WhenConnectionReturnsAfterAPoll() + { + _multiplexer.Setup(m => m.GetDatabase(It.IsAny(), It.IsAny())).Returns(_db.Object); + // Disconnected on the first poll, back by the second — the shape of a short failover + _multiplexer.SetupSequence(m => m.IsConnected).Returns(false).Returns(true); + _db.SetupSequence(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()) + .ReturnsAsync(true); + + var sut = new RedisCacheProvider(_multiplexer.Object, TimeSpan.FromSeconds(5)); + await sut.RemoveAsync("k"); + + _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Exactly(2)); + } [Fact] public async Task GetAsync_DoesNotRetry_WhenConnectionFails() { From aafcbab95eb250f637661cf4b5cb04ef8929a4a1 Mon Sep 17 00:00:00 2001 From: Aghogho Bernard Date: Sat, 19 Sep 2026 23:54:26 -0230 Subject: [PATCH 3/4] feat: expose Redis provider behaviour through RedisCacheOptions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The eviction retry window, its poll interval and the SCAN page size were hard-coded constants, reachable only from an internal constructor meant for tests. That repeated the original complaint about this package: a policy the library decided for you with no way to change it. Add RedisCacheOptions, bound through IOptions like SQLiteCacheOptions and DynamoDbCacheOptions already are, and configured via a configureCache callback on every AddCacheWeaveRedis overload — including the one taking an existing IConnectionMultiplexer, which previously offered no provider configuration at all. Defaults are unchanged: 1.5s window, 50ms poll, 250-key batches. EvictionRetryWindow = TimeSpan.Zero now genuinely disables the retry. It did not before: WaitForReconnectAsync returns true immediately when the multiplexer is already connected, so the retry still ran regardless of the window. Caught by the test written for the documented behaviour. Constructor validates the options and throws ArgumentOutOfRangeException on a negative window, a non-positive poll interval, or a scan page size below 1. Applied to CacheWeave.Legacy too. The connection-configure parameter is renamed configureConnection to sit alongside configureCache; both are new in this unreleased branch, so no shipped signature changes. --- README.md | 27 +++++-- .../Extensions/ServiceCollectionExtensions.cs | 34 +++++++-- .../Providers/RedisCacheOptions.cs | 32 +++++++++ .../Providers/RedisCacheProvider.cs | 47 ++++++------ .../Extensions/ServiceCollectionExtensions.cs | 69 ++++++++++++------ src/CacheWeave.Redis/RedisCacheOptions.cs | 29 ++++++++ src/CacheWeave.Redis/RedisCacheProvider.cs | 41 ++++++----- .../Providers/RedisCacheProviderTests.cs | 6 +- .../RedisServiceCollectionExtensionsTests.cs | 49 +++++++++++++ .../Providers/RedisCacheProviderTests.cs | 71 +++++++++++++++++-- 10 files changed, 329 insertions(+), 76 deletions(-) create mode 100644 src/CacheWeave.Legacy/Providers/RedisCacheOptions.cs create mode 100644 src/CacheWeave.Redis/RedisCacheOptions.cs diff --git a/README.md b/README.md index 92c6454..1baf702 100644 --- a/README.md +++ b/README.md @@ -195,16 +195,30 @@ Redis is treated as optional. `AddCacheWeaveRedis(connectionString)` parses the All other settings (`connectTimeout`, `connectRetry`, `syncTimeout`, `asyncTimeout`, `ssl`, `password`, …) come from the connection string. For anything a connection string can't express, pass a `configure` callback — it runs after the defaults above and can override them: ```csharp -builder.Services.AddCacheWeaveRedis("my-redis:6380,ssl=true", redis => -{ - redis.ConnectTimeout = 1000; - redis.BacklogPolicy = BacklogPolicy.Default; // opt back in to queueing during brief disconnects -}); +builder.Services.AddCacheWeaveRedis("my-redis:6380,ssl=true", + configureConnection: redis => + { + redis.ConnectTimeout = 1000; + redis.BacklogPolicy = BacklogPolicy.Default; // opt back in to queueing during brief disconnects + }, + configureCache: cache => + { + cache.EvictionRetryWindow = TimeSpan.FromSeconds(3); + }); // Or bring your own multiplexer (Sentinel, Azure token auth, shared with the rest of your app) builder.Services.AddCacheWeaveRedis(existingMultiplexer); +builder.Services.AddCacheWeaveRedis(existingMultiplexer, cache => cache.ScanPageSize = 1000); ``` +Provider behaviour is configured separately from the connection, via `RedisCacheOptions`: + +| Property | Type | Default | Description | +|---|---|---|---| +| `EvictionRetryWindow` | `TimeSpan` | `1.5s` | How long an eviction waits for a reconnect before giving up. `TimeSpan.Zero` disables the retry | +| `ReconnectPollInterval` | `TimeSpan` | `50ms` | How often the connection is polled while inside that window | +| `ScanPageSize` | `int` | `250` | SCAN page size and DEL batch size for prefix eviction | + If an `IConnectionMultiplexer` is already registered when `AddCacheWeaveRedis(connectionString)` is called, CacheWeave uses it rather than creating its own. #### Evictions during a brief outage @@ -214,7 +228,8 @@ different: a `[CacheWeaveEvict]` delete that never reaches Redis leaves the old until it expires. So evictions, and only evictions, wait up to **1.5s** for the multiplexer to reconnect and then retry once. A failover or short network blip therefore still invalidates, while a genuine outage costs a write request 1.5s at most, once per eviction, instead of `syncTimeout` on -every operation. +every operation. Tune that window with `EvictionRetryWindow`, or set it to `TimeSpan.Zero` to opt out +of the retry entirely. If the retry doesn't get through, `CacheWeaveEvictFilter` logs a warning (`eviction failed … cache may be stale`) and the request still succeeds. Watch for that warning if you need to know when the diff --git a/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs b/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs index 894fbcd..77457eb 100644 --- a/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs +++ b/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs @@ -77,7 +77,7 @@ public static IServiceCollection AddCacheWeave( public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string connectionString) - => services.AddCacheWeaveRedis(connectionString, configure: null); + => services.AddCacheWeaveRedis(connectionString, configureConnection: null); /// /// Registers the Redis provider using a connection string, allowing the parsed @@ -87,14 +87,18 @@ public static IServiceCollection AddCacheWeaveRedis( /// Redis is treated as optional: is false /// and is , so an /// unreachable Redis degrades to an immediate cache miss instead of blocking every command for - /// syncTimeout. runs after these defaults and can override them. + /// syncTimeout. runs after these defaults and can override them. /// + /// Adjusts the connection options (TLS, auth, timeouts, backlog policy). + /// Adjusts provider behaviour (eviction retry, SCAN page size). public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string connectionString, - Action? configure) + Action? configureConnection, + Action? configureCache = null) { - var configOpts = BuildRedisConfigurationOptions(connectionString, configure); + var configOpts = BuildRedisConfigurationOptions(connectionString, configureConnection); + services.ConfigureRedisCache(configureCache); services.TryAddSingleton(_ => ConnectionMultiplexer.Connect(configOpts)); services.TryAddSingleton(); @@ -120,12 +124,34 @@ internal static ConfigurationOptions BuildRedisConfigurationOptions( public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, IConnectionMultiplexer multiplexer) + => services.AddCacheWeaveRedis(multiplexer, configureCache: null); + + /// + /// Registers the Redis provider using an existing , + /// allowing the provider's own behaviour to be customised. + /// + /// Adjusts provider behaviour (eviction retry, SCAN page size). + public static IServiceCollection AddCacheWeaveRedis( + this IServiceCollection services, + IConnectionMultiplexer multiplexer, + Action? configureCache) { + services.ConfigureRedisCache(configureCache); services.TryAddSingleton(multiplexer); services.TryAddSingleton(); return services; } + private static void ConfigureRedisCache( + this IServiceCollection services, + Action? configureCache) + { + if (configureCache != null) + services.Configure(configureCache); + else + services.AddOptions(); + } + // ── InMemory ───────────────────────────────────────────────────────── /// diff --git a/src/CacheWeave.Legacy/Providers/RedisCacheOptions.cs b/src/CacheWeave.Legacy/Providers/RedisCacheOptions.cs new file mode 100644 index 0000000..bfedf14 --- /dev/null +++ b/src/CacheWeave.Legacy/Providers/RedisCacheOptions.cs @@ -0,0 +1,32 @@ +using System; + +namespace CacheWeave.Legacy.Providers +{ + /// + /// Tuning knobs for . Connection-level settings + /// (timeouts, TLS, BacklogPolicy) are configured separately, via the + /// callback on AddCacheWeaveRedis. + /// + public sealed class RedisCacheOptions + { + /// + /// How long an eviction waits for the multiplexer to reconnect before giving up, so a delete + /// issued during a failover still lands rather than leaving a stale entry served until it expires. + /// Reads and writes are unaffected — they always fail fast, since a dropped one is just a cache miss. + /// Set to to disable the retry entirely. Default: 1.5 seconds. + /// + public TimeSpan EvictionRetryWindow { get; set; } = TimeSpan.FromSeconds(1.5); + + /// + /// How often the multiplexer is polled for a restored connection while inside + /// . Default: 50 milliseconds. + /// + public TimeSpan ReconnectPollInterval { get; set; } = TimeSpan.FromMilliseconds(50); + + /// + /// Page size for the SCAN cursor and the batch size for the DEL calls used by + /// prefix eviction. Default: 250. + /// + public int ScanPageSize { get; set; } = 250; + } +} diff --git a/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs b/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs index 41d61fb..ad8a112 100644 --- a/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs +++ b/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs @@ -4,33 +4,36 @@ using System.Threading; using System.Threading.Tasks; using CacheWeave.Legacy.Abstractions; +using Microsoft.Extensions.Options; using StackExchange.Redis; namespace CacheWeave.Legacy.Providers { public sealed class RedisCacheProvider : ICacheProviderInner { - /// - /// How long an eviction waits for the multiplexer to reconnect before giving up. Reads and writes - /// fail fast — a dropped one is just a cache miss — but a dropped eviction leaves a stale entry - /// being served until it expires, so evictions ride out a brief failover instead. - /// - private static readonly TimeSpan DefaultEvictionRetryWindow = TimeSpan.FromSeconds(1.5); - - private static readonly TimeSpan ReconnectPollInterval = TimeSpan.FromMilliseconds(50); - private readonly IConnectionMultiplexer _multiplexer; - private readonly TimeSpan _evictionRetryWindow; + private readonly RedisCacheOptions _options; + /// Uses the default . public RedisCacheProvider(IConnectionMultiplexer multiplexer) - : this(multiplexer, DefaultEvictionRetryWindow) + : this(multiplexer, Options.Create(new RedisCacheOptions())) { } - internal RedisCacheProvider(IConnectionMultiplexer multiplexer, TimeSpan evictionRetryWindow) + public RedisCacheProvider(IConnectionMultiplexer multiplexer, IOptions options) { _multiplexer = multiplexer; - _evictionRetryWindow = evictionRetryWindow; + _options = options.Value; + + if (_options.EvictionRetryWindow < TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), + nameof(RedisCacheOptions.EvictionRetryWindow) + " cannot be negative."); + if (_options.ReconnectPollInterval <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), + nameof(RedisCacheOptions.ReconnectPollInterval) + " must be greater than zero."); + if (_options.ScanPageSize < 1) + throw new ArgumentOutOfRangeException(nameof(options), + nameof(RedisCacheOptions.ScanPageSize) + " must be at least 1."); } private IDatabase Db => _multiplexer.GetDatabase(); @@ -52,17 +55,18 @@ public Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationTok private async Task ScanAndDeleteAsync(string prefix) { + var batchSize = _options.ScanPageSize; var db = Db; foreach (var server in _multiplexer.GetServers()) { if (server.IsReplica) continue; - var batch = new List(250); - await foreach (var key in server.KeysAsync(pattern: $"{prefix}*", pageSize: 250).ConfigureAwait(false)) + var batch = new List(batchSize); + await foreach (var key in server.KeysAsync(pattern: $"{prefix}*", pageSize: batchSize).ConfigureAwait(false)) { batch.Add(key); - if (batch.Count == 250) + if (batch.Count == batchSize) { await db.KeyDeleteAsync(batch.ToArray()).ConfigureAwait(false); batch.Clear(); @@ -76,8 +80,8 @@ private async Task ScanAndDeleteAsync(string prefix) /// /// Runs an eviction, retrying once if the connection was unavailable but comes back within - /// . Deleting an already-deleted key is a no-op, so replaying - /// a partially applied eviction is safe. + /// . Deleting an already-deleted key is a + /// no-op, so replaying a partially applied eviction is safe. /// private async Task EvictAsync(Func evict, CancellationToken cancellationToken) { @@ -88,7 +92,8 @@ private async Task EvictAsync(Func evict, CancellationToken cancellationTo } catch (RedisConnectionException) { - if (!await WaitForReconnectAsync(cancellationToken).ConfigureAwait(false)) + if (_options.EvictionRetryWindow <= TimeSpan.Zero + || !await WaitForReconnectAsync(cancellationToken).ConfigureAwait(false)) throw; } @@ -101,10 +106,10 @@ private async Task WaitForReconnectAsync(CancellationToken cancellationTok while (!_multiplexer.IsConnected) { - if (stopwatch.Elapsed >= _evictionRetryWindow || cancellationToken.IsCancellationRequested) + if (stopwatch.Elapsed >= _options.EvictionRetryWindow || cancellationToken.IsCancellationRequested) return false; - await Task.Delay(ReconnectPollInterval, cancellationToken).ConfigureAwait(false); + await Task.Delay(_options.ReconnectPollInterval, cancellationToken).ConfigureAwait(false); } return true; diff --git a/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs b/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs index 9d430ba..11c88a3 100644 --- a/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs +++ b/src/CacheWeave.Redis/Extensions/ServiceCollectionExtensions.cs @@ -16,38 +16,79 @@ public static class ServiceCollectionExtensions public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string redisConnectionString) - => services.AddCacheWeaveRedis(redisConnectionString, configure: null); + => services.AddCacheWeaveRedis(redisConnectionString, configureConnection: null); /// /// Registers CacheWeave with a Redis backing store via , - /// allowing the parsed to be customised. + /// allowing both the connection and the provider's own behaviour to be customised. /// /// /// Redis is treated as optional: is false /// and is , so an /// unreachable Redis degrades to an immediate cache miss instead of blocking every command for - /// syncTimeout. runs after these defaults and can override them. - /// If an is already registered, it is used as-is. + /// syncTimeout. runs after these defaults and can + /// override them. If an is already registered, it is used as-is. /// /// The service collection. /// Redis connection string (e.g. "localhost:6379"). - /// Optional callback to adjust the connection options (TLS, auth, timeouts, etc.). + /// Adjusts the connection options (TLS, auth, timeouts, backlog policy). + /// Adjusts provider behaviour (eviction retry, SCAN page size). public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string redisConnectionString, - Action? configure) + Action? configureConnection, + Action? configureCache = null) { services.AddCacheWeave(); + services.ConfigureRedisCache(configureCache); if (string.IsNullOrWhiteSpace(redisConnectionString)) return services; services.TryAddSingleton(_ => - ConnectionMultiplexer.Connect(BuildConfigurationOptions(redisConnectionString, configure))); + ConnectionMultiplexer.Connect(BuildConfigurationOptions(redisConnectionString, configureConnection))); services.AddSingleton(); return services; } + /// + /// Registers CacheWeave with an existing instance. + /// Use this overload if your app already registers Redis separately. + /// + public static IServiceCollection AddCacheWeaveRedis( + this IServiceCollection services, + IConnectionMultiplexer multiplexer) + => services.AddCacheWeaveRedis(multiplexer, configureCache: null); + + /// + /// Registers CacheWeave with an existing instance, + /// allowing the provider's own behaviour to be customised. + /// + /// The service collection. + /// The connection to use. Its options are the caller's to set. + /// Adjusts provider behaviour (eviction retry, SCAN page size). + public static IServiceCollection AddCacheWeaveRedis( + this IServiceCollection services, + IConnectionMultiplexer multiplexer, + Action? configureCache) + { + services.AddCacheWeave(); + services.ConfigureRedisCache(configureCache); + services.AddSingleton(multiplexer); + services.AddSingleton(); + return services; + } + + private static void ConfigureRedisCache( + this IServiceCollection services, + Action? configureCache) + { + if (configureCache is not null) + services.Configure(configureCache); + else + services.AddOptions(); + } + internal static ConfigurationOptions BuildConfigurationOptions( string redisConnectionString, Action? configure) @@ -62,18 +103,4 @@ internal static ConfigurationOptions BuildConfigurationOptions( configure?.Invoke(options); return options; } - - /// - /// Registers CacheWeave with an existing instance. - /// Use this overload if your app already registers Redis separately. - /// - public static IServiceCollection AddCacheWeaveRedis( - this IServiceCollection services, - IConnectionMultiplexer multiplexer) - { - services.AddCacheWeave(); - services.AddSingleton(multiplexer); - services.AddSingleton(); - return services; - } } diff --git a/src/CacheWeave.Redis/RedisCacheOptions.cs b/src/CacheWeave.Redis/RedisCacheOptions.cs new file mode 100644 index 0000000..100b9ea --- /dev/null +++ b/src/CacheWeave.Redis/RedisCacheOptions.cs @@ -0,0 +1,29 @@ +namespace CacheWeave.Redis; + +/// +/// Tuning knobs for . Connection-level settings +/// (timeouts, TLS, BacklogPolicy) are configured separately, via the +/// callback on AddCacheWeaveRedis. +/// +public sealed class RedisCacheOptions +{ + /// + /// How long an eviction waits for the multiplexer to reconnect before giving up, so a delete + /// issued during a failover still lands rather than leaving a stale entry served until it expires. + /// Reads and writes are unaffected — they always fail fast, since a dropped one is just a cache miss. + /// Set to to disable the retry entirely. Default: 1.5 seconds. + /// + public TimeSpan EvictionRetryWindow { get; set; } = TimeSpan.FromSeconds(1.5); + + /// + /// How often the multiplexer is polled for a restored connection while inside + /// . Default: 50 milliseconds. + /// + public TimeSpan ReconnectPollInterval { get; set; } = TimeSpan.FromMilliseconds(50); + + /// + /// Page size for the SCAN cursor and the batch size for the DEL calls used by + /// prefix eviction. Default: 250. + /// + public int ScanPageSize { get; set; } = 250; +} diff --git a/src/CacheWeave.Redis/RedisCacheProvider.cs b/src/CacheWeave.Redis/RedisCacheProvider.cs index d9fa282..851d7e7 100644 --- a/src/CacheWeave.Redis/RedisCacheProvider.cs +++ b/src/CacheWeave.Redis/RedisCacheProvider.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using CacheWeave.Core.Abstractions; +using Microsoft.Extensions.Options; using StackExchange.Redis; @@ -11,27 +12,29 @@ namespace CacheWeave.Redis; /// public sealed class RedisCacheProvider : ICacheProviderInner { - /// - /// How long an eviction waits for the multiplexer to reconnect before giving up. Reads and writes - /// fail fast — a dropped one is just a cache miss — but a dropped eviction leaves a stale entry - /// being served until it expires, so evictions ride out a brief failover instead. - /// - private static readonly TimeSpan DefaultEvictionRetryWindow = TimeSpan.FromSeconds(1.5); - - private static readonly TimeSpan ReconnectPollInterval = TimeSpan.FromMilliseconds(50); - private readonly IConnectionMultiplexer _multiplexer; - private readonly TimeSpan _evictionRetryWindow; + private readonly RedisCacheOptions _options; + /// Uses the default . public RedisCacheProvider(IConnectionMultiplexer multiplexer) - : this(multiplexer, DefaultEvictionRetryWindow) + : this(multiplexer, Options.Create(new RedisCacheOptions())) { } - internal RedisCacheProvider(IConnectionMultiplexer multiplexer, TimeSpan evictionRetryWindow) + public RedisCacheProvider(IConnectionMultiplexer multiplexer, IOptions options) { _multiplexer = multiplexer; - _evictionRetryWindow = evictionRetryWindow; + _options = options.Value; + + if (_options.EvictionRetryWindow < TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), + $"{nameof(RedisCacheOptions.EvictionRetryWindow)} cannot be negative."); + if (_options.ReconnectPollInterval <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), + $"{nameof(RedisCacheOptions.ReconnectPollInterval)} must be greater than zero."); + if (_options.ScanPageSize < 1) + throw new ArgumentOutOfRangeException(nameof(options), + $"{nameof(RedisCacheOptions.ScanPageSize)} must be at least 1."); } private IDatabase Db => _multiplexer.GetDatabase(); @@ -55,7 +58,7 @@ public Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationTok private async Task ScanAndDeleteAsync(string prefix, CancellationToken cancellationToken) { - const int batchSize = 250; + var batchSize = _options.ScanPageSize; var pattern = $"{prefix}*"; var db = Db; var batch = new List(batchSize); @@ -86,8 +89,8 @@ private async Task ScanAndDeleteAsync(string prefix, CancellationToken cancellat /// /// Runs an eviction, retrying once if the connection was unavailable but comes back within - /// . Deleting an already-deleted key is a no-op, so replaying - /// a partially applied eviction is safe. + /// . Deleting an already-deleted key is a + /// no-op, so replaying a partially applied eviction is safe. /// private async Task EvictAsync(Func evict, CancellationToken cancellationToken) { @@ -98,7 +101,7 @@ private async Task EvictAsync(Func evict, CancellationToken cancellationTo } catch (RedisConnectionException) { - if (!await WaitForReconnectAsync(cancellationToken)) + if (_options.EvictionRetryWindow <= TimeSpan.Zero || !await WaitForReconnectAsync(cancellationToken)) throw; } @@ -111,10 +114,10 @@ private async Task WaitForReconnectAsync(CancellationToken cancellationTok while (!_multiplexer.IsConnected) { - if (stopwatch.Elapsed >= _evictionRetryWindow || cancellationToken.IsCancellationRequested) + if (stopwatch.Elapsed >= _options.EvictionRetryWindow || cancellationToken.IsCancellationRequested) return false; - await Task.Delay(ReconnectPollInterval, cancellationToken); + await Task.Delay(_options.ReconnectPollInterval, cancellationToken); } return true; diff --git a/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs b/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs index 0cf8956..ac54c44 100644 --- a/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs +++ b/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using CacheWeave.Legacy.Providers; using FluentAssertions; +using Microsoft.Extensions.Options; using Moq; using StackExchange.Redis; using Xunit; @@ -25,7 +26,10 @@ private RedisCacheProvider MakeSut(bool reconnects) return new RedisCacheProvider( _multiplexer.Object, - reconnects ? TimeSpan.FromSeconds(1) : TimeSpan.Zero); + Options.Create(new RedisCacheOptions + { + EvictionRetryWindow = reconnects ? TimeSpan.FromSeconds(1) : TimeSpan.Zero + })); } private static RedisConnectionException Disconnected() diff --git a/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs b/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs index 21e7bd0..34842d0 100644 --- a/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs +++ b/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs @@ -2,6 +2,7 @@ using CacheWeave.Redis.Extensions; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Moq; using StackExchange.Redis; using Xunit; @@ -101,6 +102,54 @@ public void AddCacheWeaveRedis_BlankConnectionString_RegistersNoMultiplexer() services.Should().NotContain(d => d.ServiceType == typeof(IConnectionMultiplexer)); } + // ------------------------------------------------------------------------- + // RedisCacheOptions — provider behaviour knobs + // ------------------------------------------------------------------------- + + [Fact] + public void AddCacheWeaveRedis_DefaultsRedisCacheOptions_WhenNotConfigured() + { + var sp = new ServiceCollection() + .AddLogging() + .AddCacheWeaveRedis("localhost:6379") + .BuildServiceProvider(); + + var options = sp.GetRequiredService>().Value; + + options.EvictionRetryWindow.Should().Be(TimeSpan.FromSeconds(1.5)); + options.ReconnectPollInterval.Should().Be(TimeSpan.FromMilliseconds(50)); + options.ScanPageSize.Should().Be(250); + } + + [Fact] + public void AddCacheWeaveRedis_AppliesConfigureCache() + { + var sp = new ServiceCollection() + .AddLogging() + .AddCacheWeaveRedis("localhost:6379", configureConnection: null, configureCache: o => + { + o.EvictionRetryWindow = TimeSpan.Zero; + o.ScanPageSize = 1000; + }) + .BuildServiceProvider(); + + var options = sp.GetRequiredService>().Value; + + options.EvictionRetryWindow.Should().Be(TimeSpan.Zero); + options.ScanPageSize.Should().Be(1000); + } + + [Fact] + public void AddCacheWeaveRedis_MultiplexerOverload_AppliesConfigureCache() + { + var sp = new ServiceCollection() + .AddLogging() + .AddCacheWeaveRedis(new Mock().Object, o => o.ScanPageSize = 25) + .BuildServiceProvider(); + + sp.GetRequiredService>().Value.ScanPageSize.Should().Be(25); + } + // ------------------------------------------------------------------------- // Behaviour against an unreachable Redis // ------------------------------------------------------------------------- diff --git a/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs b/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs index 4308f30..1ae7a4d 100644 --- a/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs +++ b/tests/CacheWeave.Tests/Providers/RedisCacheProviderTests.cs @@ -1,5 +1,6 @@ using CacheWeave.Redis; using FluentAssertions; +using Microsoft.Extensions.Options; using Moq; using StackExchange.Redis; using Xunit; @@ -190,9 +191,17 @@ private RedisCacheProvider MakeSutForEviction(bool reconnects) _multiplexer.Setup(m => m.IsConnected).Returns(reconnects); // Zero window when the connection never returns, so the test doesn't wait for it - return new RedisCacheProvider( - _multiplexer.Object, - reconnects ? TimeSpan.FromSeconds(1) : TimeSpan.Zero); + return MakeSut(o => o.EvictionRetryWindow = reconnects ? TimeSpan.FromSeconds(1) : TimeSpan.Zero); + } + + private RedisCacheProvider MakeSut(Action configure) + { + _multiplexer.Setup(m => m.GetDatabase(It.IsAny(), It.IsAny())).Returns(_db.Object); + _multiplexer.Setup(m => m.GetServers()).Returns([_server.Object]); + + var options = new RedisCacheOptions(); + configure(options); + return new RedisCacheProvider(_multiplexer.Object, Options.Create(options)); } private static RedisConnectionException Disconnected() @@ -251,11 +260,65 @@ public async Task RemoveAsync_RetriesOnce_WhenConnectionReturnsAfterAPoll() .ThrowsAsync(Disconnected()) .ReturnsAsync(true); - var sut = new RedisCacheProvider(_multiplexer.Object, TimeSpan.FromSeconds(5)); + var sut = MakeSut(o => o.EvictionRetryWindow = TimeSpan.FromSeconds(5)); await sut.RemoveAsync("k"); _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Exactly(2)); } + [Fact] + public async Task RemoveAsync_DoesNotRetry_WhenRetryWindowIsZero() + { + _multiplexer.Setup(m => m.GetDatabase(It.IsAny(), It.IsAny())).Returns(_db.Object); + _multiplexer.Setup(m => m.IsConnected).Returns(true); + _db.Setup(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(Disconnected()); + + // Zero window opts out of the retry even though the connection is available + var sut = MakeSut(o => o.EvictionRetryWindow = TimeSpan.Zero); + + await sut.Invoking(s => s.RemoveAsync("k")) + .Should().ThrowAsync(); + _db.Verify(d => d.KeyDeleteAsync((RedisKey)"k", It.IsAny()), Times.Once); + } + + [Fact] + public async Task RemoveByPrefixAsync_BatchesAtConfiguredScanPageSize() + { + var keys = Enumerable.Range(0, 5).Select(i => (RedisKey)$"products:{i}").ToArray(); + _server.Setup(s => s.KeysAsync(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(() => keys.ToAsyncEnumerable()); + _db.Setup(d => d.KeyDeleteAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(2); + + var sut = MakeSut(o => o.ScanPageSize = 2); + await sut.RemoveByPrefixAsync("products:"); + + // 5 keys at a page size of 2 → batches of 2, 2 and a final 1 + _db.Verify(d => d.KeyDeleteAsync(It.Is(k => k.Length == 2), It.IsAny()), Times.Exactly(2)); + _db.Verify(d => d.KeyDeleteAsync(It.Is(k => k.Length == 1), It.IsAny()), Times.Once); + _server.Verify(s => s.KeysAsync(It.IsAny(), It.IsAny(), 2, + It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + } + + [Theory] + [InlineData(-1, 50, 250)] // negative retry window + [InlineData(1500, 0, 250)] // non-positive poll interval + [InlineData(1500, 50, 0)] // scan page size below 1 + public void Constructor_Throws_WhenOptionsAreOutOfRange(int windowMs, int pollMs, int scanPageSize) + { + var options = Options.Create(new RedisCacheOptions + { + EvictionRetryWindow = TimeSpan.FromMilliseconds(windowMs), + ReconnectPollInterval = TimeSpan.FromMilliseconds(pollMs), + ScanPageSize = scanPageSize + }); + + var act = () => new RedisCacheProvider(_multiplexer.Object, options); + + act.Should().Throw(); + } + [Fact] public async Task GetAsync_DoesNotRetry_WhenConnectionFails() { From d5711cd1501bb4a28389b5f174c6d779346aaf03 Mon Sep 17 00:00:00 2001 From: Aghogho Bernard Date: Sun, 20 Sep 2026 00:32:56 -0230 Subject: [PATCH 4/4] docs: correct README licence to MIT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README said GPL-3.0 while LICENSE, Directory.Build.props and every csproj declare MIT, so the packaged README contradicted the package metadata it shipped alongside. A licence review before adoption would stall on the discrepancy. MIT is the real licence — the switch happened in feature/switch-to-mit-license, which updated LICENSE and the package metadata but missed this line. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8da6a4f..b56bc5d 100644 --- a/README.md +++ b/README.md @@ -287,4 +287,4 @@ public class ProductService(ICacheWeaveService cache) ## License -GPL-3.0 — see [LICENSE](LICENSE). +MIT — see [LICENSE](LICENSE).