using System.Collections.Concurrent; using System.Net.Http.Json; using System.Text.Json; using System.Text; using Heimdall.Agent; using Heimdall.Agent.Data; using Heimdall.Application.DTOs; using Heimdall.Application.Metrics; using Heimdall.Domain.Enums; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; public interface IDetectionReporter { /// Durably enqueue a detection event. True means queued, not yet delivered. Task ReportAsync( Guid cameraId, EventType type, double confidence, string? label, string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null, Guid? eventId = null, CancellationToken ct = default); } /// /// 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. /// 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 MaxSnapshotBytes = 2 * 1024 * 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 _logger; private readonly CameraConfigStore? _cameras; private readonly RecordingTriggerStore? _recordingTriggers; private readonly string _databasePath; private readonly PooledDbContextFactory _contextFactory; 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 logger) : this(state, httpClientFactory, logger, Options.Create(new AgentOptions())) { } public DetectionReporterService( AgentState state, IHttpClientFactory httpClientFactory, ILogger logger, IOptions options) : this(state, httpClientFactory, logger, options, null, null) { } public DetectionReporterService( AgentState state, IHttpClientFactory httpClientFactory, ILogger logger, IOptions options, CameraConfigStore? cameras, RecordingTriggerStore? recordingTriggers) { _state = state; _httpClientFactory = httpClientFactory; _logger = logger; _cameras = cameras; _recordingTriggers = recordingTriggers; var stateDirectory = options.Value.StateDirectory ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); _databasePath = Path.Combine(stateDirectory, "agent-events.db"); _contextFactory = new PooledDbContextFactory( new DbContextOptionsBuilder() .UseSqlite(AgentOutboxDatabaseInitializer.CreateConnectionString(_databasePath)).Options); } 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 ReportAsync( Guid cameraId, EventType type, double confidence, string? label, string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null, Guid? eventId = null, CancellationToken ct = default) { if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return false; if (eventId == Guid.Empty) return false; if (type == EventType.ManualSnapshot && snapshotJpeg is null) return false; var key = (cameraId, type); var now = DateTime.UtcNow; var cooldown = type == EventType.MotionDetected ? MotionCooldown : DefaultCooldown; if (type != EventType.ManualSnapshot && _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, eventId ?? Guid.NewGuid()); try { // Persist the capture request as soon as the qualifying event is observed. // The durable HTTP outbox can reject a report (or the process can stop // before the outbox transaction); recording must not depend on delivery. if (ShouldTriggerRecording(type) && _cameras?.Cameras.Any(camera => camera.CameraId == cameraId && camera.EventRecordingEnabled) == true && _recordingTriggers is not null) { try { await _recordingTriggers.RegisterAsync(cameraId, request.OccurredAt ?? now, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch (Exception ex) { _logger.LogWarning("Could not persist event recording trigger for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); } } var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false); if (!queued) return false; if (type != EventType.ManualSnapshot) _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 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) { if (item.SnapshotJpeg is not null) { using var content = new ByteArrayContent(item.SnapshotJpeg); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); using var upload = await client.PutAsync( $"api/events/{item.EventId:D}/snapshot/content", content, ct).ConfigureAwait(false); if (!upload.IsSuccessStatusCode) { if (IsPermanentFailure(upload.StatusCode)) { await MoveToDeadLetterAsync(item, $"Snapshot upload HTTP {(int)upload.StatusCode}", ct).ConfigureAwait(false); Interlocked.Increment(ref _deadLettered); HeimdallMetrics.RecordEventOutboxRejected("dead-letter", item.Request.Type.ToString()); _logger.LogError("Snapshot for event {EventId} moved to the local dead-letter store after HTTP {StatusCode}", item.EventId, upload.StatusCode); return true; } Interlocked.Increment(ref _failedReports); await IncrementAttemptsAsync(item.EventId, ct).ConfigureAwait(false); _logger.LogWarning("Snapshot upload for event {EventId} failed: HTTP {StatusCode}; retaining event and JPEG in the outbox", item.EventId, (int)upload.StatusCode); return false; } } 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 OpenDatabaseAsync(CancellationToken ct) { await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false); try { if (!_databaseInitialized) { await AgentOutboxDatabaseInitializer.InitializeEventsAsync(_contextFactory, _databasePath, ct).ConfigureAwait(false); _databaseInitialized = true; } return await _contextFactory.CreateDbContextAsync(ct).ConfigureAwait(false); } finally { _databaseInitializationGate.Release(); } } private async Task EnqueueAsync(CreateCameraEventRequest request, byte[]? snapshotJpeg, 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; } if (snapshotJpeg is not null && (snapshotJpeg.Length < 4 || snapshotJpeg.Length > MaxSnapshotBytes || snapshotJpeg[0] != 0xff || snapshotJpeg[1] != 0xd8 || snapshotJpeg[^2] != 0xff || snapshotJpeg[^1] != 0xd9)) { if (request.Type == EventType.ManualSnapshot) return false; _logger.LogWarning("Captured JPEG for camera {CameraId} is invalid or exceeds {MaxBytes} bytes; retaining the event without an image", request.CameraId, MaxSnapshotBytes); snapshotJpeg = null; } var itemBytes = payloadBytes + (snapshotJpeg?.Length ?? 0); var eventId = request.EventId!.Value; var priority = request.Type == EventType.MotionDetected ? 0 : 1; await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false); try { await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false); await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false); var queuedPayloads = await db.PendingEvents.AsNoTracking() .Select(item => new { item.PayloadJson, item.SnapshotJpeg }) .ToListAsync(ct).ConfigureAwait(false); var count = (long)queuedPayloads.Count; var bytes = queuedPayloads.Sum(item => (long)Encoding.UTF8.GetByteCount(item.PayloadJson) + (item.SnapshotJpeg?.LongLength ?? 0)); while (count >= MaxPendingEvents || bytes + itemBytes > MaxOutboxBytes) { var oldestMotion = await db.PendingEvents .Where(item => item.Priority == 0) .OrderBy(item => item.CreatedAt) .FirstOrDefaultAsync(ct).ConfigureAwait(false); if (oldestMotion 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; } var evictedBytes = Encoding.UTF8.GetByteCount(oldestMotion.PayloadJson) + (oldestMotion.SnapshotJpeg?.LongLength ?? 0); db.PendingEvents.Remove(oldestMotion); await db.SaveChangesAsync(ct).ConfigureAwait(false); count--; bytes -= evictedBytes; 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); } db.PendingEvents.Add(new PendingDetectionEvent { EventId = eventId.ToString("D"), EventType = (int)request.Type, Priority = priority, PayloadJson = payload, CreatedAt = DateTimeOffset.UtcNow.ToString("O"), SnapshotJpeg = snapshotJpeg }); await db.SaveChangesAsync(ct).ConfigureAwait(false); await transaction.CommitAsync(ct).ConfigureAwait(false); HeimdallMetrics.SetEventOutboxState((int)count + 1, bytes + itemBytes); HeimdallMetrics.RecordEventCreated(request.Type.ToString(), request.CameraId); return true; } finally { _databaseWriteGate.Release(); } } private static async Task<(long Count, long Bytes)> GetOutboxSizeAsync( AgentEventsDbContext db, CancellationToken ct) { var payloads = await db.PendingEvents.AsNoTracking() .Select(item => new { item.PayloadJson, item.SnapshotJpeg }) .ToListAsync(ct).ConfigureAwait(false); return (payloads.Count, payloads.Sum(item => (long)Encoding.UTF8.GetByteCount(item.PayloadJson) + (item.SnapshotJpeg?.LongLength ?? 0))); } private async Task> ReadPendingAsync(CancellationToken ct) { await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false); var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false); HeimdallMetrics.SetEventOutboxState((int)count, bytes); var rows = await db.PendingEvents.AsNoTracking() .OrderByDescending(item => item.Priority) .ThenBy(item => item.CreatedAt) .Take(ReadBatchSize) .ToListAsync(ct).ConfigureAwait(false); return rows.Select(item => new { Item = item, Request = JsonSerializer.Deserialize(item.PayloadJson, Json) }) .Where(entry => entry.Request is not null && Guid.TryParse(entry.Item.EventId, out _)) .Select(entry => new PendingDetection(Guid.Parse(entry.Item.EventId), entry.Request!, entry.Item.Attempts, entry.Item.SnapshotJpeg)) .ToList(); } private async Task DeletePendingAsync(Guid eventId, CancellationToken ct) { await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false); try { await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false); var item = await db.PendingEvents.FindAsync([eventId.ToString("D")], ct).ConfigureAwait(false); if (item is not null) { db.PendingEvents.Remove(item); await db.SaveChangesAsync(ct).ConfigureAwait(false); } var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false); HeimdallMetrics.SetEventOutboxState((int)count, bytes); } finally { _databaseWriteGate.Release(); } } private async Task IncrementAttemptsAsync(Guid eventId, CancellationToken ct) { try { await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false); var item = await db.PendingEvents.FindAsync([eventId.ToString("D")], ct).ConfigureAwait(false); if (item is not null) { item.Attempts++; await db.SaveChangesAsync(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 db = await OpenDatabaseAsync(ct).ConfigureAwait(false); await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false); var pending = await db.PendingEvents.FindAsync([item.EventId.ToString("D")], ct).ConfigureAwait(false); if (pending is null) return; var excess = await db.DeadLetters.OrderByDescending(letter => letter.CreatedAt) .Skip(MaxDeadLetterEvents - 1).ToListAsync(ct).ConfigureAwait(false); db.DeadLetters.RemoveRange(excess); db.DeadLetters.Add(new DeadLetterDetectionEvent { EventId = pending.EventId, PayloadJson = pending.PayloadJson, CreatedAt = pending.CreatedAt, LastError = error, Attempts = pending.Attempts + 1 }); db.PendingEvents.Remove(pending); await db.SaveChangesAsync(ct).ConfigureAwait(false); await transaction.CommitAsync(ct).ConfigureAwait(false); var (count, bytes) = await GetOutboxSizeAsync(db, 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; private static bool ShouldTriggerRecording(EventType type) => type is EventType.MotionDetected or EventType.PersonDetected or EventType.VehicleDetected or EventType.UnknownPerson or EventType.FaceRecognized or EventType.LicensePlateDetected; /// Map a detection label to its event category. 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, byte[]? SnapshotJpeg); }