From 8d5447f8263e77a3482291c103b035d8efd158a9 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:55:31 +0200 Subject: [PATCH] fix(agent): align failover with heartbeat intervals --- .../SetAgentSetting/SetAgentSettingCommand.cs | 4 ++ .../UpdateAppSettingCommand.cs | 4 ++ .../Validators/SetAgentSettingValidator.cs | 3 + .../BackgroundJobs/JobSetup.cs | 7 +-- .../Jobs/AgentFailoverJob.cs | 31 ++++++---- .../Jobs/HeartbeatMonitorJob.cs | 15 +++-- .../Jobs/HeartbeatTimeoutPolicy.cs | 57 +++++++++++++++++++ .../Settings/AgentDefaultsSection.razor | 2 +- .../Controllers/SettingsController.cs | 11 +++- src/Heimdall.Web/Program.cs | 14 ++++- 10 files changed, 125 insertions(+), 23 deletions(-) create mode 100644 src/Heimdall.Infrastructure/Jobs/HeartbeatTimeoutPolicy.cs diff --git a/src/Heimdall.Application/Settings/Commands/SetAgentSetting/SetAgentSettingCommand.cs b/src/Heimdall.Application/Settings/Commands/SetAgentSetting/SetAgentSettingCommand.cs index 96fbbec..2387421 100644 --- a/src/Heimdall.Application/Settings/Commands/SetAgentSetting/SetAgentSettingCommand.cs +++ b/src/Heimdall.Application/Settings/Commands/SetAgentSetting/SetAgentSettingCommand.cs @@ -19,6 +19,10 @@ public class SetAgentSettingCommandHandler : IRequestHandler 300)) + return ServiceResult.Failure("Heartbeat interval must be between 5 and 300 seconds", 400); + if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return ServiceResult.Failure("Setting is not agent-scoped", 400); diff --git a/src/Heimdall.Application/Settings/Commands/UpdateAppSetting/UpdateAppSettingCommand.cs b/src/Heimdall.Application/Settings/Commands/UpdateAppSetting/UpdateAppSettingCommand.cs index 0a5a0af..650d24c 100644 --- a/src/Heimdall.Application/Settings/Commands/UpdateAppSetting/UpdateAppSettingCommand.cs +++ b/src/Heimdall.Application/Settings/Commands/UpdateAppSetting/UpdateAppSettingCommand.cs @@ -23,6 +23,10 @@ public class UpdateAppSettingCommandHandler : IRequestHandler> Handle(UpdateAppSettingCommand request, CancellationToken ct) { + if (request.Key.Trim().Equals("heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase) && + (!int.TryParse(request.Value, out var heartbeatInterval) || heartbeatInterval is < 5 or > 300)) + return ServiceResult.Failure("Heartbeat interval must be between 5 and 300 seconds", 400); + var setting = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == request.Key, ct).ConfigureAwait(false); if (setting is null) return ServiceResult.NotFound($"Setting '{request.Key}' not found"); diff --git a/src/Heimdall.Application/Validators/SetAgentSettingValidator.cs b/src/Heimdall.Application/Validators/SetAgentSettingValidator.cs index 2b6ed4c..8535b82 100644 --- a/src/Heimdall.Application/Validators/SetAgentSettingValidator.cs +++ b/src/Heimdall.Application/Validators/SetAgentSettingValidator.cs @@ -9,5 +9,8 @@ public class SetAgentSettingValidator : AbstractValidator x.Key).NotEmpty().MaximumLength(200); RuleFor(x => x.Value).NotNull(); + When(x => string.Equals(x.Key, "heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase), () => + RuleFor(x => x.Value).Must(value => int.TryParse(value, out var seconds) && seconds is >= 5 and <= 300) + .WithMessage("Heartbeat interval must be between 5 and 300 seconds")); } } diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index aae1f8e..fb47718 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -7,10 +7,9 @@ public static class JobSetup { public static void ConfigureRecurringJobs(IRecurringJobManager manager) { - manager.AddOrUpdate( - "heartbeat-monitor", - job => job.ExecuteAsync(CancellationToken.None), - "*/1 * * * *"); + // AgentFailoverJob owns the stale -> offline transition so it can + // reassign cameras in the same pass. Remove the legacy competing job. + manager.RemoveIfExists("heartbeat-monitor"); manager.AddOrUpdate( "agent-failover", diff --git a/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs index 0d61b62..b62403d 100644 --- a/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AgentFailoverJob.cs @@ -7,8 +7,8 @@ using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Jobs; /// -/// Hangfire recurring job that detects agents whose heartbeat is stale -/// and automatically reassigns their cameras to online agents in the same site. +/// Hangfire recurring job that detects stale or offline agents and automatically +/// reassigns their cameras to online agents in the same site. /// Runs every 60 seconds. /// public sealed class AgentFailoverJob @@ -17,9 +17,6 @@ public sealed class AgentFailoverJob private readonly ICameraAssignmentService _assignmentService; private readonly ILogger _logger; - // Agents are marked offline after 90 seconds without heartbeat - private static readonly TimeSpan OfflineThreshold = TimeSpan.FromSeconds(90); - public AgentFailoverJob( IDbContextFactory dbFactory, ICameraAssignmentService assignmentService, @@ -31,25 +28,35 @@ public sealed class AgentFailoverJob } /// - /// Check all online agents. If any has a stale heartbeat while the system - /// still shows it as Online, trigger failover. + /// Check online agents for stale heartbeats and retry camera failover for + /// offline agents that still own enabled cameras. /// public async Task ExecuteAsync(CancellationToken ct = default) { await using var db = await _dbFactory.CreateDbContextAsync(ct); + var now = DateTime.UtcNow; + var maximumStaleAt = now.AddSeconds(-HeartbeatTimeoutPolicy.MaximumTimeoutSeconds); + var timeoutPolicy = await HeartbeatTimeoutPolicy.LoadAsync(db, ct).ConfigureAwait(false); var staleAgents = await db.Agents .AsTracking() - .Where(a => a.Status == AgentStatus.Online - && a.LastHeartbeat != null - && a.LastHeartbeat < DateTime.UtcNow - OfflineThreshold - && !a.IsDeleted) + .Where(a => !a.IsDeleted && + ((a.Status == AgentStatus.Online + && a.LastHeartbeat != null + && a.LastHeartbeat < maximumStaleAt) + || (a.Status == AgentStatus.Offline + && a.Cameras.Any(camera => !camera.IsDeleted && camera.Status != CameraStatus.Disabled)))) .ToListAsync(ct); + staleAgents = staleAgents + .Where(agent => agent.Status != AgentStatus.Online || + agent.LastHeartbeat < now.AddSeconds(-timeoutPolicy.GetTimeoutSeconds(agent.Id))) + .ToList(); + foreach (var agent in staleAgents) { _logger.LogWarning( - "Agent {AgentId} ({Name}) heartbeat stale — last was {LastHeartbeat}. Triggering failover.", + "Agent {AgentId} ({Name}) is offline or heartbeat stale — last was {LastHeartbeat}. Triggering failover.", agent.Id, agent.Name, agent.LastHeartbeat); agent.MarkOffline(); diff --git a/src/Heimdall.Infrastructure/Jobs/HeartbeatMonitorJob.cs b/src/Heimdall.Infrastructure/Jobs/HeartbeatMonitorJob.cs index 027b990..6e1cf0c 100644 --- a/src/Heimdall.Infrastructure/Jobs/HeartbeatMonitorJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/HeartbeatMonitorJob.cs @@ -6,7 +6,7 @@ using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Jobs; /// -/// Marks agents as Offline if no heartbeat received for 90+ seconds. +/// Marks agents Offline when their configured heartbeat cadence is exceeded. /// Runs every minute via Hangfire recurring job. /// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads. /// @@ -25,18 +25,25 @@ public class HeartbeatMonitorJob { await using var db = await _dbFactory.CreateDbContextAsync(ct); - var timeoutThreshold = DateTime.UtcNow.AddSeconds(-90); + var now = DateTime.UtcNow; + var maximumStaleAt = now.AddSeconds(-HeartbeatTimeoutPolicy.MaximumTimeoutSeconds); + var timeoutPolicy = await HeartbeatTimeoutPolicy.LoadAsync(db, ct).ConfigureAwait(false); var staleAgents = await db.Agents .Where(a => a.Status == AgentStatus.Online + && !a.IsDeleted && a.LastHeartbeat != null - && a.LastHeartbeat < timeoutThreshold) + && a.LastHeartbeat < maximumStaleAt) .ToListAsync(ct); + staleAgents = staleAgents + .Where(agent => agent.LastHeartbeat < now.AddSeconds(-timeoutPolicy.GetTimeoutSeconds(agent.Id))) + .ToList(); + if (staleAgents.Count == 0) return; - _logger.LogWarning("Marking {Count} agents as Offline (no heartbeat > 90s)", staleAgents.Count); + _logger.LogWarning("Marking {Count} agents as Offline after their configured heartbeat timeout", staleAgents.Count); foreach (var agent in staleAgents) { diff --git a/src/Heimdall.Infrastructure/Jobs/HeartbeatTimeoutPolicy.cs b/src/Heimdall.Infrastructure/Jobs/HeartbeatTimeoutPolicy.cs new file mode 100644 index 0000000..27892ce --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/HeartbeatTimeoutPolicy.cs @@ -0,0 +1,57 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Jobs; + +/// Resolves the heartbeat cadence configured globally or for one agent. +internal sealed class HeartbeatTimeoutPolicy +{ + private const string SettingKey = "heartbeat.interval.seconds"; + private const int DefaultIntervalSeconds = 30; + private const int MinimumIntervalSeconds = 5; + private const int MaximumIntervalSeconds = 300; + private const int SchedulerGraceSeconds = 60; + private const int MinimumTimeoutSeconds = 90; + + private readonly int _globalIntervalSeconds; + private readonly IReadOnlyDictionary _agentIntervals; + + private HeartbeatTimeoutPolicy(int globalIntervalSeconds, IReadOnlyDictionary agentIntervals) + { + _globalIntervalSeconds = globalIntervalSeconds; + _agentIntervals = agentIntervals; + } + + public static async Task LoadAsync(AppDbContext db, CancellationToken ct) + { + var globalValue = await db.AppSettings.AsNoTracking() + .Where(setting => setting.Key == SettingKey) + .Select(setting => setting.Value) + .FirstOrDefaultAsync(ct) + .ConfigureAwait(false); + var agentValues = await db.AgentSettings.AsNoTracking() + .Where(setting => setting.Key == SettingKey) + .Select(setting => new { setting.AgentId, setting.Value }) + .ToListAsync(ct) + .ConfigureAwait(false); + + var globalInterval = ParseInterval(globalValue, DefaultIntervalSeconds); + var overrides = agentValues.ToDictionary( + setting => setting.AgentId, + setting => ParseInterval(setting.Value, MaximumIntervalSeconds)); + return new HeartbeatTimeoutPolicy(globalInterval, overrides); + } + + public int GetTimeoutSeconds(Guid agentId) + { + var interval = _agentIntervals.GetValueOrDefault(agentId, _globalIntervalSeconds); + return Math.Max(MinimumTimeoutSeconds, interval * 2 + SchedulerGraceSeconds); + } + + public static int MaximumTimeoutSeconds => MaximumIntervalSeconds * 2 + SchedulerGraceSeconds; + + private static int ParseInterval(string? value, int fallback) => + int.TryParse(value, out var interval) && interval is >= MinimumIntervalSeconds and <= MaximumIntervalSeconds + ? interval + : fallback; +} diff --git a/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor b/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor index 4bda8f7..9e6a0f6 100644 --- a/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor +++ b/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor @@ -45,7 +45,7 @@ diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index e3f7472..9d4a75c 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -255,7 +255,16 @@ public class SettingsController : ControllerBase if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct); + var valueToApply = ""; + if (key.Equals("heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase)) + { + valueToApply = "30"; + var globalSetting = await _mediator.Send(new GetSettingByKeyQuery("heartbeat.interval.seconds"), ct); + if (globalSetting.IsSuccess && globalSetting.Data is not null) + valueToApply = globalSetting.Data.Value; + } + + await _broadcast.NotifyAgentSettingChanged(agentId, key, valueToApply, ct); _logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key); return NoContent(); } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 86c0704..1391ad0 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -296,6 +296,10 @@ public partial class Program private static async Task SeedIntegrationSettingsAsync(AppDbContext groupDb, HashSet existingKeys) { + var heartbeatInterval = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS"); + if (!int.TryParse(heartbeatInterval, out var heartbeatSeconds) || heartbeatSeconds is < 5 or > 300) + heartbeatInterval = "30"; + var defaults = new Dictionary { ["ntfy.baseUrl"] = Environment.GetEnvironmentVariable("NTFY__BASE_URL") ?? "https://ntfy.sh", @@ -312,9 +316,17 @@ public partial class Program ["ai.detection.enabled"] = Environment.GetEnvironmentVariable("AI__DETECTION__ENABLED") ?? "true", ["log.level"] = Environment.GetEnvironmentVariable("LOG__LEVEL") ?? "info", ["log.retentionDays"] = Environment.GetEnvironmentVariable("LOG__RETENTION_DAYS") ?? "7", - ["heartbeat.interval.seconds"] = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS") ?? "30", + ["heartbeat.interval.seconds"] = heartbeatInterval, ["sentry.enabled"] = "true", }; + + var existingHeartbeatSetting = await groupDb.AppSettings + .FirstOrDefaultAsync(setting => setting.Key == "heartbeat.interval.seconds"); + if (existingHeartbeatSetting is not null && + (!int.TryParse(existingHeartbeatSetting.Value, out var storedHeartbeatSeconds) || + storedHeartbeatSeconds is < 5 or > 300)) + existingHeartbeatSetting.UpdateValue(heartbeatInterval); + foreach (var (key, value) in defaults) { if (existingKeys.Contains(key)) continue;