feat(analysis): scheduler de jobs d'analyse avec routage par capacités, priorités et dead-letter (#159)

This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-26 23:44:38 +02:00
1 parent 760aa7baf8
commit ca43c6d28e
15 files changed
+1696 -1

No files matched your search

@@ -31,7 +31,7 @@ public static class DependencyInjection
services.AddHangfireServer(options =>
{
options.WorkerCount = 2;
options.Queues = ["default", "heartbeat", "email", "ntfy", "digest"];
options.Queues = ["default", "heartbeat", "email", "ntfy", "digest", "analysis"];
});
services.AddScoped<HeartbeatMonitorJob>();
@@ -45,6 +45,9 @@ public static class DependencyInjection
services.AddScoped<CleanupLicensePlatesJob>();
services.AddScoped<DatabaseMaintenanceJob>();
// Analysis job scheduler
services.AddScoped<AnalysisJobDispatcherJob>();
return services;
}
}
@@ -52,5 +52,17 @@ public static class JobSetup
"database-maintenance",
job => job.ExecuteAsync(CancellationToken.None),
"0 7 * * 0"); // Sunday at 7:00
// Analysis job dispatcher — process pending jobs every 30s
manager.AddOrUpdate<AnalysisJobDispatcherJob>(
"analysis-job-dispatch",
job => job.ExecuteAsync(CancellationToken.None),
"*/30 * * * * *"); // Every 30 seconds
// Timeout sweep — clean up stuck jobs every 60s
manager.AddOrUpdate<AnalysisJobDispatcherJob>(
"analysis-job-timeout-sweep",
job => job.ExecuteTimeoutSweepAsync(CancellationToken.None),
"*/1 * * * *"); // Every 60 seconds
}
}
@@ -66,6 +66,9 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
public DbSet<LicensePlate> LicensePlates => Set<LicensePlate>();
public DbSet<StoragePolicy> StoragePolicies => Set<StoragePolicy>();
// Analysis job scheduling
public DbSet<AnalysisJob> AnalysisJobs => Set<AnalysisJob>();
public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default)
{
await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false);
@@ -98,6 +101,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
builder.Entity<CameraDiscoveryResult>().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted);
builder.Entity<CameraEvent>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
builder.Entity<DiscoveredStreamUrl>().HasQueryFilter(e => e.DiscoveryResult == null || e.DiscoveryResult.Site == null || !e.DiscoveryResult.Site.IsDeleted);
builder.Entity<AnalysisJob>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
// Group soft-delete filters
builder.Entity<Group>().HasQueryFilter(e => !e.IsDeleted);
@@ -0,0 +1,90 @@
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class AnalysisJobConfiguration : IEntityTypeConfiguration<AnalysisJob>
{
public void Configure(EntityTypeBuilder<AnalysisJob> builder)
{
builder.ToTable("analysis_jobs");
builder.HasKey(j => j.Id);
// Core fields
builder.Property(j => j.JobType)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired();
builder.Property(j => j.Status)
.HasConversion<string>()
.HasMaxLength(30)
.IsRequired();
builder.Property(j => j.Priority)
.HasConversion<int>()
.IsRequired();
// Capability requirements
builder.Property(j => j.RequiredCpuCores)
.HasDefaultValue(0);
builder.Property(j => j.RequiredMemoryMb)
.HasDefaultValue(0L);
// Timeout stored as ticks (TimeSpan → long)
builder.Property(j => j.MaxExecutionTime)
.HasConversion(
v => v.Ticks,
v => new TimeSpan(v))
.HasDefaultValue(TimeSpan.FromMinutes(5));
// Retry
builder.Property(j => j.RetryCount)
.HasDefaultValue(0);
builder.Property(j => j.MaxRetries)
.HasDefaultValue(3);
// JSON payloads
builder.Property(j => j.ParametersJson)
.HasColumnType("jsonb");
builder.Property(j => j.ResultJson)
.HasColumnType("jsonb");
builder.Property(j => j.ErrorMessage)
.HasMaxLength(2000);
// Indexes
// Primary lookup: pending jobs ordered by priority + creation time
builder.HasIndex(j => new { j.Status, j.Priority, j.CreatedAt })
.HasDatabaseName("ix_analysis_jobs_pending");
// Timeout sweep: dispatched/running jobs with DispatchedAt
builder.HasIndex(j => new { j.Status, j.DispatchedAt })
.HasDatabaseName("ix_analysis_jobs_timeout");
// Agent workload queries
builder.HasIndex(j => new { j.AssignedAgentId, j.Status })
.HasDatabaseName("ix_analysis_jobs_agent_workload")
.HasFilter("\"AssignedAgentId\" IS NOT NULL");
// Camera lookup
builder.HasIndex(j => j.CameraId)
.HasDatabaseName("ix_analysis_jobs_camera");
// Relationships
builder.HasOne(j => j.Camera)
.WithMany()
.HasForeignKey(j => j.CameraId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(j => j.AssignedAgent)
.WithMany()
.HasForeignKey(j => j.AssignedAgentId)
.OnDelete(DeleteBehavior.SetNull);
}
}
@@ -162,6 +162,9 @@ public static class DependencyInjection
// Camera assignment service (used by CQRS handlers)
services.AddScoped<ICameraAssignmentService, CameraAssignmentService>();
// Analysis job scheduler (capability + affinity + load routing)
services.AddScoped<IAnalysisJobSchedulerService, AnalysisJobSchedulerService>();
// Notification services
services.AddScoped<INotificationService, NotificationService>();
services.AddSingleton<INotificationRateLimiter, NotificationRateLimiter>();
@@ -0,0 +1,102 @@
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Hangfire job that dispatches pending analysis jobs to agents and cleans up
/// timed-out jobs. Runs on the "analysis" queue.
///
/// Responsibilities:
/// 1. Pick pending jobs ordered by priority (security first) and dispatch to best agent
/// 2. Detect jobs stuck in Dispatched/Running past their timeout → retry or dead-letter
///
/// Uses IDbContextFactory to avoid sharing DbContext across Hangfire worker threads.
/// </summary>
public sealed class AnalysisJobDispatcherJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IAnalysisJobSchedulerService _schedulerService;
private readonly ILogger<AnalysisJobDispatcherJob> _logger;
/// <summary>Max jobs to dispatch per tick to prevent overwhelming agents.</summary>
private const int MaxDispatchPerTick = 10;
public AnalysisJobDispatcherJob(
IDbContextFactory<AppDbContext> dbFactory,
IAnalysisJobSchedulerService schedulerService,
ILogger<AnalysisJobDispatcherJob> logger)
{
_dbFactory = dbFactory;
_schedulerService = schedulerService;
_logger = logger;
}
/// <summary>
/// Main dispatcher tick: process pending jobs and clean up timed-out jobs.
/// Called every 30 seconds by Hangfire recurring job.
/// </summary>
public async Task ExecuteAsync(CancellationToken ct = default)
{
// 1. Dispatch pending jobs
var dispatched = await _schedulerService
.ProcessPendingJobsAsync(MaxDispatchPerTick, ct)
.ConfigureAwait(false);
// 2. Clean up timed-out jobs
var timedOutJobs = await _schedulerService
.GetTimedOutJobsAsync(ct)
.ConfigureAwait(false);
foreach (var job in timedOutJobs)
{
_logger.LogWarning(
"Analysis job {JobId} timed out (status={Status}, dispatched={DispatchedAt})",
job.Id, job.Status, job.DispatchedAt);
await _schedulerService.FailJobAsync(
job.Id,
$"Execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s",
ct)
.ConfigureAwait(false);
}
if (dispatched > 0 || timedOutJobs.Count > 0)
{
_logger.LogInformation(
"Analysis dispatcher: {Dispatched} dispatched, {TimedOut} timed out",
dispatched, timedOutJobs.Count);
}
}
/// <summary>
/// Timeout sweep only — runs less frequently (every 60s) to catch stuck jobs.
/// </summary>
public async Task ExecuteTimeoutSweepAsync(CancellationToken ct = default)
{
var timedOutJobs = await _schedulerService
.GetTimedOutJobsAsync(ct)
.ConfigureAwait(false);
if (timedOutJobs.Count == 0)
return;
foreach (var job in timedOutJobs)
{
_logger.LogWarning(
"Sweep: analysis job {JobId} stuck in {Status} since {DispatchedAt} (timeout={Timeout}s)",
job.Id, job.Status, job.DispatchedAt, job.MaxExecutionTime.TotalSeconds);
await _schedulerService.FailJobAsync(
job.Id,
$"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s",
ct)
.ConfigureAwait(false);
}
_logger.LogInformation("Timeout sweep: {Count} jobs cleaned up", timedOutJobs.Count);
}
}
@@ -0,0 +1,379 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
/// <summary>
/// Schedules analysis jobs by selecting the best agent based on:
/// 1. Capabilities (GPU, CPU, RAM) — agent must meet job requirements
/// 2. Site affinity — prefer agents at the same site as the camera
/// 3. Current load — prefer agents with fewer active jobs
///
/// Priority ordering: SecurityCritical > SecurityHigh > Periodic > Background.
/// Timeout/retry logic: jobs that fail are retried up to MaxRetries, then dead-lettered.
/// </summary>
public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<AnalysisJobSchedulerService> _logger;
public AnalysisJobSchedulerService(
IDbContextFactory<AppDbContext> dbFactory,
ILogger<AnalysisJobSchedulerService> logger)
{
_dbFactory = dbFactory;
_logger = logger;
}
public async Task<ServiceResult<AnalysisJob>> CreateJobAsync(
Guid cameraId,
AnalysisJobType jobType,
AnalysisJobPriority priority,
string? parametersJson = null,
CancellationToken ct = default)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var camera = await db.Cameras
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == cameraId && !c.IsDeleted, ct)
.ConfigureAwait(false);
if (camera is null)
return ServiceResult<AnalysisJob>.NotFound("Camera not found");
var job = new AnalysisJob(cameraId, camera.SiteId, jobType, priority, parametersJson);
// Set capability requirements based on job type
ApplyCapabilityRequirements(job, jobType);
db.AnalysisJobs.Add(job);
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
_logger.LogInformation(
"Analysis job {JobId} created: {JobType} for camera {CameraId} (priority={Priority})",
job.Id, jobType, cameraId, priority);
return ServiceResult<AnalysisJob>.Success(job);
}
public async Task<ServiceResult<AnalysisJob>> DispatchJobAsync(Guid jobId, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var job = await db.AnalysisJobs
.AsTracking()
.FirstOrDefaultAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Pending, ct)
.ConfigureAwait(false);
if (job is null)
return ServiceResult<AnalysisJob>.NotFound("No pending job found with this ID");
var bestAgent = await SelectBestAgentInternalAsync(db, job, ct).ConfigureAwait(false);
if (bestAgent is null)
{
_logger.LogDebug(
"No suitable agent found for job {JobId} ({JobType}), will retry later",
jobId, job.JobType);
return ServiceResult<AnalysisJob>.Failure("No suitable agent available", 503);
}
job.Dispatch(bestAgent.Id);
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
_logger.LogInformation(
"Job {JobId} dispatched to agent {AgentId} ({AgentName}) — site affinity: {SameSite}",
jobId, bestAgent.Id, bestAgent.Name, bestAgent.SiteId == job.SiteId);
return ServiceResult<AnalysisJob>.Success(job);
}
public async Task<int> ProcessPendingJobsAsync(int maxJobs, CancellationToken ct)
{
var pendingJobs = await GetPendingJobsAsync(maxJobs, ct).ConfigureAwait(false);
var dispatched = 0;
foreach (var job in pendingJobs)
{
var result = await DispatchJobAsync(job.Id, ct).ConfigureAwait(false);
if (result.IsSuccess)
dispatched++;
}
if (dispatched > 0)
{
_logger.LogInformation(
"Dispatcher processed {Dispatched}/{Total} pending jobs",
dispatched, pendingJobs.Count);
}
return dispatched;
}
public async Task<ServiceResult> StartJobAsync(Guid jobId, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var job = await db.AnalysisJobs
.AsTracking()
.FirstOrDefaultAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Dispatched, ct)
.ConfigureAwait(false);
if (job is null)
return ServiceResult.NotFound("No dispatched job found with this ID");
job.Start();
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
return ServiceResult.Success();
}
public async Task<ServiceResult> CompleteJobAsync(Guid jobId, CancellationToken ct, string? resultJson = null)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var job = await db.AnalysisJobs
.AsTracking()
.FirstOrDefaultAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Running, ct)
.ConfigureAwait(false);
if (job is null)
return ServiceResult.NotFound("No running job found with this ID");
job.Complete(resultJson);
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
_logger.LogInformation("Job {JobId} completed successfully", jobId);
return ServiceResult.Success();
}
public async Task<ServiceResult> FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var job = await db.AnalysisJobs
.AsTracking()
.FirstOrDefaultAsync(j => j.Id == jobId
&& (j.Status == AnalysisJobStatus.Running || j.Status == AnalysisJobStatus.Dispatched), ct)
.ConfigureAwait(false);
if (job is null)
return ServiceResult.NotFound("No active job found with this ID");
var previousRetryCount = job.RetryCount;
job.Fail(errorMessage);
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
if (job.Status == AnalysisJobStatus.DeadLettered)
{
_logger.LogError(
"Job {JobId} dead-lettered after {Retries} retries: {Error}",
jobId, previousRetryCount + 1, errorMessage);
}
else
{
_logger.LogWarning(
"Job {JobId} failed (retry {RetryCount}/{MaxRetries}): {Error}",
jobId, job.RetryCount, job.MaxRetries, errorMessage);
}
return ServiceResult.Success();
}
public async Task<ServiceResult> CancelJobAsync(Guid jobId, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var job = await db.AnalysisJobs
.AsTracking()
.FirstOrDefaultAsync(j => j.Id == jobId
&& (j.Status == AnalysisJobStatus.Pending || j.Status == AnalysisJobStatus.Dispatched), ct)
.ConfigureAwait(false);
if (job is null)
return ServiceResult.NotFound("No cancellable job found with this ID");
job.Cancel();
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
_logger.LogInformation("Job {JobId} cancelled", jobId);
return ServiceResult.Success();
}
public async Task<IReadOnlyList<AnalysisJob>> GetTimedOutJobsAsync(CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
// Jobs in Dispatched or Running state — filter timeout in memory
// (MaxExecutionTime has a value conversion EF Core can't translate in LINQ)
var candidates = await db.AnalysisJobs
.AsNoTracking()
.Where(j => (j.Status == AnalysisJobStatus.Dispatched || j.Status == AnalysisJobStatus.Running)
&& j.DispatchedAt != null)
.ToListAsync(ct)
.ConfigureAwait(false);
var cutoff = DateTime.UtcNow;
return candidates
.Where(j => j.DispatchedAt!.Value.Add(j.MaxExecutionTime) < cutoff)
.ToList()
.AsReadOnly();
}
public async Task<Agent?> SelectBestAgentAsync(AnalysisJob job, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
return await SelectBestAgentInternalAsync(db, job, ct).ConfigureAwait(false);
}
public async Task<IReadOnlyList<AnalysisJob>> GetPendingJobsAsync(int limit, CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
// Order by priority (lower enum value = higher priority), then by creation time (FIFO)
var jobs = await db.AnalysisJobs
.AsNoTracking()
.Where(j => j.Status == AnalysisJobStatus.Pending)
.OrderBy(j => j.Priority)
.ThenBy(j => j.CreatedAt)
.Take(limit)
.ToListAsync(ct)
.ConfigureAwait(false);
return jobs.AsReadOnly();
}
// ── Private helpers ─────────────────────────────────────────────
private static async Task<Agent?> SelectBestAgentInternalAsync(
AppDbContext db, AnalysisJob job, CancellationToken ct)
{
// Load all online agents that are not soft-deleted
var agents = await db.Agents
.AsNoTracking()
.Where(a => a.Status == AgentStatus.Online && !a.IsDeleted)
.ToListAsync(ct)
.ConfigureAwait(false);
if (agents.Count == 0)
return null;
// Load active job counts per agent (current workload)
var workload = await db.AnalysisJobs
.AsNoTracking()
.Where(j => j.Status == AnalysisJobStatus.Dispatched || j.Status == AnalysisJobStatus.Running)
.GroupBy(j => j.AssignedAgentId)
.Select(g => new { AgentId = g.Key, Count = g.Count() })
.ToListAsync(ct)
.ConfigureAwait(false);
var workloadMap = workload.ToDictionary(x => x.AgentId!.Value, x => x.Count);
// Score each agent: lower score = better candidate
var scored = agents
.Select(a => new
{
Agent = a,
Score = ComputeAgentScore(a, job, workloadMap)
})
.Where(x => x.Score >= 0) // -1 means disqualified
.OrderBy(x => x.Score)
.ThenBy(x => workloadMap.TryGetValue(x.Agent.Id, out var c) ? c : 0)
.ToList();
return scored.Count > 0 ? scored[0].Agent : null;
}
/// <summary>
/// Compute a score for an agent relative to a job.
/// Lower score = better match.
/// Returns -1 if the agent is disqualified (doesn't meet minimum requirements).
///
/// Scoring breakdown:
/// - Site affinity: 0 if same site, +10 if different site
/// - GPU: 0 if job needs GPU and agent has it, +100 if job needs GPU and agent doesn't (disqualifies)
/// - CPU: 0 if sufficient, +1 per missing core
/// - RAM: 0 if sufficient, +10 per missing GB
/// - Load: +count of active jobs (prefer less loaded agents)
/// </summary>
private static int ComputeAgentScore(Agent agent, AnalysisJob job, Dictionary<Guid, int> workload)
{
// Disqualify: GPU required but agent doesn't have it
if (job.RequiresGpu && !agent.HasGpu)
return -1;
// Disqualify: CPU cores insufficient
if (job.RequiredCpuCores > 0 && agent.CpuCores < job.RequiredCpuCores)
return -1;
// Disqualify: RAM insufficient
if (job.RequiredMemoryMb > 0 && agent.MemoryMb < job.RequiredMemoryMb)
return -1;
var score = 0;
// Site affinity (prefer same site)
if (agent.SiteId != job.SiteId)
score += 10;
// GPU bonus (if job doesn't strictly need it, GPU is a nice-to-have)
if (!job.RequiresGpu && agent.HasGpu)
score -= 2; // Slight preference for GPU agents even when not required
// CPU headroom
if (job.RequiredCpuCores > 0)
score += Math.Max(0, job.RequiredCpuCores - agent.CpuCores);
// RAM headroom (per MB)
if (job.RequiredMemoryMb > 0)
score += (int)Math.Max(0, (job.RequiredMemoryMb - agent.MemoryMb) / 1024);
// Current workload (fewer active jobs = better)
if (workload.TryGetValue(agent.Id, out var activeJobs))
score += activeJobs * 5;
return score;
}
/// <summary>
/// Apply default capability requirements based on the analysis job type.
/// </summary>
private static void ApplyCapabilityRequirements(AnalysisJob job, AnalysisJobType jobType)
{
switch (jobType)
{
case AnalysisJobType.ObjectDetection:
case AnalysisJobType.FullSceneAnalysis:
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
job.SetTimeout(TimeSpan.FromMinutes(10));
break;
case AnalysisJobType.FaceRecognition:
case AnalysisJobType.LicensePlateDetection:
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 1024);
job.SetTimeout(TimeSpan.FromMinutes(5));
break;
case AnalysisJobType.VehicleClassification:
case AnalysisJobType.PersonDetection:
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 1024);
job.SetTimeout(TimeSpan.FromMinutes(5));
break;
case AnalysisJobType.MotionDetection:
case AnalysisJobType.AnomalyDetection:
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 1, requiredMemoryMb: 512);
job.SetTimeout(TimeSpan.FromMinutes(3));
break;
default:
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 1, requiredMemoryMb: 256);
job.SetTimeout(TimeSpan.FromMinutes(2));
break;
}
}
}