forked from mtusi2026/mtusi2026lab5
76 lines
3.5 KiB
C#
76 lines
3.5 KiB
C#
using Messenger.Api.Data;
|
|
using Messenger.Api.Services;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Messenger.Api.Jobs;
|
|
|
|
public sealed record JobSettings(int MaxAttempts, TimeSpan Timeout, int Concurrency, TimeSpan FailedRetention)
|
|
{
|
|
public static JobSettings From(IConfiguration config)
|
|
{
|
|
var attempts = config.GetValue("JOB_MAX_ATTEMPTS", 5);
|
|
var timeout = config.GetValue("JOB_TIMEOUT_SECONDS", 60);
|
|
var concurrency = config.GetValue("WORKER_CONCURRENCY", 2);
|
|
var retention = config.GetValue("STAGING_RETENTION_SECONDS", 86400);
|
|
if (attempts < 1 || timeout < 1 || concurrency < 1 || retention < 0)
|
|
throw new InvalidOperationException("Некорректные настройки обработки вложений");
|
|
return new(attempts, TimeSpan.FromSeconds(timeout), concurrency, TimeSpan.FromSeconds(retention));
|
|
}
|
|
}
|
|
|
|
public sealed record JobMessage(int SchemaVersion, Guid JobId, string Type, Guid AttachmentId,
|
|
int PipelineVersion, int Attempt, DateTimeOffset CreatedAt)
|
|
{
|
|
public const string ProcessType = "attachment.process.v1";
|
|
public static JobMessage From(AttachmentJobEntity job) =>
|
|
new(1, job.Id, ProcessType, job.AttachmentId, job.PipelineVersion, job.Attempt, job.CreatedAt);
|
|
}
|
|
|
|
internal static class AttachmentJobs
|
|
{
|
|
// Все изменения состояния используют один порядок блокировок: сначала job, затем attachment.
|
|
public static async Task<AttachmentJobEntity?> LockAsync(MessengerDbContext db, Guid id, CancellationToken ct)
|
|
{
|
|
var job = await db.AttachmentJobs.FromSql($"SELECT * FROM attachment_jobs WHERE id = {id} FOR UPDATE")
|
|
.SingleOrDefaultAsync(ct);
|
|
if (job is not null)
|
|
job.Attachment = await LockAttachmentAsync(db, job.AttachmentId, ct);
|
|
return job;
|
|
}
|
|
|
|
public static Task<AttachmentEntity> LockAttachmentAsync(MessengerDbContext db, Guid id, CancellationToken ct) =>
|
|
db.Attachments.FromSql($"SELECT * FROM attachments WHERE id = {id} FOR NO KEY UPDATE").SingleAsync(ct);
|
|
|
|
public static void FailAttempt(MessengerDbContext db, AttachmentJobEntity job, JobSettings settings,
|
|
string code, bool permanent)
|
|
{
|
|
var now = Timestamps.UtcNowMilliseconds();
|
|
job.LeaseUntil = null;
|
|
job.Attachment.UpdatedAt = now;
|
|
var used = job.Attempt - job.FirstAttempt + 1;
|
|
if (permanent || used >= settings.MaxAttempts)
|
|
{
|
|
job.Attachment.Status = "failed";
|
|
job.Attachment.ErrorCode = permanent ? code : "retry_exhausted";
|
|
ScheduleCleanup(db, job, now + settings.FailedRetention);
|
|
return;
|
|
}
|
|
job.Attempt++;
|
|
job.Attachment.Status = "queued";
|
|
var delay = Math.Min(30, Math.Pow(2, used - 1));
|
|
job.NextAttemptAt = now.AddSeconds(delay + Random.Shared.NextDouble() * delay * 0.25);
|
|
job.PublishedAt = null;
|
|
}
|
|
|
|
public static void ScheduleCleanup(MessengerDbContext db, AttachmentJobEntity job, DateTimeOffset after)
|
|
{
|
|
// При переносе из ЛР4 источником служит сам постоянный оригинал.
|
|
if (job.SourceKey != $"staging/{job.AttachmentId:N}") return;
|
|
db.UploadIntents.Add(new UploadIntentEntity
|
|
{
|
|
Id = job.AttachmentId, ObjectKey = job.SourceKey, CreatedAt = Timestamps.UtcNowMilliseconds(),
|
|
ExpiresAt = after, NextAttemptAt = after
|
|
});
|
|
}
|
|
}
|