Files
Heimdall/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs
T
Arnaud Dartois 2b41ab4ea3
Heimdall Gitea / Build and tests (pull_request) Failing after 4m57s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
fix(storage): record historical object destinations
2026-10-22 19:58:55 +02:00

76 lines
2.8 KiB
C#

using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Storage;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// RetentionCheckJob — deletes expired recording objects from their recorded
/// provider before removing their database rows. Provider errors preserve the
/// rows so a later run can retry the idempotent object deletion.
/// Cron : quotidien 3h (queue default).
/// </summary>
public class RetentionCheckJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<RetentionCheckJob> _logger;
private readonly IStorageObjectDeletion _storage;
public RetentionCheckJob(
IDbContextFactory<AppDbContext> dbFactory,
ILogger<RetentionCheckJob> logger,
IStorageObjectDeletion storage)
{
_dbFactory = dbFactory;
_logger = logger;
_storage = storage;
}
public async Task ExecuteAsync(CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var now = DateTime.UtcNow;
var expired = await db.Recordings
.Where(r => (r.StoragePolicyId != null
&& r.StoragePolicy != null
&& r.Timestamp.AddDays(r.StoragePolicy.RetentionDays) < now) ||
(r.StoragePolicyId == null && r.Timestamp < now.AddDays(-30)))
.ToListAsync(ct)
.ConfigureAwait(false);
var deletable = new List<Recording>();
var captured = expired.Where(recording => recording.StorageLocationCaptured).ToArray();
foreach (var group in captured.GroupBy(recording => new StorageLocation(
recording.StorageProvider,
recording.StorageRoot,
recording.StorageEndpoint,
recording.StorageBucket)))
{
await _storage.DeleteBatchAsync(
group.Select(recording => recording.StoragePath).ToArray(), group.Key, ct).ConfigureAwait(false);
deletable.AddRange(group);
}
var withoutLocation = expired.Count - deletable.Count;
if (withoutLocation > 0)
_logger.LogWarning(
"Retention skipped {Count} expired recording(s) without a captured storage location; rows are retained to avoid deleting from the wrong destination",
withoutLocation);
if (deletable.Count > 0)
{
db.Recordings.RemoveRange(deletable);
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
}
var total = deletable.Count;
if (total > 0)
_logger.LogInformation("Retention check: purged {Count} expired recordings", total);
}
}