Merge pull request 'fix(storage): delete expired objects before references' (#47) from fix/storage-retention-object-deletion into main
This commit was merged in pull request #47.
This commit is contained in:
commit
afb58c51c7
4 files changed
+200
-70
No files matched your search
@@ -1,25 +1,30 @@
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Storage;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Infrastructure.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// RetentionCheckJob — purge les enregistrements expirés selon leur
|
||||
/// StoragePolicy (retention en jours), via ExecuteDelete (1 requête SQL,
|
||||
/// pas de boucle mémoire — Correctif D5). Le batch-delete S3 des objets
|
||||
/// orphelins est couvert par S3CleanupJob (ticket #7).
|
||||
/// 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 StorageProviderFactory? _storage;
|
||||
|
||||
public RetentionCheckJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<RetentionCheckJob> logger)
|
||||
public RetentionCheckJob(
|
||||
IDbContextFactory<AppDbContext> dbFactory,
|
||||
ILogger<RetentionCheckJob> logger,
|
||||
StorageProviderFactory? storage = null)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_logger = logger;
|
||||
_storage = storage;
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync(CancellationToken ct)
|
||||
@@ -28,23 +33,30 @@ public class RetentionCheckJob
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
// Enregistrements avec politique explicite dont la rétention est dépassée
|
||||
// (Timestamp + RetentionDays < now). Npgsql traduit AddDays en SQL.
|
||||
var expiredWithPolicy = await db.Recordings
|
||||
.Where(r => r.StoragePolicyId != null
|
||||
var expired = await db.Recordings
|
||||
.Where(r => (r.StoragePolicyId != null
|
||||
&& r.StoragePolicy != null
|
||||
&& r.Timestamp.AddDays(r.StoragePolicy.RetentionDays) < now)
|
||||
.ExecuteDeleteAsync(ct)
|
||||
&& r.Timestamp.AddDays(r.StoragePolicy.RetentionDays) < now) ||
|
||||
(r.StoragePolicyId == null && r.Timestamp < now.AddDays(-30)))
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Enregistrements sans politique : rétention par défaut 30 j.
|
||||
var expiredDefault = await db.Recordings
|
||||
.Where(r => r.StoragePolicyId == null
|
||||
&& r.Timestamp < now.AddDays(-30))
|
||||
.ExecuteDeleteAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
if (_storage is not null)
|
||||
{
|
||||
foreach (var group in expired.GroupBy(recording => recording.StorageProvider))
|
||||
{
|
||||
await _storage.DeleteBatchAsync(
|
||||
group.Select(recording => recording.StoragePath).ToArray(), group.Key, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var total = expiredWithPolicy + expiredDefault;
|
||||
if (expired.Count > 0)
|
||||
{
|
||||
db.Recordings.RemoveRange(expired);
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var total = expired.Count;
|
||||
if (total > 0)
|
||||
_logger.LogInformation("Retention check: purged {Count} expired recordings", total);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace Heimdall.Infrastructure.Storage;
|
||||
/// fallback (<c>ALARIK_ENDPOINT</c> / <c>S3_ENDPOINT</c>). Uploads use a
|
||||
/// staging prefix then a copy (atomic move semantics for the consumers).
|
||||
/// </summary>
|
||||
public sealed class AlarikStorageProvider : IStorageProvider
|
||||
public sealed class AlarikStorageProvider : IStorageProvider, IDisposable
|
||||
{
|
||||
private readonly AmazonS3Client? _client;
|
||||
private readonly string _bucket = string.Empty;
|
||||
@@ -119,18 +119,11 @@ public sealed class AlarikStorageProvider : IStorageProvider
|
||||
{
|
||||
if (_client is null)
|
||||
return;
|
||||
try
|
||||
await _client.DeleteObjectAsync(new DeleteObjectRequest
|
||||
{
|
||||
await _client.DeleteObjectAsync(new DeleteObjectRequest
|
||||
{
|
||||
BucketName = _bucket,
|
||||
Key = key,
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (AmazonS3Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "S3 delete failed for {Key}", key);
|
||||
}
|
||||
BucketName = _bucket,
|
||||
Key = key,
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
||||
@@ -144,7 +137,9 @@ public sealed class AlarikStorageProvider : IStorageProvider
|
||||
var request = new DeleteObjectsRequest { BucketName = _bucket };
|
||||
foreach (var key in chunk)
|
||||
request.AddKey(key);
|
||||
await _client.DeleteObjectsAsync(request, ct).ConfigureAwait(false);
|
||||
var response = await _client.DeleteObjectsAsync(request, ct).ConfigureAwait(false);
|
||||
if (response.DeleteErrors is { Count: > 0 } errors)
|
||||
throw new InvalidOperationException($"S3 rejected deletion of {errors.Count} object(s).");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,4 +158,6 @@ public sealed class AlarikStorageProvider : IStorageProvider
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _client?.Dispose();
|
||||
}
|
||||
@@ -93,23 +93,18 @@ public sealed class LocalStorageProvider : IStorageProvider
|
||||
public Task DeleteAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var path = ResolvePath(key);
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Local storage delete failed for {Key}", key);
|
||||
}
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
||||
public async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
||||
{
|
||||
foreach (var key in keys)
|
||||
DeleteAsync(key, ct);
|
||||
return Task.CompletedTask;
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await DeleteAsync(key, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
||||
|
||||
@@ -16,40 +16,115 @@ namespace Heimdall.Infrastructure.Storage;
|
||||
public sealed class StorageProviderFactory : IStorageProvider
|
||||
{
|
||||
private readonly IServiceProvider _services;
|
||||
private readonly ILogger<StorageProviderFactory> _logger;
|
||||
|
||||
public StorageProviderFactory(IServiceProvider services, ILogger<StorageProviderFactory> logger)
|
||||
public StorageProviderFactory(IServiceProvider services)
|
||||
{
|
||||
_services = services;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public string Provider => Resolve().Provider;
|
||||
public bool IsConfigured => Resolve().IsConfigured;
|
||||
public string Provider
|
||||
{
|
||||
get
|
||||
{
|
||||
var provider = Resolve();
|
||||
try { return provider.Provider; }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
}
|
||||
|
||||
public Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
|
||||
=> Resolve().UploadAsync(key, content, contentType, ct);
|
||||
public bool IsConfigured
|
||||
{
|
||||
get
|
||||
{
|
||||
var provider = Resolve();
|
||||
try { return provider.IsConfigured; }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
}
|
||||
|
||||
public Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
|
||||
=> Resolve().DownloadAsync(key, ct);
|
||||
public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
try { await provider.UploadAsync(key, content, contentType, ct).ConfigureAwait(false); }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
|
||||
public Task DeleteAsync(string key, CancellationToken ct = default)
|
||||
=> Resolve().DeleteAsync(key, ct);
|
||||
public async Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
try
|
||||
{
|
||||
var stream = await provider.DownloadAsync(key, ct).ConfigureAwait(false);
|
||||
if (stream is null)
|
||||
{
|
||||
DisposeProvider(provider);
|
||||
return null;
|
||||
}
|
||||
return new ProviderOwnedStream(stream, provider as IDisposable);
|
||||
}
|
||||
catch
|
||||
{
|
||||
DisposeProvider(provider);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
||||
=> Resolve().DeleteBatchAsync(keys, ct);
|
||||
public async Task DeleteAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
try { await provider.DeleteAsync(key, ct).ConfigureAwait(false); }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
|
||||
public Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
||||
=> Resolve().HealthCheckAsync(ct);
|
||||
/// <summary>Deletes an object from the provider recorded with its owning row.</summary>
|
||||
public async Task DeleteAsync(string key, Heimdall.Domain.Enums.StorageProvider provider, CancellationToken ct = default)
|
||||
{
|
||||
var resolved = Resolve(provider.ToString());
|
||||
try
|
||||
{
|
||||
await resolved.DeleteAsync(key, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally { DisposeProvider(resolved); }
|
||||
}
|
||||
|
||||
private IStorageProvider Resolve()
|
||||
public async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
try { await provider.DeleteBatchAsync(keys, ct).ConfigureAwait(false); }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
|
||||
public async Task DeleteBatchAsync(
|
||||
IReadOnlyCollection<string> keys,
|
||||
Heimdall.Domain.Enums.StorageProvider providerType,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve(providerType.ToString());
|
||||
try { await provider.DeleteBatchAsync(keys, ct).ConfigureAwait(false); }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
|
||||
public async Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
try { return await provider.HealthCheckAsync(ct).ConfigureAwait(false); }
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
|
||||
private static void DisposeProvider(IStorageProvider provider) => (provider as IDisposable)?.Dispose();
|
||||
|
||||
private IStorageProvider Resolve(string? providerOverride = null)
|
||||
{
|
||||
using var scope = _services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
||||
|
||||
var provider = GetSetting(db, "storage.provider")
|
||||
?? Environment.GetEnvironmentVariable("STORAGE__PROVIDER")
|
||||
?? "Local";
|
||||
var configuredProvider = GetSetting(db, "storage.provider");
|
||||
var environmentProvider = Environment.GetEnvironmentVariable("STORAGE__PROVIDER");
|
||||
var provider = !string.IsNullOrWhiteSpace(providerOverride)
|
||||
? providerOverride
|
||||
: !string.IsNullOrWhiteSpace(configuredProvider)
|
||||
? configuredProvider
|
||||
: !string.IsNullOrWhiteSpace(environmentProvider) ? environmentProvider : "Local";
|
||||
|
||||
if (provider.Equals("S3", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
@@ -62,9 +137,13 @@ public sealed class StorageProviderFactory : IStorageProvider
|
||||
scope.ServiceProvider.GetRequiredService<ILogger<AlarikStorageProvider>>());
|
||||
if (s3.IsConfigured)
|
||||
return s3;
|
||||
_logger.LogWarning("storage.provider=S3 mais S3 non configuré — fallback Local");
|
||||
s3.Dispose();
|
||||
throw new InvalidOperationException($"Storage provider '{provider}' is not configured; refusing to route an object to another provider.");
|
||||
}
|
||||
|
||||
if (!provider.Equals("Local", StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"Unknown storage provider '{provider}'.");
|
||||
|
||||
return new LocalStorageProvider(
|
||||
GetSetting(db, "storage.local.path"),
|
||||
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
|
||||
@@ -72,16 +151,63 @@ public sealed class StorageProviderFactory : IStorageProvider
|
||||
|
||||
private static string? GetSetting(IApplicationDbContext db, string key)
|
||||
{
|
||||
try
|
||||
var setting = db.AppSettings
|
||||
.AsNoTracking()
|
||||
.FirstOrDefault(s => s.Key == key);
|
||||
return setting?.Value;
|
||||
}
|
||||
|
||||
private sealed class ProviderOwnedStream(Stream inner, IDisposable? owner) : Stream
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public override bool CanRead => !_disposed && inner.CanRead;
|
||||
public override bool CanSeek => !_disposed && inner.CanSeek;
|
||||
public override bool CanWrite => !_disposed && inner.CanWrite;
|
||||
public override long Length => inner.Length;
|
||||
public override long Position { get => inner.Position; set => inner.Position = value; }
|
||||
public override void Flush() => inner.Flush();
|
||||
public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count);
|
||||
public override int Read(Span<byte> buffer) => inner.Read(buffer);
|
||||
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
=> inner.ReadAsync(buffer, cancellationToken);
|
||||
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
=> inner.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
|
||||
public override void SetLength(long value) => inner.SetLength(value);
|
||||
public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
|
||||
public override void Write(ReadOnlySpan<byte> buffer) => inner.Write(buffer);
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
=> inner.WriteAsync(buffer, cancellationToken);
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
=> inner.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
var setting = db.AppSettings
|
||||
.AsNoTracking()
|
||||
.FirstOrDefault(s => s.Key == key);
|
||||
return setting?.Value;
|
||||
try
|
||||
{
|
||||
if (disposing && !_disposed)
|
||||
{
|
||||
_disposed = true;
|
||||
try { inner.Dispose(); }
|
||||
finally { owner?.Dispose(); }
|
||||
}
|
||||
}
|
||||
finally { base.Dispose(disposing); }
|
||||
}
|
||||
catch
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
return null;
|
||||
try
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
_disposed = true;
|
||||
try { await inner.DisposeAsync().ConfigureAwait(false); }
|
||||
finally { owner?.Dispose(); }
|
||||
}
|
||||
}
|
||||
finally { await base.DisposeAsync().ConfigureAwait(false); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user