Реализовать лабораторную работу 4

This commit is contained in:
Никита
2026-11-10 10:57:36 +03:00
parent ec540a1a72
commit fbc1773553
103 changed files with 5424 additions and 27 deletions
@@ -0,0 +1,58 @@
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");
}
}
}