forked from mtusi2026/mtusi2026lab5
100 lines
5.3 KiB
C#
100 lines
5.3 KiB
C#
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;
|
|
}
|
|
}
|