diff --git a/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs b/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs new file mode 100644 index 0000000..d4a4ed3 --- /dev/null +++ b/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs @@ -0,0 +1,72 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; + +namespace Heimdall.Application.Services; + +/// +/// Schedules analysis jobs by selecting the best agent based on capabilities, +/// site affinity, and current load. Manages the full lifecycle of analysis jobs. +/// +public interface IAnalysisJobSchedulerService +{ + /// + /// Create a new analysis job and enqueue it for scheduling. + /// + Task> CreateJobAsync( + Guid cameraId, + AnalysisJobType jobType, + AnalysisJobPriority priority, + string? parametersJson = null, + CancellationToken ct = default); + + /// + /// 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. + /// + Task> DispatchJobAsync(Guid jobId, CancellationToken ct); + + /// + /// Process the next batch of pending jobs (called by the Hangfire dispatcher). + /// Selects agents and dispatches as many jobs as possible. + /// + Task ProcessPendingJobsAsync(int maxJobs, CancellationToken ct); + + /// + /// Mark a job as started by the agent. + /// + Task StartJobAsync(Guid jobId, CancellationToken ct); + + /// + /// Mark a job as completed with results. + /// + Task CompleteJobAsync(Guid jobId, CancellationToken ct, string? resultJson = null); + + /// + /// Report a job failure — triggers retry or dead-lettering. + /// + Task FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct); + + /// + /// Cancel a pending or running job. + /// + Task CancelJobAsync(Guid jobId, CancellationToken ct); + + /// + /// Get jobs stuck in Dispatched/Running state longer than their timeout. + /// Returns them for the dispatcher to clean up. + /// + Task> GetTimedOutJobsAsync(CancellationToken ct); + + /// + /// Get the best agent for a given job based on capabilities, site affinity, and load. + /// Used internally and for testing/validation. + /// + Task SelectBestAgentAsync(AnalysisJob job, CancellationToken ct); + + /// + /// Get pending jobs ordered by priority (security first). + /// + Task> GetPendingJobsAsync(int limit, CancellationToken ct); +} diff --git a/src/Heimdall.Domain/Entities/AnalysisJob.cs b/src/Heimdall.Domain/Entities/AnalysisJob.cs new file mode 100644 index 0000000..0eb7384 --- /dev/null +++ b/src/Heimdall.Domain/Entities/AnalysisJob.cs @@ -0,0 +1,151 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// 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. +/// +public class AnalysisJob : Entity, 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 ───────────────────────────────────────── + /// Site affinity hint — prefer agents at this site. + public Guid SiteId { get; private set; } + + /// Required capabilities bitmask (GPU, CPU cores, RAM). + public bool RequiresGpu { get; private set; } + public int RequiredCpuCores { get; private set; } + public long RequiredMemoryMb { get; private set; } + + // ── Timeout & retry ───────────────────────────────────────────── + /// Max allowed execution time before the job is considered timed out. + public TimeSpan MaxExecutionTime { get; private set; } = TimeSpan.FromMinutes(5); + + /// Current retry attempt (0-based). + public int RetryCount { get; private set; } + + /// Maximum number of retry attempts before dead-lettering. + public int MaxRetries { get; private set; } = 3; + + // ── Input / output ────────────────────────────────────────────── + /// JSON payload with job-specific parameters (detection config, thresholds, etc.). + public string? ParametersJson { get; private set; } + + /// JSON result produced by the agent after execution. + public string? ResultJson { get; private set; } + + /// Error message if the job failed or was dead-lettered. + 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; + } +} diff --git a/src/Heimdall.Domain/Enums/AnalysisJobPriority.cs b/src/Heimdall.Domain/Enums/AnalysisJobPriority.cs new file mode 100644 index 0000000..efc0277 --- /dev/null +++ b/src/Heimdall.Domain/Enums/AnalysisJobPriority.cs @@ -0,0 +1,21 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Priority levels for analysis jobs. +/// Security-related jobs always take precedence over periodic/scheduled jobs. +/// Lower numeric value = higher priority. +/// +public enum AnalysisJobPriority +{ + /// Security-critical analysis (unknown person, anomaly, intrusion). + SecurityCritical = 0, + + /// High priority — face recognition, license plate on alert. + SecurityHigh = 1, + + /// Normal priority — periodic detection sweeps, scheduled scans. + Periodic = 2, + + /// Low priority — background scene analysis, maintenance tasks. + Background = 3, +} diff --git a/src/Heimdall.Domain/Enums/AnalysisJobStatus.cs b/src/Heimdall.Domain/Enums/AnalysisJobStatus.cs new file mode 100644 index 0000000..93cef71 --- /dev/null +++ b/src/Heimdall.Domain/Enums/AnalysisJobStatus.cs @@ -0,0 +1,28 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Lifecycle states of an analysis job. +/// +public enum AnalysisJobStatus +{ + /// Job created, awaiting scheduling to an agent. + Pending = 0, + + /// Agent selected, job dispatched for execution. + Dispatched = 1, + + /// Agent is actively processing the job. + Running = 2, + + /// Job completed successfully. + Completed = 3, + + /// Job failed after all retries — moved to dead-letter. + DeadLettered = 4, + + /// Job was cancelled before completion. + Cancelled = 5, + + /// Job timed out on the agent (exceeded MaxExecutionTime). + TimedOut = 6, +} diff --git a/src/Heimdall.Domain/Enums/AnalysisJobType.cs b/src/Heimdall.Domain/Enums/AnalysisJobType.cs new file mode 100644 index 0000000..57226d6 --- /dev/null +++ b/src/Heimdall.Domain/Enums/AnalysisJobType.cs @@ -0,0 +1,31 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Types of analysis tasks that can be scheduled for execution on agents. +/// +public enum AnalysisJobType +{ + /// General motion detection analysis on a camera stream. + MotionDetection = 0, + + /// Face recognition analysis on captured frames. + FaceRecognition = 1, + + /// License plate detection and recognition. + LicensePlateDetection = 2, + + /// Object detection (YOLO) — general purpose. + ObjectDetection = 3, + + /// Vehicle classification and tracking. + VehicleClassification = 4, + + /// Person detection and tracking. + PersonDetection = 5, + + /// Anomaly detection — unusual behaviour or patterns. + AnomalyDetection = 6, + + /// Full scene analysis combining multiple detection types. + FullSceneAnalysis = 7, +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index 717f593..351b9b5 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -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(); @@ -45,6 +45,9 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); + // Analysis job scheduler + services.AddScoped(); + return services; } } diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index 0b4c7dd..66f4898 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -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( + "analysis-job-dispatch", + job => job.ExecuteAsync(CancellationToken.None), + "*/30 * * * * *"); // Every 30 seconds + + // Timeout sweep — clean up stuck jobs every 60s + manager.AddOrUpdate( + "analysis-job-timeout-sweep", + job => job.ExecuteTimeoutSweepAsync(CancellationToken.None), + "*/1 * * * *"); // Every 60 seconds } } diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 76f3c2a..a9a16fe 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -66,6 +66,9 @@ public class AppDbContext : IdentityDbContext, IApplicat public DbSet LicensePlates => Set(); public DbSet StoragePolicies => Set(); + // Analysis job scheduling + public DbSet AnalysisJobs => Set(); + 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, IApplicat builder.Entity().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted); builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); builder.Entity().HasQueryFilter(e => e.DiscoveryResult == null || e.DiscoveryResult.Site == null || !e.DiscoveryResult.Site.IsDeleted); + builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); // Group soft-delete filters builder.Entity().HasQueryFilter(e => !e.IsDeleted); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs new file mode 100644 index 0000000..b863506 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs @@ -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 +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("analysis_jobs"); + + builder.HasKey(j => j.Id); + + // Core fields + builder.Property(j => j.JobType) + .HasConversion() + .HasMaxLength(50) + .IsRequired(); + + builder.Property(j => j.Status) + .HasConversion() + .HasMaxLength(30) + .IsRequired(); + + builder.Property(j => j.Priority) + .HasConversion() + .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); + } +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 09044d9..65d55ac 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -162,6 +162,9 @@ public static class DependencyInjection // Camera assignment service (used by CQRS handlers) services.AddScoped(); + // Analysis job scheduler (capability + affinity + load routing) + services.AddScoped(); + // Notification services services.AddScoped(); services.AddSingleton(); diff --git a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs new file mode 100644 index 0000000..261863d --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs @@ -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; + +/// +/// 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. +/// +public sealed class AnalysisJobDispatcherJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly IAnalysisJobSchedulerService _schedulerService; + private readonly ILogger _logger; + + /// Max jobs to dispatch per tick to prevent overwhelming agents. + private const int MaxDispatchPerTick = 10; + + public AnalysisJobDispatcherJob( + IDbContextFactory dbFactory, + IAnalysisJobSchedulerService schedulerService, + ILogger logger) + { + _dbFactory = dbFactory; + _schedulerService = schedulerService; + _logger = logger; + } + + /// + /// Main dispatcher tick: process pending jobs and clean up timed-out jobs. + /// Called every 30 seconds by Hangfire recurring job. + /// + 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); + } + } + + /// + /// Timeout sweep only — runs less frequently (every 60s) to catch stuck jobs. + /// + 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); + } +} diff --git a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs new file mode 100644 index 0000000..f21cf83 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs @@ -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; + +/// +/// 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. +/// +public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService +{ + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public AnalysisJobSchedulerService( + IDbContextFactory dbFactory, + ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task> 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.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.Success(job); + } + + public async Task> 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.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.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.Success(job); + } + + public async Task 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 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 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 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 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> 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 SelectBestAgentAsync(AnalysisJob job, CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct); + return await SelectBestAgentInternalAsync(db, job, ct).ConfigureAwait(false); + } + + public async Task> 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 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; + } + + /// + /// 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) + /// + private static int ComputeAgentScore(Agent agent, AnalysisJob job, Dictionary 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; + } + + /// + /// Apply default capability requirements based on the analysis job type. + /// + 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; + } + } +} diff --git a/tests/Heimdall.Domain.Tests/AnalysisJobTests.cs b/tests/Heimdall.Domain.Tests/AnalysisJobTests.cs new file mode 100644 index 0000000..00ca895 --- /dev/null +++ b/tests/Heimdall.Domain.Tests/AnalysisJobTests.cs @@ -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); +} diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs new file mode 100644 index 0000000..4ea19c5 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs @@ -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 _dbFactory; + private readonly AnalysisJobSchedulerService _schedulerService; + private readonly AnalysisJobDispatcherJob _dispatcher; + + public AnalysisJobDispatcherJobTests(PostgreSqlContainerFixture postgres) + { + _dbFactory = CreateFactory(postgres.ConnectionString); + var logger = Substitute.For>(); + _schedulerService = new AnalysisJobSchedulerService(_dbFactory, logger); + var dispatcherLogger = Substitute.For>(); + _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() + .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 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 opts) + : IDbContextFactory + { + private static readonly AuditInterceptor Audit = new(); + + public AppDbContext CreateDbContext() => new(opts, Audit); + public Task CreateDbContextAsync(CancellationToken ct = default) + => Task.FromResult(new AppDbContext(opts, Audit)); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs new file mode 100644 index 0000000..bf5e677 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs @@ -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 _dbFactory; + private readonly AnalysisJobSchedulerService _service; + private readonly ILogger _logger = Substitute.For>(); + + 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() + .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 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 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 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 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 opts) + : IDbContextFactory + { + private static readonly AuditInterceptor Audit = new(); + + public AppDbContext CreateDbContext() => new(opts, Audit); + public Task CreateDbContextAsync(CancellationToken ct = default) + => Task.FromResult(new AppDbContext(opts, Audit)); + } +}