using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace Heimdall.Infrastructure.Jobs;
///
/// Records one idempotent five-minute sample for Agents with a recent heartbeat,
/// then removes samples outside the eight-day chart window in bounded batches.
///
public sealed class AgentMetricSampleJob
{
private static readonly TimeSpan SampleInterval = TimeSpan.FromMinutes(5);
private static readonly TimeSpan Retention = TimeSpan.FromDays(8);
private readonly IDbContextFactory _dbFactory;
private readonly ILogger _logger;
public AgentMetricSampleJob(IDbContextFactory dbFactory, ILogger logger)
{
_dbFactory = dbFactory;
_logger = logger;
}
public async Task ExecuteAsync(CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
var now = DateTime.UtcNow;
var capturedAt = new DateTime(now.Ticks - now.Ticks % SampleInterval.Ticks, DateTimeKind.Utc);
var activeSince = now.AddMinutes(-2);
// Parse this heartbeat field in .NET: it is agent-provided text and may
// contain malformed JSON. A bad GPU payload must not abort every sample.
var agents = await db.Agents
.AsNoTracking()
.Where(agent => agent.Status == AgentStatus.Online && !agent.IsDeleted && agent.LastHeartbeat >= activeSince)
.Select(agent => new
{
agent.Id, agent.SiteId, agent.LogicalCores, agent.CpuUsagePercent,
agent.MemoryUsageBytes, agent.MemTotalBytes, agent.MemAvailableBytes,
agent.DiskUsagePercent, agent.GpuInventoryJson, agent.TemperatureJson,
agent.InventoryObservedAtUtc
})
.ToListAsync(ct)
.ConfigureAwait(false);
var samples = new List(agents.Count);
foreach (var agent in agents)
{
var (gpuTemperature, gpuUtilization) = ReadGpuMetrics(agent.GpuInventoryJson, agent.Id);
samples.Add(new MetricSamplePayload(
agent.Id, agent.SiteId, capturedAt, agent.LogicalCores, agent.CpuUsagePercent,
agent.MemoryUsageBytes, agent.MemTotalBytes, agent.MemAvailableBytes, agent.DiskUsagePercent,
gpuTemperature, gpuUtilization, agent.TemperatureJson, agent.InventoryObservedAtUtc));
}
// The unique (AgentId, CapturedAtUtc) index makes retries and duplicate
// executions safe. Only typed, server-serialized values reach PostgreSQL.
const int batchSize = 500;
var sampled = 0;
for (var offset = 0; offset < samples.Count; offset += batchSize)
{
var payload = JsonSerializer.Serialize(samples.Skip(offset).Take(batchSize));
sampled += await db.Database.ExecuteSqlInterpolatedAsync($$"""
INSERT INTO "agent_metric_samples"
("Id", "AgentId", "SiteId", "CapturedAtUtc", "LogicalCores", "CpuUsagePercent",
"MemoryUsageBytes", "MemTotalBytes", "MemAvailableBytes", "DiskUsagePercent", "GpuTemperatureCelsius",
"GpuUtilizationPercent", "TemperatureJson", "InventoryObservedAtUtc")
SELECT gen_random_uuid(), sample."AgentId", sample."SiteId", sample."CapturedAtUtc", sample."LogicalCores",
sample."CpuUsagePercent", sample."MemoryUsageBytes", sample."MemTotalBytes", sample."MemAvailableBytes",
sample."DiskUsagePercent", sample."GpuTemperatureCelsius", sample."GpuUtilizationPercent",
sample."TemperatureJson", sample."InventoryObservedAtUtc"
FROM jsonb_to_recordset({{payload}}::jsonb) AS sample(
"AgentId" uuid, "SiteId" uuid, "CapturedAtUtc" timestamp with time zone,
"LogicalCores" integer, "CpuUsagePercent" double precision, "MemoryUsageBytes" bigint,
"MemTotalBytes" bigint, "MemAvailableBytes" bigint, "DiskUsagePercent" double precision,
"GpuTemperatureCelsius" double precision, "GpuUtilizationPercent" double precision,
"TemperatureJson" text, "InventoryObservedAtUtc" timestamp with time zone)
ON CONFLICT ("AgentId", "CapturedAtUtc") DO NOTHING
""", ct).ConfigureAwait(false);
}
var cutoff = now - Retention;
var deleted = 0;
while (true)
{
var batchIds = await db.AgentMetricSamples
.Where(sample => sample.CapturedAtUtc < cutoff)
.OrderBy(sample => sample.CapturedAtUtc)
.Take(5000)
.Select(sample => sample.Id)
.ToListAsync(ct)
.ConfigureAwait(false);
if (batchIds.Count == 0) break;
deleted += await db.AgentMetricSamples
.Where(sample => batchIds.Contains(sample.Id))
.ExecuteDeleteAsync(ct)
.ConfigureAwait(false);
await Task.Delay(100, ct).ConfigureAwait(false);
}
_logger.LogDebug("Agent metric sampling stored {SampleCount} samples and deleted {DeletedCount} expired samples",
sampled, deleted);
}
private (double? TemperatureCelsius, double? UtilizationPercent) ReadGpuMetrics(string? json, Guid agentId)
{
if (string.IsNullOrWhiteSpace(json)) return (null, null);
try
{
using var document = JsonDocument.Parse(json);
if (document.RootElement.ValueKind != JsonValueKind.Array)
{
_logger.LogWarning("Ignoring non-array GPU inventory for agent {AgentId}", agentId);
return (null, null);
}
var temperatures = new List();
var utilizations = new List();
foreach (var device in document.RootElement.EnumerateArray())
{
if (device.ValueKind != JsonValueKind.Object) continue;
AddMetric(device, "TemperatureCelsius", "temperatureCelsius", temperatures, -273.15, 2000);
AddMetric(device, "UtilizationPercent", "utilizationPercent", utilizations, 0, 100);
}
return (Average(temperatures), Average(utilizations));
}
catch (JsonException ex)
{
_logger.LogWarning(ex, "Ignoring malformed GPU inventory for agent {AgentId}", agentId);
return (null, null);
}
}
private static void AddMetric(JsonElement device, string property, string camelCaseProperty,
List values, double minimum, double maximum)
{
if (!device.TryGetProperty(property, out var value) && !device.TryGetProperty(camelCaseProperty, out value)) return;
if (value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) &&
double.IsFinite(number) && number >= minimum && number <= maximum)
values.Add(number);
}
private static double? Average(List values) => values.Count == 0 ? null : values.Average();
private sealed record MetricSamplePayload(
Guid AgentId,
Guid SiteId,
DateTime CapturedAtUtc,
int? LogicalCores,
double? CpuUsagePercent,
long? MemoryUsageBytes,
long? MemTotalBytes,
long? MemAvailableBytes,
double? DiskUsagePercent,
double? GpuTemperatureCelsius,
double? GpuUtilizationPercent,
string? TemperatureJson,
DateTime? InventoryObservedAtUtc);
}