Files
mtusi2026lab4/src/Messenger.Api/Infrastructure/RedisSessionCache.cs
T

59 lines
2.4 KiB
C#

using System.Text.Json;
using Messenger.Api.Contracts;
using StackExchange.Redis;
namespace Messenger.Api.Infrastructure;
// PostgreSQL validates the session on every request. This cache saves the user lookup
// and never grants access independently of the durable session row.
public sealed class RedisSessionCache(IConnectionMultiplexer connection, ILogger<RedisSessionCache> logger)
{
private static readonly TimeSpan OperationBudget = TimeSpan.FromMilliseconds(750);
private static string Key(byte[] hash) => "messenger:session:" + Convert.ToHexString(hash).ToLowerInvariant();
public sealed record Entry(UserDto User, DateTime ExpiresAt);
public async Task<Entry?> GetAsync(byte[] hash)
{
if (!connection.IsConnected) return null;
try
{
var value = await connection.GetDatabase().StringGetAsync(Key(hash)).WaitAsync(OperationBudget);
return value.IsNullOrEmpty ? null : JsonSerializer.Deserialize<Entry>(value.ToString());
}
catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException or JsonException)
{
logger.LogWarning("Session cache read unavailable; using PostgreSQL");
return null;
}
}
public async Task SetAsync(byte[] hash, UserDto user, DateTime expiresAt)
{
var remaining = expiresAt - DateTime.UtcNow;
if (!connection.IsConnected || remaining <= TimeSpan.Zero) return;
try
{
await connection.GetDatabase().StringSetAsync(Key(hash),
JsonSerializer.Serialize(new Entry(user, expiresAt)), remaining).WaitAsync(OperationBudget);
}
catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException)
{
logger.LogWarning("Session cache write unavailable; using PostgreSQL");
}
}
public async Task RemoveAsync(byte[] hash)
{
if (!connection.IsConnected) return;
try
{
await connection.GetDatabase().KeyDeleteAsync(Key(hash)).WaitAsync(OperationBudget);
}
catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException)
{
logger.LogWarning("Session cache invalidation unavailable; PostgreSQL still enforces revocation");
}
}
}