fix(web): retry Hangfire startup lock contention (#278)
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Failing after 4m42s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (push) Skipped
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / CI policy (push) Failing after 1s

Refs #214

## Résumé
- Réessaie l’enregistrement complet et idempotent des jobs Hangfire après une `PostgreSqlDistributedLockException`, avec nouveau scope par tentative, délais bornés et annulation à l’arrêt.
- Ajoute un test ciblé de contention transitoire et la skill projet `hangfire-startup-lock`.

## Vérifications
- `dotnet test tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj --no-restore --filter FullyQualifiedName~RecurringJobStartupRetryTests` — 1 passé.
- `dotnet build src/Heimdall.Web/Heimdall.Web.csproj --no-restore` — réussi, 0 avertissement.
- Compose disposable depuis la source: projet `heimdall214-261107080901-ae486b`, sans ports hôtes publiés; Central healthy et `hangfire.hash` confirme `recurring-job:agent-failover` avec cron `*/1 * * * *`.
- Trap de nettoyage: aucun conteneur/volume/réseau du projet et tag `heimdall:heimdall214-261107080901-ae486b-acceptance` absent. Bases PostgreSQL/.NET conservées.

Le critère de télémétrie après déploiement reste ouvert dans #214. Aucun déploiement réel n’est déclaré validé.

Reviewed-on: #278
This commit was merged in pull request #278.
This commit is contained in:
arnaud.dartois committed 2026-11-07 17:35:50 +01:00
1 parent cae09e3698
commit 188a9ad2d4
3 files changed
+83 -5

No files matched your search

+28 -5
View File
@@ -61,11 +61,7 @@ var isTesting = app.Environment.IsEnvironment(TestingEnvironment);
var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default");
if (!isTesting && !string.IsNullOrEmpty(pgConnStr))
{
using (var scope = app.Services.CreateScope())
{
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager);
}
await Program.ConfigureRecurringJobsAsync(app.Services, app.Lifetime.ApplicationStopping);
}
// ── Seed Identity roles (required in ALL environments, including Testing) ─
@@ -85,10 +81,37 @@ internal sealed record SignInRequest(
public partial class Program
{
private const string TestingEnvironment = "Testing";
private const int RecurringJobRegistrationAttempts = 5;
// SonarQube S1118: partial class used by WebApplicationFactory needs a constructor.
protected Program() { }
internal static async Task ConfigureRecurringJobsAsync(IServiceProvider services, CancellationToken cancellationToken)
{
var retryDelay = TimeSpan.FromSeconds(2);
var logger = services.GetRequiredService<ILogger<Program>>();
for (var attempt = 1; attempt <= RecurringJobRegistrationAttempts; attempt++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
using var scope = services.CreateScope();
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager);
return;
}
catch (Hangfire.PostgreSql.PostgreSqlDistributedLockException ex)
when (attempt < RecurringJobRegistrationAttempts)
{
logger.LogWarning(ex,
"Recurring Hangfire job registration hit a distributed lock (attempt {Attempt}/{MaxAttempts}); retrying in {DelaySeconds}s.",
attempt, RecurringJobRegistrationAttempts, retryDelay.TotalSeconds);
await Task.Delay(retryDelay, cancellationToken);
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 16));
}
}
}
private static string ResolveCategory(string key)
{
if (key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal))