diff --git a/docs/audits/2026-10-20-audit-complet.md b/docs/audits/2026-10-20-audit-complet.md index 0cca9f4..75c48e9 100644 --- a/docs/audits/2026-10-20-audit-complet.md +++ b/docs/audits/2026-10-20-audit-complet.md @@ -16,7 +16,8 @@ La revue initiale ci-dessous décrit les constats à la révision `7792353`. Les | Partiellement validé | BUILD-01 | PR #3, #13–#18 ; run #64 vert (tests, images et scans). Protection bloquante des branches, reproductibilité sur builds propres et publication d’une release taguée restent à démontrer sur l’instance Gitea. | | Corrigé et validé CI | OPS-05 | PR #18, run #64 vert sur `0bde726` : manifeste accessible par identité agent, ordre manuel ciblé via ConfigHub, traitement natif/Docker. | | Corrigé et fusionné | AGENT-01 à AGENT-07, PIPE-10, FEAT-05, OPS-01 (recordings) | PR #38–#43, #45–#47. PIPE-10 utilise un spool SQLite stable; FEAT-05 crée une alerte par destinataire caméra autorisé et enfile les canaux externes; OPS-01 supprime les objets avant leurs références SQL. Les runs récents n’ont pas pu valider ces changements à cause des runners. | -| Ouvert sur `main` | PIPE-01, PIPE-02, PIPE-09, OPS-02 (localisation historique complète), UI-02, FEAT-01, FEAT-02, FEAT-03, QA-01, DOC-01, AGENT-08 à AGENT-10 | Parcours incomplets, routage de stockage historique non versionné par bucket/racine/clé, et validations nécessitant des intégrations, du matériel ou de l’exploitation. | +| Partiellement corrigé | OPS-02 | PR #49 capture provider, bucket/endpoint S3 ou racine locale sur les nouveaux recordings et route leur rétention avec cette destination. Les anciennes lignes ne contiennent pas cette provenance et sont conservées; le pipeline d’enregistrement vidéo n’écrit actuellement aucun objet et devra renseigner cette métadonnée à son raccordement. | +| Ouvert sur `main` | PIPE-01, PIPE-02, PIPE-09, OPS-02 (médias hors recordings et lignes historiques), UI-02, FEAT-01, FEAT-02, FEAT-03, QA-01, DOC-01, AGENT-08 à AGENT-10 | Parcours incomplets, références de stockage historiques impossibles à reconstituer pour les anciennes lignes et intégration de la provenance aux futurs uploads de médias; validations nécessitant des intégrations, du matériel ou de l’exploitation. | | Corrigé et fusionné | UI-03 | PR #36, commit `56a6177` : digests quotidiens/hebdomadaires bornés en UTC sur `OccurredAt`, filtrés avec la politique caméra complète. Les tests Infrastructure passent (307/307); le build et les tests post-fusion #114 passent, ainsi que les archives, images et contrôles de sécurité. | | À valider hors CI | Vérifications complémentaires § ci-dessous | Caméras réelles, réseau/TURN, SMTP/ntfy, S3, charge et restauration de sauvegarde ne sont pas certifiés par le run automatisé. | diff --git a/docs/audits/2026-10-20-plan-implementation.md b/docs/audits/2026-10-20-plan-implementation.md index 47406cd..8309f6c 100644 --- a/docs/audits/2026-10-20-plan-implementation.md +++ b/docs/audits/2026-10-20-plan-implementation.md @@ -129,7 +129,7 @@ Travaux : 2. Corriger le parseur de partitions et fermer les readers avant DDL ; tester sur PostgreSQL. 3. Corriger le cron du timeout sweep, éviter les chevauchements concurrents, valider les occurrences attendues. 4. Étendre la purge idempotente de la PR #47 aux tombstones/reconciliation, objets staging et médias supprimés avec leur parent métier. -5. La PR #47 supprime les recordings par provider enregistré et refuse le fallback silencieux S3 → Local. Il reste à persister la localisation complète (provider, bucket/racine, clé) par objet et à la résoudre après changement de configuration. +5. Les PR #47 et #49 suppriment les recordings par provider et destination enregistrés (endpoint/bucket S3 ou racine locale), sans fallback silencieux. Les lignes historiques sans destination sont conservées; à l’intégration du pipeline vidéo, chaque enregistrement devra recevoir la destination capturée utilisée par son upload. Généraliser ensuite cette référence aux snapshots, objets staging et autres médias. 6. Tester la restauration isolée de PostgreSQL, des objets et des clés Data Protection ; définir RPO/RTO et procédure mesurée. 7. Vérifier readiness, métriques et alertes : modèle absent, queue pleine, backlog, disque, jobs bloqués, perte de configuration et échec livraison. diff --git a/src/Heimdall.Application/Common/IStorageObjectDeletion.cs b/src/Heimdall.Application/Common/IStorageObjectDeletion.cs new file mode 100644 index 0000000..6abdb24 --- /dev/null +++ b/src/Heimdall.Application/Common/IStorageObjectDeletion.cs @@ -0,0 +1,9 @@ +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Common; + +/// Deletes objects from the exact destination persisted with their owning records. +public interface IStorageObjectDeletion +{ + Task DeleteBatchAsync(IReadOnlyCollection keys, StorageLocation location, CancellationToken ct = default); +} diff --git a/src/Heimdall.Domain/Entities/Recording.cs b/src/Heimdall.Domain/Entities/Recording.cs index 332e341..e6bc01d 100644 --- a/src/Heimdall.Domain/Entities/Recording.cs +++ b/src/Heimdall.Domain/Entities/Recording.cs @@ -15,6 +15,10 @@ public class Recording : Entity, IAuditableEntity public string StoragePath { get; private set; } = string.Empty; public long SizeBytes { get; private set; } public StorageProvider StorageProvider { get; private set; } = StorageProvider.S3; + public string? StorageRoot { get; private set; } + public string? StorageEndpoint { get; private set; } + public string? StorageBucket { get; private set; } + public bool StorageLocationCaptured { get; private set; } public Guid? StoragePolicyId { get; private set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } @@ -32,6 +36,7 @@ public class Recording : Entity, IAuditableEntity string storagePath, long sizeBytes, StorageProvider storageProvider, + StorageLocation storageLocation, Guid? storagePolicyId = null) : base(Guid.NewGuid()) { @@ -42,7 +47,20 @@ public class Recording : Entity, IAuditableEntity SizeBytes = sizeBytes; StorageProvider = storageProvider; StoragePolicyId = storagePolicyId; + CaptureStorageLocation(storageLocation); } public void AssignStoragePolicy(Guid storagePolicyId) => StoragePolicyId = storagePolicyId; + + public void CaptureStorageLocation(StorageLocation location) + { + ArgumentNullException.ThrowIfNull(location); + if (!location.IsComplete || location.Provider != StorageProvider) + throw new ArgumentException("Storage location must be complete and match the recording provider.", nameof(location)); + + StorageRoot = location.LocalRoot; + StorageEndpoint = location.S3Endpoint; + StorageBucket = location.S3Bucket; + StorageLocationCaptured = true; + } } diff --git a/src/Heimdall.Domain/Entities/StorageLocation.cs b/src/Heimdall.Domain/Entities/StorageLocation.cs new file mode 100644 index 0000000..1d57b72 --- /dev/null +++ b/src/Heimdall.Domain/Entities/StorageLocation.cs @@ -0,0 +1,21 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Domain.Entities; + +/// +/// Immutable destination details captured when a stored object is written. +/// Credentials remain in the current secret store and are never persisted here. +/// +public sealed record StorageLocation( + StorageProvider Provider, + string? LocalRoot = null, + string? S3Endpoint = null, + string? S3Bucket = null) +{ + public bool IsComplete => Provider switch + { + StorageProvider.Local => !string.IsNullOrWhiteSpace(LocalRoot), + StorageProvider.S3 => !string.IsNullOrWhiteSpace(S3Endpoint) && !string.IsNullOrWhiteSpace(S3Bucket), + _ => false, + }; +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/RecordingConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/RecordingConfiguration.cs index e0c82a0..4ea9f53 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/RecordingConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/RecordingConfiguration.cs @@ -32,6 +32,11 @@ public class RecordingConfiguration : IEntityTypeConfiguration .IsRequired() .IsUnicode(false); + builder.Property(r => r.StorageRoot).HasMaxLength(2000); + builder.Property(r => r.StorageEndpoint).HasMaxLength(2000); + builder.Property(r => r.StorageBucket).HasMaxLength(256); + builder.Property(r => r.StorageLocationCaptured).HasDefaultValue(false).IsRequired(); + builder.Property(r => r.CreatedAt) .HasDefaultValueSql("NOW()"); diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 52531f2..51ea8fa 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -50,6 +50,7 @@ public static class DependencyInjection // chaque résolution → changement UI sans redémarrage). services.AddSingleton(); services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(sp => sp.GetRequiredService()); // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() diff --git a/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs b/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs index 00d4a93..11861b0 100644 --- a/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs @@ -1,5 +1,7 @@ using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Storage; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -15,12 +17,12 @@ public class RetentionCheckJob { private readonly IDbContextFactory _dbFactory; private readonly ILogger _logger; - private readonly StorageProviderFactory? _storage; + private readonly IStorageObjectDeletion _storage; public RetentionCheckJob( IDbContextFactory dbFactory, ILogger logger, - StorageProviderFactory? storage = null) + IStorageObjectDeletion storage) { _dbFactory = dbFactory; _logger = logger; @@ -41,22 +43,32 @@ public class RetentionCheckJob .ToListAsync(ct) .ConfigureAwait(false); - if (_storage is not null) + var deletable = new List(); + 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))) { - foreach (var group in expired.GroupBy(recording => recording.StorageProvider)) - { - await _storage.DeleteBatchAsync( - group.Select(recording => recording.StoragePath).ToArray(), group.Key, ct).ConfigureAwait(false); - } + await _storage.DeleteBatchAsync( + group.Select(recording => recording.StoragePath).ToArray(), group.Key, ct).ConfigureAwait(false); + deletable.AddRange(group); } - if (expired.Count > 0) + 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(expired); + db.Recordings.RemoveRange(deletable); await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); } - var total = expired.Count; + var total = deletable.Count; if (total > 0) _logger.LogInformation("Retention check: purged {Count} expired recordings", total); } diff --git a/src/Heimdall.Infrastructure/Migrations/20261022000000_AddRecordingStorageLocation.cs b/src/Heimdall.Infrastructure/Migrations/20261022000000_AddRecordingStorageLocation.cs new file mode 100644 index 0000000..48b3706 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261022000000_AddRecordingStorageLocation.cs @@ -0,0 +1,51 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261022000000_AddRecordingStorageLocation")] +public partial class AddRecordingStorageLocation : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "StorageRoot", + table: "recordings", + type: "character varying(2000)", + maxLength: 2000, + nullable: true); + + migrationBuilder.AddColumn( + name: "StorageEndpoint", + table: "recordings", + type: "character varying(2000)", + maxLength: 2000, + nullable: true); + + migrationBuilder.AddColumn( + name: "StorageBucket", + table: "recordings", + type: "character varying(256)", + maxLength: 256, + nullable: true); + + migrationBuilder.AddColumn( + name: "StorageLocationCaptured", + table: "recordings", + type: "boolean", + nullable: false, + defaultValue: false); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn(name: "StorageRoot", table: "recordings"); + migrationBuilder.DropColumn(name: "StorageEndpoint", table: "recordings"); + migrationBuilder.DropColumn(name: "StorageBucket", table: "recordings"); + migrationBuilder.DropColumn(name: "StorageLocationCaptured", table: "recordings"); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index cb7a2e6..496eecc 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1618,12 +1618,29 @@ namespace Heimdall.Infrastructure.Migrations b.Property("SizeBytes") .HasColumnType("bigint"); + b.Property("StorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("StorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + b.Property("StoragePath") .IsRequired() .HasMaxLength(2000) .IsUnicode(false) .HasColumnType("character varying(2000)"); + b.Property("StorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StorageLocationCaptured") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + b.Property("StoragePolicyId") .HasColumnType("uuid"); diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index ce153b9..10e1eb7 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -13,7 +13,7 @@ namespace Heimdall.Infrastructure.Storage; /// (STORAGE__PROVIDER). Reads the DB each resolution so a change made /// in the UI is picked up without restart (broadcast reload on top). /// -public sealed class StorageProviderFactory : IStorageProvider +public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Application.Common.IStorageObjectDeletion { private readonly IServiceProvider _services; @@ -44,7 +44,62 @@ public sealed class StorageProviderFactory : IStorageProvider public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default) { - var provider = Resolve(); + var location = CaptureCurrentLocation(); + await UploadAsync(key, content, contentType, location, ct).ConfigureAwait(false); + } + + /// Captures the current destination for persistence alongside an object reference. + public Heimdall.Domain.Entities.StorageLocation CaptureCurrentLocation() + { + using var scope = _services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var provider = GetSetting(db, "storage.provider"); + if (string.IsNullOrWhiteSpace(provider)) + provider = Environment.GetEnvironmentVariable("STORAGE__PROVIDER"); + if (string.IsNullOrWhiteSpace(provider)) + provider = "Local"; + + if (provider.Equals("Local", StringComparison.OrdinalIgnoreCase)) + { + var root = GetSetting(db, "storage.local.path"); + root = string.IsNullOrWhiteSpace(root) + ? Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage" + : root; + return new Heimdall.Domain.Entities.StorageLocation( + Heimdall.Domain.Enums.StorageProvider.Local, + LocalRoot: Path.GetFullPath(root)); + } + + if (provider.Equals("S3", StringComparison.OrdinalIgnoreCase)) + { + var endpoint = GetSetting(db, "storage.s3.endpoint"); + if (string.IsNullOrWhiteSpace(endpoint)) + endpoint = Environment.GetEnvironmentVariable("ALARIK_ENDPOINT"); + if (string.IsNullOrWhiteSpace(endpoint)) + endpoint = Environment.GetEnvironmentVariable("S3_ENDPOINT"); + var bucket = GetSetting(db, "storage.s3.bucket"); + bucket = string.IsNullOrWhiteSpace(bucket) ? "heimdall" : bucket; + var location = new Heimdall.Domain.Entities.StorageLocation( + Heimdall.Domain.Enums.StorageProvider.S3, + S3Endpoint: endpoint, + S3Bucket: bucket); + if (!location.IsComplete) + throw new InvalidOperationException("S3 storage is not configured; no object can be written."); + return location; + } + + throw new InvalidOperationException($"Unknown storage provider '{provider}'."); + } + + /// Uploads to an explicitly captured destination so persisted metadata matches the object. + public async Task UploadAsync( + string key, + Stream content, + string contentType, + Heimdall.Domain.Entities.StorageLocation location, + CancellationToken ct = default) + { + var provider = Resolve(location); try { await provider.UploadAsync(key, content, contentType, ct).ConfigureAwait(false); } finally { DisposeProvider(provider); } } @@ -87,6 +142,14 @@ public sealed class StorageProviderFactory : IStorageProvider finally { DisposeProvider(resolved); } } + /// Deletes using the exact non-secret destination captured on the owning object. + public async Task DeleteAsync(string key, Heimdall.Domain.Entities.StorageLocation location, CancellationToken ct = default) + { + var resolved = Resolve(location); + try { await resolved.DeleteAsync(key, ct).ConfigureAwait(false); } + finally { DisposeProvider(resolved); } + } + public async Task DeleteBatchAsync(IReadOnlyCollection keys, CancellationToken ct = default) { var provider = Resolve(); @@ -104,6 +167,17 @@ public sealed class StorageProviderFactory : IStorageProvider finally { DisposeProvider(provider); } } + /// Deletes a batch from the exact non-secret destination captured on the owning objects. + public async Task DeleteBatchAsync( + IReadOnlyCollection keys, + Heimdall.Domain.Entities.StorageLocation location, + CancellationToken ct = default) + { + var provider = Resolve(location); + try { await provider.DeleteBatchAsync(keys, ct).ConfigureAwait(false); } + finally { DisposeProvider(provider); } + } + public async Task HealthCheckAsync(CancellationToken ct = default) { var provider = Resolve(); @@ -149,6 +223,36 @@ public sealed class StorageProviderFactory : IStorageProvider scope.ServiceProvider.GetRequiredService>()); } + private IStorageProvider Resolve(Heimdall.Domain.Entities.StorageLocation location) + { + ArgumentNullException.ThrowIfNull(location); + if (!location.IsComplete) + throw new InvalidOperationException("Recorded storage location is incomplete; refusing to use current storage settings."); + + using var scope = _services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + if (location.Provider == Heimdall.Domain.Enums.StorageProvider.Local) + return new LocalStorageProvider(location.LocalRoot, + scope.ServiceProvider.GetRequiredService>()); + + if (location.Provider == Heimdall.Domain.Enums.StorageProvider.S3) + { + var s3 = new AlarikStorageProvider( + location.S3Endpoint, + location.S3Bucket, + GetSetting(db, "storage.s3.accessKey"), + GetSetting(db, "storage.s3.secretKey"), + GetSetting(db, "storage.s3.region"), + scope.ServiceProvider.GetRequiredService>()); + if (s3.IsConfigured) + return s3; + s3.Dispose(); + throw new InvalidOperationException("Recorded S3 destination is not configured; refusing to use current storage settings."); + } + + throw new InvalidOperationException($"Unknown recorded storage provider '{location.Provider}'."); + } + private static string? GetSetting(IApplicationDbContext db, string key) { var setting = db.AppSettings diff --git a/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs b/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs index b84c551..bdbb362 100644 --- a/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs +++ b/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs @@ -63,7 +63,8 @@ public class BusinessEntityTests var cameraId = Guid.NewGuid(); var policyId = Guid.NewGuid(); var ts = new DateTime(2026, 7, 1, 12, 0, 0, DateTimeKind.Utc); - var recording = new Recording(cameraId, ts, 60.0, "recordings/2026/07/01/12/cam1.mp4", 10_000_000, StorageProvider.S3, policyId); + var recording = new Recording(cameraId, ts, 60.0, "recordings/2026/07/01/12/cam1.mp4", 10_000_000, + StorageProvider.S3, new StorageLocation(StorageProvider.S3, S3Endpoint: "https://storage.test", S3Bucket: "heimdall"), policyId); recording.CameraId.ShouldBe(cameraId); recording.Timestamp.ShouldBe(ts); @@ -77,7 +78,8 @@ public class BusinessEntityTests [Fact] public void Recording_assign_policy_should_update_relation() { - var recording = new Recording(Guid.NewGuid(), DateTime.UtcNow, 60, "path.mp4", 100, StorageProvider.Local); + var recording = new Recording(Guid.NewGuid(), DateTime.UtcNow, 60, "path.mp4", 100, + StorageProvider.Local, new StorageLocation(StorageProvider.Local, LocalRoot: "/tmp/heimdall-storage")); var policyId = Guid.NewGuid(); recording.AssignStoragePolicy(policyId); diff --git a/tests/Heimdall.Infrastructure.Tests/BusinessEntityPersistenceTests.cs b/tests/Heimdall.Infrastructure.Tests/BusinessEntityPersistenceTests.cs index e8f0545..b4e3631 100644 --- a/tests/Heimdall.Infrastructure.Tests/BusinessEntityPersistenceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/BusinessEntityPersistenceTests.cs @@ -104,7 +104,8 @@ public class BusinessEntityPersistenceTests : IAsyncLifetime db.Vehicles.Add(vehicle); await db.SaveChangesAsync(); - var recording = new Recording(camera.Id, DateTime.UtcNow, 60, "rec/1.mp4", 1000, StorageProvider.S3); + var recording = new Recording(camera.Id, DateTime.UtcNow, 60, "rec/1.mp4", 1000, StorageProvider.S3, + new StorageLocation(StorageProvider.S3, S3Endpoint: "https://storage.test", S3Bucket: "heimdall")); db.Recordings.Add(recording); await db.SaveChangesAsync(); diff --git a/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs b/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs index 865f42b..a4dbb47 100644 --- a/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs @@ -1,5 +1,6 @@ using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; +using Heimdall.Application.Common; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Jobs; @@ -16,6 +17,7 @@ public class RetentionCheckJobTests : IDisposable private readonly SqliteConnection _connection; private readonly TestDbContextFactory _dbFactory; private readonly ILogger _logger = Substitute.For>(); + private readonly IStorageObjectDeletion _storage = Substitute.For(); public RetentionCheckJobTests() { @@ -64,7 +66,8 @@ public class RetentionCheckJobTests : IDisposable { await using var db = await _dbFactory.CreateDbContextAsync(); db.Recordings.Add(new Recording( - cameraId, timestamp, 10.0, $"/recordings/rec-{seq}.mp4", 1000, StorageProvider.S3, policyId)); + cameraId, timestamp, 10.0, $"recordings/rec-{seq}.mp4", 1000, StorageProvider.S3, + new StorageLocation(StorageProvider.S3, S3Endpoint: "https://storage.test", S3Bucket: "heimdall"), policyId)); await db.SaveChangesAsync(); } @@ -77,7 +80,7 @@ public class RetentionCheckJobTests : IDisposable // 10 jours < 30 j → conservé await AddRecordingAsync(cameraId, policyId, DateTime.UtcNow.AddDays(-10), 2); - await new RetentionCheckJob(_dbFactory, _logger).ExecuteAsync(CancellationToken.None); + await new RetentionCheckJob(_dbFactory, _logger, _storage).ExecuteAsync(CancellationToken.None); await using var verify = await _dbFactory.CreateDbContextAsync(); var remaining = await verify.Recordings.ToListAsync(); @@ -91,7 +94,7 @@ public class RetentionCheckJobTests : IDisposable await AddRecordingAsync(cameraId, null, DateTime.UtcNow.AddDays(-45), 3); // > 30 j défaut await AddRecordingAsync(cameraId, null, DateTime.UtcNow.AddDays(-5), 4); // conservé - await new RetentionCheckJob(_dbFactory, _logger).ExecuteAsync(CancellationToken.None); + await new RetentionCheckJob(_dbFactory, _logger, _storage).ExecuteAsync(CancellationToken.None); await using var verify = await _dbFactory.CreateDbContextAsync(); (await verify.Recordings.CountAsync()).ShouldBe(1);