Files
Heimdall/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs
T

412 lines
17 KiB
C#

using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using Heimdall.TestCommon;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly AnalysisJobSchedulerService _service;
private readonly ILogger<AnalysisJobSchedulerService> _logger = Substitute.For<ILogger<AnalysisJobSchedulerService>>();
public AnalysisJobSchedulerServiceTests(PostgreSqlContainerFixture postgres)
{
_dbFactory = CreateFactory(postgres.ConnectionString);
_service = new AnalysisJobSchedulerService(_dbFactory, _logger);
}
public async Task InitializeAsync()
{
await ResetDatabaseAsync();
}
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetDatabaseAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
await db.Database.ExecuteSqlRawAsync(
"TRUNCATE TABLE analysis_jobs, camera_events, camera_assignments, cameras, agents, sites RESTART IDENTITY CASCADE");
}
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"))
.Options;
using var ctx = new AppDbContext(opts, new AuditInterceptor());
ctx.Database.EnsureCreated();
return new TestDbContextFactory(opts);
}
// ── CreateJob ───────────────────────────────────────────────────
[Fact]
public async Task CreateJobAsync_ValidCamera_CreatesJob()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(
cameraId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.CameraId.ShouldBe(cameraId);
result.Data.SiteId.ShouldBe(siteId);
result.Data.JobType.ShouldBe(AnalysisJobType.MotionDetection);
result.Data.Priority.ShouldBe(AnalysisJobPriority.Periodic);
result.Data.Status.ShouldBe(AnalysisJobStatus.Pending);
}
[Fact]
public async Task CreateJobAsync_InvalidCamera_ReturnsNotFound()
{
var result = await _service.CreateJobAsync(
Guid.NewGuid(), AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task CreateJobAsync_SetsCapabilityRequirements()
{
var (_, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(
cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
result.IsSuccess.ShouldBeTrue();
result.Data!.RequiresGpu.ShouldBeTrue();
result.Data.RequiredCpuCores.ShouldBe(2);
result.Data.RequiredMemoryMb.ShouldBe(2048);
}
// ── SelectBestAgent ─────────────────────────────────────────────
[Fact]
public async Task SelectBestAgentAsync_PrefersSameSite()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var otherSiteId = await CreateSiteAsync("Other Site");
await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await SeedAgentAsync(otherSiteId, "Remote Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldNotBeNull();
bestAgent.Name.ShouldBe("Local Agent");
}
[Fact]
public async Task SelectBestAgentAsync_PrefersGpuWhenRequired()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "CPU Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldNotBeNull();
bestAgent.Name.ShouldBe("GPU Agent");
}
[Fact]
public async Task SelectBestAgentAsync_ExcludesInsufficientGpu()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldBeNull();
}
[Fact]
public async Task SelectBestAgentAsync_PrefersLessLoadedAgent()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var idleAgentId = await SeedAgentAsync(siteId, "Idle Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var busyAgentId = await SeedAgentAsync(siteId, "Busy Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
// Give busy agent 3 active jobs
for (var i = 0; i < 3; i++)
{
var cam = await CreateCameraForSiteAsync(siteId, $"Busy Cam {i}");
var j = new AnalysisJob(cam, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
j.Dispatch(busyAgentId);
j.Start();
await using var db = await _dbFactory.CreateDbContextAsync();
db.AnalysisJobs.Add(j);
await db.SaveChangesAsync();
}
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldNotBeNull();
bestAgent.Name.ShouldBe("Idle Agent");
}
[Fact]
public async Task SelectBestAgentAsync_ExcludesOfflineAgents()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
bestAgent.ShouldBeNull();
}
// ── DispatchJob ─────────────────────────────────────────────────
[Fact]
public async Task DispatchJobAsync_PendingJob_DispatchesToAgent()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var result = await _service.DispatchJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Status.ShouldBe(AnalysisJobStatus.Dispatched);
result.Data.AssignedAgentId.ShouldNotBeNull();
result.Data.DispatchedAt.ShouldNotBeNull();
}
[Fact]
public async Task DispatchJobAsync_NoSuitableAgent_Returns503()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
var result = await _service.DispatchJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(503);
}
// ── StartJob / CompleteJob / FailJob ────────────────────────────
[Fact]
public async Task StartJobAsync_DispatchedJob_SetsRunning()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
var result = await _service.StartJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Running);
loaded.StartedAt.ShouldNotBeNull();
}
[Fact]
public async Task CompleteJobAsync_RunningJob_SetsCompleted()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
await _service.StartJobAsync(job.Id, CancellationToken.None);
var result = await _service.CompleteJobAsync(job.Id, CancellationToken.None, resultJson: "{\"detections\":5}");
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Completed);
loaded.ResultJson.ShouldNotBeNull();
loaded.ResultJson!.ShouldContain("detections");
}
[Fact]
public async Task FailJobAsync_RunningJob_TriggersRetry()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
await _service.StartJobAsync(job.Id, CancellationToken.None);
var result = await _service.FailJobAsync(job.Id, "Timeout on agent", CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Pending);
loaded.RetryCount.ShouldBe(1);
loaded.AssignedAgentId.ShouldBeNull();
}
[Fact]
public async Task FailJobAsync_ExceedsMaxRetries_DeadLetters()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
for (var i = 0; i < 3; i++)
{
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
await _service.StartJobAsync(job.Id, CancellationToken.None);
await _service.FailJobAsync(job.Id, $"Error {i + 1}", CancellationToken.None);
}
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.DeadLettered);
loaded.RetryCount.ShouldBe(3);
}
// ── CancelJob ───────────────────────────────────────────────────
[Fact]
public async Task CancelJobAsync_PendingJob_SetsCancelled()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
var result = await _service.CancelJobAsync(job.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await using var db = await _dbFactory.CreateDbContextAsync();
var loaded = await db.AnalysisJobs.FindAsync(job.Id);
loaded!.Status.ShouldBe(AnalysisJobStatus.Cancelled);
}
// ── GetPendingJobs (priority ordering) ──────────────────────────
[Fact]
public async Task GetPendingJobsAsync_OrdersByPriority()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Background);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.SecurityCritical);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.SecurityHigh);
var jobs = await _service.GetPendingJobsAsync(10, CancellationToken.None);
jobs.Count.ShouldBe(4);
jobs[0].Priority.ShouldBe(AnalysisJobPriority.SecurityCritical);
jobs[1].Priority.ShouldBe(AnalysisJobPriority.SecurityHigh);
jobs[2].Priority.ShouldBe(AnalysisJobPriority.Periodic);
jobs[3].Priority.ShouldBe(AnalysisJobPriority.Background);
}
// ── Helpers ─────────────────────────────────────────────────────
private async Task<Guid> CreateSiteAsync(string name)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var site = new Site(name, "test-token", "Europe/Paris");
db.Sites.Add(site);
await db.SaveChangesAsync();
return site.Id;
}
private async Task<(Guid siteId, Guid cameraId)> SeedSiteAndCameraAsync()
{
var siteId = await CreateSiteAsync("Test Site");
var cameraId = await CreateCameraForSiteAsync(siteId, "Main Camera");
return (siteId, cameraId);
}
private async Task<Guid> CreateCameraForSiteAsync(Guid siteId, string name)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var camera = new Camera(siteId, name, "rtsp://test");
db.Cameras.Add(camera);
await db.SaveChangesAsync();
return camera.Id;
}
private async Task<Guid> SeedAgentAsync(
Guid siteId, string name, bool hasGpu, int cpuCores, long memoryMb,
AgentStatus status = AgentStatus.Online)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var agent = new Agent(siteId, name, $"host-{name}", "1.0.0");
agent.UpdateCapabilities(hasGpu, cpuCores, memoryMb, hasGpu ? GpuAcceleration.NvidiaCuda : GpuAcceleration.None);
if (status == AgentStatus.Online)
agent.UpdateHeartbeat("127.0.0.1");
else
agent.MarkOffline();
db.Agents.Add(agent);
await db.SaveChangesAsync();
return agent.Id;
}
private async Task<AnalysisJob> CreateJobInDbAsync(
Guid cameraId, Guid siteId, AnalysisJobType jobType, AnalysisJobPriority priority)
{
var job = new AnalysisJob(cameraId, siteId, jobType, priority);
// Apply capability requirements (mirrors the service logic)
switch (jobType)
{
case AnalysisJobType.ObjectDetection:
case AnalysisJobType.FullSceneAnalysis:
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
job.SetTimeout(TimeSpan.FromMinutes(10));
break;
case AnalysisJobType.FaceRecognition:
case AnalysisJobType.LicensePlateDetection:
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 1024);
job.SetTimeout(TimeSpan.FromMinutes(5));
break;
default:
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 1, requiredMemoryMb: 512);
job.SetTimeout(TimeSpan.FromMinutes(3));
break;
}
await using var db = await _dbFactory.CreateDbContextAsync();
db.AnalysisJobs.Add(job);
await db.SaveChangesAsync();
return job;
}
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(opts, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts, Audit));
}
}