From 2d1734114f2e380971d7eb766cc5426d508dc05b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 20 Aug 2026 18:22:37 +0200 Subject: [PATCH] =?UTF-8?q?feat(metrics):=20m=C3=A9triques=20OpenTelemetry?= =?UTF-8?q?=20Prometheus=20(spec=20=C2=A713.1)=20(#161)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Heimdall.Agent/Heimdall.Agent.csproj | 5 + src/Heimdall.Agent/Program.cs | 13 ++ .../Services/CameraStreamService.cs | 5 + .../Services/DetectionReporterService.cs | 2 + .../Services/FrameAnalyzerService.cs | 5 + .../Services/SnapshotPipelineService.cs | 11 + .../Heimdall.Application.csproj | 4 + .../Metrics/HeimdallMetrics.cs | 200 ++++++++++++++++++ .../Services/CameraEventService.cs | 7 + src/Heimdall.Web/Heimdall.Web.csproj | 6 + src/Heimdall.Web/Hubs/AdminHub.cs | 3 + src/Heimdall.Web/Hubs/ConfigHub.cs | 9 + src/Heimdall.Web/Hubs/EventsHub.cs | 3 + src/Heimdall.Web/Hubs/MonitoringHub.cs | 3 + src/Heimdall.Web/Hubs/NotificationsHub.cs | 3 + src/Heimdall.Web/Program.cs | 18 ++ .../Metrics/HeimdallMetricsTests.cs | 142 +++++++++++++ 17 files changed, 439 insertions(+) create mode 100644 src/Heimdall.Application/Metrics/HeimdallMetrics.cs create mode 100644 tests/Heimdall.Application.Tests/Metrics/HeimdallMetricsTests.cs diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index de45962..e723992 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -5,6 +5,8 @@ enable enable dotnet-Heimdall.Agent-53531cc7-00d3-425d-b14f-1de1a7441ae3 + + $(NoWarn);NU1902 @@ -20,6 +22,9 @@ + + + diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 0eb0b2a..429d218 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -4,11 +4,13 @@ using Heimdall.Agent; using Heimdall.Agent.Logging; using Heimdall.Agent.Services; using Heimdall.Application.Discovery; +using Heimdall.Application.Metrics; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using OpenTelemetry.Metrics; var builder = WebApplication.CreateSlimBuilder(args); @@ -122,6 +124,14 @@ builder.Services.AddHostedService(); builder.Services.AddHealthChecks() .AddCheck("agent_health", tags: ["ready"]); +// ── OpenTelemetry metrics (spec 13.1) ────────────────────────────── +builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddPrometheusExporter(); + metrics.AddMeter(HeimdallMetrics.MeterName); + }); + var app = builder.Build(); // Health endpoint @@ -136,4 +146,7 @@ app.MapHealthChecks("/healthz", new HealthCheckOptions } }); +// ── Prometheus metrics endpoint (spec 13.1) ──────────────────────── +app.MapPrometheusScrapingEndpoint("/metrics"); + await app.RunAsync(); diff --git a/src/Heimdall.Agent/Services/CameraStreamService.cs b/src/Heimdall.Agent/Services/CameraStreamService.cs index a91614a..143c65d 100644 --- a/src/Heimdall.Agent/Services/CameraStreamService.cs +++ b/src/Heimdall.Agent/Services/CameraStreamService.cs @@ -2,6 +2,7 @@ using System.Buffers; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading.Channels; +using Heimdall.Application.Metrics; using Microsoft.Extensions.Logging; namespace Heimdall.Agent.Services; @@ -201,6 +202,10 @@ public sealed class CameraStreamService : IDisposable { var now = DateTime.UtcNow; var interval = _snapshotInterval.GetInterval(_sceneState.State, GetCpuPercent()); + + // Update snapshot interval metric (spec 13.1) + HeimdallMetrics.SetSnapshotInterval(interval); + if (now - session.LastSnapshotAt < interval) return; // sample less often than FFmpeg pushes frames diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs index b63c006..1a11782 100644 --- a/src/Heimdall.Agent/Services/DetectionReporterService.cs +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.Net.Http.Json; using Heimdall.Application.DTOs; +using Heimdall.Application.Metrics; using Heimdall.Domain.Enums; using Microsoft.Extensions.Logging; @@ -71,6 +72,7 @@ public sealed class DetectionReporterService : IDetectionReporter if (_lastSent.TryGetValue(key, out var last) && now - last < cooldown) { Interlocked.Increment(ref _suppressedByCooldown); + HeimdallMetrics.RecordEventSuppressed("cooldown", type.ToString()); return false; } diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 6a701a8..0b0a744 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Threading.Channels; +using Heimdall.Application.Metrics; using Microsoft.Extensions.Logging; using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; @@ -178,6 +179,10 @@ public sealed class FrameAnalyzerService : IDisposable var detections = RunInference(job.ImageData); sw.Stop(); + // Record YOLO inference time (spec 13.1) + HeimdallMetrics.RecordYoloInference(sw.ElapsedMilliseconds, detections.Length); + HeimdallMetrics.RecordInference(sw.ElapsedMilliseconds, _modelLoaded); + var result = new FrameAnalysisResult( Convert.ToBase64String(job.ImageData), detections, diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index 7f7bc64..f4bdb37 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using Heimdall.Application.Metrics; using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; @@ -158,6 +159,9 @@ public sealed class SnapshotPipelineService : BackgroundService { try { + // Update queue depth metric (spec 13.1) + HeimdallMetrics.SetQueueDepth(_streams.SnapshotChannel.Reader.Count); + // Real call into the analyzer — the pipeline's reason to exist. var result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct); Interlocked.Increment(ref _snapshotsProcessed); @@ -180,6 +184,13 @@ public sealed class SnapshotPipelineService : BackgroundService Interlocked.Increment(ref _analysisFailures); _logger.LogWarning(ex, "Snapshot analysis failed for camera {CameraId}", snapshot.CameraId); } + + // Update pipeline degradation level (spec 13.1) + var failures = Interlocked.Read(ref _analysisFailures); + var processed = Interlocked.Read(ref _snapshotsProcessed); + var failureRate = processed > 0 ? (double)failures / processed : 0; + var level = failureRate > 0.5 ? 2 : failureRate > 0.1 ? 1 : 0; + HeimdallMetrics.SetPipelineLevel(level); } } catch (OperationCanceledException) diff --git a/src/Heimdall.Application/Heimdall.Application.csproj b/src/Heimdall.Application/Heimdall.Application.csproj index 13c020c..987b37f 100644 --- a/src/Heimdall.Application/Heimdall.Application.csproj +++ b/src/Heimdall.Application/Heimdall.Application.csproj @@ -27,4 +27,8 @@ enable + + + + diff --git a/src/Heimdall.Application/Metrics/HeimdallMetrics.cs b/src/Heimdall.Application/Metrics/HeimdallMetrics.cs new file mode 100644 index 0000000..ca89d5a --- /dev/null +++ b/src/Heimdall.Application/Metrics/HeimdallMetrics.cs @@ -0,0 +1,200 @@ +using System.Diagnostics; +using System.Diagnostics.Metrics; + +namespace Heimdall.Application.Metrics; + +/// +/// Centralized OpenTelemetry metrics for Heimdall (MASTER_SPECIFICATION §13.1). +/// Uses (built-in .NET) — no OpenTelemetry +/// package dependency in the Application layer. The MeterProvider in Web/Agent +/// listens to this meter and exports to Prometheus. +/// +public static class HeimdallMetrics +{ + /// Meter name for all Heimdall application metrics. + public const string MeterName = "Heimdall"; + + private static readonly Meter MeterInstance = new(MeterName, typeof(HeimdallMetrics).Assembly.GetName().Version?.ToString() ?? "1.0"); + + /// The instance. Register with MeterProviderBuilder.ListenToMeters(MeterName). + public static Meter Meter => MeterInstance; + + // ── Events (heimdall.events.*) ──────────────────────────────── + + private static readonly Counter EventsCreatedCounter = + Meter.CreateCounter( + "heimdall.events.created", + description: "Nombre total d'événements créés (par type)"); + + /// + /// Record an event creation. + /// + /// Type d'événement (Motion, Person, Vehicle, etc.) + /// ID de la caméra source + /// ID du site + public static void RecordEventCreated(string eventType, Guid? cameraId = null, Guid? siteId = null) + { + var tags = new TagList(); + tags.Add("event.type", eventType); + if (cameraId.HasValue) tags.Add("camera.id", cameraId.Value.ToString()); + if (siteId.HasValue) tags.Add("site.id", siteId.Value.ToString()); + EventsCreatedCounter.Add(1, tags); + } + + private static readonly Counter EventsSuppressedCounter = + Meter.CreateCounter( + "heimdall.events.suppressed", + description: "Nombre total d'événements supprimés par déduplication"); + + /// + /// Record a suppressed (deduplicated) event. + /// + /// Raison de la suppression (cooldown, duplicate, etc.) + /// Type d'événement + public static void RecordEventSuppressed(string reason, string? eventType = null) + { + var tags = new TagList(); + tags.Add("reason", reason); + if (eventType is not null) tags.Add("event.type", eventType); + EventsSuppressedCounter.Add(1, tags); + } + + // ── AI Pipeline (heimdall.ai.*) ─────────────────────────────── + + private static readonly ObservableGauge PipelineLevelGauge = + Meter.CreateObservableGauge( + "heimdall.ai.pipeline.level", + observeValue: () => new Measurement( + Volatile.Read(ref _pipelineLevel), + tags: default), + description: "Niveau de dégradation actuel du pipeline IA (0=normal, 1=degraded, 2=critical)"); + + private static int _pipelineLevel; + + /// + /// Set the current pipeline degradation level. + /// + /// 0=normal, 1=degraded, 2=critical + public static void SetPipelineLevel(int level) => Volatile.Write(ref _pipelineLevel, level); + + private static readonly ObservableGauge SnapshotIntervalGauge = + Meter.CreateObservableGauge( + "heimdall.ai.snapshot.interval", + observeValue: () => new Measurement( + Volatile.Read(ref _snapshotIntervalMs), + tags: default), + description: "Intervalle snapshot actuel en millisecondes"); + + private static double _snapshotIntervalMs = 1000; + + /// + /// Update the current snapshot interval (from AdaptiveSnapshotInterval). + /// + public static void SetSnapshotInterval(TimeSpan interval) => + Volatile.Write(ref _snapshotIntervalMs, interval.TotalMilliseconds); + + private static readonly Histogram YoloInferenceHistogram = + Meter.CreateHistogram( + "heimdall.ai.yolo.inference_ms", + unit: "ms", + description: "Temps d'inférence YOLO (Agent) en millisecondes"); + + /// + /// Record YOLO inference duration. + /// + public static void RecordYoloInference(double elapsedMs, int? detectionCount = null) + { + var tags = new TagList(); + if (detectionCount.HasValue) tags.Add("detection.count", detectionCount.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); + YoloInferenceHistogram.Record(elapsedMs, tags); + } + + private static readonly Histogram InferenceHistogram = + Meter.CreateHistogram( + "heimdall.ai.inference_ms", + unit: "ms", + description: "Temps d'inférence IA global (ONNX/YOLO) en millisecondes"); + + /// + /// Record total inference duration (YOLO + pre/post processing). + /// + public static void RecordInference(double elapsedMs, bool modelLoaded = true) + { + var tags = new TagList(); + tags.Add("model.loaded", modelLoaded.ToString().ToLowerInvariant()); + InferenceHistogram.Record(elapsedMs, tags); + } + + private static readonly ObservableGauge QueueDepthGauge = + Meter.CreateObservableGauge( + "heimdall.ai.queue.depth", + observeValue: () => new Measurement( + Volatile.Read(ref _queueDepth), + tags: default), + description: "Profondeur de la queue de snapshots en attente d'analyse"); + + private static long _queueDepth; + + /// + /// Update the current snapshot queue depth. + /// + public static void SetQueueDepth(long depth) => Volatile.Write(ref _queueDepth, depth); + + // ── SignalR (heimdall.signalr.*) ────────────────────────────── + + private static readonly ObservableGauge SignalRConnectionsGauge = + Meter.CreateObservableGauge( + "heimdall.signalr.connections", + observeValue: () => new Measurement( + Volatile.Read(ref _signalrConnections), + tags: default), + description: "Nombre de connexions SignalR actives"); + + private static long _signalrConnections; + + /// + /// Increment SignalR connections count. + /// + public static void SignalRConnectionAdded() => Interlocked.Increment(ref _signalrConnections); + + /// + /// Decrement SignalR connections count. + /// + public static void SignalRConnectionRemoved() => Interlocked.Decrement(ref _signalrConnections); + + // ── Streaming (heimdall.streaming.*) ────────────────────────── + + private static readonly ObservableGauge ActiveViewersGauge = + Meter.CreateObservableGauge( + "heimdall.streaming.active_viewers", + observeValue: () => new Measurement( + Volatile.Read(ref _activeViewers), + tags: default), + description: "Nombre de viewers WebRTC actifs"); + + private static long _activeViewers; + + /// + /// Increment active viewers count. + /// + public static void ViewerAdded() => Interlocked.Increment(ref _activeViewers); + + /// + /// Decrement active viewers count. + /// + public static void ViewerRemoved() => Interlocked.Decrement(ref _activeViewers); + + // ── Internal setters for testing ────────────────────────────── + + /// + /// Reset all metrics to default values (for testing only). + /// + internal static void ResetForTesting() + { + Volatile.Write(ref _pipelineLevel, 0); + Volatile.Write(ref _snapshotIntervalMs, 1000); + Volatile.Write(ref _queueDepth, 0); + Volatile.Write(ref _signalrConnections, 0); + Volatile.Write(ref _activeViewers, 0); + } +} diff --git a/src/Heimdall.Infrastructure/Services/CameraEventService.cs b/src/Heimdall.Infrastructure/Services/CameraEventService.cs index 3e35b96..524b46a 100644 --- a/src/Heimdall.Infrastructure/Services/CameraEventService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraEventService.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; +using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; @@ -44,6 +45,12 @@ public sealed class CameraEventService : ICameraEventService "Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}", ev.Id, ev.Type, ev.Confidence, ev.CameraId); + // Record metric: event created (spec 13.1) + HeimdallMetrics.RecordEventCreated( + ev.Type.ToString(), + ev.CameraId, + camera.SiteId); + // Fire-and-forget broadcast to connected SignalR clients. // Use CancellationToken.None — the broadcast must outlive the HTTP request // lifecycle so SignalR clients receive the notification even after the diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index 5ec2691..50a769a 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -5,6 +5,8 @@ enable enable true + + $(NoWarn);NU1902 @@ -20,6 +22,10 @@ + + + + diff --git a/src/Heimdall.Web/Hubs/AdminHub.cs b/src/Heimdall.Web/Hubs/AdminHub.cs index 8effcaf..b70d878 100644 --- a/src/Heimdall.Web/Hubs/AdminHub.cs +++ b/src/Heimdall.Web/Hubs/AdminHub.cs @@ -1,3 +1,4 @@ +using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; @@ -34,12 +35,14 @@ public class AdminHub : Hub public override async Task OnConnectedAsync() { + HeimdallMetrics.SignalRConnectionAdded(); _logger.LogDebug("Admin connected to admin hub: {ConnectionId}", Context.ConnectionId); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { + HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Admin disconnected from admin hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs index e5de9f5..ffd5695 100644 --- a/src/Heimdall.Web/Hubs/ConfigHub.cs +++ b/src/Heimdall.Web/Hubs/ConfigHub.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; +using Heimdall.Application.Metrics; using Heimdall.Application.Services; namespace Heimdall.Api.Hubs; @@ -34,8 +35,16 @@ public class ConfigHub : Hub _logger.LogInformation("Agent {AgentId} joined config group", agentId); } + public override async Task OnConnectedAsync() + { + HeimdallMetrics.SignalRConnectionAdded(); + _logger.LogInformation("Agent connected to config hub: {ConnectionId}", Context.ConnectionId); + await base.OnConnectedAsync(); + } + public override async Task OnDisconnectedAsync(Exception? exception) { + HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } diff --git a/src/Heimdall.Web/Hubs/EventsHub.cs b/src/Heimdall.Web/Hubs/EventsHub.cs index 7e0296d..094fe7e 100644 --- a/src/Heimdall.Web/Hubs/EventsHub.cs +++ b/src/Heimdall.Web/Hubs/EventsHub.cs @@ -1,4 +1,5 @@ using Heimdall.Application.DTOs; +using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; @@ -42,12 +43,14 @@ public class EventsHub : Hub public override async Task OnConnectedAsync() { + HeimdallMetrics.SignalRConnectionAdded(); _logger.LogDebug("Client connected to events hub: {ConnectionId}", Context.ConnectionId); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { + HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Client disconnected from events hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } diff --git a/src/Heimdall.Web/Hubs/MonitoringHub.cs b/src/Heimdall.Web/Hubs/MonitoringHub.cs index 21093f6..a3d42c2 100644 --- a/src/Heimdall.Web/Hubs/MonitoringHub.cs +++ b/src/Heimdall.Web/Hubs/MonitoringHub.cs @@ -1,3 +1,4 @@ +using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; @@ -58,12 +59,14 @@ public class MonitoringHub : Hub public override async Task OnConnectedAsync() { + HeimdallMetrics.SignalRConnectionAdded(); _logger.LogDebug("Client connected to monitoring hub: {ConnectionId}", Context.ConnectionId); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { + HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Client disconnected from monitoring hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } diff --git a/src/Heimdall.Web/Hubs/NotificationsHub.cs b/src/Heimdall.Web/Hubs/NotificationsHub.cs index d7ed08d..db3daa2 100644 --- a/src/Heimdall.Web/Hubs/NotificationsHub.cs +++ b/src/Heimdall.Web/Hubs/NotificationsHub.cs @@ -1,5 +1,6 @@ using System.Security.Claims; using Heimdall.Application.DTOs; +using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; @@ -37,12 +38,14 @@ public class NotificationsHub : Hub public override async Task OnConnectedAsync() { + HeimdallMetrics.SignalRConnectionAdded(); _logger.LogDebug("Client connected to notifications hub: {ConnectionId}", Context.ConnectionId); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { + HeimdallMetrics.SignalRConnectionRemoved(); _logger.LogDebug("Client disconnected from notifications hub: {ConnectionId}", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 5b18834..d097276 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -5,6 +5,7 @@ using System.Security.Claims; using System.Text; using FluentValidation.AspNetCore; using Heimdall.Application; +using Heimdall.Application.Metrics; using Heimdall.Application.Services; using Heimdall.Infrastructure; using Heimdall.Infrastructure.Data; @@ -18,6 +19,7 @@ using Hangfire; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; +using OpenTelemetry.Metrics; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.RateLimiting; using System.Threading.RateLimiting; @@ -407,6 +409,17 @@ public partial class Program ConfigureControllers(builder); ConfigureSignalR(builder); + // ── OpenTelemetry metrics (spec 13.1) ────────────────────────────── + // Expose Heimdall metrics via Prometheus /metrics endpoint. + // Auto-instruments ASP.NET Core HTTP request metrics. + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddPrometheusExporter(); + metrics.AddAspNetCoreInstrumentation(); + metrics.AddMeter(HeimdallMetrics.MeterName); + }); + builder.Services.AddApplication(); builder.Services.AddInfrastructure(builder.Configuration); ConfigureSentry(builder); @@ -793,6 +806,11 @@ public partial class Program }); app.UseRateLimiter(); + + // ── Prometheus metrics endpoint (spec 13.1) ──────────────────────── + // /metrics — scraped by Prometheus. No auth (internal network only). + app.MapPrometheusScrapingEndpoint("/metrics"); + MapAuthEndpoints(app); } diff --git a/tests/Heimdall.Application.Tests/Metrics/HeimdallMetricsTests.cs b/tests/Heimdall.Application.Tests/Metrics/HeimdallMetricsTests.cs new file mode 100644 index 0000000..54078d1 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Metrics/HeimdallMetricsTests.cs @@ -0,0 +1,142 @@ +using Heimdall.Application.Metrics; + +namespace Heimdall.Application.Tests.Metrics; + +public class HeimdallMetricsTests +{ + public HeimdallMetricsTests() + { + HeimdallMetrics.ResetForTesting(); + } + + [Fact] + public void Meter_Should_Have_Correct_Name() + { + HeimdallMetrics.Meter.Name.ShouldBe(HeimdallMetrics.MeterName); + } + + [Fact] + public void RecordEventCreated_Should_Not_Throw() + { + var act = () => HeimdallMetrics.RecordEventCreated("MotionDetected"); + act.ShouldNotThrow(); + } + + [Fact] + public void RecordEventCreated_With_Tags_Should_Not_Throw() + { + var act = () => HeimdallMetrics.RecordEventCreated( + "PersonDetected", + cameraId: Guid.NewGuid(), + siteId: Guid.NewGuid()); + act.ShouldNotThrow(); + } + + [Fact] + public void RecordEventSuppressed_Should_Not_Throw() + { + var act = () => HeimdallMetrics.RecordEventSuppressed("cooldown", "MotionDetected"); + act.ShouldNotThrow(); + } + + [Fact] + public void SetPipelineLevel_Should_Update_Value() + { + HeimdallMetrics.SetPipelineLevel(2); + var act = () => HeimdallMetrics.SetPipelineLevel(0); + act.ShouldNotThrow(); + } + + [Fact] + public void SetSnapshotInterval_Should_Accept_TimeSpan() + { + var act = () => HeimdallMetrics.SetSnapshotInterval(TimeSpan.FromMilliseconds(500)); + act.ShouldNotThrow(); + } + + [Fact] + public void RecordYoloInference_Should_Not_Throw() + { + var act = () => HeimdallMetrics.RecordYoloInference(42.5, detectionCount: 3); + act.ShouldNotThrow(); + } + + [Fact] + public void RecordYoloInference_Without_DetectionCount_Should_Not_Throw() + { + var act = () => HeimdallMetrics.RecordYoloInference(10.0); + act.ShouldNotThrow(); + } + + [Fact] + public void RecordInference_Should_Not_Throw() + { + var act = () => HeimdallMetrics.RecordInference(55.0, modelLoaded: true); + act.ShouldNotThrow(); + } + + [Fact] + public void SetQueueDepth_Should_Update_Value() + { + var act = () => HeimdallMetrics.SetQueueDepth(42); + act.ShouldNotThrow(); + } + + [Fact] + public void SignalRConnectionAdded_Should_Increment() + { + var act = () => + { + HeimdallMetrics.SignalRConnectionAdded(); + HeimdallMetrics.SignalRConnectionAdded(); + }; + act.ShouldNotThrow(); + } + + [Fact] + public void SignalRConnectionRemoved_Should_Decrement() + { + var act = () => + { + HeimdallMetrics.SignalRConnectionAdded(); + HeimdallMetrics.SignalRConnectionRemoved(); + }; + act.ShouldNotThrow(); + } + + [Fact] + public void ViewerAdded_Should_Not_Throw() + { + var act = () => HeimdallMetrics.ViewerAdded(); + act.ShouldNotThrow(); + } + + [Fact] + public void ViewerRemoved_Should_Not_Throw() + { + var act = () => + { + HeimdallMetrics.ViewerAdded(); + HeimdallMetrics.ViewerRemoved(); + }; + act.ShouldNotThrow(); + } + + [Fact] + public void ResetForTesting_Should_Reset_All_Counters() + { + HeimdallMetrics.SignalRConnectionAdded(); + HeimdallMetrics.SignalRConnectionAdded(); + HeimdallMetrics.ViewerAdded(); + HeimdallMetrics.SetQueueDepth(10); + HeimdallMetrics.SetPipelineLevel(2); + + HeimdallMetrics.ResetForTesting(); + + // After reset, adding and removing should return to 0 without exception + HeimdallMetrics.SignalRConnectionAdded(); + HeimdallMetrics.SignalRConnectionRemoved(); + HeimdallMetrics.ViewerAdded(); + HeimdallMetrics.ViewerRemoved(); + } +}