refactor(docker): merge worker and web into single heimdall image

Combine Heimdall.Web and Heimdall.Workers into one process/image.
Hangfire background jobs now run inside the web process.

- Move job classes to Infrastructure/Jobs/ (no Worker SDK dependency)
- Add Hangfire server + recurring jobs to Web/Program.cs
- Add missing AddInfrastructure/AddApplication DI registrations to Web
- Rename image: heimdall (was heimdall-web / heimdall-workers)
- Remove src/Heimdall.Workers project entirely
- Remove tests/Heimdall.Workers.Tests (placeholder)
- Simplify Dockerfile: single build target, no workers publish
- Update docker-compose files: one service heimdall, no workers
- Update Makefile, .env.example
This commit is contained in:
Arnaud Dartois committed 2026-07-20 17:22:56 +00:00
1 parent 252724a2fd
commit 630e7987fe
18 files changed
+139 -324

No files matched your search

+96
View File
@@ -1,13 +1,19 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Heimdall.Application;
using Heimdall.Infrastructure;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Jobs;
using Heimdall.Infrastructure.Security;
using Heimdall.Web.Components;
using Heimdall.Web.Services;
using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using MudBlazor.Services;
@@ -79,6 +85,42 @@ builder.Services.AddMudServices(config =>
config.SnackbarConfiguration.VisibleStateDuration = 4000;
});
// ── Application layer ─────────────────────────────────────────────
builder.Services.AddApplication();
// ── Infrastructure layer ──────────────────────────────────────────
builder.Services.AddInfrastructure(builder.Configuration,
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
// ── Database connection string (for Hangfire) ─────────────────────
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? builder.Configuration.GetConnectionString("Default")
?? throw new InvalidOperationException(
"DATABASE_URL is not configured. Set the DATABASE_URL environment variable " +
"or configure a Default connection string in appsettings.json. " +
"Example: Host=host;Port=5432;Database=heimdall;Username=user;Password=password");
// ── Hangfire ──────────────────────────────────────────────────────
#pragma warning disable CS0618
builder.Services.AddHangfire(config =>
{
config.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions
{
SchemaName = "hangfire"
});
});
#pragma warning restore CS0618
builder.Services.AddHangfireServer(options =>
{
options.WorkerCount = 2;
options.Queues = ["default", "heartbeat"];
});
// ── Jobs ──────────────────────────────────────────────────────────
builder.Services.AddScoped<HeartbeatMonitorJob>();
builder.Services.AddScoped<AgentFailoverJob>();
// ── HTTP client for Heimdall API ──────────────────────────────────
builder.Services.AddScoped<HeimdallApiClient>();
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
@@ -224,6 +266,60 @@ app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> l
return Results.Ok();
});
// ── Apply pending database migrations ────────────────────────────────
// Retry with exponential backoff to handle container startup races where
// PostgreSQL accepts TCP connections but isn't ready to serve queries yet.
using (var scope = app.Services.CreateScope())
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var maxRetries = 5;
var retryDelay = TimeSpan.FromSeconds(2);
for (var attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
if (db.Database.GetPendingMigrations().Any())
{
logger.LogInformation("Applying pending database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
db.Database.Migrate();
logger.LogInformation("Database migrations applied successfully");
}
break;
}
catch (Exception ex) when (attempt < maxRetries)
{
logger.LogWarning(ex,
"Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...",
attempt, maxRetries, retryDelay.TotalSeconds);
await Task.Delay(retryDelay);
retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2);
}
catch (Exception ex)
{
logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries);
throw;
}
}
}
// ── Register recurring Hangfire jobs ─────────────────────────────────
using (var scope = app.Services.CreateScope())
{
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
manager.AddOrUpdate<HeartbeatMonitorJob>(
"heartbeat-monitor",
job => job.ExecuteAsync(CancellationToken.None),
"*/1 * * * *"); // Every minute
manager.AddOrUpdate<AgentFailoverJob>(
"agent-failover",
job => job.ExecuteAsync(CancellationToken.None),
"*/1 * * * *"); // Every minute — checks for stale heartbeats
}
app.Run();
// ─── DTO for the cookie sign-in request ───────────────────────────