Реализовать лабораторную работу 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,55 @@
using Messenger.Api.Data;
using StackExchange.Redis;
namespace Messenger.Api.Infrastructure;
// Registry entries live ten minutes; an eight-second heartbeat gap means unavailable.
// A Redis outage is reported as unknown, never as proof that an API has stopped.
public sealed class ClusterPresence(IConnectionMultiplexer redis, InstanceIdentity identity,
ReadinessState readiness, AppDatabase database, ILogger<ClusterPresence> logger) : BackgroundService
{
private const string Registry = "messenger:ui:instances";
public sealed record Node(string Id, bool Ready, long LastSeen);
public sealed record Snapshot(bool RedisAvailable, bool PostgresAvailable, long CheckedAt, List<Node> Instances);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
try
{
do
{
try
{
if (redis.IsConnected && !readiness.IsStopping && await database.IsReadyAsync())
{
var db = redis.GetDatabase();
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
await db.SortedSetAddAsync(Registry, identity.Id, now).WaitAsync(TimeSpan.FromSeconds(1), stoppingToken);
await db.SortedSetRemoveRangeByScoreAsync(Registry, double.NegativeInfinity, now - 600_000);
await db.KeyExpireAsync(Registry, TimeSpan.FromMinutes(15));
}
}
catch (Exception error) when (error is RedisException or TimeoutException)
{ logger.LogDebug("Cluster heartbeat unavailable"); }
} while (await timer.WaitForNextTickAsync(stoppingToken));
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
}
public async Task<Snapshot> ReadAsync()
{
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var postgres = await database.IsReadyAsync();
try
{
if (!redis.IsConnected) return new(false, postgres, now, []);
var entries = await redis.GetDatabase().SortedSetRangeByScoreWithScoresAsync(Registry,
now - 600_000, double.PositiveInfinity).WaitAsync(TimeSpan.FromSeconds(1));
return new(true, postgres, now, entries.Select(entry => new Node(entry.Element.ToString(),
now - entry.Score < 8000, (long)entry.Score)).ToList());
}
catch (Exception error) when (error is RedisException or TimeoutException)
{ return new(false, postgres, now, []); }
}
}
@@ -0,0 +1,6 @@
namespace Messenger.Api.Infrastructure;
public sealed class InstanceIdentity
{
public string Id { get; } = Guid.NewGuid().ToString("N");
}
@@ -0,0 +1,8 @@
namespace Messenger.Api.Infrastructure;
public sealed class ReadinessState
{
private int _stopping;
public bool IsStopping => Volatile.Read(ref _stopping) != 0;
public void Stop() => Interlocked.Exchange(ref _stopping, 1);
}
@@ -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");
}
}
}
@@ -0,0 +1,26 @@
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;
namespace Messenger.Api.Infrastructure;
public sealed class S3Storage : IDisposable
{
public AmazonS3Client Client { get; }
public string Bucket { get; }
public S3Storage(IConfiguration config)
{
Bucket=config["S3_BUCKET"] ?? "messenger";
Client=new AmazonS3Client(new BasicAWSCredentials(
File.ReadAllText(config["S3_ACCESS_KEY_FILE"]!).Trim(),
File.ReadAllText(config["S3_SECRET_KEY_FILE"]!).Trim()),new AmazonS3Config {
ServiceURL=config["S3_ENDPOINT"] ?? "http://s3:9000", ForcePathStyle=true,
AuthenticationRegion="us-east-1", MaxErrorRetry=0, Timeout=TimeSpan.FromSeconds(20)
});
}
public async Task<bool> ReadyAsync()
{
using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(1));
try { await Client.ListObjectsV2Async(new ListObjectsV2Request {BucketName=Bucket,MaxKeys=1},timeout.Token); return true; }
catch { return false; }
}
public void Dispose() => Client.Dispose();
}