Files
Heimdall/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs
T
Arnaud Dartois 5cf508950f
Heimdall Gitea / Build and tests (pull_request) Failing after 3m31s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
feat(storage): retain known destination inventory
2026-10-24 17:04:57 +02:00

156 lines
7.2 KiB
C#

using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>Reconciles final snapshot objects against exact persisted destinations and keys.</summary>
public sealed class StorageFinalOrphanCleanupJob(
IDbContextFactory<AppDbContext> dbFactory,
StorageProviderFactory storage,
ILogger<StorageFinalOrphanCleanupJob> logger)
{
private const string Prefix = "snapshots/";
private const int PageSize = 250;
public async Task ExecuteAsync(CancellationToken ct)
{
// A week leaves ample time for an interrupted upload or delayed database retry.
var cutoff = DateTime.UtcNow.AddDays(-7);
await using var db = await dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
var destinations = new HashSet<StorageLocation>();
try { destinations.Add(storage.CaptureCurrentLocation()); }
catch (Exception ex) when (ex is not OperationCanceledException)
{ logger.LogWarning(ex, "Current snapshot storage destination cannot be inventoried"); }
var knownLocations = await db.StorageDestinations.AsNoTracking()
.ToListAsync(ct).ConfigureAwait(false);
foreach (var item in knownLocations)
{
var location = item.ToLocation();
if (location.IsComplete) destinations.Add(location);
else logger.LogWarning("Ignoring incomplete registered storage destination for {Provider}", item.Provider);
}
// Soft-deleted cameras still own snapshot references until the event itself is removed.
// Include those rows when discovering old destinations and protecting referenced objects.
var recorded = await db.CameraEvents.IgnoreQueryFilters().AsNoTracking()
.Where(e => (e.SnapshotObjectKey != null || e.SnapshotThumbObjectKey != null) &&
e.SnapshotStorageProvider != null)
.Select(e => new
{
e.SnapshotStorageProvider, e.SnapshotStorageRoot,
e.SnapshotStorageEndpoint, e.SnapshotStorageBucket
})
.Distinct().ToListAsync(ct).ConfigureAwait(false);
foreach (var item in recorded)
{
var location = new StorageLocation(item.SnapshotStorageProvider!.Value,
item.SnapshotStorageRoot, item.SnapshotStorageEndpoint, item.SnapshotStorageBucket);
if (location.IsComplete) destinations.Add(location);
}
foreach (var location in destinations)
{
string? cursor = null;
var deleted = 0;
try
{
do
{
ct.ThrowIfCancellationRequested();
var page = await storage.ListObjectsPageAsync(Prefix, cursor, PageSize, location, ct)
.ConfigureAwait(false);
var candidates = page.Objects
.Where(item => item.LastModifiedUtc < cutoff && IsManagedSnapshotKey(item.Key))
.ToArray();
var referenced = await GetReferencedKeysAsync(db,
candidates.Select(item => item.Key).Distinct(StringComparer.Ordinal).ToArray(),
location, ct).ConfigureAwait(false);
foreach (var item in candidates)
{
if (referenced.Contains(item.Key)) continue;
await storage.DeleteAsync(item.Key, location, ct).ConfigureAwait(false);
deleted++;
}
cursor = page.NextCursor;
} while (cursor is not null);
if (deleted > 0)
logger.LogInformation("Removed {Count} unreferenced final snapshot objects from {Provider}",
deleted, location.Provider);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception ex)
{
logger.LogWarning(ex, "Final snapshot reconciliation failed for {Provider}; remaining objects retained",
location.Provider);
}
}
}
private static async Task<HashSet<string>> GetReferencedKeysAsync(AppDbContext db, string[] keys,
StorageLocation candidate, CancellationToken ct)
{
var referenced = new HashSet<string>(StringComparer.Ordinal);
if (keys.Length == 0) return referenced;
var keySet = new HashSet<string>(keys, StringComparer.Ordinal);
var events = await db.CameraEvents.IgnoreQueryFilters().AsNoTracking()
.Where(e => keys.Contains(e.SnapshotObjectKey!) || keys.Contains(e.SnapshotThumbObjectKey!))
.Select(e => new
{
e.SnapshotObjectKey, e.SnapshotThumbObjectKey,
e.SnapshotStorageProvider, e.SnapshotStorageRoot,
e.SnapshotStorageEndpoint, e.SnapshotStorageBucket
}).ToListAsync(ct).ConfigureAwait(false);
foreach (var item in events)
{
// Missing provenance is historical: its destination cannot be disproved.
var protectsCandidate = item.SnapshotStorageProvider is null;
if (!protectsCandidate)
{
var recorded = new StorageLocation(item.SnapshotStorageProvider!.Value,
item.SnapshotStorageRoot, item.SnapshotStorageEndpoint, item.SnapshotStorageBucket);
protectsCandidate = !recorded.IsComplete || recorded == candidate;
}
if (!protectsCandidate) continue;
if (item.SnapshotObjectKey is { } snapshot && keySet.Contains(snapshot)) referenced.Add(snapshot);
if (item.SnapshotThumbObjectKey is { } thumb && keySet.Contains(thumb)) referenced.Add(thumb);
}
var recordings = await db.Recordings.AsNoTracking()
.Where(r => keys.Contains(r.StoragePath))
.Select(r => new
{
r.StoragePath, r.StorageLocationCaptured, r.StorageProvider,
r.StorageRoot, r.StorageEndpoint, r.StorageBucket
}).ToListAsync(ct).ConfigureAwait(false);
foreach (var item in recordings)
{
if (!item.StorageLocationCaptured)
{
referenced.Add(item.StoragePath);
continue;
}
var recorded = new StorageLocation(item.StorageProvider,
item.StorageRoot, item.StorageEndpoint, item.StorageBucket);
if (!recorded.IsComplete || recorded == candidate) referenced.Add(item.StoragePath);
}
return referenced;
}
private static bool IsManagedSnapshotKey(string key)
{
var parts = key.Split('/');
if (parts.Length != 4 || parts[0] != "snapshots" ||
!Guid.TryParseExact(parts[1], "D", out _) ||
!Guid.TryParseExact(parts[2], "D", out _)) return false;
var name = parts[3];
var suffix = name.EndsWith(".thumb.jpg", StringComparison.Ordinal)
? ".thumb.jpg" : ".jpg";
return name.EndsWith(suffix, StringComparison.Ordinal) &&
Guid.TryParseExact(name[..^suffix.Length], "N", out _);
}
}