using EnvelopeGenerator.Application.PdfSigning; using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Infrastructure; using MediatR; using Microsoft.EntityFrameworkCore; namespace EnvelopeGenerator.Server.Services; public sealed class EnvelopeFinalizationWorker( IServiceScopeFactory scopeFactory, ILogger logger) : BackgroundService { private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { using var scope = scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService(); var sender = scope.ServiceProvider.GetRequiredService(); var envelopeIds = await dbContext.Envelopes .AsNoTracking() .Where(e => e.Status == EnvelopeStatus.EnvelopeCompletelySigned && e.DocResult == null) .Select(e => e.Id) .ToListAsync(stoppingToken); foreach(var envelopeId in envelopeIds) { try { await sender.Send(new FinalizeEnvelopeCommand() { Id = envelopeId, BurnedAllowed = false, SaveDocResult = true, }, stoppingToken); } catch(Exception ex) { // TODO: integrate rabbit mq and handle exception (such as delete) logger.LogError(ex, "Unexpected exception happened during finalization of envelope. Envelope ID: {EnvelopeId}", envelopeId); } } // continue here logger.LogDebug("EnvelopeFinalizationWorker found {Count} signed envelope(s) without DOC_RESULT.", envelopeIds.Count); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { logger.LogError(ex, "EnvelopeFinalizationWorker failed while reading envelopes."); } await Task.Delay(PollInterval, stoppingToken); } } }