fix: resolve GlitchTip anomalies — DB retry, query filters, Sentry DSN, Workers tracking

- 🔴 Fix startup crash when DB is temporarily unavailable: add 5x retry
  with exponential backoff to Database.MigrateAsync() in API and Workers
- 🔴 Fix EF Core 'required navigation with query filter' warnings:
  add matching soft-delete query filters to AgentSetting, CameraCredentials,
  CameraDetectionProfile, UserSite
- 🔴 Add Sentry error tracking to Workers (Hangfire background jobs)
- 🟡 Make Sentry/GlitchTip DSN configurable via SENTRY_DSN env var
  (applies to API, Web, Agent, Workers)
- 🟡 Suppress EF Core RedundantIndexRemoved informational messages

Closes GlitchTip #538
This commit is contained in:
Arnaud Dartois committed 2026-07-18 20:31:37 +00:00
1 parent ee66cf5971
commit fdfd506977
7 files changed
+108 -34

No files matched your search

+3
View File
@@ -23,6 +23,9 @@ ALARIK_ADMIN_USERNAME=heimdall
ALARIK_ADMIN_PASSWORD=heimdall123
ALARIK_JWT=ChangeMeAtLeast32BytesLongKeyInProd!
# Sentry / GlitchTip (error tracking)
# SENTRY_DSN=https://key@glitchtip.tordais.cc/6
# Agent (set per agent instance)
Agent__CentralUrl=http://heimdall-central:8080
Agent__SiteToken=replace-with-actual-token
+4 -3
View File
@@ -4,15 +4,16 @@ using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
// ── Sentry (GlitchTip) — hardcoded DSN, not overridable by env ────
const string SentryDsn = "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
var builder = WebApplication.CreateSlimBuilder(args);
// ── Sentry ────────────────────────────────────────────────────────
builder.WebHost.UseSentry(options =>
{
options.Dsn = SentryDsn;
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = 0.1;
+34 -24
View File
@@ -11,15 +11,16 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
// ── Sentry (GlitchTip) — hardcoded DSN, not overridable by env ────
const string SentryDsn = "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
var builder = WebApplication.CreateBuilder(args);
// ── Sentry ────────────────────────────────────────────────────────
builder.WebHost.UseSentry(options =>
{
options.Dsn = SentryDsn;
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = 0.1;
@@ -143,35 +144,44 @@ var app = builder.Build();
// Migration runs inline (not as IHostedService) to guarantee the schema
// exists before Identity seeding below and before the web host starts
// serving requests. Using a separate scope keeps migration lifetime
// independent of the seeding scope. 120s timeout covers slow connections
// and large migrations on first deploy.
// independent of the seeding scope.
// Retry with exponential backoff to handle container startup races where
// PostgreSQL accepts TCP connections but isn't ready to serve queries yet
// (see GlitchTip #538 — Failed executing DbCommand on __EFMigrationsHistory).
if (!app.Environment.IsEnvironment("Testing"))
{
using var migrationScope = app.Services.CreateScope();
var migrationLogger = migrationScope.ServiceProvider
.GetRequiredService<ILogger<Program>>();
var db = migrationScope.ServiceProvider.GetRequiredService<AppDbContext>();
using var migrationCts = new CancellationTokenSource(TimeSpan.FromSeconds(120));
try
var maxRetries = 5;
var retryDelay = TimeSpan.FromSeconds(2);
for (var attempt = 1; attempt <= maxRetries; attempt++)
{
migrationLogger.LogInformation("Applying pending database migrations...");
await db.Database.MigrateAsync(migrationCts.Token);
migrationLogger.LogInformation("Database migrations applied successfully");
}
catch (OperationCanceledException) when (!migrationCts.IsCancellationRequested)
{
migrationLogger.LogError("Database migration timed out after 120 seconds. " +
"Ensure the database server is running and accessible.");
throw new InvalidOperationException(
"Database migration timed out after 120 seconds. " +
"Check database connectivity and migration script correctness.");
}
catch (Exception ex)
{
migrationLogger.LogCritical(ex, "Failed to apply database migrations. " +
"The application cannot start without a migrated database.");
throw;
try
{
migrationLogger.LogInformation("Applying pending database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
await db.Database.MigrateAsync(CancellationToken.None);
migrationLogger.LogInformation("Database migrations applied successfully");
break;
}
catch (Exception ex) when (attempt < maxRetries)
{
migrationLogger.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); // Exponential backoff
}
catch (Exception ex)
{
migrationLogger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts. " +
"The application cannot start without a migrated database. " +
"Ensure the database server is running and accessible.", maxRetries);
throw;
}
}
}
@@ -3,6 +3,7 @@ using Heimdall.Infrastructure.Data.Interceptors;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Heimdall.Infrastructure.Data;
@@ -28,10 +29,19 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
// Global soft-delete filter
// Global soft-delete filter — principal entities
builder.Entity<Site>().HasQueryFilter(e => !e.IsDeleted);
builder.Entity<Agent>().HasQueryFilter(e => !e.IsDeleted);
builder.Entity<Camera>().HasQueryFilter(e => !e.IsDeleted);
// Matching query filters on dependent entities to prevent
// "required navigation with query filter" EF Core warnings.
// Without these, loading an AgentSetting whose Agent was soft-deleted
// would cause a null reference on the required navigation.
builder.Entity<AgentSetting>().HasQueryFilter(e => e.Agent == null || !e.Agent.IsDeleted);
builder.Entity<CameraCredentials>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
builder.Entity<CameraDetectionProfile>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
builder.Entity<UserSite>().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
@@ -40,6 +50,15 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
new AuditInterceptor(),
new SoftDeleteInterceptor());
// Suppress informational EF Core messages that create noise in
// error tracking (GlitchTip #538). Redundant index warnings are
// automatically handled by EF Core — it simply skips creating FK
// indexes that are already covered by composite indexes/PKs.
optionsBuilder.ConfigureWarnings(warnings =>
{
warnings.Ignore(CoreEventId.RedundantIndexRemoved);
});
base.OnConfiguring(optionsBuilder);
}
}
+4 -3
View File
@@ -4,15 +4,16 @@ using Heimdall.Web.Services;
using Microsoft.AspNetCore.Components.Authorization;
using MudBlazor.Services;
// ── Sentry (GlitchTip) — hardcoded DSN, not overridable by env ────
const string SentryDsn = "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
var builder = WebApplication.CreateBuilder(args);
// ── Sentry ────────────────────────────────────────────────────────
builder.WebHost.UseSentry(options =>
{
options.Dsn = SentryDsn;
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = 0.1;
@@ -12,6 +12,7 @@
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.17" />
<PackageReference Include="Hangfire.PostgreSql" Version="1.20.10" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.8" />
<PackageReference Include="Sentry.AspNetCore" Version="6.7.0" />
</ItemGroup>
<ItemGroup>
+42 -3
View File
@@ -7,9 +7,22 @@ using Hangfire.PostgreSql;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Sentry;
// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
var builder = Host.CreateApplicationBuilder(args);
// ── Sentry (GlitchTip) ────────────────────────────────────────────
builder.Logging.AddSentry(options =>
{
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
});
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? builder.Configuration.GetConnectionString("Default")
?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall";
@@ -41,13 +54,39 @@ builder.Services.AddScoped<HeartbeatMonitorJob>();
var host = builder.Build();
// Apply migrations
// Apply migrations with retry (handles container startup races)
using (var scope = host.Services.CreateScope())
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
if (db.Database.GetPendingMigrations().Any())
var maxRetries = 5;
var retryDelay = TimeSpan.FromSeconds(2);
for (var attempt = 1; attempt <= maxRetries; attempt++)
{
db.Database.Migrate();
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);
Thread.Sleep(retryDelay);
retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2);
}
catch (Exception ex)
{
logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries);
throw;
}
}
}