using System.Diagnostics; using Heimdall.Contracts; using Heimdall.Agent.Services; using MassTransit; using Microsoft.Extensions.Logging; namespace Heimdall.Agent; /// /// MassTransit consumer that processes messages. /// When the Central dispatches an analysis job via RabbitMQ, this consumer runs the /// local AI pipeline (YOLO/ONNX) on the provided frame and publishes a completion /// or failure message back to the Central. /// /// Configuration: PrefetchCount=1, ConcurrentMessageLimit=1 (one job at a time) /// to avoid overloading the agent's GPU/CPU resources. /// public sealed class AnalysisJobConsumer : IConsumer { private readonly FrameAnalyzerService _frameAnalyzer; private readonly AgentState _state; private readonly ILogger _logger; public AnalysisJobConsumer( FrameAnalyzerService frameAnalyzer, AgentState state, ILogger logger) { _frameAnalyzer = frameAnalyzer; _state = state; _logger = logger; } public async Task Consume(ConsumeContext context) { var job = context.Message; var agentId = _state.AgentId; if (agentId == Guid.Empty) { _logger.LogWarning( "Ignoring analysis job {JobId}: agent not registered yet", job.Id); await context.Publish(new AnalysisJobFailed { JobId = job.Id, Reason = "Agent not registered", IsTransient = true, }); return; } if (agentId != job.AgentId) { _logger.LogDebug( "Ignoring analysis job {JobId}: assigned to agent {TargetAgentId}, not {LocalAgentId}", job.Id, job.AgentId, agentId); return; } _logger.LogInformation( "Processing analysis job {JobId} for camera {CameraId} (site {SiteId})", job.Id, job.CameraId, job.SiteId); var stopwatch = Stopwatch.StartNew(); try { // Decode the Base64 frame data var frameData = Convert.FromBase64String(job.FrameData); // Run the local AI analysis pipeline var result = await _frameAnalyzer.AnalyzeFrameAsync( frameData, ct: context.CancellationToken); if (result is null) throw new InvalidOperationException("Inference unavailable, skipped or saturated; no detection result produced"); stopwatch.Stop(); var detections = result?.Detections; var detectionCount = detections?.Count ?? 0; var averageConfidence = detectionCount > 0 ? detections!.Average(d => d.Confidence) : 0.0; _logger.LogInformation( "Job {JobId} completed: {DetectionCount} detections, {Confidence:P0} confidence, {Duration}ms", job.Id, detectionCount, averageConfidence, stopwatch.ElapsedMilliseconds); // Publish completion back to the Central await context.Publish(new AnalysisJobCompleted { JobId = job.Id, Detections = detectionCount, Confidence = averageConfidence, DurationMs = stopwatch.ElapsedMilliseconds, DetectionDetails = detectionCount > 0 ? System.Text.Json.JsonSerializer.Serialize(detections) : null, }); } catch (Exception ex) { stopwatch.Stop(); _logger.LogError(ex, "Job {JobId} failed after {Duration}ms: {Reason}", job.Id, stopwatch.ElapsedMilliseconds, ex.Message); await context.Publish(new AnalysisJobFailed { JobId = job.Id, Reason = ex.Message, IsTransient = IsTransientException(ex), }); } } private static bool IsTransientException(Exception ex) => ex switch { TimeoutException => true, OperationCanceledException => true, System.Net.Http.HttpRequestException => true, System.IO.IOException => true, _ => false, }; }