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.HasValue) .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 null; // Disqualify: CPU cores insufficient if (job.RequiredCpuCores > 0 && agent.CpuCores < job.RequiredCpuCores) return null; // Disqualify: RAM insufficient if (job.RequiredMemoryMb > 0 && agent.MemoryMb < job.RequiredMemoryMb) return null; 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; } } }