Improve robustness of EnvelopeFinalizationWorker

- Reduced polling interval from 1 minute to 10 seconds.
- Added failure handling with a 6-hour block duration for retries.
- Introduced `BlockedEnvelopes` to track and exclude failed envelopes.
- Implemented cleanup for expired blocks in `BlockedEnvelopes`.
- Enhanced error logging to include block duration details.
- Updated debug logging to show counts of blocked envelopes.
- Refactored code for better readability and maintainability.
- Added necessary `using` directives for new functionality.
This commit is contained in:
2026-11-26 19:40:47 +01:00
parent 4b3358828f
commit af6d172087

View File

@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using EnvelopeGenerator.Application.PdfSigning;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Infrastructure;
@@ -15,7 +16,9 @@ public sealed class EnvelopeFinalizationWorker(
IServiceScopeFactory scopeFactory,
ILogger<EnvelopeFinalizationWorker> logger) : BackgroundService
{
private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1);
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(10);
private static readonly TimeSpan FailureBlockDuration = TimeSpan.FromHours(6);
private static readonly ConcurrentDictionary<int, DateTimeOffset> BlockedEnvelopes = new();
/// <summary>
///
@@ -28,11 +31,20 @@ public sealed class EnvelopeFinalizationWorker(
{
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 envelopeIds = await dbContext.Envelopes
var envelopesQuery = dbContext.Envelopes
.AsNoTracking()
.Where(e => e.DocResult == null)
.Where(e => e.EnvelopeReceivers.Any())
@@ -40,7 +52,12 @@ public sealed class EnvelopeFinalizationWorker(
dbContext.EnvelopeHistories.Any(h =>
h.EnvelopeId == e.Id &&
h.Status == EnvelopeStatus.DocumentSigned &&
h.UserReference == er.Receiver.EmailAddress)))
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);
@@ -55,13 +72,21 @@ public sealed class EnvelopeFinalizationWorker(
}
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}", envelopeId);
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.", envelopeIds.Count);
logger.LogDebug(
"EnvelopeFinalizationWorker found {Count} signed envelope(s) without DOC_RESULT. {BlockedCount} envelope(s) blocked.",
envelopeIds.Count,
blockedEnvelopeIds.Length);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{