Files

91 lines
4.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Messenger.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace Messenger.Api.Services;
public sealed record UploadCleanupSettings(TimeSpan Grace, TimeSpan Interval)
{
public static UploadCleanupSettings From(IConfiguration configuration)
{
var grace = configuration.GetValue("UPLOAD_CLEANUP_GRACE_SECONDS", 300);
var interval = configuration.GetValue("UPLOAD_CLEANUP_INTERVAL_SECONDS", 30);
// Grace > HTTP timeout 30 с + SDK retry/таймауты + запас на отмену.
if (grace < 120 || interval < 1)
throw new InvalidOperationException("Cleanup: grace >= 120, interval >= 1");
return new(TimeSpan.FromSeconds(grace), TimeSpan.FromSeconds(interval));
}
}
public sealed record UploadCleanupResult(int Scanned, int Deleted, int Protected, int Failed);
public sealed class UploadCleanup(IServiceScopeFactory scopes, UploadCleanupSettings settings, ILogger<UploadCleanup> logger)
{
public async Task<UploadCleanupResult> RunOnceAsync(CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
var storage = scope.ServiceProvider.GetRequiredService<IAttachmentStorage>();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
deadline.CancelAfter(TimeSpan.FromSeconds(20));
ct = deadline.Token;
await using var tx = await db.Database.BeginTransactionAsync(ct);
// Несколько реплик не очищают одну запись одновременно. Финализация upload
// блокирует ту же строку и запрещена после истечения lease.
var intents = await db.UploadIntents.FromSqlRaw("""
SELECT * FROM upload_intents
WHERE expires_at <= clock_timestamp() AND next_attempt_at <= clock_timestamp()
ORDER BY next_attempt_at, id LIMIT 16 FOR UPDATE SKIP LOCKED
""").ToListAsync(ct);
int deleted = 0, protectedCount = 0, failed = 0;
foreach (var intent in intents)
{
if (await db.Attachments.AsNoTracking().AnyAsync(a => a.ObjectKey == intent.ObjectKey, ct))
{
db.UploadIntents.Remove(intent); // Опубликованный объект никогда не удаляем.
protectedCount++;
continue;
}
if (intent.ObjectKey != $"originals/{intent.Id:N}")
throw new InvalidOperationException("Invalid cleanup object key");
intent.NextAttemptAt = DateTimeOffset.UtcNow + settings.Interval;
try
{
await storage.DeleteAsync(intent.ObjectKey, ct); // DELETE отсутствующего объекта идемпотентен.
intent.DeleteCount++;
deleted++;
// Tombstone сохраняется: даже запоздавший PUT после crash не
// превратится в забытый объект. Цена — запись в БД на неудачную загрузку.
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed++;
logger.LogWarning("S3 cleanup retry for {UploadId}: {Error}", intent.Id, ex.GetType().Name);
}
}
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
return new(intents.Count, deleted, protectedCount, failed);
}
}
public sealed class UploadCleanupWorker(UploadCleanup cleanup, UploadCleanupSettings settings,
ILogger<UploadCleanupWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(settings.Interval);
while (!stoppingToken.IsCancellationRequested)
{
try
{
var result = await cleanup.RunOnceAsync(stoppingToken);
if (result.Scanned > 0) logger.LogInformation("Upload cleanup: {Result}", result);
}
catch (Exception ex) when (!stoppingToken.IsCancellationRequested)
{ logger.LogWarning("Upload cleanup will retry: {Error}", ex.GetType().Name); }
try { if (!await timer.WaitForNextTickAsync(stoppingToken)) break; }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
}
}