Wire notification service and finalization worker into server host

This commit is contained in:
2026-10-22 01:35:22 +02:00
parent 658cb28e1c
commit fb155fe706
4 changed files with 98 additions and 24 deletions

View File

@@ -0,0 +1,63 @@
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<EnvelopeFinalizationWorker> 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<EGDbContext>();
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
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)
{
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);
}
}
}