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 TestDbContextFactory _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"); 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"); camera.AssignAgent(agent.Id); db.Cameras.Add(camera); 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: 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; 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)); } }