Files
Heimdall/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs
T
arnaud.dartois 636154572b
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s
Complete remaining Heimdall features and acceptance
Merge pull request #138

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-06 11:14:49 +01:00

500 lines
22 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 TestDbContextFactory _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);
}
public static IEnumerable<object[]> GpuScenarios =>
from type in new[] { AnalysisJobType.ObjectDetection }
from sameSite in new[] { true, false }
from loaded in new[] { true, false }
select new object[] { type, sameSite, loaded };
[Theory]
[MemberData(nameof(GpuScenarios))]
public async Task SelectBestAgent_SoleGpu_RemainsEligible(AnalysisJobType type, bool sameSite, bool loaded)
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
await using var db = await _dbFactory.CreateDbContextAsync();
var otherSite = new Site("remote", "remote", "UTC");
if (!sameSite) db.Sites.Add(otherSite);
var agent = new Agent(sameSite ? siteId : otherSite.Id, "gpu", "gpu", "1.0");
agent.Register("hash", "prefix");
agent.UpdateCapabilities(true, 8, 8192, GpuAcceleration.NvidiaCuda);
db.Agents.Add(agent);
(await db.Cameras.SingleAsync(c => c.Id == cameraId)).AssignAgent(agent.Id);
if (loaded)
{
var active = new AnalysisJob(cameraId, siteId, type, AnalysisJobPriority.Periodic);
active.Dispatch(agent.Id);
db.AnalysisJobs.Add(active);
}
await db.SaveChangesAsync();
var created = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic);
var selected = await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None);
if (sameSite) selected!.Id.ShouldBe(agent.Id);
else selected.ShouldBeNull();
}
// ── CreateJob ───────────────────────────────────────────────────
[Fact]
public async Task CreateJobAsync_ValidCamera_CreatesJob()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(
cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.CameraId.ShouldBe(cameraId);
result.Data.SiteId.ShouldBe(siteId);
result.Data.JobType.ShouldBe(AnalysisJobType.ObjectDetection);
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.ShouldBeFalse();
result.Data.RequiredCpuCores.ShouldBe(2);
result.Data.RequiredMemoryMb.ShouldBe(2048);
}
[Theory]
[InlineData(AnalysisJobType.PersonDetection, 1024, 2)]
[InlineData(AnalysisJobType.VehicleClassification, 1024, 2)]
[InlineData(AnalysisJobType.MotionDetection, 512, 1)]
public async Task CreateJobAsync_SupportedFilteredDetectionTypes_SetsCpuRequirements(
AnalysisJobType type, int memoryMb, int cpuCores)
{
var (_, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeTrue();
result.Data!.JobType.ShouldBe(type);
result.Data.RequiresGpu.ShouldBeFalse();
result.Data.RequiredCpuCores.ShouldBe(cpuCores);
result.Data.RequiredMemoryMb.ShouldBe(memoryMb);
}
[Theory]
[InlineData(AnalysisJobType.FaceRecognition)]
[InlineData(AnalysisJobType.LicensePlateDetection)]
[InlineData(AnalysisJobType.AnomalyDetection)]
[InlineData(AnalysisJobType.FullSceneAnalysis)]
public async Task CreateJobAsync_UnimplementedDetectionTypes_ReturnsFailure(AnalysisJobType type)
{
var (_, cameraId) = await SeedSiteAndCameraAsync();
var result = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic);
result.IsSuccess.ShouldBeFalse();
result.Error!.ShouldContain(type.ToString());
}
// ── SelectBestAgent ─────────────────────────────────────────────
[Fact]
public async Task SelectBestAgentAsync_PrefersSameSite()
{
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
var otherSiteId = await CreateSiteAsync("Other Site");
var localAgentId = await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, localAgentId);
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);
var gpuAgentId = await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, gpuAgentId);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
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();
var cpuAgentId = await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, cpuAgentId);
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
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);
await AssignCameraAsync(cameraId, idleAgentId);
// 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();
var offlineAgentId = await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline);
await AssignCameraAsync(cameraId, offlineAgentId);
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();
var agentId = await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, agentId);
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();
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, agentId);
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();
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, agentId);
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();
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, agentId);
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();
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
await AssignCameraAsync(cameraId, agentId);
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 AssignCameraAsync(Guid cameraId, Guid agentId)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var camera = await db.Cameras.SingleAsync(c => c.Id == cameraId);
camera.AssignAgent(agentId);
await db.SaveChangesAsync();
}
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:
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<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));
}
}