fix(agent): persist camera status reports
This commit is contained in:
1 parent
75a09aaf9a
commit
3d07ea4b37
4 files changed
+199
-42
No files matched your search
@@ -22,6 +22,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" />
|
||||
<PackageReference Include="OpenTelemetry" Version="1.17.0" />
|
||||
|
||||
@@ -112,6 +112,7 @@ builder.Services.AddSingleton<IMdnsClient, MdnsClient>();
|
||||
builder.Services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
|
||||
builder.Services.AddSingleton<CameraStatusReporterService>();
|
||||
builder.Services.AddSingleton<ICameraStatusReporter>(sp => sp.GetRequiredService<CameraStatusReporterService>());
|
||||
builder.Services.AddHostedService<CameraStatusReporterService>(sp => sp.GetRequiredService<CameraStatusReporterService>());
|
||||
builder.Services.AddSingleton<DetectionReporterService>();
|
||||
builder.Services.AddSingleton<IDetectionReporter>(sp => sp.GetRequiredService<DetectionReporterService>());
|
||||
builder.Services.AddSingleton<DiscoveryScanTrigger>();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports camera live status to the Central (PUT /api/agents/{id}/cameras/{cameraId}/status,
|
||||
/// API Key auth). Keeps <c>Camera.Status</c> 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.
|
||||
/// </summary>
|
||||
public sealed class CameraStatusReporterService : ICameraStatusReporter
|
||||
/// <summary>Durably queues camera status updates and retries them until Central accepts them.</summary>
|
||||
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<CameraStatusReporterService> _logger;
|
||||
private readonly ConcurrentDictionary<Guid, string> _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<CameraStatusReporterService> logger)
|
||||
ILogger<CameraStatusReporterService> logger,
|
||||
IOptions<AgentOptions> 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");
|
||||
}
|
||||
|
||||
/// <summary>Number of failed status report attempts (drop, not retried).</summary>
|
||||
/// <summary>Number of failed status report attempts. Failed reports remain queued.</summary>
|
||||
public long FailedReports => Interlocked.Read(ref _failedReports);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<SqliteConnection> 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<List<PendingCameraStatus>> 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<PendingCameraStatus>();
|
||||
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);
|
||||
}
|
||||
@@ -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 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user