From 8d5447f8263e77a3482291c103b035d8efd158a9 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:55:31 +0200 Subject: [PATCH 1/7] 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; From aea3b46f68405b2001dc66bea5ed9537b092f790 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:56:06 +0200 Subject: [PATCH 2/7] docs(agent): describe heartbeat failover policy --- docs/implementation.md | 10 ++++++---- todo.md | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/implementation.md b/docs/implementation.md index e9fe9dd..735ff35 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -23,7 +23,7 @@ La **vidéo live** arrive en dernier dans l'IHM. ⏳ Phase 12 : AI Pipeline [EN ATTENTE - hardware requis] ⏳ Phase 13 : Storage (RustFS/S3) [EN ATTENTE - v2] ⏳ Phase 14 : SignalR Hubs [EN ATTENTE - v2] -✅ Phase 15 : Hangfire Central [FAIT - heartbeat monitor] +✅ Phase 15 : Hangfire Central [FAIT - surveillance heartbeat et failover] ⏳ Phase 16 : Hangfire Agent (InMemory) [EN ATTENTE - v2] ⏳ Phase 17 : Notifications [EN ATTENTE - v2] ✅ Phase 18 : Blazor UI [FAIT - 13 pages] @@ -335,10 +335,12 @@ Le token d'enregistrement est : | API Key envoyée dans header Authorization | ✅ | | Détection GPU/CPU capabilities | ✅ | -### HeartbeatMonitor (Hangfire) +### Surveillance heartbeat et failover (Hangfire) -- Job planifié toutes les minutes ✅ -- Marque les agents Offline après 90s sans heartbeat ✅ +- Vérification et failover planifiés toutes les minutes ✅ +- Le délai utilise l'intervalle global ou la surcharge de l'agent, avec deux intervalles et une marge d'ordonnanceur (minimum 90 s) ✅ +- Le job de failover effectue la transition Offline et réessaie la réaffectation des caméras actives des agents déjà Offline ✅ +- Les intervalles sont limités à 5–300 s, conformément à la plage appliquée par l'Agent ✅ --- diff --git a/todo.md b/todo.md index fd277b2..00300b3 100644 --- a/todo.md +++ b/todo.md @@ -21,6 +21,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. +- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent. CI et validation sur plusieurs Agents attendues. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62 et #63 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), le test des anciens stockages inaccessibles et la vérification du changement de provider. - [ ] **OPS-05 / AGENT-06** Les deux Compose de production (principal et généré par l’interface) montent maintenant la clé publique de release depuis un fichier hôte indépendant de Central, en lecture seule, et configurent `Agent__UpdatePublicKeyPath`; l’absence du fichier empêche explicitement le démarrage Docker. Restent l’installation des clés de signature CI/publication réelle, puis la validation de release, digest/signature, mise à jour native et Docker, arrêt propre et rollback. From d543eced8d1ca6c08e8a84b4406df0e8b5ef2b1b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:58:06 +0200 Subject: [PATCH 3/7] fix(agent): wake heartbeat loop when interval changes --- .../Services/AgentRegistrationService.cs | 21 ++++++++++++++++++- src/Heimdall.Agent/Services/AgentState.cs | 13 +++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index 63a69d9..0822698 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -143,7 +143,26 @@ public class AgentRegistrationService : BackgroundService // takes effect without a restart. heartbeatInterval = TimeSpan.FromSeconds( _state.HeartbeatIntervalSeconds ?? _options.HeartbeatIntervalSeconds); - await Task.Delay(heartbeatInterval, stoppingToken); + await WaitForNextHeartbeatAsync(heartbeatInterval, stoppingToken); + } + } + + private async Task WaitForNextHeartbeatAsync(TimeSpan interval, CancellationToken stoppingToken) + { + using var waitCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + var delay = Task.Delay(interval, waitCts.Token); + var intervalChanged = _state.WaitForHeartbeatIntervalChangeAsync(waitCts.Token); + + await Task.WhenAny(delay, intervalChanged).ConfigureAwait(false); + waitCts.Cancel(); + + try + { + await Task.WhenAll(delay, intervalChanged).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) + { + // Either the interval elapsed or a config update woke the loop. } } diff --git a/src/Heimdall.Agent/Services/AgentState.cs b/src/Heimdall.Agent/Services/AgentState.cs index fc1ef2c..b420da0 100644 --- a/src/Heimdall.Agent/Services/AgentState.cs +++ b/src/Heimdall.Agent/Services/AgentState.cs @@ -28,6 +28,7 @@ namespace Heimdall.Agent.Services; /// public sealed class AgentState { + private readonly SemaphoreSlim _heartbeatIntervalChanged = new(0, 1); /// Data Protection purpose used to encrypt/decrypt the API key. public const string KeyProtectionPurpose = "Heimdall.Agent.ApiKey"; @@ -116,9 +117,19 @@ public sealed class AgentState public int? HeartbeatIntervalSeconds { get => _snapshot.HeartbeatIntervalSeconds; - set => Interlocked.Exchange(ref _snapshot, _snapshot with { HeartbeatIntervalSeconds = value }); + set + { + var previous = Interlocked.Exchange(ref _snapshot, _snapshot with { HeartbeatIntervalSeconds = value }); + if (previous.HeartbeatIntervalSeconds == value) return; + + try { _heartbeatIntervalChanged.Release(); } + catch (SemaphoreFullException) { } + } } + /// Waits until a remote heartbeat interval change needs to re-arm the send loop. + public Task WaitForHeartbeatIntervalChangeAsync(CancellationToken ct) => _heartbeatIntervalChanged.WaitAsync(ct); + /// /// Loads a previously saved identity, or returns null if none exists or the /// state cannot be read. Legacy plaintext files are detected, kept in From 3d871b72ac7cf9b12763daf2af9fdba4f27a920a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:08:00 +0100 Subject: [PATCH 4/7] fix(agent): use a lightweight heartbeat change signal --- .../Services/AgentRegistrationService.cs | 21 +++++++------- src/Heimdall.Agent/Services/AgentState.cs | 28 +++++++++++++------ 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index 0822698..31ddaee 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -141,28 +141,27 @@ public class AgentRegistrationService : BackgroundService // Re-read the interval each cycle so a remote setting change // (ConfigReceiverService → AgentState.HeartbeatIntervalSeconds) // takes effect without a restart. + var intervalSnapshot = _state.GetHeartbeatIntervalSnapshot(); heartbeatInterval = TimeSpan.FromSeconds( - _state.HeartbeatIntervalSeconds ?? _options.HeartbeatIntervalSeconds); - await WaitForNextHeartbeatAsync(heartbeatInterval, stoppingToken); + intervalSnapshot.IntervalSeconds ?? _options.HeartbeatIntervalSeconds); + await WaitForNextHeartbeatAsync(heartbeatInterval, intervalSnapshot.Changed, stoppingToken); } } - private async Task WaitForNextHeartbeatAsync(TimeSpan interval, CancellationToken stoppingToken) + private static async Task WaitForNextHeartbeatAsync( + TimeSpan interval, Task intervalChanged, CancellationToken stoppingToken) { - using var waitCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); - var delay = Task.Delay(interval, waitCts.Token); - var intervalChanged = _state.WaitForHeartbeatIntervalChangeAsync(waitCts.Token); - + using var delayCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + var delay = Task.Delay(interval, delayCts.Token); await Task.WhenAny(delay, intervalChanged).ConfigureAwait(false); - waitCts.Cancel(); - + delayCts.Cancel(); try { - await Task.WhenAll(delay, intervalChanged).ConfigureAwait(false); + await delay.ConfigureAwait(false); } catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) { - // Either the interval elapsed or a config update woke the loop. + // A config update woke the loop before the scheduled interval elapsed. } } diff --git a/src/Heimdall.Agent/Services/AgentState.cs b/src/Heimdall.Agent/Services/AgentState.cs index b420da0..b107470 100644 --- a/src/Heimdall.Agent/Services/AgentState.cs +++ b/src/Heimdall.Agent/Services/AgentState.cs @@ -28,7 +28,8 @@ namespace Heimdall.Agent.Services; /// public sealed class AgentState { - private readonly SemaphoreSlim _heartbeatIntervalChanged = new(0, 1); + private readonly object _heartbeatIntervalLock = new(); + private TaskCompletionSource _heartbeatIntervalChanged = NewHeartbeatIntervalSignal(); /// Data Protection purpose used to encrypt/decrypt the API key. public const string KeyProtectionPurpose = "Heimdall.Agent.ApiKey"; @@ -119,16 +120,27 @@ public sealed class AgentState get => _snapshot.HeartbeatIntervalSeconds; set { - var previous = Interlocked.Exchange(ref _snapshot, _snapshot with { HeartbeatIntervalSeconds = value }); - if (previous.HeartbeatIntervalSeconds == value) return; - - try { _heartbeatIntervalChanged.Release(); } - catch (SemaphoreFullException) { } + TaskCompletionSource signal; + lock (_heartbeatIntervalLock) + { + if (_snapshot.HeartbeatIntervalSeconds == value) return; + Interlocked.Exchange(ref _snapshot, _snapshot with { HeartbeatIntervalSeconds = value }); + signal = _heartbeatIntervalChanged; + _heartbeatIntervalChanged = NewHeartbeatIntervalSignal(); + } + signal.TrySetResult(); } } - /// Waits until a remote heartbeat interval change needs to re-arm the send loop. - public Task WaitForHeartbeatIntervalChangeAsync(CancellationToken ct) => _heartbeatIntervalChanged.WaitAsync(ct); + /// Reads the current cadence and its corresponding change signal atomically. + public (int? IntervalSeconds, Task Changed) GetHeartbeatIntervalSnapshot() + { + lock (_heartbeatIntervalLock) + return (_snapshot.HeartbeatIntervalSeconds, _heartbeatIntervalChanged.Task); + } + + private static TaskCompletionSource NewHeartbeatIntervalSignal() => + new(TaskCreationOptions.RunContinuationsAsynchronously); /// /// Loads a previously saved identity, or returns null if none exists or the From b41d8d3910307b5412d495475598dbb883cd7995 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:18:51 +0100 Subject: [PATCH 5/7] test(agent): use supported stale heartbeat threshold --- tests/Heimdall.Infrastructure.Tests/AgentFailoverJobTests.cs | 2 +- .../Heimdall.Infrastructure.Tests/HeartbeatMonitorJobTests.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Heimdall.Infrastructure.Tests/AgentFailoverJobTests.cs b/tests/Heimdall.Infrastructure.Tests/AgentFailoverJobTests.cs index be0bce9..22f1b2d 100644 --- a/tests/Heimdall.Infrastructure.Tests/AgentFailoverJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AgentFailoverJobTests.cs @@ -68,7 +68,7 @@ public class AgentFailoverJobTests : IAsyncLifetime var agent = new Agent(site.Id, "stale-agent", "host1", "1.0"); agent.Register("hash", "pref"); - SetField(agent, "LastHeartbeat", DateTime.UtcNow.AddSeconds(-180)); + SetField(agent, "LastHeartbeat", DateTime.UtcNow.AddSeconds(-900)); SetField(agent, "Status", AgentStatus.Online); db.Agents.Add(agent); await db.SaveChangesAsync(); diff --git a/tests/Heimdall.Infrastructure.Tests/HeartbeatMonitorJobTests.cs b/tests/Heimdall.Infrastructure.Tests/HeartbeatMonitorJobTests.cs index c48d6fb..cd7a6ae 100644 --- a/tests/Heimdall.Infrastructure.Tests/HeartbeatMonitorJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/HeartbeatMonitorJobTests.cs @@ -83,7 +83,7 @@ public class HeartbeatMonitorJobTests : IDisposable [Fact] public async Task ExecuteAsync_StaleAgent_MarksOffline() { - await SeedOnlineAgentAsync(DateTime.UtcNow.AddSeconds(-180)); + await SeedOnlineAgentAsync(DateTime.UtcNow.AddSeconds(-900)); var job = new HeartbeatMonitorJob(_dbFactory, _logger); await job.ExecuteAsync(CancellationToken.None); @@ -96,7 +96,7 @@ public class HeartbeatMonitorJobTests : IDisposable [Fact] public async Task ExecuteAsync_MixedStaleAndFresh_MarksOnlyStale() { - await SeedOnlineAgentAsync(DateTime.UtcNow.AddSeconds(-180)); + await SeedOnlineAgentAsync(DateTime.UtcNow.AddSeconds(-900)); await SeedOnlineAgentAsync(DateTime.UtcNow.AddSeconds(-10)); var job = new HeartbeatMonitorJob(_dbFactory, _logger); From f310fe0ebfed73867f0c3577986d20bedda386e0 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:19:58 +0100 Subject: [PATCH 6/7] docs(agent): clarify heartbeat failover validation --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 00300b3..f4f3a36 100644 --- a/todo.md +++ b/todo.md @@ -21,7 +21,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. -- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent. CI et validation sur plusieurs Agents attendues. +- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. CI du dernier commit en attente; validation sur plusieurs Agents reste à faire. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62 et #63 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), le test des anciens stockages inaccessibles et la vérification du changement de provider. - [ ] **OPS-05 / AGENT-06** Les deux Compose de production (principal et généré par l’interface) montent maintenant la clé publique de release depuis un fichier hôte indépendant de Central, en lecture seule, et configurent `Agent__UpdatePublicKeyPath`; l’absence du fichier empêche explicitement le démarrage Docker. Restent l’installation des clés de signature CI/publication réelle, puis la validation de release, digest/signature, mise à jour native et Docker, arrêt propre et rollback. From e9c61e64317ffc2f11445602dae9ccf51b44167e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 03:20:33 +0100 Subject: [PATCH 7/7] docs(agent): record heartbeat failover validation --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index f4f3a36..df791ac 100644 --- a/todo.md +++ b/todo.md @@ -21,7 +21,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. -- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. CI du dernier commit en attente; validation sur plusieurs Agents reste à faire. +- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62 et #63 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), le test des anciens stockages inaccessibles et la vérification du changement de provider. - [ ] **OPS-05 / AGENT-06** Les deux Compose de production (principal et généré par l’interface) montent maintenant la clé publique de release depuis un fichier hôte indépendant de Central, en lecture seule, et configurent `Agent__UpdatePublicKeyPath`; l’absence du fichier empêche explicitement le démarrage Docker. Restent l’installation des clés de signature CI/publication réelle, puis la validation de release, digest/signature, mise à jour native et Docker, arrêt propre et rollback.