forked from mtusi2026/mtusi2026lab5
Реализация 5 лабораторной работы
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Security.Cryptography;
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
public sealed class AttachmentProcessor(MessengerDbContext db, IAttachmentStorage storage,
|
||||
JobSettings settings, UploadSettings limits, ILogger<AttachmentProcessor> logger)
|
||||
{
|
||||
public async Task ProcessAsync(JobMessage message, CancellationToken stopping)
|
||||
{
|
||||
var job = await ClaimAsync(message, stopping);
|
||||
if (job is null) return;
|
||||
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stopping);
|
||||
deadline.CancelAfter(settings.Timeout);
|
||||
var ct = deadline.Token;
|
||||
try
|
||||
{
|
||||
var attachment = job.Attachment;
|
||||
JobFaultInjection.At("transient", attachment.Id);
|
||||
using var original = new LimitedDownloadStream(Math.Min(attachment.SizeBytes, limits.MaxBytes));
|
||||
await storage.CopyToAsync(job.SourceKey, original, ct);
|
||||
original.Position = 0;
|
||||
if (original.Length != attachment.SizeBytes ||
|
||||
Convert.ToHexStringLower(await SHA256.HashDataAsync(original, ct)) != attachment.ChecksumSha256)
|
||||
throw new InvalidDataException("Source checksum mismatch");
|
||||
var variants = await ImageRenderer.RenderAsync(original, attachment.ContentType, limits.MaxPixels, message.PipelineVersion, ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await PublishResultAsync(message, original, variants, ct);
|
||||
}
|
||||
catch (Exception ex) when (!stopping.IsCancellationRequested)
|
||||
{
|
||||
logger.LogWarning("Job {JobId} attempt {Attempt} failed ({Kind})",
|
||||
message.JobId, message.Attempt, ex.GetType().Name);
|
||||
db.ChangeTracker.Clear();
|
||||
await using var tx = await db.Database.BeginTransactionAsync(stopping);
|
||||
var current = await AttachmentJobs.LockAsync(db, message.JobId, stopping);
|
||||
if (OwnsAttempt(current, message))
|
||||
{
|
||||
var permanent = ex is InvalidDataException;
|
||||
AttachmentJobs.FailAttempt(db, current!, settings, "invalid_image", permanent);
|
||||
await db.SaveChangesAsync(stopping);
|
||||
}
|
||||
await tx.CommitAsync(stopping);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AttachmentJobEntity?> ClaimAsync(JobMessage message, CancellationToken ct)
|
||||
{
|
||||
await using var tx = await db.Database.BeginTransactionAsync(ct);
|
||||
var job = await AttachmentJobs.LockAsync(db, message.JobId, ct);
|
||||
if (job is null || job.AttachmentId != message.AttachmentId || job.PipelineVersion != message.PipelineVersion ||
|
||||
job.Attempt != message.Attempt || job.Attachment.PipelineVersion != message.PipelineVersion ||
|
||||
job.Attachment.Status != "queued")
|
||||
return null;
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
job.Attachment.Status = "processing";
|
||||
job.Attachment.UpdatedAt = now;
|
||||
job.PublishedAt ??= now;
|
||||
job.LeaseUntil = now + settings.Timeout;
|
||||
await db.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
return job;
|
||||
}
|
||||
|
||||
private static bool OwnsAttempt(AttachmentJobEntity? job, JobMessage message) =>
|
||||
job is not null && job.Attempt == message.Attempt && job.Attachment.PipelineVersion == message.PipelineVersion &&
|
||||
job.Attachment.Status == "processing";
|
||||
|
||||
private async Task PublishResultAsync(JobMessage message, Stream original, ImageVariant[] variants, CancellationToken ct)
|
||||
{
|
||||
db.ChangeTracker.Clear();
|
||||
await using var tx = await db.Database.BeginTransactionAsync(ct);
|
||||
var job = await AttachmentJobs.LockAsync(db, message.JobId, ct);
|
||||
if (!OwnsAttempt(job, message)) return;
|
||||
var attachment = job!.Attachment;
|
||||
JobFaultInjection.At("before-write", attachment.Id);
|
||||
// Устаревшая попытка не может писать в S3 после захвата работы другой попыткой.
|
||||
if (job.SourceKey != attachment.ObjectKey)
|
||||
{
|
||||
original.Position = 0;
|
||||
await storage.PutAsync(attachment.ObjectKey, original, attachment.ContentType, ct, createOnly: true);
|
||||
}
|
||||
foreach (var variant in variants)
|
||||
{
|
||||
var extension = variant.ContentType == "image/webp" ? "webp" : "jpg";
|
||||
var key = $"variants/{attachment.Id:N}/v{job.PipelineVersion}/{variant.Name}.{extension}";
|
||||
using var file = new MemoryStream(variant.Bytes, writable: false);
|
||||
await storage.PutAsync(key, file, variant.ContentType, ct, createOnly: true);
|
||||
db.AttachmentVariants.Add(new AttachmentVariantEntity
|
||||
{
|
||||
AttachmentId = attachment.Id, PipelineVersion = job.PipelineVersion, Name = variant.Name,
|
||||
ObjectKey = key, ContentType = variant.ContentType, Width = variant.Width, Height = variant.Height,
|
||||
SizeBytes = file.Length, Sha256 = Convert.ToHexStringLower(SHA256.HashData(variant.Bytes))
|
||||
});
|
||||
}
|
||||
JobFaultInjection.At("after-write", attachment.Id);
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
attachment.Status = "ready";
|
||||
attachment.UpdatedAt = now;
|
||||
job.LeaseUntil = null;
|
||||
AttachmentJobs.ScheduleCleanup(db, job, now);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Text.Json;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using RabbitMQ.Client;
|
||||
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
internal sealed class AttachmentQueue(ConnectionFactory connections, IServiceScopeFactory scopes,
|
||||
JobSettings settings, bool publisher, ILogger<AttachmentQueue> logger) : BackgroundService
|
||||
{
|
||||
internal const string QueueName = "attachments.v1";
|
||||
private static readonly JsonSerializerOptions WireFormat = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
|
||||
Task.WhenAll(Enumerable.Range(0, publisher ? 1 : settings.Concurrency).Select(_ => RunChannelAsync(stoppingToken)));
|
||||
|
||||
private async Task RunChannelAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = await connections.CreateConnectionAsync(ct);
|
||||
var options = new CreateChannelOptions(publisherConfirmationsEnabled: publisher,
|
||||
publisherConfirmationTrackingEnabled: publisher);
|
||||
await using var channel = await connection.CreateChannelAsync(options, ct);
|
||||
await channel.QueueDeclareAsync(QueueName, durable: true, exclusive: false, autoDelete: false,
|
||||
arguments: new Dictionary<string, object?> { ["x-queue-type"] = "classic" }, cancellationToken: ct);
|
||||
while (channel.IsOpen && !ct.IsCancellationRequested)
|
||||
{
|
||||
var didWork = publisher ? await PublishNextAsync(channel, ct) : await ConsumeNextAsync(channel, ct);
|
||||
if (!didWork) await Task.Delay(400, ct);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
// Закрытие канала возвращает брокеру все доставки, которым worker ещё не послал ack.
|
||||
logger.LogWarning("Attachment queue reconnecting after {Kind}", ex.GetType().Name);
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> PublishNextAsync(IChannel channel, CancellationToken ct)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
|
||||
await using var tx = await db.Database.BeginTransactionAsync(ct);
|
||||
var job = await db.AttachmentJobs.FromSqlRaw("""
|
||||
SELECT * FROM attachment_jobs
|
||||
WHERE (published_at IS NULL AND next_attempt_at <= clock_timestamp())
|
||||
OR lease_until <= clock_timestamp()
|
||||
ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
""").SingleOrDefaultAsync(ct);
|
||||
if (job is null) return false;
|
||||
if (job.LeaseUntil.HasValue)
|
||||
{
|
||||
job.Attachment = await AttachmentJobs.LockAttachmentAsync(db, job.AttachmentId, ct);
|
||||
AttachmentJobs.FailAttempt(db, job, settings, "processing_timeout", permanent: false);
|
||||
}
|
||||
else
|
||||
{
|
||||
JobFaultInjection.At("before-publish", job.AttachmentId);
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(JobMessage.From(job), WireFormat);
|
||||
var properties = new BasicProperties { Persistent = true, ContentType = "application/json", MessageId = job.Id.ToString() };
|
||||
using var confirm = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
confirm.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
await channel.BasicPublishAsync("", QueueName, mandatory: true, properties, payload, confirm.Token);
|
||||
job.PublishedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
await db.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> ConsumeNextAsync(IChannel channel, CancellationToken ct)
|
||||
{
|
||||
// Один неподтверждённый файл на канал. Каждый параллельный обработчик имеет собственный канал.
|
||||
var delivery = await channel.BasicGetAsync(QueueName, autoAck: false, ct);
|
||||
if (delivery is null) return false;
|
||||
JobMessage? message;
|
||||
try { message = JsonSerializer.Deserialize<JobMessage>(delivery.Body.Span, WireFormat); }
|
||||
catch (JsonException) { message = null; }
|
||||
if (message is not { SchemaVersion: 1, Type: JobMessage.ProcessType, PipelineVersion: 1 or 2, Attempt: >= 1 } ||
|
||||
message.JobId == Guid.Empty || message.AttachmentId == Guid.Empty || message.CreatedAt == default)
|
||||
{
|
||||
logger.LogWarning("Discarded malformed attachment job");
|
||||
await channel.BasicRejectAsync(delivery.DeliveryTag, requeue: false, ct);
|
||||
return true;
|
||||
}
|
||||
using var scope = scopes.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<AttachmentProcessor>().ProcessAsync(message, ct);
|
||||
JobFaultInjection.At("before-ack", message.AttachmentId, message.Attempt);
|
||||
await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false, ct);
|
||||
logger.LogInformation("Ack job {JobId} attempt {Attempt} redelivered {Redelivered}",
|
||||
message.JobId, message.Attempt, delivery.Redelivered);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using ImageMagick;
|
||||
using Messenger.Api.Services;
|
||||
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
internal static class ImageRenderer
|
||||
{
|
||||
public static async Task<ImageVariant[]> RenderAsync(Stream input, string mime, long maxPixels, int version,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// Нативное декодирование выполняется в дочернем процессе, который можно завершить по дедлайну.
|
||||
var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet")
|
||||
{
|
||||
RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false
|
||||
};
|
||||
start.ArgumentList.Add(typeof(ImageRenderer).Assembly.Location);
|
||||
start.ArgumentList.Add("--render-attachment");
|
||||
start.ArgumentList.Add(mime);
|
||||
start.ArgumentList.Add(maxPixels.ToString(CultureInfo.InvariantCulture));
|
||||
start.ArgumentList.Add(version.ToString(CultureInfo.InvariantCulture));
|
||||
using var process = Process.Start(start) ?? throw new IOException("Cannot start image renderer");
|
||||
try
|
||||
{
|
||||
var response = process.StandardOutput.ReadToEndAsync(ct);
|
||||
input.Position = 0;
|
||||
try
|
||||
{
|
||||
await input.CopyToAsync(process.StandardInput.BaseStream, ct);
|
||||
process.StandardInput.Close();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Дочерний процесс может завершиться до окончания передачи.
|
||||
process.StandardInput.Close();
|
||||
}
|
||||
await process.WaitForExitAsync(ct);
|
||||
var json = await response;
|
||||
return process.ExitCode switch
|
||||
{
|
||||
0 => JsonSerializer.Deserialize<ImageVariant[]>(json) ?? throw new IOException("Empty renderer result"),
|
||||
2 => throw new InvalidDataException("Invalid image"),
|
||||
_ => throw new IOException($"Image renderer exit code {process.ExitCode}")
|
||||
};
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!process.HasExited)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); }
|
||||
catch (InvalidOperationException) { }
|
||||
await process.WaitForExitAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<int> RunAsync(string mime, long maxPixels, int version)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var original = new LimitedDownloadStream(10485760);
|
||||
await Console.OpenStandardInput().CopyToAsync(original);
|
||||
var result = ImageVariant.CreateAll(original, mime, maxPixels, version);
|
||||
await JsonSerializer.SerializeAsync(Console.OpenStandardOutput(), result);
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or MagickCorruptImageErrorException or MagickCoderErrorException)
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"Image renderer: {ex.GetType().Name}");
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using ImageMagick;
|
||||
using StbImageSharp;
|
||||
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
public sealed record ImageVariant(string Name, string ContentType, byte[] Bytes, int Width, int Height)
|
||||
{
|
||||
public static ImageVariant[] CreateAll(Stream original, string mime, long maxPixels, int version)
|
||||
{
|
||||
if (version is not (1 or 2) || mime is not ("image/png" or "image/jpeg"))
|
||||
throw new InvalidDataException("Unsupported image or pipeline version");
|
||||
original.Position = 0;
|
||||
var header = ImageInfo.FromStream(original);
|
||||
if (header is null || header.Value.Width <= 0 || header.Value.Height <= 0 ||
|
||||
(long)header.Value.Width * header.Value.Height > maxPixels)
|
||||
throw new InvalidDataException("Invalid image dimensions");
|
||||
original.Position = 0;
|
||||
var read = new MagickReadSettings
|
||||
{
|
||||
Format = mime == "image/png" ? MagickFormat.Png : MagickFormat.Jpeg, FrameCount = 1
|
||||
};
|
||||
using var image = new MagickImage(original, read);
|
||||
if (image.Width != header.Value.Width || image.Height != header.Value.Height)
|
||||
throw new InvalidDataException("Image dimensions changed during decode");
|
||||
image.AutoOrient();
|
||||
image.Strip();
|
||||
|
||||
using var thumbnail = image.Clone();
|
||||
Fit(thumbnail, 256);
|
||||
using var crop = image.Clone();
|
||||
var side = Math.Min(crop.Width, crop.Height);
|
||||
crop.Crop(side, side, Gravity.Center);
|
||||
crop.ResetPage();
|
||||
crop.Resize(128, 128);
|
||||
|
||||
Fit(image, 1280);
|
||||
image.Quality = version == 1 ? 78u : 86u;
|
||||
return [EncodeJpeg(thumbnail, "thumbnail", version == 1 ? 85u : 92u),
|
||||
EncodeJpeg(crop, "crop", 85),
|
||||
new ImageVariant("optimized", "image/webp", image.ToByteArray(MagickFormat.WebP), (int)image.Width, (int)image.Height)];
|
||||
}
|
||||
|
||||
private static void Fit(IMagickImage<byte> image, uint limit)
|
||||
{
|
||||
var longest = Math.Max(image.Width, image.Height);
|
||||
if (longest <= limit) return;
|
||||
var width = (uint)Math.Max(1L, image.Width * (long)limit / longest);
|
||||
var height = (uint)Math.Max(1L, image.Height * (long)limit / longest);
|
||||
image.Resize(new MagickGeometry(width, height) { IgnoreAspectRatio = true });
|
||||
}
|
||||
|
||||
private static ImageVariant EncodeJpeg(IMagickImage<byte> image, string name, uint quality)
|
||||
{
|
||||
image.BackgroundColor = MagickColors.White;
|
||||
image.Alpha(AlphaAction.Remove);
|
||||
image.Quality = quality;
|
||||
return new(name, "image/jpeg", image.ToByteArray(MagickFormat.Jpeg), (int)image.Width, (int)image.Height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
internal static class JobFaultInjection
|
||||
{
|
||||
public static void At(string stage, Guid attachmentId, int? attempt = null)
|
||||
{
|
||||
var target = attempt is null ? $"{stage}:{attachmentId:D}" : $"{stage}:{attachmentId:D}:{attempt}";
|
||||
if (Environment.GetEnvironmentVariable("LAB5_TEST_FAULT") != target) return;
|
||||
Console.Error.WriteLine($"Injected fault {stage} for {attachmentId:D}");
|
||||
if (stage == "transient") throw new IOException("Injected storage error");
|
||||
Environment.Exit(71);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
internal static class JobOperations
|
||||
{
|
||||
public static async Task<int> RunAsync(string action, Guid id = default)
|
||||
{
|
||||
var config = Host.CreateApplicationBuilder().Configuration;
|
||||
var options = new DbContextOptionsBuilder<MessengerDbContext>()
|
||||
.UseNpgsql(DatabaseSettings.From(config).ConnectionString).UseSnakeCaseNamingConvention().Options;
|
||||
await using var db = new MessengerDbContext(options);
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
var ct = timeout.Token;
|
||||
|
||||
if (action == "--failed-jobs")
|
||||
{
|
||||
var failed = await db.AttachmentJobs.Where(j => j.Attachment.Status == "failed" &&
|
||||
j.Attachment.PipelineVersion == j.PipelineVersion).OrderByDescending(j => j.Attachment.UpdatedAt)
|
||||
.Take(100).Select(j => new { j.Id, j.AttachmentId, j.PipelineVersion, j.Attempt, j.Attachment.ErrorCode }).ToListAsync(ct);
|
||||
foreach (var job in failed)
|
||||
Console.WriteLine($"{job.Id} attachment={job.AttachmentId} version={job.PipelineVersion} attempt={job.Attempt} code={job.ErrorCode}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
await using var tx = await db.Database.BeginTransactionAsync(ct);
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
if (action == "--replay-job")
|
||||
{
|
||||
var job = await AttachmentJobs.LockAsync(db, id, ct);
|
||||
if (job is null || job.Attachment.Status != "failed" || job.Attachment.PipelineVersion != job.PipelineVersion)
|
||||
return Reject("Job must be the failed current version");
|
||||
if (job.SourceKey != job.Attachment.ObjectKey)
|
||||
{
|
||||
var intent = await db.UploadIntents.FromSql($"""
|
||||
SELECT * FROM upload_intents WHERE id = {job.AttachmentId}
|
||||
AND expires_at > clock_timestamp() FOR UPDATE
|
||||
""").SingleOrDefaultAsync(ct);
|
||||
if (intent is null) return Reject("The staged original is outside its retention window");
|
||||
db.UploadIntents.Remove(intent);
|
||||
}
|
||||
job.Attempt = checked(job.Attempt + 1);
|
||||
job.FirstAttempt = job.Attempt;
|
||||
job.ReplayedAt = now;
|
||||
job.NextAttemptAt = now;
|
||||
job.PublishedAt = null;
|
||||
SetQueued(job.Attachment, now);
|
||||
}
|
||||
else
|
||||
{
|
||||
var attachment = await db.Attachments.FromSql($"SELECT * FROM attachments WHERE id = {id} FOR NO KEY UPDATE")
|
||||
.SingleOrDefaultAsync(ct);
|
||||
if (attachment is not { Status: "ready", PipelineVersion: 1 })
|
||||
return Reject("Version 2 requires a ready version 1");
|
||||
attachment.PipelineVersion = 2;
|
||||
SetQueued(attachment, now);
|
||||
var job = new AttachmentJobEntity
|
||||
{
|
||||
Id = Guid.CreateVersion7(), AttachmentId = id, PipelineVersion = 2, SourceKey = attachment.ObjectKey,
|
||||
CreatedAt = now, NextAttemptAt = now
|
||||
};
|
||||
db.AttachmentJobs.Add(job);
|
||||
id = job.Id;
|
||||
}
|
||||
await db.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
Console.WriteLine($"Queued job {id}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void SetQueued(AttachmentEntity attachment, DateTimeOffset now)
|
||||
{
|
||||
attachment.Status = "queued";
|
||||
attachment.ErrorCode = null;
|
||||
attachment.UpdatedAt = now;
|
||||
}
|
||||
|
||||
private static int Reject(string message)
|
||||
{
|
||||
Console.Error.WriteLine(message);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using RabbitMQ.Client;
|
||||
|
||||
namespace Messenger.Api.Jobs;
|
||||
|
||||
internal static class QueueHost
|
||||
{
|
||||
public static async Task RunAsync(bool publisher)
|
||||
{
|
||||
var builder = Host.CreateApplicationBuilder();
|
||||
var config = builder.Configuration;
|
||||
var urlFile = config["BROKER_URL_FILE"] ?? throw new InvalidOperationException("BROKER_URL_FILE не задан");
|
||||
var connections = new ConnectionFactory
|
||||
{
|
||||
Uri = new Uri(File.ReadAllText(urlFile).Trim()), AutomaticRecoveryEnabled = false,
|
||||
RequestedConnectionTimeout = TimeSpan.FromSeconds(5)
|
||||
};
|
||||
var settings = JobSettings.From(config);
|
||||
var database = DatabaseSettings.From(config);
|
||||
builder.Logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
|
||||
builder.Services.AddSingleton(settings);
|
||||
builder.Services.AddDbContext<MessengerDbContext>(options =>
|
||||
options.UseNpgsql(database.ConnectionString).UseSnakeCaseNamingConvention());
|
||||
if (!publisher)
|
||||
{
|
||||
builder.Services.AddSingleton(UploadSettings.From(config));
|
||||
builder.Services.AddSingleton<IAttachmentStorage>(_ => new S3AttachmentStorage(S3Settings.From(config)));
|
||||
builder.Services.AddScoped<AttachmentProcessor>();
|
||||
}
|
||||
builder.Services.AddHostedService(sp => new AttachmentQueue(connections,
|
||||
sp.GetRequiredService<IServiceScopeFactory>(), settings, publisher, sp.GetRequiredService<ILogger<AttachmentQueue>>()));
|
||||
using var host = builder.Build();
|
||||
await host.RunAsync();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user