Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down Expand Up @@ -287,4 +339,4 @@ public class ProductService(ICacheWeaveService cache)

## License

GPL-3.0 — see [LICENSE](LICENSE).
MIT — see [LICENSE](LICENSE).
4 changes: 4 additions & 0 deletions src/CacheWeave.Legacy/CacheWeave.Legacy.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
<None Include="../../README.md" Pack="true" PackagePath="\" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="CacheWeave.Legacy.Tests" />
</ItemGroup>

<ItemGroup>
<!-- Core DI and options abstractions compatible with net48 -->
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
Expand Down
60 changes: 58 additions & 2 deletions src/CacheWeave.Legacy/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,25 +77,81 @@ public static IServiceCollection AddCacheWeave(
public static IServiceCollection AddCacheWeaveRedis(
this IServiceCollection services,
string connectionString)
=> services.AddCacheWeaveRedis(connectionString, configureConnection: null);

/// <summary>
/// Registers the Redis provider using a connection string, allowing the parsed
/// <see cref="ConfigurationOptions"/> to be customised.
/// </summary>
/// <remarks>
/// Redis is treated as optional: <see cref="ConfigurationOptions.AbortOnConnectFail"/> is <c>false</c>
/// and <see cref="ConfigurationOptions.BacklogPolicy"/> is <see cref="BacklogPolicy.FailFast"/>, so an
/// unreachable Redis degrades to an immediate cache miss instead of blocking every command for
/// <c>syncTimeout</c>. <paramref name="configureConnection"/> runs after these defaults and can override them.
/// </remarks>
/// <param name="configureConnection">Adjusts the connection options (TLS, auth, timeouts, backlog policy).</param>
/// <param name="configureCache">Adjusts provider behaviour (eviction retry, SCAN page size).</param>
public static IServiceCollection AddCacheWeaveRedis(
this IServiceCollection services,
string connectionString,
Action<ConfigurationOptions>? configureConnection,
Action<RedisCacheOptions>? configureCache = null)
{
var configOpts = ConfigurationOptions.Parse(connectionString);
configOpts.AbortOnConnectFail = false;
var configOpts = BuildRedisConfigurationOptions(connectionString, configureConnection);
services.ConfigureRedisCache(configureCache);
services.TryAddSingleton<IConnectionMultiplexer>(_ =>
ConnectionMultiplexer.Connect(configOpts));
services.TryAddSingleton<ICacheProviderInner, RedisCacheProvider>();
return services;
}

internal static ConfigurationOptions BuildRedisConfigurationOptions(
string connectionString,
Action<ConfigurationOptions>? 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;
}

/// <summary>Registers the Redis provider using an existing <see cref="IConnectionMultiplexer"/>.</summary>
public static IServiceCollection AddCacheWeaveRedis(
this IServiceCollection services,
IConnectionMultiplexer multiplexer)
=> services.AddCacheWeaveRedis(multiplexer, configureCache: null);

/// <summary>
/// Registers the Redis provider using an existing <see cref="IConnectionMultiplexer"/>,
/// allowing the provider's own behaviour to be customised.
/// </summary>
/// <param name="configureCache">Adjusts provider behaviour (eviction retry, SCAN page size).</param>
public static IServiceCollection AddCacheWeaveRedis(
this IServiceCollection services,
IConnectionMultiplexer multiplexer,
Action<RedisCacheOptions>? configureCache)
{
services.ConfigureRedisCache(configureCache);
services.TryAddSingleton(multiplexer);
services.TryAddSingleton<ICacheProviderInner, RedisCacheProvider>();
return services;
}

private static void ConfigureRedisCache(
this IServiceCollection services,
Action<RedisCacheOptions>? configureCache)
{
if (configureCache != null)
services.Configure(configureCache);
else
services.AddOptions<RedisCacheOptions>();
}

// ── InMemory ─────────────────────────────────────────────────────────

/// <summary>
Expand Down
32 changes: 32 additions & 0 deletions src/CacheWeave.Legacy/Providers/RedisCacheOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;

namespace CacheWeave.Legacy.Providers
{
/// <summary>
/// Tuning knobs for <see cref="RedisCacheProvider"/>. Connection-level settings
/// (timeouts, TLS, BacklogPolicy) are configured separately, via the
/// <see cref="StackExchange.Redis.ConfigurationOptions"/> callback on AddCacheWeaveRedis.
/// </summary>
public sealed class RedisCacheOptions
{
/// <summary>
/// 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 <see cref="TimeSpan.Zero"/> to disable the retry entirely. Default: 1.5 seconds.
/// </summary>
public TimeSpan EvictionRetryWindow { get; set; } = TimeSpan.FromSeconds(1.5);

/// <summary>
/// How often the multiplexer is polled for a restored connection while inside
/// <see cref="EvictionRetryWindow"/>. Default: 50 milliseconds.
/// </summary>
public TimeSpan ReconnectPollInterval { get; set; } = TimeSpan.FromMilliseconds(50);

/// <summary>
/// Page size for the SCAN cursor and the batch size for the DEL calls used by
/// prefix eviction. Default: 250.
/// </summary>
public int ScanPageSize { get; set; } = 250;
}
}
71 changes: 66 additions & 5 deletions src/CacheWeave.Legacy/Providers/RedisCacheProvider.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@
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
{
public sealed class RedisCacheProvider : ICacheProviderInner
{
private readonly IConnectionMultiplexer _multiplexer;
private readonly RedisCacheOptions _options;

/// <summary>Uses the default <see cref="RedisCacheOptions"/>.</summary>
public RedisCacheProvider(IConnectionMultiplexer multiplexer)
: this(multiplexer, Options.Create(new RedisCacheOptions()))
{
}

public RedisCacheProvider(IConnectionMultiplexer multiplexer, IOptions<RedisCacheOptions> 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();
Expand All @@ -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<RedisKey>(250);
await foreach (var key in server.KeysAsync(pattern: $"{prefix}*", pageSize: 250).ConfigureAwait(false))
var batch = new List<RedisKey>(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();
Expand All @@ -53,5 +77,42 @@ public async Task RemoveByPrefixAsync(string prefix, CancellationToken cancellat
await db.KeyDeleteAsync(batch.ToArray()).ConfigureAwait(false);
}
}

/// <summary>
/// Runs an eviction, retrying once if the connection was unavailable but comes back within
/// <see cref="RedisCacheOptions.EvictionRetryWindow"/>. Deleting an already-deleted key is a
/// no-op, so replaying a partially applied eviction is safe.
/// </summary>
private async Task EvictAsync(Func<Task> 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<bool> 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;
}
}
}
4 changes: 4 additions & 0 deletions src/CacheWeave.Redis/CacheWeave.Redis.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
<None Include="../../README.md" Pack="true" PackagePath="\" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="CacheWeave.Tests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CacheWeave.Core\CacheWeave.Core.csproj" />
</ItemGroup>
Expand Down
Loading
Loading