2026-08-12 09:18:42 +02:00
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Net.Http.Json;
|
2026-10-22 19:24:18 +02:00
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using Heimdall.Agent;
|
2026-10-26 08:19:44 +01:00
|
|
|
using Heimdall.Agent.Data;
|
2026-08-12 09:18:42 +02:00
|
|
|
using Heimdall.Application.DTOs;
|
2026-08-20 18:22:37 +02:00
|
|
|
using Heimdall.Application.Metrics;
|
2026-08-12 09:18:42 +02:00
|
|
|
using Heimdall.Domain.Enums;
|
2026-10-26 08:19:44 +01:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
2026-08-12 09:18:42 +02:00
|
|
|
using Microsoft.Extensions.Logging;
|
2026-10-22 19:24:18 +02:00
|
|
|
using Microsoft.Extensions.Options;
|
2026-08-12 09:18:42 +02:00
|
|
|
|
|
|
|
|
namespace Heimdall.Agent.Services;
|
|
|
|
|
|
|
|
|
|
public interface IDetectionReporter
|
|
|
|
|
{
|
2026-10-22 19:24:18 +02:00
|
|
|
/// <summary>Durably enqueue a detection event. True means queued, not yet delivered.</summary>
|
2026-08-12 09:18:42 +02:00
|
|
|
Task<bool> ReportAsync(
|
2026-10-22 19:24:18 +02:00
|
|
|
Guid cameraId, EventType type, double confidence, string? label,
|
2026-10-22 20:56:49 +02:00
|
|
|
string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null,
|
2026-10-23 07:20:47 +02:00
|
|
|
Guid? eventId = null,
|
2026-10-22 20:56:49 +02:00
|
|
|
CancellationToken ct = default);
|
2026-08-12 09:18:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2026-10-22 19:24:18 +02:00
|
|
|
/// 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.
|
2026-08-12 09:18:42 +02:00
|
|
|
/// </summary>
|
2026-10-22 19:24:18 +02:00
|
|
|
public sealed class DetectionReporterService : BackgroundService, IDetectionReporter
|
2026-08-12 09:18:42 +02:00
|
|
|
{
|
2026-10-22 19:24:18 +02:00
|
|
|
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;
|
2026-10-22 20:50:40 +02:00
|
|
|
private const int MaxSnapshotBytes = 2 * 1024 * 1024;
|
2026-10-22 19:24:18 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-08-12 09:18:42 +02:00
|
|
|
private readonly AgentState _state;
|
|
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
|
|
|
private readonly ILogger<DetectionReporterService> _logger;
|
2026-10-22 19:24:18 +02:00
|
|
|
private readonly string _databasePath;
|
2026-10-26 08:19:44 +01:00
|
|
|
private readonly PooledDbContextFactory<AgentEventsDbContext> _contextFactory;
|
2026-10-22 19:24:18 +02:00
|
|
|
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;
|
2026-08-12 09:18:42 +02:00
|
|
|
|
|
|
|
|
private long _failedReports;
|
|
|
|
|
private long _suppressedByCooldown;
|
2026-10-22 19:24:18 +02:00
|
|
|
private long _rejectedByCapacity;
|
|
|
|
|
private long _deadLettered;
|
2026-08-12 09:18:42 +02:00
|
|
|
|
|
|
|
|
public DetectionReporterService(
|
|
|
|
|
AgentState state,
|
|
|
|
|
IHttpClientFactory httpClientFactory,
|
|
|
|
|
ILogger<DetectionReporterService> logger)
|
2026-10-22 19:24:18 +02:00
|
|
|
: this(state, httpClientFactory, logger, Options.Create(new AgentOptions()))
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public DetectionReporterService(
|
|
|
|
|
AgentState state,
|
|
|
|
|
IHttpClientFactory httpClientFactory,
|
|
|
|
|
ILogger<DetectionReporterService> logger,
|
|
|
|
|
IOptions<AgentOptions> options)
|
2026-08-12 09:18:42 +02:00
|
|
|
{
|
|
|
|
|
_state = state;
|
|
|
|
|
_httpClientFactory = httpClientFactory;
|
|
|
|
|
_logger = logger;
|
2026-10-22 19:24:18 +02:00
|
|
|
var stateDirectory = options.Value.StateDirectory
|
|
|
|
|
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
|
|
|
|
|
_databasePath = Path.Combine(stateDirectory, "agent-events.db");
|
2026-10-26 08:19:44 +01:00
|
|
|
_contextFactory = new PooledDbContextFactory<AgentEventsDbContext>(
|
|
|
|
|
new DbContextOptionsBuilder<AgentEventsDbContext>()
|
|
|
|
|
.UseSqlite(AgentOutboxDatabaseInitializer.CreateConnectionString(_databasePath)).Options);
|
2026-08-12 09:18:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public long FailedReports => Interlocked.Read(ref _failedReports);
|
|
|
|
|
public long SuppressedByCooldown => Interlocked.Read(ref _suppressedByCooldown);
|
2026-10-22 19:24:18 +02:00
|
|
|
public long RejectedByCapacity => Interlocked.Read(ref _rejectedByCapacity);
|
|
|
|
|
public long DeadLettered => Interlocked.Read(ref _deadLettered);
|
2026-08-12 09:18:42 +02:00
|
|
|
|
|
|
|
|
public async Task<bool> ReportAsync(
|
|
|
|
|
Guid cameraId, EventType type, double confidence, string? label,
|
2026-10-22 20:56:49 +02:00
|
|
|
string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null,
|
2026-10-23 07:20:47 +02:00
|
|
|
Guid? eventId = null,
|
2026-10-22 20:56:49 +02:00
|
|
|
CancellationToken ct = default)
|
2026-08-12 09:18:42 +02:00
|
|
|
{
|
2026-10-22 19:24:18 +02:00
|
|
|
if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey))
|
2026-08-12 09:18:42 +02:00
|
|
|
return false;
|
2026-10-23 07:20:47 +02:00
|
|
|
if (eventId == Guid.Empty) return false;
|
|
|
|
|
if (type == EventType.ManualSnapshot && snapshotJpeg is null) return false;
|
2026-08-12 09:18:42 +02:00
|
|
|
|
|
|
|
|
var key = (cameraId, type);
|
|
|
|
|
var now = DateTime.UtcNow;
|
2026-10-22 19:24:18 +02:00
|
|
|
var cooldown = type == EventType.MotionDetected ? MotionCooldown : DefaultCooldown;
|
2026-10-23 07:20:47 +02:00
|
|
|
if (type != EventType.ManualSnapshot && _lastQueued.TryGetValue(key, out var last) && now - last < cooldown)
|
2026-08-12 09:18:42 +02:00
|
|
|
{
|
|
|
|
|
Interlocked.Increment(ref _suppressedByCooldown);
|
2026-08-20 18:22:37 +02:00
|
|
|
HeimdallMetrics.RecordEventSuppressed("cooldown", type.ToString());
|
2026-08-12 09:18:42 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:24:18 +02:00
|
|
|
var request = new CreateCameraEventRequest(
|
2026-10-23 07:20:47 +02:00
|
|
|
cameraId, type, confidence, label, metadataJson, occurredAt ?? now, eventId ?? Guid.NewGuid());
|
2026-08-12 09:18:42 +02:00
|
|
|
try
|
|
|
|
|
{
|
2026-10-22 20:50:40 +02:00
|
|
|
var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
if (!queued)
|
|
|
|
|
return false;
|
2026-08-12 09:18:42 +02:00
|
|
|
|
2026-10-23 07:20:47 +02:00
|
|
|
if (type != EventType.ManualSnapshot) _lastQueued[key] = now;
|
2026-10-22 19:24:18 +02:00
|
|
|
try { _wake.Release(); }
|
|
|
|
|
catch (SemaphoreFullException) { }
|
|
|
|
|
return true;
|
2026-08-12 09:18:42 +02:00
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Interlocked.Increment(ref _failedReports);
|
2026-10-22 19:24:18 +02:00
|
|
|
_logger.LogError(ex, "Could not persist detection event for camera {CameraId}; Central was not updated", cameraId);
|
2026-08-12 09:18:42 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:24:18 +02:00
|
|
|
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)
|
|
|
|
|
{
|
2026-10-22 20:50:40 +02:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-10-22 19:24:18 +02:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-26 08:19:44 +01:00
|
|
|
private async Task<AgentEventsDbContext> OpenDatabaseAsync(CancellationToken ct)
|
2026-10-22 19:24:18 +02:00
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
try
|
|
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
if (!_databaseInitialized)
|
2026-10-22 19:24:18 +02:00
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
await AgentOutboxDatabaseInitializer.InitializeEventsAsync(_contextFactory, _databasePath, ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
_databaseInitialized = true;
|
|
|
|
|
}
|
2026-10-26 08:19:44 +01:00
|
|
|
return await _contextFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
}
|
2026-10-26 08:19:44 +01:00
|
|
|
finally { _databaseInitializationGate.Release(); }
|
2026-10-22 19:24:18 +02:00
|
|
|
}
|
|
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
private async Task<bool> EnqueueAsync(CreateCameraEventRequest request, byte[]? snapshotJpeg, CancellationToken ct)
|
2026-10-22 19:24:18 +02:00
|
|
|
{
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
if (snapshotJpeg is not null &&
|
|
|
|
|
(snapshotJpeg.Length < 4 || snapshotJpeg.Length > MaxSnapshotBytes ||
|
|
|
|
|
snapshotJpeg[0] != 0xff || snapshotJpeg[1] != 0xd8 ||
|
|
|
|
|
snapshotJpeg[^2] != 0xff || snapshotJpeg[^1] != 0xd9))
|
|
|
|
|
{
|
2026-10-23 07:20:47 +02:00
|
|
|
if (request.Type == EventType.ManualSnapshot) return false;
|
2026-10-22 20:50:40 +02:00
|
|
|
_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);
|
|
|
|
|
|
2026-10-22 19:24:18 +02:00
|
|
|
var eventId = request.EventId!.Value;
|
|
|
|
|
var priority = request.Type == EventType.MotionDetected ? 0 : 1;
|
|
|
|
|
await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false);
|
|
|
|
|
try
|
|
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
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));
|
2026-10-22 20:50:40 +02:00
|
|
|
while (count >= MaxPendingEvents || bytes + itemBytes > MaxOutboxBytes)
|
2026-10-22 19:24:18 +02:00
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
var oldestMotion = await db.PendingEvents
|
|
|
|
|
.Where(item => item.Priority == 0)
|
|
|
|
|
.OrderBy(item => item.CreatedAt)
|
|
|
|
|
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
|
|
|
|
|
if (oldestMotion is null)
|
2026-10-22 19:24:18 +02:00
|
|
|
{
|
|
|
|
|
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;
|
|
|
|
|
}
|
2026-10-26 08:19:44 +01:00
|
|
|
var evictedBytes = Encoding.UTF8.GetByteCount(oldestMotion.PayloadJson) + (oldestMotion.SnapshotJpeg?.LongLength ?? 0);
|
|
|
|
|
db.PendingEvents.Remove(oldestMotion);
|
|
|
|
|
await db.SaveChangesAsync(ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
count--;
|
2026-10-26 08:19:44 +01:00
|
|
|
bytes -= evictedBytes;
|
2026-10-22 19:24:18 +02:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-26 08:19:44 +01:00
|
|
|
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);
|
2026-10-22 19:24:18 +02:00
|
|
|
await transaction.CommitAsync(ct).ConfigureAwait(false);
|
2026-10-22 20:50:40 +02:00
|
|
|
HeimdallMetrics.SetEventOutboxState((int)count + 1, bytes + itemBytes);
|
2026-10-22 19:24:18 +02:00
|
|
|
HeimdallMetrics.RecordEventCreated(request.Type.ToString(), request.CameraId);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
finally { _databaseWriteGate.Release(); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static async Task<(long Count, long Bytes)> GetOutboxSizeAsync(
|
2026-10-26 08:19:44 +01:00
|
|
|
AgentEventsDbContext db, CancellationToken ct)
|
2026-10-22 19:24:18 +02:00
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
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)));
|
2026-10-22 19:24:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<List<PendingDetection>> ReadPendingAsync(CancellationToken ct)
|
|
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
|
|
|
|
|
var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
|
2026-10-26 08:19:44 +01:00
|
|
|
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<CreateCameraEventRequest>(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();
|
2026-10-22 19:24:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task DeletePendingAsync(Guid eventId, CancellationToken ct)
|
|
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
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(); }
|
2026-10-22 19:24:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task IncrementAttemptsAsync(Guid eventId, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
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);
|
|
|
|
|
}
|
2026-10-22 19:24:18 +02:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
|
{
|
2026-10-26 08:19:44 +01:00
|
|
|
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);
|
2026-10-22 19:24:18 +02:00
|
|
|
await transaction.CommitAsync(ct).ConfigureAwait(false);
|
2026-10-26 08:19:44 +01:00
|
|
|
var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false);
|
2026-10-22 19:24:18 +02:00
|
|
|
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>
|
2026-08-12 09:18:42 +02:00
|
|
|
public static EventType? MapDetectionToEventType(string label)
|
|
|
|
|
{
|
2026-10-22 19:24:18 +02:00
|
|
|
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")
|
2026-08-12 09:18:42 +02:00
|
|
|
return EventType.VehicleDetected;
|
2026-10-22 19:24:18 +02:00
|
|
|
if (normalized is "cat" or "dog" or "bird" or "horse" or "cow" or "sheep")
|
|
|
|
|
return null;
|
2026-08-12 09:18:42 +02:00
|
|
|
return EventType.MotionDetected;
|
|
|
|
|
}
|
2026-10-22 19:24:18 +02:00
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
private sealed record PendingDetection(Guid EventId, CreateCameraEventRequest Request, int Attempts, byte[]? SnapshotJpeg);
|
2026-08-12 09:18:42 +02:00
|
|
|
}
|