using System.Text.Json; using Messenger.Api.Infrastructure; using Npgsql; using RabbitMQ.Client; namespace Messenger.Api.Pipeline; public sealed class OutboxDispatcher(NpgsqlDataSource db,S3Storage storage,IConfiguration config) { public async Task RunAsync(CancellationToken ct) { var jobs=new JobStore(db,config);var maintenance=new PipelineMaintenance(db,storage,config); var nextMaintenance=DateTime.MinValue; while(!ct.IsCancellationRequested) { try { await using var broker=await BrokerConnection.OpenAsync(config,ct); await using var channel=await broker.CreateChannelAsync(new CreateChannelOptions(publisherConfirmationsEnabled:true,publisherConfirmationTrackingEnabled:true),ct); await BrokerConnection.DeclareAsync(channel,ct); while(!ct.IsCancellationRequested && channel.IsOpen) { if(DateTime.UtcNow>=nextMaintenance) { await jobs.RecoverAsync(ct);await maintenance.CleanupAsync(ct); nextMaintenance=DateTime.UtcNow.AddSeconds(5); } await using var connection=await db.OpenConnectionAsync(ct); await using var tx=await connection.BeginTransactionAsync(ct); JobEnvelope? job=null; await using(var select=JobStore.Command(connection,""" SELECT j.id,j.attachment_id,j.pipeline_version,j.attempts+1,j.created_at FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.published_at IS NULL AND o.available_at<=clock_timestamp() AND j.state='queued' ORDER BY o.available_at,o.job_id LIMIT 1 FOR UPDATE OF o SKIP LOCKED """)) await using(var r=await select.ExecuteReaderAsync(ct)) if(await r.ReadAsync(ct))job=new(1,r.GetGuid(0),"attachment.process.v1",r.GetGuid(1),r.GetInt32(2),r.GetInt32(3),r.GetDateTime(4).ToString("O")); if(job is null) {await tx.CommitAsync(ct);await Task.Delay(100,ct);continue;} using var confirmation=CancellationTokenSource.CreateLinkedTokenSource(ct);confirmation.CancelAfter(TimeSpan.FromSeconds(5)); await channel.BasicPublishAsync("",BrokerConnection.Queue,true, new BasicProperties {Persistent=true,ContentType="application/json",MessageId=job.JobId.ToString()}, JsonSerializer.SerializeToUtf8Bytes(job,JobJson.Options),confirmation.Token); await FaultInjection.HitAsync(config,"after_publish",job.JobId,ct); await using var mark=JobStore.Command(connection,"UPDATE attachment_outbox SET published_at=clock_timestamp() WHERE job_id=@id",("id",job.JobId)); await mark.ExecuteNonQueryAsync(ct);await JobStore.EventAsync(connection,job.JobId,"published",job.Attempt,ct);await tx.CommitAsync(ct); } } catch(OperationCanceledException) when(ct.IsCancellationRequested) {break;} catch(Exception ex) {Console.WriteLine("Outbox deferred: "+ex.GetType().Name);await Task.Delay(2000,ct);} } } }