Files
EnvelopeGenerator/EnvelopeGenerator.Server/EnvelopeGenerator.Server/BackgroundServices/EnvelopeFinalizationWorker.cs
TekH 43758e3390 Add envelope finalization trigger and workflow updates
Introduced `EnvelopeFinalizationTrigger` to enable external
triggering of the `EnvelopeFinalizationWorker` for immediate
envelope processing. Updated `EnvelopeFinalizationWorker` to
support both polling and external triggers, improving
performance and flexibility.

Added `BackgroundServicesController` with an API endpoint to
trigger the worker, including configuration checks for
availability. Temporarily used `[AllowAnonymous]` with plans
to replace it with sender-scoped authorization.

Enhanced manual testing workflows in `AGENTS.md`:
- Standardized request-to-domain mapping policy.
- Migrated dynamic SQL to parameterized queries for security.
- Improved UX for deterministic row double-click behavior.
- Implemented SPA-style language switching.
- Added sender-scoped caching for recent receiver suggestions.

Updated dependency injection in `Program.cs` to register
`EnvelopeFinalizationTrigger` and ensure the worker is only
enabled when configured.
2026-11-27 13:07:50 +01:00

112 lines
4.4 KiB
C#

using System.Collections.Concurrent;
using EnvelopeGenerator.Application.Common.Interfaces;
using EnvelopeGenerator.Application.PdfSigning;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Server.BackgroundServices;
/// <summary>
///
/// </summary>
/// <param name="scopeFactory"></param>
/// <param name="trigger"></param>
/// <param name="logger"></param>
public sealed class EnvelopeFinalizationWorker(
IServiceScopeFactory scopeFactory,
EnvelopeFinalizationTrigger trigger,
ILogger<EnvelopeFinalizationWorker> logger) : BackgroundService
{
private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1);
private static readonly TimeSpan FailureBlockDuration = TimeSpan.FromHours(6);
private static readonly ConcurrentDictionary<int, DateTimeOffset> BlockedEnvelopes = new();
/// <summary>
///
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
var now = DateTimeOffset.UtcNow;
foreach (var blockedEntry in BlockedEnvelopes)
{
if (blockedEntry.Value <= now)
BlockedEnvelopes.TryRemove(blockedEntry.Key, out _);
}
var blockedEnvelopeIds = BlockedEnvelopes.Keys.ToArray();
using var scope = scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<EGDbContext>();
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
var envelopesQuery = dbContext.Envelopes
.AsNoTracking()
.Where(e => e.DocResult == null)
.Where(e => e.EnvelopeReceivers.Any())
.Where(e => e.EnvelopeReceivers.All(er =>
dbContext.EnvelopeHistories.Any(h =>
h.EnvelopeId == e.Id &&
h.Status == EnvelopeStatus.DocumentSigned &&
h.UserReference == er.Receiver.EmailAddress)));
if (blockedEnvelopeIds.Length > 0)
envelopesQuery = envelopesQuery.Where(e => !blockedEnvelopeIds.Contains(e.Id));
var envelopeIds = await envelopesQuery
.Select(e => e.Id)
.ToListAsync(stoppingToken);
foreach(var envelopeId in envelopeIds)
{
try
{
await sender.Send(new FinalizeEnvelopeCommand()
{
Id = envelopeId
}, stoppingToken);
}
catch(Exception ex)
{
BlockedEnvelopes[envelopeId] = DateTimeOffset.UtcNow.Add(FailureBlockDuration);
// TODO: integrate rabbit mq and handle exception (such as delete)
logger.LogError(ex,
"Unexpected exception happened during finalization of envelope. Envelope ID: {EnvelopeId}. Blocked for {BlockHours} hour(s).",
envelopeId,
FailureBlockDuration.TotalHours);
}
}
// continue here
logger.LogDebug(
"EnvelopeFinalizationWorker found {Count} signed envelope(s) without DOC_RESULT. {BlockedCount} envelope(s) blocked.",
envelopeIds.Count,
blockedEnvelopeIds.Length);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(ex, "EnvelopeFinalizationWorker failed while reading envelopes.");
}
var delayTask = Task.Delay(PollInterval, stoppingToken);
var triggerTask = trigger.WaitAsync(stoppingToken);
var completedTask = await Task.WhenAny(delayTask, triggerTask);
if (completedTask == triggerTask)
trigger.Drain();
}
}
}