ЛР 2: PostgreSQL, сессии, Redis и исследование
Skeleton contracts / contracts (pull_request) Failing after 30s
Skeleton contracts / contracts (pull_request) Failing after 30s
This commit is contained in:
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user