diff --git a/scripts/ci/security.sh b/scripts/ci/security.sh index b27d088..5635246 100644 --- a/scripts/ci/security.sh +++ b/scripts/ci/security.sh @@ -2,6 +2,7 @@ set -euo pipefail mkdir -p artifacts/security echo "Checking restored NuGet dependencies for advisories" +dotnet restore Heimdall.slnx --locked-mode dotnet list Heimdall.slnx package --no-restore --vulnerable --include-transitive --format json > artifacts/security/nuget.json || { echo "NuGet advisory query failed; see artifacts/security/nuget.json" >&2 exit 1 diff --git a/scripts/ci/validate-compose.sh b/scripts/ci/validate-compose.sh index c0a551b..d3c64fa 100644 --- a/scripts/ci/validate-compose.sh +++ b/scripts/ci/validate-compose.sh @@ -2,7 +2,7 @@ set -euo pipefail # Never print the rendered configuration: it contains credentials. docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet -docker compose --env-file .env.example -f docker/docker-compose.prod.yml config --quiet +AGENT_IMAGE_REFERENCE=heimdall-agent:ci docker compose --env-file .env.example -f docker/docker-compose.prod.yml config --quiet docker compose --env-file .env.example -f docker/docker-compose.yml -f docker/docker-compose.backup.yml config --quiet for required in JWT__KEY JWT__REFRESHKEY HEIMDALL_SITE_TOKEN DATABASE_URL POSTGRES_PASSWORD RUSTFS_ACCESS_KEY RUSTFS_SECRET_KEY COTURN_SECRET; do if env "$required=" docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet >/dev/null 2>&1; then diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index f27c0cf..46fab03 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -119,6 +119,7 @@ builder.Services.AddSingleton(sp => sp.GetRequiredService builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs index 1a11782..c212b33 100644 --- a/src/Heimdall.Agent/Services/DetectionReporterService.cs +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -1,102 +1,115 @@ 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; -/// Reports detection events to the Central (see ). public interface IDetectionReporter { + /// Durably enqueue a detection event. True means queued, not yet delivered. Task ReportAsync( - Guid cameraId, Heimdall.Domain.Enums.EventType type, double confidence, string? label, + Guid cameraId, EventType type, double confidence, string? label, string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default); } /// -/// Reports detection events from the agent to the Central (POST /api/events, -/// API Key auth). The snapshot pipeline calls this when the scene becomes -/// active (motion) or when the analyzer produces detections. -/// Anti-spam: per (camera, type) cooldown so a stationary object does not -/// flood the Central (the 4-level dedup #5 runs on the Central as well). -/// Failures are dropped with a counter (rate-limited log) — the capture -/// pipeline must never block on the network. +/// 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 : IDetectionReporter +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 _logger; - - private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastSent = new(); - - private static readonly TimeSpan DefaultCooldown = TimeSpan.FromSeconds(10); - private static readonly TimeSpan MotionCooldown = TimeSpan.FromSeconds(30); + 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 logger) + : this(state, httpClientFactory, logger, Options.Create(new AgentOptions())) + { + } + + public DetectionReporterService( + AgentState state, + IHttpClientFactory httpClientFactory, + ILogger logger, + IOptions 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"); } - /// Number of failed event reports (dropped, not retried). public long FailedReports => Interlocked.Read(ref _failedReports); - - /// Number of events suppressed by the per-camera cooldown. public long SuppressedByCooldown => Interlocked.Read(ref _suppressedByCooldown); + public long RejectedByCapacity => Interlocked.Read(ref _rejectedByCapacity); + public long DeadLettered => Interlocked.Read(ref _deadLettered); - /// - /// Report a detection event if the (camera, type) cooldown has elapsed. - /// Returns true when the event was actually sent. - /// public async Task ReportAsync( Guid cameraId, EventType type, double confidence, string? label, string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default) { - if (_state.AgentId == Guid.Empty) + if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return false; var key = (cameraId, type); - var cooldown = type == EventType.MotionDetected ? MotionCooldown : DefaultCooldown; - var now = DateTime.UtcNow; - if (_lastSent.TryGetValue(key, out var last) && now - last < cooldown) + 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 { - using var client = _httpClientFactory.CreateClient("Central"); - client.DefaultRequestHeaders.Remove("X-API-Key"); - client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + var queued = await EnqueueAsync(request, ct).ConfigureAwait(false); + if (!queued) + return false; - var request = new CreateCameraEventRequest( - cameraId, type, confidence, label, metadataJson, occurredAt ?? now); - var response = await client.PostAsJsonAsync("api/events", request, ct).ConfigureAwait(false); - - if (response.IsSuccessStatusCode) - { - _lastSent[key] = now; - return true; - } - - Interlocked.Increment(ref _failedReports); - _logger.LogWarning( - "Event report failed for camera {CameraId} ({Type}): {StatusCode} ({Reason})", - cameraId, type, response.StatusCode, response.ReasonPhrase); - return false; + _lastQueued[key] = now; + try { _wake.Release(); } + catch (SemaphoreFullException) { } + return true; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -105,25 +118,297 @@ public sealed class DetectionReporterService : IDetectionReporter catch (Exception ex) { Interlocked.Increment(ref _failedReports); - _logger.LogDebug(ex, "Event report dropped for camera {CameraId} ({Type})", cameraId, type); + _logger.LogError(ex, "Could not persist detection event for camera {CameraId}; Central was not updated", cameraId); return false; } } - /// - /// Map a YOLO COCO detection label to a Heimdall EventType (person → Person, - /// vehicle classes → Vehicle, everything else → Motion). Returns null when - /// the label has no meaningful event mapping. - /// + 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) + { + 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) + { + 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 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); + var (count, bytes) = await GetOutboxSizeAsync(connection, 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 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> 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(); + await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + { + var request = JsonSerializer.Deserialize(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; + + /// Map a detection label to its event category. public static EventType? MapDetectionToEventType(string label) { - var l = label.ToLowerInvariant(); - if (l == "person") - return EventType.PersonDetected; - if (l is "car" or "truck" or "bus" or "motorcycle" or "bicycle" or "boat" or "train" or "airplane") + 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 (l is "cat" or "dog" or "bird" or "horse" or "cow" or "sheep") - return null; // pas d'EventType animal — motion suffit + 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); } diff --git a/src/Heimdall.Application/DTOs/CameraEventDto.cs b/src/Heimdall.Application/DTOs/CameraEventDto.cs index 2351048..f356492 100644 --- a/src/Heimdall.Application/DTOs/CameraEventDto.cs +++ b/src/Heimdall.Application/DTOs/CameraEventDto.cs @@ -22,7 +22,8 @@ public record CreateCameraEventRequest( double Confidence, string? Label, string? MetadataJson, - DateTime? OccurredAt); + DateTime? OccurredAt, + Guid? EventId = null); public record CameraEventFilterRequest( Guid? CameraId, diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs index c90cf2d..18273b8 100644 --- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs +++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs @@ -11,4 +11,5 @@ public record CreateEventCommand( double Confidence, string? Label, string? MetadataJson, - DateTime? OccurredAt) : IRequest>; + DateTime? OccurredAt, + Guid? EventId = null) : IRequest>; diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs index 8da7b3e..5dceca4 100644 --- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs +++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs @@ -22,16 +22,39 @@ public class CreateEventHandler : IRequestHandler> Handle(CreateEventCommand request, CancellationToken ct) { + var occurredAt = CameraEvent.NormalizeOccurredAt(request.OccurredAt ?? DateTime.UtcNow); var camera = await _context.Cameras.FindAsync([request.CameraId], ct).ConfigureAwait(false); if (camera is null) return ServiceResult.NotFound("Camera not found"); - var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, request.OccurredAt); + var eventId = request.EventId ?? Guid.NewGuid(); + if (request.EventId.HasValue) + { + var existing = await _context.CameraEvents + .Include(e => e.Camera) + .FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct) + .ConfigureAwait(false); + if (existing is not null) + return ServiceResult.Success(MapResponse(existing)); + } + + var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, occurredAt, eventId); if (request.Label is not null || request.MetadataJson is not null) ev.SetMetadata(request.Label, request.MetadataJson); _context.CameraEvents.Add(ev); - await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + try + { + await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + } + catch (DbUpdateException) when (request.EventId.HasValue) + { + var duplicate = await _context.CameraEvents.AsNoTracking().Include(e => e.Camera) + .FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct) + .ConfigureAwait(false); + if (duplicate is null) throw; + return ServiceResult.Success(MapResponse(duplicate)); + } var response = MapResponse(ev); await _publisher.Publish(new EventCreatedNotification(response), ct).ConfigureAwait(false); diff --git a/src/Heimdall.Application/Metrics/HeimdallMetrics.cs b/src/Heimdall.Application/Metrics/HeimdallMetrics.cs index ca89d5a..824a376 100644 --- a/src/Heimdall.Application/Metrics/HeimdallMetrics.cs +++ b/src/Heimdall.Application/Metrics/HeimdallMetrics.cs @@ -59,6 +59,40 @@ public static class HeimdallMetrics EventsSuppressedCounter.Add(1, tags); } + private static readonly Counter EventOutboxRejectedCounter = + Meter.CreateCounter( + "heimdall.events.outbox.rejected", + description: "Nombre d'événements refusés ou évincés par la capacité du spool agent"); + + private static readonly ObservableGauge EventOutboxItemsGauge = + Meter.CreateObservableGauge( + "heimdall.events.outbox.items", + observeValue: () => Volatile.Read(ref _eventOutboxItems), + description: "Nombre d'événements en attente dans le spool local de l'agent"); + + private static readonly ObservableGauge EventOutboxBytesGauge = + Meter.CreateObservableGauge( + "heimdall.events.outbox.bytes", + observeValue: () => Interlocked.Read(ref _eventOutboxBytes), + description: "Taille en octets des événements en attente dans le spool local de l'agent"); + + private static int _eventOutboxItems; + private static long _eventOutboxBytes; + + public static void RecordEventOutboxRejected(string reason, string? eventType = null) + { + var tags = new TagList(); + tags.Add("reason", reason); + if (eventType is not null) tags.Add("event.type", eventType); + EventOutboxRejectedCounter.Add(1, tags); + } + + public static void SetEventOutboxState(int itemCount, long sizeBytes) + { + Volatile.Write(ref _eventOutboxItems, Math.Max(0, itemCount)); + Interlocked.Exchange(ref _eventOutboxBytes, Math.Max(0, sizeBytes)); + } + // ── AI Pipeline (heimdall.ai.*) ─────────────────────────────── private static readonly ObservableGauge PipelineLevelGauge = diff --git a/src/Heimdall.Domain/Entities/CameraEvent.cs b/src/Heimdall.Domain/Entities/CameraEvent.cs index 5391625..e5e4d68 100644 --- a/src/Heimdall.Domain/Entities/CameraEvent.cs +++ b/src/Heimdall.Domain/Entities/CameraEvent.cs @@ -52,13 +52,25 @@ public class CameraEvent : Entity, IAuditableEntity private CameraEvent() { } // EF Core - public CameraEvent(Guid cameraId, EventType type, double confidence, DateTime? occurredAt = null) - : base(Guid.NewGuid()) + public CameraEvent(Guid cameraId, EventType type, double confidence, DateTime? occurredAt = null, Guid? id = null) + : base(id ?? Guid.NewGuid()) { CameraId = cameraId; Type = type; Confidence = confidence; - OccurredAt = occurredAt ?? DateTime.UtcNow; + OccurredAt = NormalizeOccurredAt(occurredAt ?? DateTime.UtcNow); + } + + /// Normalizes event timestamps to UTC and PostgreSQL's microsecond precision. + public static DateTime NormalizeOccurredAt(DateTime value) + { + var utc = value.Kind switch + { + DateTimeKind.Local => value.ToUniversalTime(), + DateTimeKind.Unspecified => DateTime.SpecifyKind(value, DateTimeKind.Utc), + _ => value + }; + return new DateTime(utc.Ticks - utc.Ticks % 10, DateTimeKind.Utc); } public void SetSnapshot(string snapshotUrl, string? thumbUrl = null) diff --git a/src/Heimdall.Infrastructure/Services/CameraEventService.cs b/src/Heimdall.Infrastructure/Services/CameraEventService.cs index 3be0f88..4867f63 100644 --- a/src/Heimdall.Infrastructure/Services/CameraEventService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraEventService.cs @@ -29,17 +29,40 @@ public sealed class CameraEventService : ICameraEventService public async Task> CreateAsync(CreateCameraEventRequest request, CancellationToken ct) { await using var db = await _dbFactory.CreateDbContextAsync(ct); + var occurredAt = CameraEvent.NormalizeOccurredAt(request.OccurredAt ?? DateTime.UtcNow); + var eventId = request.EventId ?? Guid.NewGuid(); var camera = await db.Cameras.FindAsync([request.CameraId], ct).ConfigureAwait(false); if (camera is null) return ServiceResult.NotFound("Camera not found"); - var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, request.OccurredAt); + if (request.EventId.HasValue) + { + var existing = await db.CameraEvents.Include(e => e.Camera) + .FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct) + .ConfigureAwait(false); + if (existing is not null) + return ServiceResult.Success(MapResponse(existing)); + } + + var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, occurredAt, eventId); if (request.Label is not null || request.MetadataJson is not null) ev.SetMetadata(request.Label, request.MetadataJson); db.CameraEvents.Add(ev); - await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + try + { + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + } + catch (DbUpdateException) when (request.EventId.HasValue) + { + db.Entry(ev).State = EntityState.Detached; + var duplicate = await db.CameraEvents.AsNoTracking().Include(e => e.Camera) + .FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct) + .ConfigureAwait(false); + if (duplicate is null) throw; + return ServiceResult.Success(MapResponse(duplicate)); + } _logger.LogDebug( "Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}", diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs index 30b2fc3..e8c1231 100644 --- a/src/Heimdall.Web/Controllers/EventsController.cs +++ b/src/Heimdall.Web/Controllers/EventsController.cs @@ -35,7 +35,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateCameraEventRequest request, CancellationToken ct) { - var command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt); + var command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt, request.EventId); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data)