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 on the agent assigned to the camera, after checking /// its reported capabilities. The source frame remains on that agent. /// /// 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"); if (jobType != AnalysisJobType.ObjectDetection) return ServiceResult.Failure("Only ObjectDetection jobs are currently supported"); 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() .Include(j => j.Camera) .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"); // Frames are captured locally by the camera's assigned agent. Choosing // another online agent would dispatch a job it cannot execute. var bestAgent = await db.Agents.AsNoTracking() .Where(a => a.Id == job.Camera.AgentId && a.SiteId == job.SiteId && a.Status == AgentStatus.Online && !a.IsDeleted && (!job.RequiresGpu || a.HasGpu) && a.CpuCores >= job.RequiredCpuCores && a.MemoryMb >= job.RequiredMemoryMb) .FirstOrDefaultAsync(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); } var attemptId = Guid.NewGuid(); var dispatchedAt = DateTime.UtcNow; var updated = await db.AnalysisJobs .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Pending && j.Camera.AgentId == bestAgent.Id) .ExecuteUpdateAsync(setters => setters .SetProperty(j => j.AssignedAgentId, bestAgent.Id) .SetProperty(j => j.AttemptId, attemptId) .SetProperty(j => j.Status, AnalysisJobStatus.Dispatched) .SetProperty(j => j.DispatchedAt, dispatchedAt) .SetProperty(j => j.StartedAt, (DateTime?)null), ct).ConfigureAwait(false); if (updated == 0) return ServiceResult.Conflict("Job was already dispatched or camera assignment changed"); db.Entry(job).State = EntityState.Detached; job = await db.AnalysisJobs.AsNoTracking().FirstAsync(j => j.Id == jobId, 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); } /// Atomically claims a dispatched job for the authenticated agent. public async Task ClaimNextJobAsync(Guid agentId, CancellationToken ct) { if (agentId == Guid.Empty) return null; await using var db = await _dbFactory.CreateDbContextAsync(ct); var candidates = await db.AnalysisJobs.AsNoTracking() .Where(j => j.Status == AnalysisJobStatus.Dispatched && j.AssignedAgentId == agentId && j.AttemptId != null && j.Camera.AgentId == agentId && !j.Camera.IsDeleted) .OrderBy(j => j.Priority).ThenBy(j => j.CreatedAt) .Select(j => j.Id).Take(16).ToListAsync(ct).ConfigureAwait(false); foreach (var jobId in candidates) { var startedAt = DateTime.UtcNow; var claimed = await db.AnalysisJobs .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Dispatched && j.AssignedAgentId == agentId && j.Camera.AgentId == agentId) .ExecuteUpdateAsync(setters => setters .SetProperty(j => j.Status, AnalysisJobStatus.Running) .SetProperty(j => j.StartedAt, startedAt), ct).ConfigureAwait(false); if (claimed == 1) return await db.AnalysisJobs.AsNoTracking().SingleAsync(j => j.Id == jobId, ct).ConfigureAwait(false); } return null; } 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(); } /// Completes only the current attempt owned by this agent. public async Task CompleteJobAsync( Guid jobId, Guid agentId, Guid attemptId, CancellationToken ct, string? resultJson = null) { if (agentId == Guid.Empty || attemptId == Guid.Empty) return ServiceResult.Conflict("Invalid analysis job attempt"); await using var db = await _dbFactory.CreateDbContextAsync(ct); var now = DateTime.UtcNow; var updated = await db.AnalysisJobs .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Running && j.AssignedAgentId == agentId && j.AttemptId == attemptId && j.Camera.AgentId == agentId) .ExecuteUpdateAsync(setters => setters .SetProperty(j => j.Status, AnalysisJobStatus.Completed) .SetProperty(j => j.ResultJson, resultJson) .SetProperty(j => j.CompletedAt, now) .SetProperty(j => j.ErrorMessage, (string?)null), ct).ConfigureAwait(false); if (updated == 1) return ServiceResult.Success(); var alreadyCompleted = await db.AnalysisJobs.AsNoTracking() .AnyAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Completed && j.AssignedAgentId == agentId && j.AttemptId == attemptId, ct).ConfigureAwait(false); return alreadyCompleted ? ServiceResult.Success() : ServiceResult.Conflict("Analysis job attempt is no longer active"); } 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(); } /// Fails only the current attempt and assigned agent. public async Task FailJobAsync( Guid jobId, Guid agentId, Guid attemptId, string errorMessage, CancellationToken ct) { if (agentId == Guid.Empty || attemptId == Guid.Empty) return ServiceResult.Conflict("Invalid analysis job attempt"); await using var db = await _dbFactory.CreateDbContextAsync(ct); var safeError = string.IsNullOrWhiteSpace(errorMessage) ? "Agent analysis failed" : errorMessage[..Math.Min(errorMessage.Length, 2000)]; var updated = await db.AnalysisJobs .Where(j => j.Id == jobId && (j.Status == AnalysisJobStatus.Running || j.Status == AnalysisJobStatus.Dispatched) && j.AssignedAgentId == agentId && j.AttemptId == attemptId) .ExecuteUpdateAsync(setters => setters .SetProperty(j => j.RetryCount, j => j.RetryCount + 1) .SetProperty(j => j.Status, j => j.RetryCount + 1 >= j.MaxRetries ? AnalysisJobStatus.DeadLettered : AnalysisJobStatus.Pending) .SetProperty(j => j.ErrorMessage, safeError) .SetProperty(j => j.AssignedAgentId, (Guid?)null) .SetProperty(j => j.AttemptId, (Guid?)null) .SetProperty(j => j.DispatchedAt, (DateTime?)null) .SetProperty(j => j.StartedAt, (DateTime?)null), ct).ConfigureAwait(false); return updated == 1 ? ServiceResult.Success() : ServiceResult.Conflict("Analysis job attempt is no longer active"); } 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) { var assignedAgentId = await db.Cameras.AsNoTracking() .Where(c => c.Id == job.CameraId && !c.IsDeleted) .Select(c => c.AgentId).SingleOrDefaultAsync(ct).ConfigureAwait(false); if (assignedAgentId is null) return null; // Only the assigned agent can access the local camera stream. var agents = await db.Agents .AsNoTracking() .Where(a => a.Id == assignedAgentId && a.SiteId == job.SiteId && 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: job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048); job.SetTimeout(TimeSpan.FromMinutes(10)); break; 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; } } }