using Messenger.Api.Data; using Messenger.Api.Services; using Microsoft.EntityFrameworkCore; namespace Messenger.Api.Jobs; internal static class JobOperations { public static async Task RunAsync(string action, Guid id = default) { var config = Host.CreateApplicationBuilder().Configuration; var options = new DbContextOptionsBuilder() .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; } }