Files
Heimdall/src/Heimdall.Agent/Services/DetectionReporterService.cs
T

414 lines
21 KiB
C#
Raw Normal View History

using System.Collections.Concurrent;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Heimdall.Agent;
using Heimdall.Application.DTOs;
using Heimdall.Application.Metrics;
using Heimdall.Domain.Enums;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
public interface IDetectionReporter
{
/// <summary>Durably enqueue a detection event. True means queued, not yet delivered.</summary>
Task<bool> ReportAsync(
Guid cameraId, EventType type, double confidence, string? label,
string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default);
}
/// <summary>
/// Persists events before attempting delivery. Events are retried until Central
/// acknowledges them; the stable event ID makes retries idempotent there.
/// The local outbox is bounded by both row count and payload bytes.
/// </summary>
public sealed class DetectionReporterService : BackgroundService, IDetectionReporter
{
private const int MaxPendingEvents = 10_000;
private const int MaxDeadLetterEvents = 1_000;
private const long MaxOutboxBytes = 64L * 1024 * 1024;
private const int MaxEventPayloadBytes = 512 * 1024;
private const int ReadBatchSize = 100;
private static readonly TimeSpan DefaultCooldown = TimeSpan.FromSeconds(10);
private static readonly TimeSpan MotionCooldown = TimeSpan.FromSeconds(30);
private static readonly TimeSpan MinimumRetryDelay = TimeSpan.FromSeconds(5);
private static readonly TimeSpan MaximumRetryDelay = TimeSpan.FromMinutes(5);
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly AgentState _state;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<DetectionReporterService> _logger;
private readonly string _databasePath;
private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastQueued = new();
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;
private long _suppressedByCooldown;
private long _rejectedByCapacity;
private long _deadLettered;
public DetectionReporterService(
AgentState state,
IHttpClientFactory httpClientFactory,
ILogger<DetectionReporterService> logger)
: this(state, httpClientFactory, logger, Options.Create(new AgentOptions()))
{
}
public DetectionReporterService(
AgentState state,
IHttpClientFactory httpClientFactory,
ILogger<DetectionReporterService> 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-events.db");
}
public long FailedReports => Interlocked.Read(ref _failedReports);
public long SuppressedByCooldown => Interlocked.Read(ref _suppressedByCooldown);
public long RejectedByCapacity => Interlocked.Read(ref _rejectedByCapacity);
public long DeadLettered => Interlocked.Read(ref _deadLettered);
public async Task<bool> ReportAsync(
Guid cameraId, EventType type, double confidence, string? label,
string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default)
{
if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey))
return false;
var key = (cameraId, type);
var now = DateTime.UtcNow;
var cooldown = type == EventType.MotionDetected ? MotionCooldown : DefaultCooldown;
if (_lastQueued.TryGetValue(key, out var last) && now - last < cooldown)
{
Interlocked.Increment(ref _suppressedByCooldown);
HeimdallMetrics.RecordEventSuppressed("cooldown", type.ToString());
return false;
}
var request = new CreateCameraEventRequest(
cameraId, type, confidence, label, metadataJson, occurredAt ?? now, Guid.NewGuid());
try
{
var queued = await EnqueueAsync(request, ct).ConfigureAwait(false);
if (!queued)
return false;
_lastQueued[key] = now;
try { _wake.Release(); }
catch (SemaphoreFullException) { }
return true;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return false;
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedReports);
_logger.LogError(ex, "Could not persist detection event for camera {CameraId}; Central was not updated", cameraId);
return false;
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var retryDelay = MinimumRetryDelay;
while (!stoppingToken.IsCancellationRequested)
{
try
{
await _wake.WaitAsync(retryDelay, stoppingToken).ConfigureAwait(false);
if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey))
continue;
var pending = await ReadPendingAsync(stoppingToken).ConfigureAwait(false);
var failed = false;
foreach (var item in pending)
{
if (stoppingToken.IsCancellationRequested) break;
if (!await SendAsync(item, stoppingToken).ConfigureAwait(false))
failed = true;
}
if (failed)
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, MaximumRetryDelay.TotalSeconds));
else
retryDelay = MinimumRetryDelay;
if (pending.Count == ReadBatchSize)
{
try { _wake.Release(); }
catch (SemaphoreFullException) { }
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedReports);
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, MaximumRetryDelay.TotalSeconds));
_logger.LogWarning(ex, "Detection outbox dispatch failed; persisted events will be retried");
}
}
}
private async Task<bool> SendAsync(PendingDetection item, 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.PostAsJsonAsync("api/events", item.Request, Json, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
await DeletePendingAsync(item.EventId, ct).ConfigureAwait(false);
return true;
}
if (IsPermanentFailure(response.StatusCode))
{
await MoveToDeadLetterAsync(item, $"HTTP {(int)response.StatusCode}", ct).ConfigureAwait(false);
Interlocked.Increment(ref _deadLettered);
HeimdallMetrics.RecordEventOutboxRejected("dead-letter", item.Request.Type.ToString());
_logger.LogError("Event {EventId} moved to the local dead-letter store after HTTP {StatusCode}",
item.EventId, response.StatusCode);
return true;
}
Interlocked.Increment(ref _failedReports);
await IncrementAttemptsAsync(item.EventId, ct).ConfigureAwait(false);
_logger.LogWarning("Event report {EventId} failed: {StatusCode} ({Reason}); retaining it in the outbox",
item.EventId, response.StatusCode, response.ReasonPhrase);
return false;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return false; }
catch (Exception ex)
{
Interlocked.Increment(ref _failedReports);
await IncrementAttemptsAsync(item.EventId, ct).ConfigureAwait(false);
_logger.LogDebug(ex, "Event report {EventId} failed; retaining it in the outbox", item.EventId);
return false;
}
}
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_detection_events (event_id TEXT PRIMARY KEY NOT NULL, event_type INTEGER NOT NULL, priority INTEGER NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS ix_pending_detection_events_priority_created ON pending_detection_events(priority DESC, created_at); CREATE TABLE IF NOT EXISTS dead_letter_detection_events (event_id TEXT PRIMARY KEY NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, last_error TEXT NOT NULL, attempts INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS ix_dead_letter_detection_events_created ON dead_letter_detection_events(created_at); 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<bool> EnqueueAsync(CreateCameraEventRequest request, CancellationToken ct)
{
var payload = JsonSerializer.Serialize(request, Json);
var payloadBytes = Encoding.UTF8.GetByteCount(payload);
if (payloadBytes > MaxEventPayloadBytes)
{
Interlocked.Increment(ref _rejectedByCapacity);
HeimdallMetrics.RecordEventOutboxRejected("payload-too-large", request.Type.ToString());
_logger.LogError("Event payload for camera {CameraId} exceeds the {MaxBytes}-byte outbox item limit",
request.CameraId, MaxEventPayloadBytes);
return false;
}
var eventId = request.EventId!.Value;
var priority = request.Type == EventType.MotionDetected ? 0 : 1;
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);
2026-10-22 20:03:48 +02:00
var (count, bytes) = await GetOutboxSizeAsync(connection, (SqliteTransaction)transaction, ct).ConfigureAwait(false);
while (count >= MaxPendingEvents || bytes + payloadBytes > MaxOutboxBytes)
{
var evictedBytes = await EvictOldestMotionEventAsync(connection, transaction, ct).ConfigureAwait(false);
if (evictedBytes is null)
{
Interlocked.Increment(ref _rejectedByCapacity);
HeimdallMetrics.RecordEventOutboxRejected("spool-full", request.Type.ToString());
_logger.LogCritical("Detection outbox is full ({Count} events, {Bytes} bytes); refusing event {EventId} ({Type})",
count, bytes, eventId, request.Type);
return false;
}
count--;
bytes -= evictedBytes.Value;
Interlocked.Increment(ref _rejectedByCapacity);
HeimdallMetrics.RecordEventOutboxRejected("evicted-motion", EventType.MotionDetected.ToString());
_logger.LogError("Detection outbox reached capacity; evicted the oldest motion event to retain event {EventId}", eventId);
}
await using var insert = connection.CreateCommand();
insert.Transaction = (SqliteTransaction)transaction;
insert.CommandText = "INSERT INTO pending_detection_events(event_id,event_type,priority,payload_json,created_at) VALUES($id,$type,$priority,$payload,$created);";
insert.Parameters.AddWithValue("$id", eventId.ToString("D"));
insert.Parameters.AddWithValue("$type", (int)request.Type);
insert.Parameters.AddWithValue("$priority", priority);
insert.Parameters.AddWithValue("$payload", payload);
insert.Parameters.AddWithValue("$created", DateTimeOffset.UtcNow.ToString("O"));
await insert.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await transaction.CommitAsync(ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count + 1, bytes + payloadBytes);
HeimdallMetrics.RecordEventCreated(request.Type.ToString(), request.CameraId);
return true;
}
finally { _databaseWriteGate.Release(); }
}
private static async Task<(long Count, long Bytes)> GetOutboxSizeAsync(
SqliteConnection connection, SqliteTransaction? transaction, CancellationToken ct)
{
await using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "SELECT COUNT(*), COALESCE(SUM(length(CAST(payload_json AS BLOB))),0) FROM pending_detection_events;";
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
await reader.ReadAsync(ct).ConfigureAwait(false);
return (reader.GetInt64(0), reader.GetInt64(1));
}
private static async Task<long?> EvictOldestMotionEventAsync(
SqliteConnection connection, System.Data.Common.DbTransaction transaction, CancellationToken ct)
{
await using var command = connection.CreateCommand();
command.Transaction = (SqliteTransaction)transaction;
command.CommandText = "DELETE FROM pending_detection_events WHERE event_id=(SELECT event_id FROM pending_detection_events WHERE priority=0 ORDER BY created_at LIMIT 1) RETURNING length(CAST(payload_json AS BLOB));";
var result = await command.ExecuteScalarAsync(ct).ConfigureAwait(false);
return result is null or DBNull ? null : Convert.ToInt64(result, System.Globalization.CultureInfo.InvariantCulture);
}
private async Task<List<PendingDetection>> ReadPendingAsync(CancellationToken ct)
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
await using var command = connection.CreateCommand();
command.CommandText = "SELECT event_id,payload_json,attempts FROM pending_detection_events ORDER BY priority DESC,created_at LIMIT $limit;";
command.Parameters.AddWithValue("$limit", ReadBatchSize);
var results = new List<PendingDetection>();
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
var request = JsonSerializer.Deserialize<CreateCameraEventRequest>(reader.GetString(1), Json);
if (request is not null && Guid.TryParse(reader.GetString(0), out var id))
results.Add(new PendingDetection(id, request, reader.GetInt32(2)));
}
return results;
}
private async Task DeletePendingAsync(Guid eventId, CancellationToken ct)
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = "DELETE FROM pending_detection_events WHERE event_id=$id;";
command.Parameters.AddWithValue("$id", eventId.ToString("D"));
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
}
private async Task IncrementAttemptsAsync(Guid eventId, CancellationToken ct)
{
try
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = "UPDATE pending_detection_events SET attempts=attempts+1 WHERE event_id=$id;";
command.Parameters.AddWithValue("$id", eventId.ToString("D"));
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
catch (Exception ex) { _logger.LogWarning(ex, "Could not update retry count for event {EventId}", eventId); }
}
private async Task MoveToDeadLetterAsync(PendingDetection item, string error, 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 trim = connection.CreateCommand();
trim.Transaction = (SqliteTransaction)transaction;
trim.CommandText = "DELETE FROM dead_letter_detection_events WHERE event_id IN (SELECT event_id FROM dead_letter_detection_events ORDER BY created_at DESC LIMIT -1 OFFSET $keep);";
trim.Parameters.AddWithValue("$keep", MaxDeadLetterEvents - 1);
await trim.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var insert = connection.CreateCommand();
insert.Transaction = (SqliteTransaction)transaction;
insert.CommandText = "INSERT OR REPLACE INTO dead_letter_detection_events(event_id,payload_json,created_at,last_error,attempts) SELECT event_id,payload_json,created_at,$error,attempts+1 FROM pending_detection_events WHERE event_id=$id; DELETE FROM pending_detection_events WHERE event_id=$id;";
insert.Parameters.AddWithValue("$error", error);
insert.Parameters.AddWithValue("$id", item.EventId.ToString("D"));
await insert.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await transaction.CommitAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
}
finally { _databaseWriteGate.Release(); }
}
private static bool IsPermanentFailure(System.Net.HttpStatusCode statusCode) =>
statusCode is System.Net.HttpStatusCode.BadRequest
or System.Net.HttpStatusCode.NotFound
or System.Net.HttpStatusCode.Conflict
or System.Net.HttpStatusCode.Gone
or System.Net.HttpStatusCode.UnprocessableEntity;
/// <summary>Map a detection label to its event category.</summary>
public static EventType? MapDetectionToEventType(string label)
{
var normalized = label.ToLowerInvariant();
if (normalized == "person") return EventType.PersonDetected;
if (normalized is "car" or "truck" or "bus" or "motorcycle" or "bicycle" or "boat" or "train" or "airplane")
return EventType.VehicleDetected;
if (normalized is "cat" or "dog" or "bird" or "horse" or "cow" or "sheep")
return null;
return EventType.MotionDetected;
}
private sealed record PendingDetection(Guid EventId, CreateCameraEventRequest Request, int Attempts);
}