From 3d07ea4b375295d623bf5ca0eacd11f105d1801f Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 22 Oct 2026 07:15:05 +0200 Subject: [PATCH] fix(agent): persist camera status reports --- src/Heimdall.Agent/Heimdall.Agent.csproj | 1 + src/Heimdall.Agent/Program.cs | 1 + .../Services/CameraStatusReporterService.cs | 234 +++++++++++++++--- src/Heimdall.Agent/packages.lock.json | 5 +- 4 files changed, 199 insertions(+), 42 deletions(-) diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index 56316cf..a2a9a39 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -22,6 +22,7 @@ + diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 641e10a..3d5b568 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -112,6 +112,7 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/CameraStatusReporterService.cs b/src/Heimdall.Agent/Services/CameraStatusReporterService.cs index b21a730..55724de 100644 --- a/src/Heimdall.Agent/Services/CameraStatusReporterService.cs +++ b/src/Heimdall.Agent/Services/CameraStatusReporterService.cs @@ -1,7 +1,9 @@ -using System.Collections.Concurrent; using System.Net.Http.Json; +using Heimdall.Agent; using Heimdall.Application.DTOs; +using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; @@ -11,68 +13,50 @@ public interface ICameraStatusReporter Task ReportAsync(Guid cameraId, string status, CancellationToken ct); } -/// -/// Reports camera live status to the Central (PUT /api/agents/{id}/cameras/{cameraId}/status, -/// API Key auth). Keeps Camera.Status in sync with the real capture state: -/// capture active → Online, ffmpeg failed/missing → Error, camera removed/disabled -/// → Disabled. Fire-and-forget with per-camera cooldown: only sends when the state -/// actually changes, never per heartbeat. Failures are dropped (with a counter + -/// rate-limited log) — the pipeline must never block on the network. -/// -public sealed class CameraStatusReporterService : ICameraStatusReporter +/// Durably queues camera status updates and retries them until Central accepts them. +public sealed class CameraStatusReporterService : BackgroundService, ICameraStatusReporter { + private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(5); private readonly AgentState _state; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; - private readonly ConcurrentDictionary _lastReported = new(); + private readonly string _databasePath; + private readonly SemaphoreSlim _wake = new(0, 1); + private readonly SemaphoreSlim _databaseWriteGate = new(1, 1); + private readonly SemaphoreSlim _databaseInitializationGate = new(1, 1); + private bool _databaseInitialized; private long _failedReports; public CameraStatusReporterService( AgentState state, IHttpClientFactory httpClientFactory, - ILogger logger) + ILogger logger, + IOptions options) { _state = state; _httpClientFactory = httpClientFactory; _logger = logger; + var stateDirectory = options.Value.StateDirectory + ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); + Directory.CreateDirectory(stateDirectory); + _databasePath = Path.Combine(stateDirectory, "agent-outbox.db"); } - /// Number of failed status report attempts (drop, not retried). + /// Number of failed status report attempts. Failed reports remain queued. public long FailedReports => Interlocked.Read(ref _failedReports); /// - /// Report the status for one camera. No-op when the status is unchanged - /// since the last report or when the agent is not registered. + /// Persist the latest desired status for one camera before returning. A newer + /// status replaces an older unsent status for that camera. /// public async Task ReportAsync(Guid cameraId, string status, CancellationToken ct) { - if (_state.AgentId == Guid.Empty) - return; - if (_lastReported.TryGetValue(cameraId, out var last) && last == status) - return; - try { - using var client = _httpClientFactory.CreateClient("Central"); - client.DefaultRequestHeaders.Remove("X-API-Key"); - client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); - - var response = await client.PutAsJsonAsync( - $"api/agents/{_state.AgentId}/cameras/{cameraId}/status", - new ReportCameraStatusRequest(status), ct).ConfigureAwait(false); - - if (response.IsSuccessStatusCode) - { - _lastReported[cameraId] = status; - } - else - { - Interlocked.Increment(ref _failedReports); - _logger.LogWarning( - "Camera status report failed for {CameraId}: {StatusCode} ({Reason})", - cameraId, response.StatusCode, response.ReasonPhrase); - } + await UpsertPendingStatusAsync(cameraId, status, ct).ConfigureAwait(false); + try { _wake.Release(); } + catch (SemaphoreFullException) { } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -81,7 +65,177 @@ public sealed class CameraStatusReporterService : ICameraStatusReporter catch (Exception ex) { Interlocked.Increment(ref _failedReports); - _logger.LogDebug(ex, "Camera status report dropped for {CameraId}", cameraId); + _logger.LogError(ex, "Could not persist camera status for {CameraId}; Central was not updated", cameraId); } } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await _wake.WaitAsync(RetryDelay, stoppingToken).ConfigureAwait(false); + if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) + continue; + + foreach (var pending in await ReadPendingStatusesAsync(stoppingToken).ConfigureAwait(false)) + { + if (stoppingToken.IsCancellationRequested) break; + await SendPendingStatusAsync(pending, stoppingToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + Interlocked.Increment(ref _failedReports); + _logger.LogWarning(ex, "Camera status outbox dispatch failed; pending statuses will be retried"); + try { await Task.Delay(RetryDelay, stoppingToken).ConfigureAwait(false); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + } + } + } + + private async Task SendPendingStatusAsync(PendingCameraStatus pending, CancellationToken ct) + { + try + { + using var client = _httpClientFactory.CreateClient("Central"); + client.DefaultRequestHeaders.Remove("X-API-Key"); + client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + using var response = await client.PutAsJsonAsync( + $"api/agents/{_state.AgentId}/cameras/{pending.CameraId}/status", + new ReportCameraStatusRequest(pending.Status), ct).ConfigureAwait(false); + + if (response.IsSuccessStatusCode) + { + await DeletePendingStatusAsync(pending, ct).ConfigureAwait(false); + return; + } + + Interlocked.Increment(ref _failedReports); + _logger.LogWarning("Camera status report failed for {CameraId}: {StatusCode} ({Reason})", pending.CameraId, response.StatusCode, response.ReasonPhrase); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { } + catch (Exception ex) + { + Interlocked.Increment(ref _failedReports); + _logger.LogDebug(ex, "Camera status report failed for {CameraId}; retaining it in the outbox", pending.CameraId); + } + } + + private async Task OpenDatabaseAsync(CancellationToken ct) + { + var connection = new SqliteConnection(new SqliteConnectionStringBuilder + { + DataSource = _databasePath, + Mode = SqliteOpenMode.ReadWriteCreate, + DefaultTimeout = 5 + }.ToString()); + try + { + await connection.OpenAsync(ct).ConfigureAwait(false); + await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false); + try + { + await using var command = connection.CreateCommand(); + command.CommandText = _databaseInitialized + ? "PRAGMA synchronous=FULL;" + : "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS pending_camera_status (camera_id TEXT PRIMARY KEY NOT NULL, status TEXT NOT NULL, updated_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS acknowledged_camera_status (camera_id TEXT PRIMARY KEY NOT NULL, status TEXT NOT NULL); PRAGMA user_version=1;"; + await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + _databaseInitialized = true; + } + finally { _databaseInitializationGate.Release(); } + + if (OperatingSystem.IsLinux()) + { + try { File.SetUnixFileMode(_databasePath, UnixFileMode.UserRead | UnixFileMode.UserWrite); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + return connection; + } + catch + { + await connection.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + private async Task UpsertPendingStatusAsync(Guid cameraId, string status, CancellationToken ct) + { + await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false); + try + { + await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false); + await using (var pendingCheck = connection.CreateCommand()) + { + pendingCheck.CommandText = "SELECT status FROM pending_camera_status WHERE camera_id=$id;"; + pendingCheck.Parameters.AddWithValue("$id", cameraId.ToString("D")); + var pendingStatus = await pendingCheck.ExecuteScalarAsync(ct).ConfigureAwait(false) as string; + if (pendingStatus is not null) + { + if (string.Equals(pendingStatus, status, StringComparison.Ordinal)) return; + } + else + { + await using var acknowledgedCheck = connection.CreateCommand(); + acknowledgedCheck.CommandText = "SELECT status FROM acknowledged_camera_status WHERE camera_id=$id;"; + acknowledgedCheck.Parameters.AddWithValue("$id", cameraId.ToString("D")); + if (string.Equals(await acknowledgedCheck.ExecuteScalarAsync(ct).ConfigureAwait(false) as string, status, StringComparison.Ordinal)) + return; + } + } + + await using var command = connection.CreateCommand(); + command.CommandText = "INSERT INTO pending_camera_status(camera_id,status,updated_at) VALUES($id,$status,$updated) ON CONFLICT(camera_id) DO UPDATE SET status=excluded.status, updated_at=excluded.updated_at;"; + command.Parameters.AddWithValue("$id", cameraId.ToString("D")); + command.Parameters.AddWithValue("$status", status); + command.Parameters.AddWithValue("$updated", DateTimeOffset.UtcNow.ToString("O")); + await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + } + finally { _databaseWriteGate.Release(); } + } + + private async Task> ReadPendingStatusesAsync(CancellationToken ct) + { + await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false); + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT camera_id,status,updated_at FROM pending_camera_status ORDER BY updated_at;"; + var results = new List(); + await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + if (Guid.TryParse(reader.GetString(0), out var id)) results.Add(new PendingCameraStatus(id, reader.GetString(1), reader.GetString(2))); + return results; + } + + private async Task DeletePendingStatusAsync(PendingCameraStatus pending, CancellationToken ct) + { + await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false); + try + { + await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false); + await using var transaction = await connection.BeginTransactionAsync(ct).ConfigureAwait(false); + await using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM pending_camera_status WHERE camera_id=$id AND status=$status AND updated_at=$updated;"; + command.Transaction = (SqliteTransaction)transaction; + command.Parameters.AddWithValue("$id", pending.CameraId.ToString("D")); + command.Parameters.AddWithValue("$status", pending.Status); + command.Parameters.AddWithValue("$updated", pending.UpdatedAt); + await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + await using var acknowledged = connection.CreateCommand(); + acknowledged.Transaction = (SqliteTransaction)transaction; + acknowledged.CommandText = "INSERT INTO acknowledged_camera_status(camera_id,status) VALUES($id,$status) ON CONFLICT(camera_id) DO UPDATE SET status=excluded.status;"; + acknowledged.Parameters.AddWithValue("$id", pending.CameraId.ToString("D")); + acknowledged.Parameters.AddWithValue("$status", pending.Status); + await acknowledged.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + await transaction.CommitAsync(ct).ConfigureAwait(false); + } + finally { _databaseWriteGate.Release(); } + } + + private sealed record PendingCameraStatus(Guid CameraId, string Status, string UpdatedAt); } diff --git a/src/Heimdall.Agent/packages.lock.json b/src/Heimdall.Agent/packages.lock.json index ce7bc42..084880c 100644 --- a/src/Heimdall.Agent/packages.lock.json +++ b/src/Heimdall.Agent/packages.lock.json @@ -124,7 +124,8 @@ "contentHash": "zfCQ0/J/rATKKcpwcpQYFz8sxhvrzgGyblsATcfxqSCibRkPFmDZcFmfD0UfLi38q+VDMpwEVuzOCO3TpRy99Q==" }, "Microsoft.Data.Sqlite": { - "type": "Transitive", + "type": "Direct", + "requested": "[10.0.13, )", "resolved": "10.0.13", "contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==", "dependencies": { @@ -303,4 +304,4 @@ } } } -} \ No newline at end of file +}