From 6bbf592c27a367100e3328e2da074ba82b0e7522 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 13:38:12 +0200 Subject: [PATCH] Complete durable agent analysis job flow --- .gitea/workflows/build.yml | 1 + docs/agent-release-signing.md | 2 + scripts/ci/publish.sh | 25 ++- src/Heimdall.Agent/Program.cs | 1 + .../Services/AnalysisJobPollingService.cs | 170 ++++++++++++++++++ .../Common/IApplicationDbContext.cs | 1 + .../Services/IAnalysisJobSchedulerService.cs | 17 +- src/Heimdall.Domain/Entities/AnalysisJob.cs | 15 +- .../BackgroundJobs/JobSetup.cs | 9 +- .../AnalysisJobConfiguration.cs | 2 + .../Jobs/AnalysisJobDispatcherJob.cs | 16 +- .../20261024010000_AddAnalysisJobAttempt.cs | 18 ++ .../Migrations/AppDbContextModelSnapshot.cs | 3 + .../Services/AnalysisJobSchedulerService.cs | 125 ++++++++++++- .../Controllers/AnalysisJobsController.cs | 130 ++++++++++++++ .../AnalysisJobDispatcherJobTests.cs | 6 +- .../AnalysisJobSchedulerServiceTests.cs | 54 ++++-- 17 files changed, 551 insertions(+), 44 deletions(-) create mode 100644 src/Heimdall.Agent/Services/AnalysisJobPollingService.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs create mode 100644 src/Heimdall.Web/Controllers/AnalysisJobsController.cs diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 907907b..bc27df3 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -153,4 +153,5 @@ jobs: AGENT_REGISTRY_TOKEN: ${{ secrets.AGENT_REGISTRY_TOKEN }} RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }} RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }} + EXPECTED_BUILD_SERVER_URL: ${{ vars.RELEASE_SERVER_URL }} run: bash scripts/ci/publish.sh diff --git a/docs/agent-release-signing.md b/docs/agent-release-signing.md index 7342367..4a4b864 100644 --- a/docs/agent-release-signing.md +++ b/docs/agent-release-signing.md @@ -14,6 +14,8 @@ base64 -w0 agent-release-private.pem La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Distribuer `agent-release-public.pem` par un canal d’administration indépendant de Central. La publication d’une release échoue si le secret de signature manque. +Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant tout accès au registre ou création de release. Elle en déduit l’hôte du registre pour l’image serveur ; le dépôt de l’image Agent reste défini dans `docker/agent-image.json`. + La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent et le dépôt ainsi que le digest immuable de l’image Docker. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé. ## Installer un Agent natif diff --git a/scripts/ci/publish.sh b/scripts/ci/publish.sh index 23488ab..d3107aa 100644 --- a/scripts/ci/publish.sh +++ b/scripts/ci/publish.sh @@ -5,8 +5,25 @@ set -euo pipefail : "${RELEASE_TOKEN:?Dedicated Gitea release token is required}" : "${RELEASE_SIGNING_KEY_B64:?Publisher ECDSA P-256 private key is required}" : "${BUILD_SERVER_URL:?Gitea URL is required}" +: "${EXPECTED_BUILD_SERVER_URL:?Expected Gitea URL is required}" : "${BUILD_REPOSITORY:?Repository is required}" -[[ "$BUILD_SERVER_URL" == https://sources.tordais.cc ]] || { echo 'Unexpected publication host' >&2; exit 1; } +registry_host=$(python3 - "$BUILD_SERVER_URL" "$EXPECTED_BUILD_SERVER_URL" <<'PY' +import sys +from urllib.parse import urlsplit + +actual, expected = (urlsplit(value) for value in sys.argv[1:]) +def valid_origin(value): + return (value.scheme == 'https' and bool(value.hostname) and + value.path in ('', '/') and not value.query and not value.fragment and + value.username is None and value.password is None) + +if (not valid_origin(actual) or not valid_origin(expected) or + actual.hostname.lower() != expected.hostname.lower() or + (actual.port or 443) != (expected.port or 443)): + raise SystemExit('Unexpected publication host') +print(actual.netloc) +PY +) [[ "$BUILD_REPOSITORY" == arnaud.dartois/Heimdall ]] || { echo 'Unexpected publication repository' >&2; exit 1; } sha=$(git rev-parse HEAD) umask 077 @@ -33,14 +50,14 @@ bash scripts/ci/images.sh export DOCKER_CONFIG DOCKER_CONFIG=$(mktemp -d) trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT -printf '%s' "$REGISTRY_TOKEN" | docker login sources.tordais.cc -u "$REGISTRY_USER" --password-stdin +printf '%s' "$REGISTRY_TOKEN" | docker login "$registry_host" -u "$REGISTRY_USER" --password-stdin agent_image=$(python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])') [[ "$agent_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${agent_image##*/}" != *:* ]] || { echo 'Invalid agent image repository in docker/agent-image.json' >&2; exit 1; } agent_registry=${agent_image%%/*} if [[ "$agent_registry" == "$agent_image" || ( "$agent_registry" != *.* && "$agent_registry" != *:* && "$agent_registry" != localhost* ) ]]; then agent_registry=docker.io fi -if [[ "$agent_registry" != sources.tordais.cc ]]; then +if [[ "$agent_registry" != "$registry_host" ]]; then : "${AGENT_REGISTRY_USER:?Agent registry user is required for $agent_registry}" : "${AGENT_REGISTRY_TOKEN:?Agent registry token is required for $agent_registry}" printf '%s' "$AGENT_REGISTRY_TOKEN" | docker login "$agent_registry" -u "$AGENT_REGISTRY_USER" --password-stdin @@ -50,7 +67,7 @@ for component in server agent; do if [[ "$component" == agent ]]; then image=$agent_image else - image="sources.tordais.cc/arnaud.dartois/heimdall-server" + image="$registry_host/arnaud.dartois/heimdall-server" fi for image_tag in "sha-$sha" "${tag#v}"; do if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index a437b44..289e988 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -126,6 +126,7 @@ builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); // Video capture pipeline (ticket #1): FFmpeg capture per assigned camera, // bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService. diff --git a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs new file mode 100644 index 0000000..a2fe66b --- /dev/null +++ b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs @@ -0,0 +1,170 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Domain.Enums; + +namespace Heimdall.Agent.Services; + +/// +/// Claims one durable analysis job at a time over the agent's outbound Central connection. +/// Central owns the lease and attempt ID; a repeated result uses that same ID. +/// +public sealed class AnalysisJobPollingService : BackgroundService +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5); + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + private readonly AgentState _state; + private readonly CameraConfigStore _cameras; + private readonly CameraStreamService _streams; + private readonly FrameAnalyzerService _analyzer; + private readonly IHttpClientFactory _clients; + private readonly ILogger _logger; + + public AnalysisJobPollingService(AgentState state, CameraConfigStore cameras, + CameraStreamService streams, FrameAnalyzerService analyzer, IHttpClientFactory clients, + ILogger logger) + { + _state = state; + _cameras = cameras; + _streams = streams; + _analyzer = analyzer; + _clients = clients; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (_state.AgentId != Guid.Empty && !string.IsNullOrWhiteSpace(_state.ApiKey)) + await PollOnceAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Analysis job polling failed; Central will retain or retry the leased job"); + } + + try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + } + } + + private async Task PollOnceAsync(CancellationToken ct) + { + var agentId = _state.AgentId; + using var client = _clients.CreateClient("Central"); + client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + using var response = await client.GetAsync($"api/agents/{agentId:D}/analysis-jobs/next", ct) + .ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NoContent) return; + if (!response.IsSuccessStatusCode) + { + _logger.LogWarning("Analysis job claim failed with HTTP {StatusCode}", (int)response.StatusCode); + return; + } + + var job = await response.Content.ReadFromJsonAsync(Json, ct).ConfigureAwait(false); + if (job is null || job.JobId == Guid.Empty || job.CameraId == Guid.Empty || job.AttemptId == Guid.Empty) + { + _logger.LogError("Central returned an invalid analysis job lease"); + return; + } + + var result = await ExecuteJobAsync(job, ct).ConfigureAwait(false); + await SendResultAsync(client, agentId, job.JobId, result, ct).ConfigureAwait(false); + } + + private async Task ExecuteJobAsync(LeasedJob job, CancellationToken ct) + { + if (!IsObjectDetection(job.JobType)) + return Failure(job.AttemptId, "Unsupported analysis job type"); + + var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled); + if (camera is null || !_streams.IsStreamActive(job.CameraId)) + return Failure(job.AttemptId, "Camera is not assigned, enabled, or streaming"); + if (!_analyzer.ModelAvailable) + return Failure(job.AttemptId, "Object detection model is unavailable"); + + Snapshot? frame; + try + { + frame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + frame = null; + } + if (frame is null) + return Failure(job.AttemptId, "Camera frame capture failed or timed out"); + + var confidence = camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence; + var analysis = await _analyzer.AnalyzeFrameAsync(frame.JpegData, confidence, ct).ConfigureAwait(false); + if (analysis is null) + return Failure(job.AttemptId, "Object detection was unavailable or saturated"); + + return new AnalysisResult(job.AttemptId, true, null, analysis.Detections + .Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex)) + .ToArray()); + } + + private async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId, + AnalysisResult result, CancellationToken ct) + { + var retryDelay = TimeSpan.FromSeconds(2); + while (!ct.IsCancellationRequested) + { + try + { + using var response = await client.PutAsJsonAsync( + $"api/agents/{agentId:D}/analysis-jobs/{jobId:D}/result", result, Json, ct) + .ConfigureAwait(false); + if (response.IsSuccessStatusCode) return; + if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.NotFound) + { + _logger.LogInformation("Analysis job {JobId} attempt {AttemptId} is no longer current", + jobId, result.AttemptId); + return; + } + _logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying", + jobId, (int)response.StatusCode); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + break; + } + catch (HttpRequestException ex) + { + _logger.LogWarning(ex, "Analysis result delivery failed for job {JobId}; retrying", jobId); + } + catch (TaskCanceledException ex) when (!ct.IsCancellationRequested) + { + _logger.LogWarning(ex, "Analysis result delivery timed out for job {JobId}; retrying", jobId); + } + + await Task.Delay(retryDelay, ct).ConfigureAwait(false); + retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 30)); + } + } + + private static bool IsObjectDetection(JsonElement type) => type.ValueKind switch + { + JsonValueKind.String => string.Equals(type.GetString(), nameof(AnalysisJobType.ObjectDetection), + StringComparison.OrdinalIgnoreCase), + JsonValueKind.Number => type.TryGetInt32(out var value) && value == (int)AnalysisJobType.ObjectDetection, + _ => false, + }; + + private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []); + + private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType); + private sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, + float Width, float Height, int? ClassIndex); + private sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error, + IReadOnlyList Detections); +} diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 0650128..86d91a3 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -8,6 +8,7 @@ public interface IApplicationDbContext DbSet Agents { get; } DbSet AgentLogEntries { get; } DbSet AgentSettings { get; } + DbSet AnalysisJobs { get; } DbSet ApiKeys { get; } DbSet AppSettings { get; } DbSet Users { get; } diff --git a/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs b/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs index d4a4ed3..e38fbf7 100644 --- a/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs +++ b/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs @@ -21,12 +21,14 @@ public interface IAnalysisJobSchedulerService CancellationToken ct = default); /// - /// Select the best agent for a pending job and dispatch it. - /// Selection criteria: capabilities → site affinity → current load. - /// Returns null if no suitable agent is available. + /// Dispatches a pending job only to the agent currently assigned to its camera. + /// Returns a failure if that agent is unavailable or lacks the required resources. /// Task> DispatchJobAsync(Guid jobId, CancellationToken ct); + /// Atomically claim the next durable job assigned to an agent. + Task ClaimNextJobAsync(Guid agentId, CancellationToken ct); + /// /// Process the next batch of pending jobs (called by the Hangfire dispatcher). /// Selects agents and dispatches as many jobs as possible. @@ -43,11 +45,17 @@ public interface IAnalysisJobSchedulerService /// Task CompleteJobAsync(Guid jobId, CancellationToken ct, string? resultJson = null); + /// Complete only the current attempt owned by the authenticated agent. + Task CompleteJobAsync(Guid jobId, Guid agentId, Guid attemptId, CancellationToken ct, string? resultJson = null); + /// /// Report a job failure — triggers retry or dead-lettering. /// Task FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct); + /// Fail only the current attempt owned by the authenticated agent. + Task FailJobAsync(Guid jobId, Guid agentId, Guid attemptId, string errorMessage, CancellationToken ct); + /// /// Cancel a pending or running job. /// @@ -60,8 +68,7 @@ public interface IAnalysisJobSchedulerService Task> GetTimedOutJobsAsync(CancellationToken ct); /// - /// Get the best agent for a given job based on capabilities, site affinity, and load. - /// Used internally and for testing/validation. + /// Scores an agent for legacy scheduling scenarios. Camera jobs dispatch to their assigned agent. /// Task SelectBestAgentAsync(AnalysisJob job, CancellationToken ct); diff --git a/src/Heimdall.Domain/Entities/AnalysisJob.cs b/src/Heimdall.Domain/Entities/AnalysisJob.cs index 0eb7384..a8807b3 100644 --- a/src/Heimdall.Domain/Entities/AnalysisJob.cs +++ b/src/Heimdall.Domain/Entities/AnalysisJob.cs @@ -12,6 +12,8 @@ public class AnalysisJob : Entity, IAuditableEntity { public Guid CameraId { get; private set; } public Guid? AssignedAgentId { get; private set; } + /// Changes on every dispatch so late replies cannot complete a retried job. + public Guid? AttemptId { get; private set; } public AnalysisJobType JobType { get; private set; } public AnalysisJobStatus Status { get; private set; } = AnalysisJobStatus.Pending; public AnalysisJobPriority Priority { get; private set; } = AnalysisJobPriority.Periodic; @@ -90,6 +92,7 @@ public class AnalysisJob : Entity, IAuditableEntity public void Dispatch(Guid agentId) { AssignedAgentId = agentId; + AttemptId = Guid.NewGuid(); Status = AnalysisJobStatus.Dispatched; DispatchedAt = DateTime.UtcNow; } @@ -111,6 +114,10 @@ public class AnalysisJob : Entity, IAuditableEntity { RetryCount++; ErrorMessage = errorMessage; + AssignedAgentId = null; + AttemptId = null; + DispatchedAt = null; + StartedAt = null; if (RetryCount >= MaxRetries) { @@ -120,8 +127,6 @@ public class AnalysisJob : Entity, IAuditableEntity { // Reset to pending for retry — agent will be re-selected Status = AnalysisJobStatus.Pending; - AssignedAgentId = null; - DispatchedAt = null; } } @@ -130,6 +135,10 @@ public class AnalysisJob : Entity, IAuditableEntity Status = AnalysisJobStatus.TimedOut; ErrorMessage = $"Job exceeded maximum execution time of {MaxExecutionTime.TotalSeconds}s"; RetryCount++; + AssignedAgentId = null; + AttemptId = null; + DispatchedAt = null; + StartedAt = null; if (RetryCount >= MaxRetries) { @@ -138,8 +147,6 @@ public class AnalysisJob : Entity, IAuditableEntity else { Status = AnalysisJobStatus.Pending; - AssignedAgentId = null; - DispatchedAt = null; } } diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index 7c03f73..880db28 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -68,8 +68,13 @@ public static class JobSetup job => job.ExecuteAsync(CancellationToken.None), "0 7 * * 0"); // Sunday at 7:00 - // Legacy analysis job timeout cleanup. Dispatch stays disabled until the - // Agent job path is implemented over the authenticated SignalR channel. + // PostgreSQL-backed analysis jobs are dispatched durably; agents claim + // assigned work over their authenticated outbound HTTP connection. + manager.AddOrUpdate( + "analysis-job-dispatch", + job => job.ExecuteAsync(CancellationToken.None), + "* * * * *"); + manager.AddOrUpdate( "analysis-job-timeout-sweep", job => job.ExecuteTimeoutSweepAsync(CancellationToken.None), diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs index b863506..67d34c2 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs @@ -27,6 +27,8 @@ public class AnalysisJobConfiguration : IEntityTypeConfiguration .HasConversion() .IsRequired(); + builder.Property(j => j.AttemptId); + // Capability requirements builder.Property(j => j.RequiredCpuCores) .HasDefaultValue(0); diff --git a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs index d1c2ad1..c9dba19 100644 --- a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs @@ -70,11 +70,17 @@ public sealed class AnalysisJobDispatcherJob "Sweep: analysis job {JobId} stuck in {Status} since {DispatchedAt} (timeout={Timeout}s)", job.Id, job.Status, job.DispatchedAt, job.MaxExecutionTime.TotalSeconds); - await _schedulerService.FailJobAsync( - job.Id, - $"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s", - ct) - .ConfigureAwait(false); + var reason = $"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s"; + if (job.AssignedAgentId is Guid agentId && job.AttemptId is Guid attemptId) + { + await _schedulerService.FailJobAsync(job.Id, agentId, attemptId, reason, ct) + .ConfigureAwait(false); + } + else + { + // Upgrade path for jobs dispatched before attempt IDs were added. + await _schedulerService.FailJobAsync(job.Id, reason, ct).ConfigureAwait(false); + } } _logger.LogInformation("Timeout sweep: {Count} jobs cleaned up", timedOutJobs.Count); diff --git a/src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs b/src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs new file mode 100644 index 0000000..75fd335 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs @@ -0,0 +1,18 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261024010000_AddAnalysisJobAttempt")] +public partial class AddAnalysisJobAttempt : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + => migrationBuilder.AddColumn("AttemptId", "analysis_jobs", type: "uuid", nullable: true); + + protected override void Down(MigrationBuilder migrationBuilder) + => migrationBuilder.DropColumn("AttemptId", "analysis_jobs"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index cda546b..639438a 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -308,6 +308,9 @@ namespace Heimdall.Infrastructure.Migrations b.Property("AssignedAgentId") .HasColumnType("uuid"); + b.Property("AttemptId") + .HasColumnType("uuid"); + b.Property("CameraId") .HasColumnType("uuid"); diff --git a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs index a509a9d..acf85b9 100644 --- a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs +++ b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs @@ -9,10 +9,8 @@ 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 +/// 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. @@ -47,6 +45,9 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService 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 @@ -68,13 +69,21 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService 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"); - var bestAgent = await SelectBestAgentInternalAsync(db, job, ct).ConfigureAwait(false); + // 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( @@ -83,8 +92,21 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.Failure("No suitable agent available", 503); } - job.Dispatch(bestAgent.Id); - await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + 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}", @@ -93,6 +115,33 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService 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); @@ -151,6 +200,31 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService 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); @@ -184,6 +258,29 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.Success(); } + /// Fails only the current attempt owned by this 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.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); @@ -252,10 +349,16 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService private static async Task SelectBestAgentInternalAsync( AppDbContext db, AnalysisJob job, CancellationToken ct) { - // Load all online agents that are not soft-deleted + 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.Status == AgentStatus.Online && !a.IsDeleted) + .Where(a => a.Id == assignedAgentId && a.SiteId == job.SiteId && + a.Status == AgentStatus.Online && !a.IsDeleted) .ToListAsync(ct) .ConfigureAwait(false); @@ -347,6 +450,10 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService 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)); diff --git a/src/Heimdall.Web/Controllers/AnalysisJobsController.cs b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs new file mode 100644 index 0000000..dbfa9b6 --- /dev/null +++ b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs @@ -0,0 +1,130 @@ +using System.Text.Json; +using Heimdall.Api.Security; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api")] +public sealed class AnalysisJobsController( + IApplicationDbContext db, + IAnalysisJobSchedulerService scheduler, + ResourceAccess access) : ControllerBase +{ + private static readonly JsonSerializerOptions ResultJsonOptions = new(JsonSerializerDefaults.Web); + private const int MaxDetections = 500; + + public sealed record CreateAnalysisJobRequest(string JobType = "ObjectDetection", string? ParametersJson = null); + public sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, + float Width, float Height, int? ClassIndex = null); + public sealed record SubmitAnalysisResult(Guid AttemptId, bool Success, string? Error, + IReadOnlyList? Detections = null); + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [HttpPost("cameras/{cameraId:guid}/analysis-jobs")] + public async Task Create(Guid cameraId, [FromBody] CreateAnalysisJobRequest request, + CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + if (!Enum.TryParse(request.JobType, true, out var type) || + type != AnalysisJobType.ObjectDetection) + return BadRequest(new { error = "Only ObjectDetection jobs are currently supported" }); + if (request.ParametersJson is { Length: > 16_384 } || !IsJsonObjectOrNull(request.ParametersJson)) + return BadRequest(new { error = "ParametersJson must be a JSON object of at most 16 KiB" }); + + var created = await scheduler.CreateJobAsync(cameraId, type, AnalysisJobPriority.SecurityHigh, + request.ParametersJson, ct); + return created.IsSuccess + ? AcceptedAtAction(nameof(Get), new { cameraId, jobId = created.Data!.Id }, + new { jobId = created.Data!.Id, status = created.Data.Status.ToString() }) + : StatusCode(created.StatusCode ?? 400, new { error = created.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("cameras/{cameraId:guid}/analysis-jobs/{jobId:guid}")] + public async Task Get(Guid cameraId, Guid jobId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + var job = await db.AnalysisJobs.AsNoTracking() + .Where(j => j.Id == jobId && j.CameraId == cameraId) + .Select(j => new { j.Id, j.JobType, j.Status, j.RetryCount, j.ErrorMessage, + j.ResultJson, j.CreatedAt, j.DispatchedAt, j.CompletedAt }) + .FirstOrDefaultAsync(ct); + return job is null ? NotFound() : Ok(job); + } + + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpGet("agents/{agentId:guid}/analysis-jobs/next")] + public async Task ClaimNext(Guid agentId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await access.AgentAsync(requester, agentId, ct)) return Forbid(); + var job = await scheduler.ClaimNextJobAsync(agentId, ct); + return job is null ? NoContent() : Ok(new + { + jobId = job.Id, + cameraId = job.CameraId, + attemptId = job.AttemptId, + jobType = job.JobType.ToString(), + parametersJson = job.ParametersJson + }); + } + + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPut("agents/{agentId:guid}/analysis-jobs/{jobId:guid}/result")] + public async Task SubmitResult(Guid agentId, Guid jobId, + [FromBody] SubmitAnalysisResult result, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await access.AgentAsync(requester, agentId, ct)) return Forbid(); + if (result.AttemptId == Guid.Empty) return BadRequest(new { error = "AttemptId is required" }); + if (result.Success && (result.Detections?.Count ?? 0) > MaxDetections) + return BadRequest(new { error = $"At most {MaxDetections} detections are accepted" }); + if (result.Success && result.Detections?.Any(d => string.IsNullOrWhiteSpace(d.Label) || + d.Label.Length > 120 || !float.IsFinite(d.Confidence) || d.Confidence is < 0 or > 1 || + !float.IsFinite(d.X) || !float.IsFinite(d.Y) || !float.IsFinite(d.Width) || + !float.IsFinite(d.Height) || d.X < 0 || d.Y < 0 || d.Width < 0 || d.Height < 0 || + d.X + d.Width > 1.001f || d.Y + d.Height > 1.001f) == true) + return BadRequest(new { error = "Detection values are invalid" }); + + ServiceResult updated; + if (result.Success) + { + var payload = JsonSerializer.Serialize(new { detections = result.Detections ?? [] }, ResultJsonOptions); + updated = await scheduler.CompleteJobAsync(jobId, agentId, result.AttemptId, ct, payload); + } + else + { + var error = string.IsNullOrWhiteSpace(result.Error) ? "Agent reported analysis failure" : result.Error; + updated = await scheduler.FailJobAsync(jobId, agentId, result.AttemptId, error[..Math.Min(error.Length, 2000)], ct); + } + if (updated.IsSuccess) return NoContent(); + if (updated.StatusCode == 404) return NotFound(); + if (updated.StatusCode == 409) return Conflict(new { error = updated.Error }); + return StatusCode(updated.StatusCode ?? 400, new { error = updated.Error }); + } + + private static bool IsJsonObjectOrNull(string? value) + { + if (value is null) return true; + try + { + using var document = JsonDocument.Parse(value); + return document.RootElement.ValueKind == JsonValueKind.Object; + } + catch (JsonException) { return false; } + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs index 136b19b..a63771c 100644 --- a/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs @@ -172,11 +172,12 @@ public class AnalysisJobDispatcherJobTests : IAsyncLifetime await db.SaveChangesAsync(); var camera = new Camera(site.Id, "Main Camera", "rtsp://test"); - db.Cameras.Add(camera); 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(); @@ -191,6 +192,9 @@ public class AnalysisJobDispatcherJobTests : IAsyncLifetime 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)); diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs index 8540e04..4d04bb2 100644 --- a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs @@ -54,7 +54,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime } public static IEnumerable GpuScenarios => - from type in Enum.GetValues() + from type in new[] { AnalysisJobType.ObjectDetection } from sameSite in new[] { true, false } from loaded in new[] { true, false } select new object[] { type, sameSite, loaded }; @@ -71,6 +71,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime 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); @@ -79,7 +80,9 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime } await db.SaveChangesAsync(); var created = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic); - (await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None))!.Id.ShouldBe(agent.Id); + var selected = await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None); + if (sameSite) selected!.Id.ShouldBe(agent.Id); + else selected.ShouldBeNull(); } // ── CreateJob ─────────────────────────────────────────────────── @@ -90,13 +93,13 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime var (siteId, cameraId) = await SeedSiteAndCameraAsync(); var result = await _service.CreateJobAsync( - cameraId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); + 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.MotionDetection); + result.Data.JobType.ShouldBe(AnalysisJobType.ObjectDetection); result.Data.Priority.ShouldBe(AnalysisJobPriority.Periodic); result.Data.Status.ShouldBe(AnalysisJobStatus.Pending); } @@ -120,7 +123,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical); result.IsSuccess.ShouldBeTrue(); - result.Data!.RequiresGpu.ShouldBeTrue(); + result.Data!.RequiresGpu.ShouldBeFalse(); result.Data.RequiredCpuCores.ShouldBe(2); result.Data.RequiredMemoryMb.ShouldBe(2048); } @@ -132,7 +135,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); var otherSiteId = await CreateSiteAsync("Other Site"); - await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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); @@ -148,9 +152,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime { 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 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); @@ -162,9 +168,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task SelectBestAgentAsync_ExcludesInsufficientGpu() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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); @@ -177,6 +185,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime 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++) @@ -202,7 +211,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime 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 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); @@ -217,7 +227,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task DispatchJobAsync_PendingJob_DispatchesToAgent() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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); @@ -246,7 +257,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task StartJobAsync_DispatchedJob_SetsRunning() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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); @@ -264,7 +276,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task CompleteJobAsync_RunningJob_SetsCompleted() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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); @@ -284,7 +297,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task FailJobAsync_RunningJob_TriggersRetry() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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); @@ -304,7 +318,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task FailJobAsync_ExceedsMaxRetries_DeadLetters() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + 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++) @@ -384,6 +399,14 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime 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 SeedAgentAsync( Guid siteId, string name, bool hasGpu, int cpuCores, long memoryMb, AgentStatus status = AgentStatus.Online) @@ -408,6 +431,9 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime 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));