Skip to content

Support for never expire cache items when expiration time is null #88

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 21, 2025
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
28 changes: 23 additions & 5 deletions CachingTest/DatabaseOperationsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,17 +273,35 @@ await Assert.ThrowsAsync<InvalidOperationException>(() =>
}

[Fact]
public async Task SetCacheItem_WithNoExpiration_ThrowsInvalidOperationException()
public async Task SetCacheItem_WithNoExpiration_Should_Work()
{
// Arrange
await InitializeAsync();
Assert.NotNull(_databaseOperations);
var key = "no-expiration-test";
var value = new byte[] { 1, 2, 3 };
var value = new byte[]
{
1, 2, 3
};

// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(() =>
_databaseOperations!.SetCacheItemAsync(key, value, new DistributedCacheEntryOptions(), CancellationToken.None));
var operations = new DatabaseOperations(Options.Create(
new PostgreSqlCacheOptions
{
ConnectionString = _postgresContainer.GetConnectionString(),
SchemaName = "cache",
TableName = "distributed_cache",
CreateInfrastructure = true,
DefaultSlidingExpiration = null
}),
_logger);

// Act
await operations.SetCacheItemAsync(key, value, new DistributedCacheEntryOptions(), CancellationToken.None);

var result = await operations.GetCacheItemAsync(key, CancellationToken.None);

// Assert
Assert.NotNull(result);
}

[Fact]
Expand Down
4 changes: 0 additions & 4 deletions CachingTest/DatabaseResilienceIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,6 @@
dbOperations.SetCacheItem("test-key", new byte[] { 1, 2, 3 },
new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.UtcNow.AddMinutes(-1) }));

Assert.Throws<InvalidOperationException>(() =>
dbOperations.SetCacheItem("test-key", new byte[] { 1, 2, 3 },
new DistributedCacheEntryOptions()));

await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
dbOperations.SetCacheItemAsync("test-key", new byte[] { 1, 2, 3 },
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(-1) },
Expand All @@ -183,7 +179,7 @@
}

[Fact]
public async Task DatabaseOperations_PerformanceUnderFailure_ShouldNotExceedThresholds()

Check warning on line 182 in CachingTest/DatabaseResilienceIntegrationTests.cs

View workflow job for this annotation

GitHub Actions / build-test-coverage

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 182 in CachingTest/DatabaseResilienceIntegrationTests.cs

View workflow job for this annotation

GitHub Actions / build-test-coverage

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
// Arrange
var invalidConnectionString = "Host=nonexistent-host;Database=test;Username=test;Password=test";
Expand Down Expand Up @@ -354,7 +350,7 @@
}

[Fact]
public async Task DatabaseOperations_LongRunningOperations_ShouldRespectTimeout()

Check warning on line 353 in CachingTest/DatabaseResilienceIntegrationTests.cs

View workflow job for this annotation

GitHub Actions / build-test-coverage

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 353 in CachingTest/DatabaseResilienceIntegrationTests.cs

View workflow job for this annotation

GitHub Actions / build-test-coverage

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
// Arrange - Use a very short timeout to test timeout behavior
var invalidConnectionString = "Host=nonexistent-host;Database=test;Username=test;Password=test";
Expand Down
4 changes: 2 additions & 2 deletions CachingTest/SqlCommandsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void GetCacheItemSql_WithValidParameters_GeneratesCorrectSql()
// Assert
Assert.Contains("SELECT \"Value\"", sql);
Assert.Contains("FROM \"test_schema\".\"test_table\"", sql);
Assert.Contains("WHERE \"Id\" = @Id AND @UtcNow <= \"ExpiresAtTime\"", sql);
Assert.Contains("WHERE \"Id\" = @Id AND (\"ExpiresAtTime\" IS NULL OR @UtcNow <= \"ExpiresAtTime\")", sql);
}

[Fact]
Expand Down Expand Up @@ -83,7 +83,7 @@ public void UpdateCacheItemSql_WithValidParameters_GeneratesCorrectSql()
Assert.Contains("UPDATE \"test_schema\".\"test_table\"", sql);
Assert.Contains("SET \"ExpiresAtTime\" = LEAST(\"AbsoluteExpiration\", @UtcNow + \"SlidingExpirationInSeconds\" * interval '1 second')", sql);
Assert.Contains("WHERE \"Id\" = @Id", sql);
Assert.Contains("AND @UtcNow <= \"ExpiresAtTime\"", sql);
Assert.Contains("AND (\"ExpiresAtTime\" IS NULL OR @UtcNow <= \"ExpiresAtTime\")", sql);
Assert.Contains("AND \"SlidingExpirationInSeconds\" IS NOT NULL", sql);
Assert.Contains("AND (\"AbsoluteExpiration\" IS NULL OR \"AbsoluteExpiration\" <> \"ExpiresAtTime\")", sql);
}
Expand Down
22 changes: 10 additions & 12 deletions Extensions.Caching.PostgreSql/DatabaseOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,10 @@ public void SetCacheItem(string key, byte[] value, DistributedCacheEntryOptions
var utcNow = SystemClock.UtcNow;

var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);

using var connection = ConnectionFactory();

var expiresAtTime = options.SlidingExpiration == null
? absoluteExpiration!.Value
: utcNow.Add(options.SlidingExpiration.Value);
var expiresAtTime = GetExpiresAtTime(utcNow, absoluteExpiration, options.SlidingExpiration);

var setCache = new CommandDefinition(
SqlCommands.SetCacheSql,
Expand All @@ -238,13 +235,10 @@ await ExecuteWithResilienceAsync(async () =>
var utcNow = SystemClock.UtcNow;

var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);

await using var connection = ConnectionFactory();

var expiresAtTime = options.SlidingExpiration == null
? absoluteExpiration!.Value
: utcNow.Add(options.SlidingExpiration.Value);
var expiresAtTime = GetExpiresAtTime(utcNow, absoluteExpiration, options.SlidingExpiration);

var setCache = new CommandDefinition(
SqlCommands.SetCacheSql,
Expand Down Expand Up @@ -336,13 +330,17 @@ private async Task<byte[]> GetCacheItemAsync(string key, bool includeValue, Canc
return absoluteExpiration;
}

private void ValidateOptions(TimeSpan? slidingExpiration, DateTimeOffset? absoluteExpiration)
private DateTimeOffset? GetExpiresAtTime(DateTimeOffset utcNow, DateTimeOffset? absoluteExpiration, TimeSpan? slidingExpiration)
{
if (!slidingExpiration.HasValue && !absoluteExpiration.HasValue)
if (!slidingExpiration.HasValue)
{
throw new InvalidOperationException("Either absolute or sliding expiration needs " +
"to be provided.");
return absoluteExpiration;
}

var expiration = utcNow.Add(slidingExpiration.Value);

// Pick whichever comes first: the absolute or the sliding deadline
return absoluteExpiration.HasValue && expiration > absoluteExpiration.Value ? absoluteExpiration : expiration;
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion Extensions.Caching.PostgreSql/PostGreSqlCacheOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public class PostgreSqlCacheOptions : IOptions<PostgreSqlCacheOptions>
/// The default sliding expiration set for a cache entry if neither Absolute or SlidingExpiration has been set explicitly.
/// By default, its 20 minutes.
/// </summary>
public TimeSpan DefaultSlidingExpiration { get; set; } = TimeSpan.FromMinutes(20);
public TimeSpan? DefaultSlidingExpiration { get; set; } = TimeSpan.FromMinutes(20);

/// <summary>
/// If set to true this instance of the cache will not remove expired items.
Expand Down
2 changes: 1 addition & 1 deletion Extensions.Caching.PostgreSql/PostgreSqlCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Community.Microsoft.Extensions.Caching.PostgreSql
internal sealed class PostgreSqlCache : IDistributedCache
{
private readonly IDatabaseOperations _dbOperations;
private readonly TimeSpan _defaultSlidingExpiration;
private readonly TimeSpan? _defaultSlidingExpiration;

[Obsolete("Do not use constructor directly instead pull IDistributedCache from DI. For this add 'services.AddDistributedPostgreSqlCache'")]
public PostgreSqlCache(
Expand Down
2 changes: 1 addition & 1 deletion Extensions.Caching.PostgreSql/SqlCommandTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public record ItemIdUtcNow
public record ItemFull
{
public string Id { get; internal set; }
public DateTimeOffset ExpiresAtTime { get; internal set; }
public DateTimeOffset? ExpiresAtTime { get; internal set; }
public byte[] Value { get; internal set; }
public double? SlidingExpirationInSeconds { get; internal set; }
public DateTimeOffset? AbsoluteExpiration { get; internal set; }
Expand Down
4 changes: 2 additions & 2 deletions Extensions.Caching.PostgreSql/SqlCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS "{_schemaName}"."{_tableName}"
$"""
SELECT "Value"
FROM "{_schemaName}"."{_tableName}"
WHERE "Id" = @Id AND @UtcNow <= "ExpiresAtTime"
WHERE "Id" = @Id AND ("ExpiresAtTime" IS NULL OR @UtcNow <= "ExpiresAtTime")
""";

public string SetCacheSql =>
Expand All @@ -49,7 +49,7 @@ UPDATE SET
UPDATE "{_schemaName}"."{_tableName}"
SET "ExpiresAtTime" = LEAST("AbsoluteExpiration", @UtcNow + "SlidingExpirationInSeconds" * interval '1 second')
WHERE "Id" = @Id
AND @UtcNow <= "ExpiresAtTime"
AND ("ExpiresAtTime" IS NULL OR @UtcNow <= "ExpiresAtTime")
AND "SlidingExpirationInSeconds" IS NOT NULL
AND ("AbsoluteExpiration" IS NULL OR "AbsoluteExpiration" <> "ExpiresAtTime")
""";
Expand Down
Loading