Complete durable agent analysis job flow
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 12m24s
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 12m24s
This commit is contained in:
1 parent
6af7fceb03
commit
6fc8efc438
27 files changed
+689
-123
No files matched your search
@@ -9,10 +9,8 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 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<AnalysisJob>.NotFound("Camera not found");
|
||||
|
||||
if (jobType != AnalysisJobType.ObjectDetection)
|
||||
return ServiceResult<AnalysisJob>.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<AnalysisJob>.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<AnalysisJob>.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<AnalysisJob>.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<AnalysisJob>.Success(job);
|
||||
}
|
||||
|
||||
/// <summary>Atomically claims a dispatched job for the authenticated agent.</summary>
|
||||
public async Task<AnalysisJob?> 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<int> 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();
|
||||
}
|
||||
|
||||
/// <summary>Completes only the current attempt owned by this agent.</summary>
|
||||
public async Task<ServiceResult> 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<ServiceResult> 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();
|
||||
}
|
||||
|
||||
/// <summary>Fails only the current attempt owned by this agent.</summary>
|
||||
public async Task<ServiceResult> 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<ServiceResult> 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<Agent?> 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));
|
||||
|
||||
Reference in new issue
Block a user