using Hangfire; using Heimdall.Infrastructure.Metrics; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.BackgroundJobs; /// /// Periodically exports bounded Hangfire monitoring data without reading its /// provider tables directly. Job identifiers and payloads are never exported. /// internal sealed class HangfireMetricsReporter( JobStorage storage, ILogger logger) : BackgroundService { private const int JobsPerQueueToInspect = 100; private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(30); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(PollInterval); do { try { var snapshot = await Task.Run(ReadSnapshot, CancellationToken.None); HangfireJobMetrics.SetJobState( snapshot.OldestEnqueuedAgeSeconds, snapshot.OldestProcessingAgeSeconds, snapshot.FailedJobs, monitoringAvailable: true); } catch (Exception exception) when (!stoppingToken.IsCancellationRequested) { HangfireJobMetrics.SetJobState(0, 0, 0, monitoringAvailable: false); logger.LogWarning( "Hangfire monitoring poll failed ({ExceptionType})", exception.GetType().Name); } if (!await timer.WaitForNextTickAsync(stoppingToken)) break; } while (!stoppingToken.IsCancellationRequested); } private Snapshot ReadSnapshot() { var monitoring = storage.GetMonitoringApi(); var failedJobs = monitoring.GetStatistics().Failed; long oldestEnqueuedAgeSeconds = 0; foreach (var queue in monitoring.Queues()) { var page = monitoring.EnqueuedJobs(queue.Name, 0, JobsPerQueueToInspect); foreach (var job in page) oldestEnqueuedAgeSeconds = Math.Max( oldestEnqueuedAgeSeconds, GetAgeSeconds(job.Value?.EnqueuedAt)); } long oldestProcessingAgeSeconds = 0; foreach (var job in monitoring.ProcessingJobs(0, JobsPerQueueToInspect)) oldestProcessingAgeSeconds = Math.Max( oldestProcessingAgeSeconds, GetAgeSeconds(job.Value?.StartedAt)); return new Snapshot( oldestEnqueuedAgeSeconds, oldestProcessingAgeSeconds, failedJobs); } private static long GetAgeSeconds(DateTime? timestamp) { if (timestamp is not { } value) return 0; var utcTimestamp = value.Kind switch { DateTimeKind.Utc => value, DateTimeKind.Local => value.ToUniversalTime(), _ => DateTime.SpecifyKind(value, DateTimeKind.Utc) }; return Math.Max(0, (long)(DateTime.UtcNow - utcTimestamp).TotalSeconds); } private sealed record Snapshot( long OldestEnqueuedAgeSeconds, long OldestProcessingAgeSeconds, long FailedJobs); }