Files
Heimdall/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs
T
arnaud.dartois 636154572b
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s
Complete remaining Heimdall features and acceptance
Merge pull request #138

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-06 11:14:49 +01:00

241 lines
11 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.Domain.Enums;
namespace Heimdall.Agent.Services;
/// <summary>
/// Claims one durable analysis job at a time over the agent's outbound Central connection.
/// Central owns the lease and attempt ID; a repeated result uses that same ID.
/// </summary>
public sealed class AnalysisJobPollingService : BackgroundService
{
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5);
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly AgentState _state;
private readonly CameraConfigStore _cameras;
private readonly CameraStreamService _streams;
private readonly FrameAnalyzerService _analyzer;
private readonly IHttpClientFactory _clients;
private readonly ILogger<AnalysisJobPollingService> _logger;
public AnalysisJobPollingService(AgentState state, CameraConfigStore cameras,
CameraStreamService streams, FrameAnalyzerService analyzer, IHttpClientFactory clients,
ILogger<AnalysisJobPollingService> logger)
{
_state = state;
_cameras = cameras;
_streams = streams;
_analyzer = analyzer;
_clients = clients;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
if (_state.AgentId != Guid.Empty && !string.IsNullOrWhiteSpace(_state.ApiKey))
await PollOnceAsync(stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Analysis job polling failed; Central will retain or retry the leased job");
}
try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
}
private async Task PollOnceAsync(CancellationToken ct)
{
var agentId = _state.AgentId;
using var client = _clients.CreateClient("Central");
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
using var response = await client.GetAsync($"api/agents/{agentId:D}/analysis-jobs/next", ct)
.ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.NoContent) return;
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Analysis job claim failed with HTTP {StatusCode}", (int)response.StatusCode);
return;
}
var job = await response.Content.ReadFromJsonAsync<LeasedJob>(Json, ct).ConfigureAwait(false);
if (job is null || job.JobId == Guid.Empty || job.CameraId == Guid.Empty || job.AttemptId == Guid.Empty)
{
_logger.LogError("Central returned an invalid analysis job lease");
return;
}
var result = await ExecuteJobAsync(job, ct).ConfigureAwait(false);
await SendResultAsync(client, agentId, job.JobId, result, ct).ConfigureAwait(false);
}
private async Task<AnalysisResult> ExecuteJobAsync(LeasedJob job, CancellationToken ct)
{
if (!TryGetSupportedJobType(job.JobType, out var jobType))
return Failure(job.AttemptId, "Unsupported analysis job type");
var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled);
if (camera is null || !_streams.IsStreamActive(job.CameraId))
return Failure(job.AttemptId, "Camera is not assigned, enabled, or streaming");
if (jobType != AnalysisJobType.MotionDetection && !_analyzer.ModelAvailable)
return Failure(job.AttemptId, "Object detection model is unavailable");
Snapshot? frame;
try
{
frame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
frame = null;
}
if (frame is null)
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
if (jobType == AnalysisJobType.MotionDetection)
{
await Task.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false);
Snapshot? nextFrame;
try
{
nextFrame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
nextFrame = null;
}
if (nextFrame is null)
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
var motion = MotionDetectionAnalyzer.Compare(frame.JpegData, nextFrame.JpegData);
return new AnalysisResult(job.AttemptId, true, null, motion
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
.ToArray());
}
var confidence = TryGetMinConfidence(job.ParametersJson, out var requestedConfidence)
? requestedConfidence
: camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence;
var analysis = await _analyzer.AnalyzeFrameAsync(frame.JpegData, confidence, ct).ConfigureAwait(false);
if (analysis is null)
return Failure(job.AttemptId, "Object detection was unavailable or saturated");
var detections = SelectDetections(jobType, analysis.Detections);
return new AnalysisResult(job.AttemptId, true, null, detections
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
.ToArray());
}
internal async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId,
AnalysisResult result, CancellationToken ct)
{
var retryDelay = TimeSpan.FromSeconds(2);
while (!ct.IsCancellationRequested)
{
try
{
using var response = await client.PutAsJsonAsync(
$"api/agents/{agentId:D}/analysis-jobs/{jobId:D}/result", result, Json, ct)
.ConfigureAwait(false);
if (response.IsSuccessStatusCode) return;
if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.NotFound)
{
_logger.LogInformation("Analysis job {JobId} attempt {AttemptId} is no longer current",
jobId, result.AttemptId);
return;
}
if ((int)response.StatusCode is >= 400 and < 500)
{
_logger.LogError(
"Analysis result for job {JobId} was permanently rejected with HTTP {StatusCode}; stopping retries",
jobId, (int)response.StatusCode);
return;
}
_logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying",
jobId, (int)response.StatusCode);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (HttpRequestException ex)
{
_logger.LogWarning(ex, "Analysis result delivery failed for job {JobId}; retrying", jobId);
}
catch (TaskCanceledException ex) when (!ct.IsCancellationRequested)
{
_logger.LogWarning(ex, "Analysis result delivery timed out for job {JobId}; retrying", jobId);
}
await Task.Delay(retryDelay, ct).ConfigureAwait(false);
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 30));
}
}
internal static IReadOnlyList<DetectionResult> SelectDetections(
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections) => jobType switch
{
AnalysisJobType.ObjectDetection => detections,
AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(),
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(),
_ => [],
};
private static bool IsPerson(DetectionResult detection) =>
detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase);
private static bool IsVehicle(DetectionResult detection) =>
detection.ClassIndex is 2 or 3 or 5 or 7 || detection.Label.ToLowerInvariant() is "car" or "motorcycle" or "bus" or "truck";
internal static bool TryGetSupportedJobType(JsonElement type, out AnalysisJobType jobType)
{
if (type.ValueKind == JsonValueKind.String && Enum.TryParse(type.GetString(), true, out jobType))
return IsSupported(jobType);
if (type.ValueKind == JsonValueKind.Number && type.TryGetInt32(out var value) && Enum.IsDefined(typeof(AnalysisJobType), value))
{
jobType = (AnalysisJobType)value;
return IsSupported(jobType);
}
jobType = default;
return false;
}
private static bool IsSupported(AnalysisJobType type) => type is AnalysisJobType.ObjectDetection or
AnalysisJobType.PersonDetection or AnalysisJobType.VehicleClassification or AnalysisJobType.MotionDetection;
private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []);
private static bool TryGetMinConfidence(string? parametersJson, out float confidence)
{
confidence = default;
if (string.IsNullOrWhiteSpace(parametersJson)) return false;
try
{
using var document = JsonDocument.Parse(parametersJson);
return document.RootElement.ValueKind == JsonValueKind.Object &&
document.RootElement.TryGetProperty("minConfidence", out var value) &&
value.ValueKind == JsonValueKind.Number && value.TryGetSingle(out confidence) &&
float.IsFinite(confidence) && confidence is >= 0 and <= 1;
}
catch (JsonException) { return false; }
}
private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType,
string? ParametersJson);
internal sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
float Width, float Height, int? ClassIndex);
internal sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error,
IReadOnlyList<AnalysisDetection> Detections);
}