Files
Heimdall/src/Heimdall.Agent/Services/SnapshotPipelineService.cs
T
Arnaud Dartois be05bdabcf fix(mapping): corriger AgentExtensions.ToResponse — ajouter GPU fields manquants
fix(mapping): corriger AgentExtensions.ToResponse — ajouter GPU fields manquants

La CI était cassée sur main avec 20 erreurs CS1503 dans AgentExtensions.cs.
Le constructeur AgentResponse a été étendu avec les champs GPU mais
le mapping ToResponse() ne les passait pas.

Fixes le build cassé sur main et débloque les PRs en attente.
2026-08-27 15:02:17 +02:00

455 lines
18 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Concurrent;
using Heimdall.Application.Metrics;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>
/// Bundles the dependencies required by <see cref="SnapshotPipelineService"/>
/// to avoid exceeding the SonarQube cognitive/parameter-count threshold (S107).
/// </summary>
public sealed record SnapshotPipelineServiceOptions(
AgentState State,
IOptions<AgentOptions> Options,
CameraConfigStore CameraStore,
CameraStreamService Streams,
FrameAnalyzerService Analyzer,
SceneStateTracker SceneState,
ICameraStatusReporter StatusReporter,
IDetectionReporter DetectionReporter,
ILogger<SnapshotPipelineService> Logger,
PipelineDegradationManager DegradationManager,
SystemMetricsProvider Metrics,
IRemoteFrameBroker? Broker = null,
FrameResizer? Resizer = null);
/// <summary>
/// Orchestrates the video capture pipeline (MASTER_SPEC Phase 15):
/// keeps the FFmpeg capture streams in sync with the assigned cameras
/// (from the Central config, local fallback before that) and consumes the
/// bounded snapshot channel, forwarding each frame to the analysis pipeline
/// (local YOLO or remote broker, depending on AnalysisMode) and updating
/// the scene state that drives the adaptive snapshot interval.
///
/// Integrates with <see cref="PipelineDegradationManager"/> for graceful
/// degradation:
/// - Level 0 (Normal): full IA pipeline
/// - Level 1 (SlowExecutor): inference runs with lowered confidence
/// - Level 2 (ExecutorDown): motion-only mode (skip inference)
/// - Level 3 (CpuSaturation): snapshots reduced by half
/// </summary>
public sealed class SnapshotPipelineService : BackgroundService
{
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly CameraConfigStore _cameraStore;
private readonly CameraStreamService _streams;
private readonly FrameAnalyzerService _analyzer;
private readonly SceneStateTracker _sceneState;
private readonly ICameraStatusReporter _statusReporter;
private readonly IDetectionReporter _detectionReporter;
private readonly PipelineDegradationManager _degradationManager;
private readonly SystemMetricsProvider _metrics;
private readonly IRemoteFrameBroker? _broker;
private readonly FrameResizer? _resizer;
private readonly ILogger<SnapshotPipelineService> _logger;
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new();
private long _snapshotsProcessed;
private long _analysisFailures;
private long _snapshotsSkippedByDegradation;
private long _remoteSubmissions;
private long _remoteFallbacks;
private bool _storeSubscribed;
private DateTime _lastCpuCheckAt = DateTime.MinValue;
private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10);
public SnapshotPipelineService(SnapshotPipelineServiceOptions options)
{
_state = options.State;
_options = options.Options.Value;
_cameraStore = options.CameraStore;
_streams = options.Streams;
_analyzer = options.Analyzer;
_sceneState = options.SceneState;
_statusReporter = options.StatusReporter;
_detectionReporter = options.DetectionReporter;
_degradationManager = options.DegradationManager;
_metrics = options.Metrics;
_logger = options.Logger;
_broker = options.Broker;
_resizer = options.Resizer;
}
/// <summary>Number of snapshots handed to the analyzer (real calls).</summary>
public long SnapshotsProcessed => Interlocked.Read(ref _snapshotsProcessed);
/// <summary>Number of frames that failed analysis (analyzer exceptions).</summary>
public long AnalysisFailures => Interlocked.Read(ref _analysisFailures);
/// <summary>Number of snapshots skipped because of pipeline degradation.</summary>
public long SnapshotsSkippedByDegradation => Interlocked.Read(ref _snapshotsSkippedByDegradation);
/// <summary>Number of frames submitted to the remote broker.</summary>
public long RemoteSubmissions => Interlocked.Read(ref _remoteSubmissions);
/// <summary>Number of remote submissions that fell back to local analysis.</summary>
public long RemoteFallbacks => Interlocked.Read(ref _remoteFallbacks);
/// <summary>Whether the pipeline is operating in remote analysis mode.</summary>
public bool IsRemoteMode => _options.AnalysisMode == AnalysisMode.Remote && _broker is not null;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Local fallback (Agent:Cameras) until the Central camera list arrives.
_cameraStore.SetLocalFallback(BuildLocalCameras());
if (_options.AnalysisMode == AnalysisMode.Remote)
{
if (string.IsNullOrEmpty(_options.BrokerUrl))
_logger.LogWarning("AnalysisMode is Remote but BrokerUrl is not configured — remote analysis disabled");
else
_logger.LogInformation(
"Analysis mode: Remote (broker: {BrokerUrl}). Fallback to local if broker unreachable.",
_options.BrokerUrl);
}
else
{
_logger.LogInformation("Analysis mode: Local (YOLO/ONNX on agent)");
}
// Wait until the agent is registered (has an AgentId), same as
// ConfigReceiverService — the Central config needs the agent identity.
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
await Task.Delay(1000, stoppingToken);
if (stoppingToken.IsCancellationRequested) return;
_cameraStore.Changed += OnCameraConfigChanged;
_storeSubscribed = true;
var consumer = Task.Run(() => ConsumeSnapshotsAsync(stoppingToken), stoppingToken);
var cpuMonitor = Task.Run(() => MonitorCpuAsync(stoppingToken), stoppingToken);
try
{
await SyncStreamsAsync(stoppingToken);
// Periodic resync catches assignments missed while we were busy
// (e.g. camera settings applied before we subscribed).
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
await SyncStreamsAsync(stoppingToken);
}
}
finally
{
if (_storeSubscribed)
_cameraStore.Changed -= OnCameraConfigChanged;
try { await consumer; }
catch (OperationCanceledException)
{
// Intentional: suppress cancellation during graceful shutdown
}
try { await cpuMonitor; } catch (OperationCanceledException) { }
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await _streams.StopAllAsync();
await base.StopAsync(cancellationToken);
}
private void OnCameraConfigChanged(object? sender, EventArgs e)
{
// Fire-and-forget resync; SyncStreamsAsync is idempotent and cheap.
_ = Task.Run(() => SyncStreamsAsync(CancellationToken.None));
}
private async Task SyncStreamsAsync(CancellationToken ct)
{
var desired = _cameraStore.Cameras
.Where(c => c.Enabled && !string.IsNullOrWhiteSpace(c.EffectiveRtspUrl))
.ToList();
// Stop streams for cameras no longer assigned/disabled.
var toStop = _streams.ActiveCameraIds
.Where(activeId => !desired.Any(c => c.CameraId == activeId))
.ToList();
foreach (var activeId in toStop)
{
await _streams.StopStreamAsync(activeId);
// Camera removed/disabled → Disabled status at the Central.
await _statusReporter.ReportAsync(activeId, "Disabled", ct);
}
// Start streams for newly assigned cameras.
foreach (var camera in desired)
{
if (_streams.IsStreamActive(camera.CameraId))
{
// Capture already running → Online.
await _statusReporter.ReportAsync(camera.CameraId, "Online", ct);
continue;
}
var started = await _streams.StartStreamAsync(camera.CameraId, camera.EffectiveRtspUrl, ct);
if (started)
{
_logger.LogInformation("Capture started for camera {CameraId} ({Name})", camera.CameraId, camera.Name);
await _statusReporter.ReportAsync(camera.CameraId, "Online", ct);
}
else
{
_logger.LogWarning(
"Capture failed to start for camera {CameraId} ({Name}) — will retry at next sync",
camera.CameraId, camera.Name);
// ffmpeg unavailable / invalid URL → Error at the Central.
await _statusReporter.ReportAsync(camera.CameraId, "Error", ct);
}
}
}
/// <summary>
/// Monitor CPU usage and report to the degradation manager.
/// Runs in the background, checking every <see cref="CpuCheckInterval"/>.
/// </summary>
private async Task MonitorCpuAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(CpuCheckInterval, ct);
var now = DateTime.UtcNow;
if (now - _lastCpuCheckAt < CpuCheckInterval)
continue;
_lastCpuCheckAt = now;
var metrics = _metrics.Collect();
if (metrics.CpuUsagePercent is { } cpu)
_degradationManager.ReportCpuSaturation(cpu);
}
}
catch (OperationCanceledException)
{
// Shutdown.
}
}
private async Task ConsumeSnapshotsAsync(CancellationToken ct)
{
try
{
await foreach (var snapshot in _streams.SnapshotChannel.Reader.ReadAllAsync(ct))
{
try
{
// Update queue depth metric (spec 13.1)
HeimdallMetrics.SetQueueDepth(_streams.SnapshotChannel.Reader.Count);
// Check degradation level before processing
var level = _degradationManager.Level;
// Motion detection runs in both modes — it gates remote submission.
var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector());
var motion = detector.Detect(snapshot.JpegData);
FrameAnalysisResult? result = null;
if (IsRemoteMode && motion)
{
// Remote mode + motion: submit frame to broker, fallback to local if unreachable.
result = await AnalyzeRemoteAsync(snapshot, ct);
}
if (result is null)
{
// Local analysis: either Local mode, or Remote mode with broker fallback,
// or Remote mode but no motion (still run local for detection coverage).
result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct: ct);
}
Interlocked.Increment(ref _snapshotsProcessed);
_sceneState.UpdateFromAnalysis(
result?.Detections.Count > 0,
motion);
if (level >= DegradationLevel.ExecutorDown)
{
// Motion-only mode: skip IA inference reporting
Interlocked.Increment(ref _snapshotsSkippedByDegradation);
await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false);
}
else
{
// Normal or SlowExecutor: report full analysis
await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false);
await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
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 pipelineLevel = failureRate > 0.5 ? 2 : failureRate > 0.1 ? 1 : 0;
HeimdallMetrics.SetPipelineLevel(pipelineLevel);
}
}
catch (OperationCanceledException)
{
// Shutdown.
}
}
/// <summary>
/// Submit a motion-detected frame to the remote broker. Returns detection results
/// on success, or null if the broker is unreachable (caller should fall back to local).
/// </summary>
private async Task<FrameAnalysisResult?> AnalyzeRemoteAsync(Snapshot snapshot, CancellationToken ct)
{
if (_broker is null || _resizer is null)
return null;
try
{
// Downscale to 640×640 for the broker
var resized = _resizer.Resize(snapshot.JpegData);
var brokerResult = await _broker.SubmitFrameAsync(
snapshot.CameraId, resized, snapshot.TimestampUtc, ct).ConfigureAwait(false);
if (brokerResult is null)
{
// Broker unreachable — fall back to local
Interlocked.Increment(ref _remoteFallbacks);
_logger.LogDebug(
"Broker unreachable for camera {CameraId} — falling back to local analysis",
snapshot.CameraId);
return null;
}
Interlocked.Increment(ref _remoteSubmissions);
// Map broker detections to the existing FrameAnalysisResult format
var detections = brokerResult.Detections
.Select(d => new DetectionResult(
d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height))
.ToList();
return new FrameAnalysisResult(
Convert.ToBase64String(resized),
detections,
brokerResult.ProcessingMs);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return null;
}
catch (Exception ex)
{
Interlocked.Increment(ref _remoteFallbacks);
_logger.LogDebug(ex, "Remote analysis failed for camera {CameraId} — falling back to local", snapshot.CameraId);
return null;
}
}
/// <summary>
/// Report a MotionDetected event on the idle → active scene transition
/// (per camera, once per transition — the reporter's cooldown prevents
/// spam while the scene stays active).
/// </summary>
private async Task ReportSceneTransitionsAsync(Guid cameraId, CancellationToken ct)
{
var current = _sceneState.State;
var reported = _reportedSceneState.GetOrAdd(cameraId, SceneState.Idle);
// Rising edge: idle → motion/object detected.
if (current != SceneState.Idle && reported == SceneState.Idle)
{
await _detectionReporter.ReportAsync(
cameraId, Heimdall.Domain.Enums.EventType.MotionDetected,
confidence: 0.9, label: "motion", occurredAt: DateTime.UtcNow, ct: ct)
.ConfigureAwait(false);
}
_reportedSceneState[cameraId] = current;
}
/// <summary>
/// Report analyzer detections as typed events (PersonDetected,
/// VehicleDetected, …). The reporter dedupes by (camera, type) cooldown.
/// </summary>
private async Task ReportDetectionsAsync(Guid cameraId, FrameAnalysisResult? result, CancellationToken ct)
{
if (result is null || result.Detections.Count == 0)
return;
foreach (var detection in result.Detections)
{
var eventType = DetectionReporterService.MapDetectionToEventType(detection.Label);
if (eventType is null)
continue;
var metadata = System.Text.Json.JsonSerializer.Serialize(new
{
detection.Label,
detection.Confidence,
detection.X,
detection.Y,
detection.Width,
detection.Height,
});
await _detectionReporter.ReportAsync(
cameraId, eventType.Value,
detection.Confidence, detection.Label, metadata,
occurredAt: DateTime.UtcNow, ct: ct)
.ConfigureAwait(false);
}
}
private List<AgentCameraConfig> BuildLocalCameras()
{
var list = new List<AgentCameraConfig>();
var index = 0;
foreach (var camera in _options.Cameras)
{
index++;
if (string.IsNullOrWhiteSpace(camera.RtspUrl))
continue;
list.Add(new AgentCameraConfig(
StableCameraId(camera.Name, camera.RtspUrl),
string.IsNullOrWhiteSpace(camera.Name) ? $"camera-{index}" : camera.Name,
camera.RtspUrl,
string.IsNullOrWhiteSpace(camera.SubRtspUrl) ? null : camera.SubRtspUrl,
Enabled: true));
}
return list;
}
/// <summary>Stable ID for a locally-declared camera (no Central ID yet).</summary>
private static Guid StableCameraId(string name, string rtspUrl)
{
var hash = System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.UTF8.GetBytes($"{name}|{rtspUrl}"));
return new Guid(hash.AsSpan(0, 16));
}
}