forked from mtusi2026/mtusi2026lab5
Реализация 5 лабораторной работы
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user