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-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-22 19:24:18 +02:00
using Microsoft.Data.Sqlite ;
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 ,
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 ;
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 ());
Directory . CreateDirectory ( stateDirectory );
_databasePath = Path . Combine ( stateDirectory , "agent-events.db" );
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 ,
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 ;
var key = ( cameraId , type );
var now = DateTime . UtcNow ;
2026-10-22 19:24:18 +02:00
var cooldown = type == EventType . MotionDetected ? MotionCooldown : DefaultCooldown ;
if ( _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 (
cameraId , type , confidence , label , metadataJson , occurredAt ?? now , 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-22 19:24:18 +02:00
_lastQueued [ key ] = now ;
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 ;
}
}
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;"
2026-10-22 20:50:40 +02:00
: "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);" ;
2026-10-22 19:24:18 +02:00
await command . ExecuteNonQueryAsync ( ct ). ConfigureAwait ( false );
2026-10-22 20:50:40 +02:00
if (! _databaseInitialized )
{
await using var check = connection . CreateCommand ();
check . CommandText = "SELECT COUNT(*) FROM pragma_table_info('pending_detection_events') WHERE name='snapshot_jpeg';" ;
if ( Convert . ToInt32 ( await check . ExecuteScalarAsync ( ct ). ConfigureAwait ( false ), System . Globalization . CultureInfo . InvariantCulture ) == 0 )
{
await using var upgrade = connection . CreateCommand ();
upgrade . CommandText = "ALTER TABLE pending_detection_events ADD COLUMN snapshot_jpeg BLOB NULL; PRAGMA user_version=2;" ;
await upgrade . ExecuteNonQueryAsync ( ct ). ConfigureAwait ( false );
}
}
2026-10-22 19:24:18 +02:00
_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 ;
}
}
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 ))
{
_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
{
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 );
2026-10-22 20:50:40 +02:00
while ( count >= MaxPendingEvents || bytes + itemBytes > MaxOutboxBytes )
2026-10-22 19:24:18 +02:00
{
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 ;
2026-10-22 20:50:40 +02:00
insert . CommandText = "INSERT INTO pending_detection_events(event_id,event_type,priority,payload_json,created_at,snapshot_jpeg) VALUES($id,$type,$priority,$payload,$created,$snapshot);" ;
2026-10-22 19:24:18 +02:00
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" ));
2026-10-22 20:50:40 +02:00
insert . Parameters . AddWithValue ( "$snapshot" , ( object? ) snapshotJpeg ?? DBNull . Value );
2026-10-22 19:24:18 +02:00
await insert . ExecuteNonQueryAsync ( ct ). ConfigureAwait ( false );
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 (
SqliteConnection connection , SqliteTransaction ? transaction , CancellationToken ct )
{
await using var command = connection . CreateCommand ();
command . Transaction = transaction ;
2026-10-22 20:50:40 +02:00
command . CommandText = "SELECT COUNT(*), COALESCE(SUM(length(CAST(payload_json AS BLOB)) + COALESCE(length(snapshot_jpeg),0)),0) FROM pending_detection_events;" ;
2026-10-22 19:24:18 +02:00
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 ;
2026-10-22 20:50:40 +02:00
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)) + COALESCE(length(snapshot_jpeg),0);" ;
2026-10-22 19:24:18 +02:00
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 ();
2026-10-22 20:50:40 +02:00
command . CommandText = "SELECT event_id,payload_json,attempts,snapshot_jpeg FROM pending_detection_events ORDER BY priority DESC,created_at LIMIT $limit;" ;
2026-10-22 19:24:18 +02:00
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 ))
2026-10-22 20:50:40 +02:00
results . Add ( new PendingDetection ( id , request , reader . GetInt32 ( 2 ), reader . IsDBNull ( 3 ) ? null : reader . GetFieldValue < byte []>( 3 )));
2026-10-22 19:24:18 +02:00
}
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>
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
}