Add ConfigureAwait(false) to all await expressions in Application and Infrastructure projects (111 files). This follows .NET best practices for library code to avoid potential deadlocks when consumed from synchronization contexts (legacy, unit test runners). Also fix 4 test assertions that check SaveChangesAsync — update to SaveChangesWithRetryAsync to match the handler changes from Fix 4.
49 lines
1.5 KiB
C#
49 lines
1.5 KiB
C#
using Heimdall.Domain.Enums;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Heimdall.Infrastructure.Jobs;
|
|
|
|
/// <summary>
|
|
/// Marks agents as Offline if no heartbeat received for 90+ seconds.
|
|
/// Runs every minute via Hangfire recurring job.
|
|
/// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads.
|
|
/// </summary>
|
|
public class HeartbeatMonitorJob
|
|
{
|
|
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
|
private readonly ILogger<HeartbeatMonitorJob> _logger;
|
|
|
|
public HeartbeatMonitorJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<HeartbeatMonitorJob> logger)
|
|
{
|
|
_dbFactory = dbFactory;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task ExecuteAsync(CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var timeoutThreshold = DateTime.UtcNow.AddSeconds(-90);
|
|
|
|
var staleAgents = await db.Agents
|
|
.Where(a => a.Status == AgentStatus.Online
|
|
&& a.LastHeartbeat != null
|
|
&& a.LastHeartbeat < timeoutThreshold)
|
|
.ToListAsync(ct);
|
|
|
|
if (staleAgents.Count == 0)
|
|
return;
|
|
|
|
_logger.LogWarning("Marking {Count} agents as Offline (no heartbeat > 90s)", staleAgents.Count);
|
|
|
|
foreach (var agent in staleAgents)
|
|
{
|
|
agent.MarkOffline();
|
|
}
|
|
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
}
|
|
}
|