using Hangfire;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
///
/// Hangfire job that dispatches pending analysis jobs to agents and cleans up
/// timed-out jobs. Runs on the "analysis" queue.
///
/// Responsibilities:
/// 1. Pick pending jobs ordered by priority (security first) and dispatch to best agent
/// 2. Detect jobs stuck in Dispatched/Running past their timeout → retry or dead-letter
///
/// Uses IDbContextFactory to avoid sharing DbContext across Hangfire worker threads.
///
public sealed class AnalysisJobDispatcherJob
{
private readonly IDbContextFactory _dbFactory;
private readonly IAnalysisJobSchedulerService _schedulerService;
private readonly ILogger _logger;
/// Max jobs to dispatch per tick to prevent overwhelming agents.
private const int MaxDispatchPerTick = 10;
public AnalysisJobDispatcherJob(
IDbContextFactory dbFactory,
IAnalysisJobSchedulerService schedulerService,
ILogger logger)
{
_dbFactory = dbFactory;
_schedulerService = schedulerService;
_logger = logger;
}
///
/// Main dispatcher tick: process pending jobs. Timeouts belong to the minute sweep.
/// Called every 30 seconds by Hangfire recurring job.
///
public async Task ExecuteAsync(CancellationToken ct = default)
{
// 1. Dispatch pending jobs
var dispatched = await _schedulerService
.ProcessPendingJobsAsync(MaxDispatchPerTick, ct)
.ConfigureAwait(false);
if (dispatched > 0)
_logger.LogInformation("Analysis dispatcher: {Dispatched} dispatched", dispatched);
}
///
/// Timeout sweep only — runs less frequently (every 60s) to catch stuck jobs.
///
[DisableConcurrentExecution(timeoutInSeconds: 60)]
public async Task ExecuteTimeoutSweepAsync(CancellationToken ct = default)
{
var timedOutJobs = await _schedulerService
.GetTimedOutJobsAsync(ct)
.ConfigureAwait(false);
if (timedOutJobs.Count == 0)
return;
foreach (var job in timedOutJobs)
{
_logger.LogWarning(
"Sweep: analysis job {JobId} stuck in {Status} since {DispatchedAt} (timeout={Timeout}s)",
job.Id, job.Status, job.DispatchedAt, job.MaxExecutionTime.TotalSeconds);
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);
}
}