diff --git a/README.md b/README.md index 8da6a4f..7d128de 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,58 @@ 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", + 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 + +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. 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 +cache and your data have diverged. + --- ## .NET Framework 4.8 Support (`CacheWeave.Legacy`) @@ -287,4 +339,4 @@ public class ProductService(ICacheWeaveService cache) ## License -GPL-3.0 — see [LICENSE](LICENSE). +MIT — see [LICENSE](LICENSE). 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..77457eb 100644 --- a/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs +++ b/src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs @@ -77,25 +77,81 @@ public static IServiceCollection AddCacheWeave( public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string connectionString) + => services.AddCacheWeaveRedis(connectionString, configureConnection: 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. + /// + /// 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? configureConnection, + Action? configureCache = null) { - var configOpts = ConfigurationOptions.Parse(connectionString); - configOpts.AbortOnConnectFail = false; + var configOpts = BuildRedisConfigurationOptions(connectionString, configureConnection); + services.ConfigureRedisCache(configureCache); 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, 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 cbbb767..ad8a112 100644 --- a/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs +++ b/src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using CacheWeave.Legacy.Abstractions; +using Microsoft.Extensions.Options; using StackExchange.Redis; namespace CacheWeave.Legacy.Providers @@ -10,10 +12,28 @@ namespace CacheWeave.Legacy.Providers public sealed class RedisCacheProvider : ICacheProviderInner { private readonly IConnectionMultiplexer _multiplexer; + private readonly RedisCacheOptions _options; + /// Uses the default . public RedisCacheProvider(IConnectionMultiplexer multiplexer) + : this(multiplexer, Options.Create(new RedisCacheOptions())) + { + } + + public RedisCacheProvider(IConnectionMultiplexer multiplexer, IOptions options) { _multiplexer = multiplexer; + _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(); @@ -28,21 +48,25 @@ 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 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(); @@ -53,5 +77,42 @@ 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 (_options.EvictionRetryWindow <= TimeSpan.Zero + || !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 >= _options.EvictionRetryWindow || cancellationToken.IsCancellationRequested) + return false; + + await Task.Delay(_options.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..11c88a3 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,18 +16,37 @@ public static class ServiceCollectionExtensions public static IServiceCollection AddCacheWeaveRedis( this IServiceCollection services, string redisConnectionString) + => services.AddCacheWeaveRedis(redisConnectionString, configureConnection: null); + + /// + /// Registers CacheWeave with a Redis backing store via , + /// 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. + /// + /// The service collection. + /// Redis connection string (e.g. "localhost:6379"). + /// 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? configureConnection, + Action? configureCache = null) { services.AddCacheWeave(); + services.ConfigureRedisCache(configureCache); 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, configureConnection))); services.AddSingleton(); return services; } @@ -38,10 +58,49 @@ public static IServiceCollection AddCacheWeaveRedis( 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) + { + 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; + } } 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 0e9b83a..851d7e7 100644 --- a/src/CacheWeave.Redis/RedisCacheProvider.cs +++ b/src/CacheWeave.Redis/RedisCacheProvider.cs @@ -1,4 +1,6 @@ +using System.Diagnostics; using CacheWeave.Core.Abstractions; +using Microsoft.Extensions.Options; using StackExchange.Redis; @@ -11,10 +13,28 @@ namespace CacheWeave.Redis; public sealed class RedisCacheProvider : ICacheProviderInner { private readonly IConnectionMultiplexer _multiplexer; + private readonly RedisCacheOptions _options; + /// Uses the default . public RedisCacheProvider(IConnectionMultiplexer multiplexer) + : this(multiplexer, Options.Create(new RedisCacheOptions())) + { + } + + public RedisCacheProvider(IConnectionMultiplexer multiplexer, IOptions options) { _multiplexer = multiplexer; + _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(); @@ -30,14 +50,15 @@ 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 async Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + public Task RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + => EvictAsync(() => ScanAndDeleteAsync(prefix, cancellationToken), cancellationToken); + + 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); @@ -65,4 +86,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 (_options.EvictionRetryWindow <= TimeSpan.Zero || !await WaitForReconnectAsync(cancellationToken)) + throw; + } + + await evict(); + } + + private async Task WaitForReconnectAsync(CancellationToken cancellationToken) + { + var stopwatch = Stopwatch.StartNew(); + + while (!_multiplexer.IsConnected) + { + if (stopwatch.Elapsed >= _options.EvictionRetryWindow || cancellationToken.IsCancellationRequested) + return false; + + await Task.Delay(_options.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..ac54c44 --- /dev/null +++ b/tests/CacheWeave.Legacy.Tests/Providers/RedisCacheProviderTests.cs @@ -0,0 +1,108 @@ +using System; +using System.Threading.Tasks; +using CacheWeave.Legacy.Providers; +using FluentAssertions; +using Microsoft.Extensions.Options; +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, + Options.Create(new RedisCacheOptions + { + EvictionRetryWindow = 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..34842d0 --- /dev/null +++ b/tests/CacheWeave.Tests/Extensions/RedisServiceCollectionExtensionsTests.cs @@ -0,0 +1,172 @@ +using CacheWeave.Redis; +using CacheWeave.Redis.Extensions; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +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)); + } + + // ------------------------------------------------------------------------- + // 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 + // ------------------------------------------------------------------------- + + [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..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; @@ -178,6 +179,159 @@ 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 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() + => 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 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 = 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() + { + _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