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

@@ -0,0 +1,72 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
namespace Heimdall.Application.Services;
/// <summary>
/// Schedules analysis jobs by selecting the best agent based on capabilities,
/// site affinity, and current load. Manages the full lifecycle of analysis jobs.
/// </summary>
public interface IAnalysisJobSchedulerService
{
/// <summary>
/// Create a new analysis job and enqueue it for scheduling.
/// </summary>
Task<ServiceResult<AnalysisJob>> CreateJobAsync(
Guid cameraId,
AnalysisJobType jobType,
AnalysisJobPriority priority,
string? parametersJson = null,
CancellationToken ct = default);
/// <summary>
/// Select the best agent for a pending job and dispatch it.
/// Selection criteria: capabilities → site affinity → current load.
/// Returns null if no suitable agent is available.
/// </summary>
Task<ServiceResult<AnalysisJob>> DispatchJobAsync(Guid jobId, CancellationToken ct);
/// <summary>
/// Process the next batch of pending jobs (called by the Hangfire dispatcher).
/// Selects agents and dispatches as many jobs as possible.
/// </summary>
Task<int> ProcessPendingJobsAsync(int maxJobs, CancellationToken ct);
/// <summary>
/// Mark a job as started by the agent.
/// </summary>
Task<ServiceResult> StartJobAsync(Guid jobId, CancellationToken ct);
/// <summary>
/// Mark a job as completed with results.
/// </summary>
Task<ServiceResult> CompleteJobAsync(Guid jobId, CancellationToken ct, string? resultJson = null);
/// <summary>
/// Report a job failure — triggers retry or dead-lettering.
/// </summary>
Task<ServiceResult> FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct);
/// <summary>
/// Cancel a pending or running job.
/// </summary>
Task<ServiceResult> CancelJobAsync(Guid jobId, CancellationToken ct);
/// <summary>
/// Get jobs stuck in Dispatched/Running state longer than their timeout.
/// Returns them for the dispatcher to clean up.
/// </summary>
Task<IReadOnlyList<AnalysisJob>> GetTimedOutJobsAsync(CancellationToken ct);
/// <summary>
/// Get the best agent for a given job based on capabilities, site affinity, and load.
/// Used internally and for testing/validation.
/// </summary>
Task<Agent?> SelectBestAgentAsync(AnalysisJob job, CancellationToken ct);
/// <summary>
/// Get pending jobs ordered by priority (security first).
/// </summary>
Task<IReadOnlyList<AnalysisJob>> GetPendingJobsAsync(int limit, CancellationToken ct);
}
+151
View File
@@ -0,0 +1,151 @@
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// Represents an analysis job to be scheduled and executed on an agent.
/// Tracks the full lifecycle: pending → dispatched → running → completed/dead-lettered.
/// Includes retry state, timeout config, and agent selection metadata.
/// </summary>
public class AnalysisJob : Entity<Guid>, IAuditableEntity
{
public Guid CameraId { get; private set; }
public Guid? AssignedAgentId { get; private set; }
public AnalysisJobType JobType { get; private set; }
public AnalysisJobStatus Status { get; private set; } = AnalysisJobStatus.Pending;
public AnalysisJobPriority Priority { get; private set; } = AnalysisJobPriority.Periodic;
// ── Scheduling metadata ─────────────────────────────────────────
/// <summary>Site affinity hint — prefer agents at this site.</summary>
public Guid SiteId { get; private set; }
/// <summary>Required capabilities bitmask (GPU, CPU cores, RAM).</summary>
public bool RequiresGpu { get; private set; }
public int RequiredCpuCores { get; private set; }
public long RequiredMemoryMb { get; private set; }
// ── Timeout & retry ─────────────────────────────────────────────
/// <summary>Max allowed execution time before the job is considered timed out.</summary>
public TimeSpan MaxExecutionTime { get; private set; } = TimeSpan.FromMinutes(5);
/// <summary>Current retry attempt (0-based).</summary>
public int RetryCount { get; private set; }
/// <summary>Maximum number of retry attempts before dead-lettering.</summary>
public int MaxRetries { get; private set; } = 3;
// ── Input / output ──────────────────────────────────────────────
/// <summary>JSON payload with job-specific parameters (detection config, thresholds, etc.).</summary>
public string? ParametersJson { get; private set; }
/// <summary>JSON result produced by the agent after execution.</summary>
public string? ResultJson { get; private set; }
/// <summary>Error message if the job failed or was dead-lettered.</summary>
public string? ErrorMessage { get; private set; }
// ── Timestamps ──────────────────────────────────────────────────
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime? DispatchedAt { get; private set; }
public DateTime? StartedAt { get; private set; }
public DateTime? CompletedAt { get; private set; }
// ── Navigation ──────────────────────────────────────────────────
public Camera Camera { get; private set; } = null!;
public Agent? AssignedAgent { get; private set; }
private AnalysisJob() { } // EF Core
public AnalysisJob(
Guid cameraId,
Guid siteId,
AnalysisJobType jobType,
AnalysisJobPriority priority,
string? parametersJson = null)
: base(Guid.NewGuid())
{
CameraId = cameraId;
SiteId = siteId;
JobType = jobType;
Priority = priority;
ParametersJson = parametersJson;
Status = AnalysisJobStatus.Pending;
}
// ── Behaviour ───────────────────────────────────────────────────
public void SetCapabilityRequirements(bool requiresGpu, int requiredCpuCores, long requiredMemoryMb)
{
RequiresGpu = requiresGpu;
RequiredCpuCores = requiredCpuCores;
RequiredMemoryMb = requiredMemoryMb;
}
public void SetTimeout(TimeSpan maxExecutionTime) => MaxExecutionTime = maxExecutionTime;
public void SetMaxRetries(int maxRetries) => MaxRetries = maxRetries;
public void Dispatch(Guid agentId)
{
AssignedAgentId = agentId;
Status = AnalysisJobStatus.Dispatched;
DispatchedAt = DateTime.UtcNow;
}
public void Start()
{
Status = AnalysisJobStatus.Running;
StartedAt = DateTime.UtcNow;
}
public void Complete(string? resultJson = null)
{
Status = AnalysisJobStatus.Completed;
ResultJson = resultJson;
CompletedAt = DateTime.UtcNow;
}
public void Fail(string errorMessage)
{
RetryCount++;
ErrorMessage = errorMessage;
if (RetryCount >= MaxRetries)
{
Status = AnalysisJobStatus.DeadLettered;
}
else
{
// Reset to pending for retry — agent will be re-selected
Status = AnalysisJobStatus.Pending;
AssignedAgentId = null;
DispatchedAt = null;
}
}
public void TimeOut()
{
Status = AnalysisJobStatus.TimedOut;
ErrorMessage = $"Job exceeded maximum execution time of {MaxExecutionTime.TotalSeconds}s";
RetryCount++;
if (RetryCount >= MaxRetries)
{
Status = AnalysisJobStatus.DeadLettered;
}
else
{
Status = AnalysisJobStatus.Pending;
AssignedAgentId = null;
DispatchedAt = null;
}
}
public void Cancel()
{
Status = AnalysisJobStatus.Cancelled;
CompletedAt = DateTime.UtcNow;
}
}
@@ -0,0 +1,21 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// Priority levels for analysis jobs.
/// Security-related jobs always take precedence over periodic/scheduled jobs.
/// Lower numeric value = higher priority.
/// </summary>
public enum AnalysisJobPriority
{
/// <summary>Security-critical analysis (unknown person, anomaly, intrusion).</summary>
SecurityCritical = 0,
/// <summary>High priority — face recognition, license plate on alert.</summary>
SecurityHigh = 1,
/// <summary>Normal priority — periodic detection sweeps, scheduled scans.</summary>
Periodic = 2,
/// <summary>Low priority — background scene analysis, maintenance tasks.</summary>
Background = 3,
}
@@ -0,0 +1,28 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// Lifecycle states of an analysis job.
/// </summary>
public enum AnalysisJobStatus
{
/// <summary>Job created, awaiting scheduling to an agent.</summary>
Pending = 0,
/// <summary>Agent selected, job dispatched for execution.</summary>
Dispatched = 1,
/// <summary>Agent is actively processing the job.</summary>
Running = 2,
/// <summary>Job completed successfully.</summary>
Completed = 3,
/// <summary>Job failed after all retries — moved to dead-letter.</summary>
DeadLettered = 4,
/// <summary>Job was cancelled before completion.</summary>
Cancelled = 5,
/// <summary>Job timed out on the agent (exceeded MaxExecutionTime).</summary>
TimedOut = 6,
}
@@ -0,0 +1,31 @@
namespace Heimdall.Domain.Enums;
/// <summary>
/// Types of analysis tasks that can be scheduled for execution on agents.
/// </summary>
public enum AnalysisJobType
{
/// <summary>General motion detection analysis on a camera stream.</summary>
MotionDetection = 0,
/// <summary>Face recognition analysis on captured frames.</summary>
FaceRecognition = 1,
/// <summary>License plate detection and recognition.</summary>
LicensePlateDetection = 2,
/// <summary>Object detection (YOLO) — general purpose.</summary>
ObjectDetection = 3,
/// <summary>Vehicle classification and tracking.</summary>
VehicleClassification = 4,
/// <summary>Person detection and tracking.</summary>
PersonDetection = 5,
/// <summary>Anomaly detection — unusual behaviour or patterns.</summary>
AnomalyDetection = 6,
/// <summary>Full scene analysis combining multiple detection types.</summary>
FullSceneAnalysis = 7,
}
@@ -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;
}
}
}
@@ -0,0 +1,165 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Shouldly;
namespace Heimdall.Domain.Tests;
public class AnalysisJobTests
{
private static readonly Guid TestCameraId = Guid.NewGuid();
private static readonly Guid TestSiteId = Guid.NewGuid();
[Fact]
public void Constructor_SetsDefaultValues()
{
var job = new AnalysisJob(
TestCameraId, TestSiteId,
AnalysisJobType.MotionDetection,
AnalysisJobPriority.Periodic);
job.CameraId.ShouldBe(TestCameraId);
job.SiteId.ShouldBe(TestSiteId);
job.JobType.ShouldBe(AnalysisJobType.MotionDetection);
job.Priority.ShouldBe(AnalysisJobPriority.Periodic);
job.Status.ShouldBe(AnalysisJobStatus.Pending);
job.RetryCount.ShouldBe(0);
job.MaxRetries.ShouldBe(3);
job.MaxExecutionTime.ShouldBe(TimeSpan.FromMinutes(5));
}
[Fact]
public void Dispatch_SetsStatusAndTimestamp()
{
var job = CreatePendingJob();
var agentId = Guid.NewGuid();
job.Dispatch(agentId);
job.Status.ShouldBe(AnalysisJobStatus.Dispatched);
job.AssignedAgentId.ShouldBe(agentId);
job.DispatchedAt.ShouldNotBeNull();
}
[Fact]
public void Start_SetsRunningAndTimestamp()
{
var job = CreatePendingJob();
job.Dispatch(Guid.NewGuid());
job.Start();
job.Status.ShouldBe(AnalysisJobStatus.Running);
job.StartedAt.ShouldNotBeNull();
}
[Fact]
public void Complete_SetsCompletedWithResult()
{
var job = CreatePendingJob();
job.Dispatch(Guid.NewGuid());
job.Start();
job.Complete("{\"detections\": 5}");
job.Status.ShouldBe(AnalysisJobStatus.Completed);
job.ResultJson.ShouldBe("{\"detections\": 5}");
job.CompletedAt.ShouldNotBeNull();
}
[Fact]
public void Fail_BelowMaxRetries_ReturnsToPending()
{
var job = CreatePendingJob();
job.Dispatch(Guid.NewGuid());
job.Start();
job.Fail("Agent crashed");
job.Status.ShouldBe(AnalysisJobStatus.Pending);
job.RetryCount.ShouldBe(1);
job.AssignedAgentId.ShouldBeNull(); // Cleared for re-selection
job.ErrorMessage.ShouldBe("Agent crashed");
}
[Fact]
public void Fail_ExceedsMaxRetries_DeadLetters()
{
var job = CreatePendingJob();
job.SetMaxRetries(2);
// Fail twice
job.Dispatch(Guid.NewGuid());
job.Start();
job.Fail("Error 1");
job.Dispatch(Guid.NewGuid());
job.Start();
job.Fail("Error 2");
job.Status.ShouldBe(AnalysisJobStatus.DeadLettered);
job.RetryCount.ShouldBe(2);
}
[Fact]
public void TimeOut_BelowMaxRetries_ReturnsToPending()
{
var job = CreatePendingJob();
job.Dispatch(Guid.NewGuid());
job.Start();
job.TimeOut();
job.Status.ShouldBe(AnalysisJobStatus.Pending);
job.RetryCount.ShouldBe(1);
job.ErrorMessage.ShouldNotBeNull();
job.ErrorMessage!.ShouldContain("exceeded maximum execution time");
}
[Fact]
public void TimeOut_ExceedsMaxRetries_DeadLetters()
{
var job = CreatePendingJob();
job.SetMaxRetries(1);
job.Dispatch(Guid.NewGuid());
job.Start();
job.TimeOut();
job.Status.ShouldBe(AnalysisJobStatus.DeadLettered);
}
[Fact]
public void Cancel_SetsCancelled()
{
var job = CreatePendingJob();
job.Cancel();
job.Status.ShouldBe(AnalysisJobStatus.Cancelled);
job.CompletedAt.ShouldNotBeNull();
}
[Fact]
public void SetCapabilityRequirements_StoresValues()
{
var job = CreatePendingJob();
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 4, requiredMemoryMb: 4096);
job.RequiresGpu.ShouldBeTrue();
job.RequiredCpuCores.ShouldBe(4);
job.RequiredMemoryMb.ShouldBe(4096);
}
[Fact]
public void SetTimeout_StoresValue()
{
var job = CreatePendingJob();
job.SetTimeout(TimeSpan.FromMinutes(10));
job.MaxExecutionTime.ShouldBe(TimeSpan.FromMinutes(10));
}
private static AnalysisJob CreatePendingJob() =>
new(TestCameraId, TestSiteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
}
@@ -0,0 +1,223 @@
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Jobs;
using Heimdall.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using Heimdall.TestCommon;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class AnalysisJobDispatcherJobTests : IAsyncLifetime
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly AnalysisJobSchedulerService _schedulerService;
private readonly AnalysisJobDispatcherJob _dispatcher;
public AnalysisJobDispatcherJobTests(PostgreSqlContainerFixture postgres)
{
_dbFactory = CreateFactory(postgres.ConnectionString);
var logger = Substitute.For<ILogger<AnalysisJobSchedulerService>>();
_schedulerService = new AnalysisJobSchedulerService(_dbFactory, logger);
var dispatcherLogger = Substitute.For<ILogger<AnalysisJobDispatcherJob>>();
_dispatcher = new AnalysisJobDispatcherJob(_dbFactory, _schedulerService, dispatcherLogger);
}
public async Task InitializeAsync()
{
await ResetDatabaseAsync();
}
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetDatabaseAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
await db.Database.ExecuteSqlRawAsync(
"TRUNCATE TABLE analysis_jobs, camera_events, camera_assignments, cameras, agents, sites RESTART IDENTITY CASCADE");
}
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"))
.Options;
using var ctx = new AppDbContext(opts, new AuditInterceptor());
ctx.Database.EnsureCreated();
return new TestDbContextFactory(opts);
}
// ── ExecuteAsync (dispatch pending) ─────────────────────────────
[Fact]
public async Task ExecuteAsync_PendingJobs_DispatchesToAgents()
{
var (siteId, cameraId, agentId) = await SeedFullSiteAsync();
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _dispatcher.ExecuteAsync();
await using var db = await _dbFactory.CreateDbContextAsync();
var job = await db.AnalysisJobs.SingleAsync();
job.Status.ShouldBe(AnalysisJobStatus.Dispatched);
job.AssignedAgentId.ShouldBe(agentId);
}
[Fact]
public async Task ExecuteAsync_NoAgents_JobsStayPending()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _dispatcher.ExecuteAsync();
await using var db = await _dbFactory.CreateDbContextAsync();
var job = await db.AnalysisJobs.SingleAsync();
job.Status.ShouldBe(AnalysisJobStatus.Pending);
}
// ── ExecuteTimeoutSweepAsync ────────────────────────────────────
[Fact]
public async Task ExecuteTimeoutSweepAsync_TimedOutJob_RetriesOrDeadLetters()
{
var (siteId, cameraId, agentId) = await SeedFullSiteAsync();
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
// Dispatch and start the job
await _schedulerService.DispatchJobAsync(job.Id, CancellationToken.None);
await _schedulerService.StartJobAsync(job.Id, CancellationToken.None);
// Fake an old DispatchedAt via SQL (property is private set)
await using (var conn = await _dbFactory.CreateDbContextAsync())
{
var dispatchedAt = DateTime.UtcNow.AddMinutes(-10);
await conn.Database.ExecuteSqlRawAsync(
"UPDATE analysis_jobs SET \"DispatchedAt\" = @p0 WHERE \"Id\" = @p1",
dispatchedAt, job.Id);
}
await _dispatcher.ExecuteTimeoutSweepAsync();
await using var db = await _dbFactory.CreateDbContextAsync();
var loadedJob = await db.AnalysisJobs.FindAsync(job.Id);
loadedJob!.Status.ShouldBe(AnalysisJobStatus.Pending); // Retry
loadedJob.RetryCount.ShouldBe(1);
}
[Fact]
public async Task ExecuteTimeoutSweepAsync_HealthyJobs_Ignored()
{
var (siteId, cameraId, _) = await SeedFullSiteAsync();
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _schedulerService.DispatchJobAsync(job.Id, CancellationToken.None);
await _schedulerService.StartJobAsync(job.Id, CancellationToken.None);
await _dispatcher.ExecuteTimeoutSweepAsync();
await using var db = await _dbFactory.CreateDbContextAsync();
var loadedJob = await db.AnalysisJobs.FindAsync(job.Id);
loadedJob!.Status.ShouldBe(AnalysisJobStatus.Running); // Untouched
}
// ── Priority dispatch ───────────────────────────────────────────
[Fact]
public async Task ExecuteAsync_SecurityJobDispatchedBeforeBackground()
{
var (siteId, cameraId, _) = await SeedFullSiteAsync();
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Background);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.SecurityCritical);
await _dispatcher.ExecuteAsync();
await using var db = await _dbFactory.CreateDbContextAsync();
var jobs = await db.AnalysisJobs.OrderBy(j => j.Priority).ToListAsync();
jobs.Count.ShouldBe(2);
jobs.ShouldAllBe(j => j.Status == AnalysisJobStatus.Dispatched);
}
// ── Helpers ─────────────────────────────────────────────────────
private async Task<(Guid siteId, Guid cameraId)> SeedSiteAndCameraAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
var site = new Site("Test Site", "test-token", "Europe/Paris");
db.Sites.Add(site);
await db.SaveChangesAsync();
var camera = new Camera(site.Id, "Main Camera", "rtsp://test");
db.Cameras.Add(camera);
await db.SaveChangesAsync();
return (site.Id, camera.Id);
}
private async Task<(Guid siteId, Guid cameraId, Guid agentId)> SeedFullSiteAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
var site = new Site("Test Site", "test-token", "Europe/Paris");
db.Sites.Add(site);
await db.SaveChangesAsync();
var camera = new Camera(site.Id, "Main Camera", "rtsp://test");
db.Cameras.Add(camera);
var agent = new Agent(site.Id, "Test Agent", "test-host", "1.0.0");
agent.UpdateCapabilities(false, 4, 8192, GpuAcceleration.None);
agent.UpdateHeartbeat("127.0.0.1");
db.Agents.Add(agent);
await db.SaveChangesAsync();
return (site.Id, camera.Id, agent.Id);
}
private async Task<AnalysisJob> CreateJobInDbAsync(
Guid cameraId, Guid siteId, AnalysisJobType jobType, AnalysisJobPriority priority)
{
var job = new AnalysisJob(cameraId, siteId, jobType, priority);
// Apply capability requirements (mirrors the service logic)
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;
default:
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 1, requiredMemoryMb: 512);
job.SetTimeout(TimeSpan.FromMinutes(3));
break;
}
await using var db = await _dbFactory.CreateDbContextAsync();
db.AnalysisJobs.Add(job);
await db.SaveChangesAsync();
return job;
}
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(opts, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts, Audit));
}
}
@@ -0,0 +1,411 @@
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using Heimdall.TestCommon;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly AnalysisJobSchedulerService _service;
private readonly ILogger<AnalysisJobSchedulerService> _logger = Substitute.For<ILogger<AnalysisJobSchedulerService>>();
public AnalysisJobSchedulerServiceTests(PostgreSqlContainerFixture postgres)
{
_dbFactory = CreateFactory(postgres.ConnectionString);
_service = new AnalysisJobSchedulerService(_dbFactory, _logger);
}
public async Task InitializeAsync()
{
await ResetDatabaseAsync();
}
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetDatabaseAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
await db.Database.ExecuteSqlRawAsync(
"TRUNCATE TABLE analysis_jobs, camera_events, camera_assignments, cameras, agents, sites RESTART IDENTITY CASCADE");
}
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"))
.Options;
using var ctx = new AppDbContext(opts, new AuditInterceptor());
ctx.Database.EnsureCreated();
return new TestDbContextFactory(opts);
}
// ── CreateJob ───────────────────────────────────────────────────
[Fact]
public async Task CreateJobAsync_ValidCamera_CreatesJob()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(
cameraId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.CameraId.ShouldBe(cameraId);
result.Data.SiteId.ShouldBe(siteId);
result.Data.JobType.ShouldBe(AnalysisJobType.MotionDetection);
result.Data.Priority.ShouldBe(AnalysisJobPriority.Periodic);
result.Data.Status.ShouldBe(AnalysisJobStatus.Pending);
}
[Fact]
public async Task CreateJobAsync_InvalidCamera_ReturnsNotFound()
{
var result = await _service.CreateJobAsync(
Guid.NewGuid(), AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task CreateJobAsync_SetsCapabilityRequirements()
{
var (_, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(
cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
result.IsSuccess.ShouldBeTrue();
result.Data!.RequiresGpu.ShouldBeTrue();
result.Data.RequiredCpuCores.ShouldBe(2);
result.Data.RequiredMemoryMb.ShouldBe(2048);
}
// ── SelectBestAgent ─────────────────────────────────────────────
[Fact]
public async Task SelectBestAgentAsync_PrefersSameSite()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var otherSiteId = await CreateSiteAsync("Other Site");
await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await SeedAgentAsync(otherSiteId, "Remote Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldNotBeNull();
bestAgent.Name.ShouldBe("Local Agent");
}
[Fact]
public async Task SelectBestAgentAsync_PrefersGpuWhenRequired()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "CPU Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldNotBeNull();
bestAgent.Name.ShouldBe("GPU Agent");
}
[Fact]
public async Task SelectBestAgentAsync_ExcludesInsufficientGpu()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldBeNull();
}
[Fact]
public async Task SelectBestAgentAsync_PrefersLessLoadedAgent()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var idleAgentId = await SeedAgentAsync(siteId, "Idle Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var busyAgentId = await SeedAgentAsync(siteId, "Busy Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
// Give busy agent 3 active jobs
for (var i = 0; i < 3; i++)
{
var cam = await CreateCameraForSiteAsync(siteId, $"Busy Cam {i}");
var j = new AnalysisJob(cam, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
j.Dispatch(busyAgentId);
j.Start();
await using var db = await _dbFactory.CreateDbContextAsync();
db.AnalysisJobs.Add(j);
await db.SaveChangesAsync();
}
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldNotBeNull();
bestAgent.Name.ShouldBe("Idle Agent");
}
[Fact]
public async Task SelectBestAgentAsync_ExcludesOfflineAgents()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldBeNull();
}
// ── DispatchJob ─────────────────────────────────────────────────
[Fact]
public async Task DispatchJobAsync_PendingJob_DispatchesToAgent()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var result = await _service.DispatchJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Status.ShouldBe(AnalysisJobStatus.Dispatched);
result.Data.AssignedAgentId.ShouldNotBeNull();
result.Data.DispatchedAt.ShouldNotBeNull();
}
[Fact]
public async Task DispatchJobAsync_NoSuitableAgent_Returns503()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
var result = await _service.DispatchJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(503);
}
// ── StartJob / CompleteJob / FailJob ────────────────────────────
[Fact]
public async Task StartJobAsync_DispatchedJob_SetsRunning()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
var result = await _service.StartJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Running);
loaded.StartedAt.ShouldNotBeNull();
}
[Fact]
public async Task CompleteJobAsync_RunningJob_SetsCompleted()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
await _service.StartJobAsync(job.Id, CancellationToken.None);
var result = await _service.CompleteJobAsync(job.Id, CancellationToken.None, resultJson: "{\"detections\":5}");
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Completed);
loaded.ResultJson.ShouldNotBeNull();
loaded.ResultJson!.ShouldContain("detections");
}
[Fact]
public async Task FailJobAsync_RunningJob_TriggersRetry()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
await _service.StartJobAsync(job.Id, CancellationToken.None);
var result = await _service.FailJobAsync(job.Id, "Timeout on agent", CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Pending);
loaded.RetryCount.ShouldBe(1);
loaded.AssignedAgentId.ShouldBeNull();
}
[Fact]
public async Task FailJobAsync_ExceedsMaxRetries_DeadLetters()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
for (var i = 0; i < 3; i++)
{
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
await _service.StartJobAsync(job.Id, CancellationToken.None);
await _service.FailJobAsync(job.Id, $"Error {i + 1}", CancellationToken.None);
}
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.DeadLettered);
loaded.RetryCount.ShouldBe(3);
}
// ── CancelJob ───────────────────────────────────────────────────
[Fact]
public async Task CancelJobAsync_PendingJob_SetsCancelled()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var result = await _service.CancelJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Cancelled);
}
// ── GetPendingJobs (priority ordering) ──────────────────────────
[Fact]
public async Task GetPendingJobsAsync_OrdersByPriority()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Background);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.SecurityCritical);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.SecurityHigh);
var jobs = await _service.GetPendingJobsAsync(10, CancellationToken.None);
jobs.Count.ShouldBe(4);
jobs[0].Priority.ShouldBe(AnalysisJobPriority.SecurityCritical);
jobs[1].Priority.ShouldBe(AnalysisJobPriority.SecurityHigh);
jobs[2].Priority.ShouldBe(AnalysisJobPriority.Periodic);
jobs[3].Priority.ShouldBe(AnalysisJobPriority.Background);
}
// ── Helpers ─────────────────────────────────────────────────────
private async Task<Guid> CreateSiteAsync(string name)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var site = new Site(name, "test-token", "Europe/Paris");
db.Sites.Add(site);
await db.SaveChangesAsync();
return site.Id;
}
private async Task<(Guid siteId, Guid cameraId)> SeedSiteAndCameraAsync()
{
var siteId = await CreateSiteAsync("Test Site");
var cameraId = await CreateCameraForSiteAsync(siteId, "Main Camera");
return (siteId, cameraId);
}
private async Task<Guid> CreateCameraForSiteAsync(Guid siteId, string name)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var camera = new Camera(siteId, name, "rtsp://test");
db.Cameras.Add(camera);
await db.SaveChangesAsync();
return camera.Id;
}
private async Task<Guid> SeedAgentAsync(
Guid siteId, string name, bool hasGpu, int cpuCores, long memoryMb,
AgentStatus status = AgentStatus.Online)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var agent = new Agent(siteId, name, $"host-{name}", "1.0.0");
agent.UpdateCapabilities(hasGpu, cpuCores, memoryMb, hasGpu ? GpuAcceleration.NvidiaCuda : GpuAcceleration.None);
if (status == AgentStatus.Online)
agent.UpdateHeartbeat("127.0.0.1");
else
agent.MarkOffline();
db.Agents.Add(agent);
await db.SaveChangesAsync();
return agent.Id;
}
private async Task<AnalysisJob> CreateJobInDbAsync(
Guid cameraId, Guid siteId, AnalysisJobType jobType, AnalysisJobPriority priority)
{
var job = new AnalysisJob(cameraId, siteId, jobType, priority);
// Apply capability requirements (mirrors the service logic)
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;
default:
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 1, requiredMemoryMb: 512);
job.SetTimeout(TimeSpan.FromMinutes(3));
break;
}
await using var db = await _dbFactory.CreateDbContextAsync();
db.AnalysisJobs.Add(job);
await db.SaveChangesAsync();
return job;
}
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(opts, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts, Audit));
}
}