From 5a8dfedaa855fcc524f61b70b80047c6329603d3 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 19:27:04 +0100 Subject: [PATCH 1/2] test(storage): cover cleanup after destination changes --- .../StorageFinalOrphanCleanupJobTests.cs | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs diff --git a/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs b/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs new file mode 100644 index 0000000..f88b308 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs @@ -0,0 +1,133 @@ +using Heimdall.Application.Common.Persistence; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.Infrastructure.Jobs; +using Heimdall.Infrastructure.Storage; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public sealed class StorageFinalOrphanCleanupJobTests : IDisposable +{ + private readonly SqliteConnection _connection = new("DataSource=:memory:"); + private readonly TestDbContextFactory _dbFactory; + private readonly string _root = Path.Combine(Path.GetTempPath(), $"heimdall-orphan-{Guid.NewGuid():N}"); + + public StorageFinalOrphanCleanupJobTests() + { + _connection.Open(); + var options = new DbContextOptionsBuilder().UseSqlite(_connection).Options; + using (var db = new AppDbContext(options, new AuditInterceptor())) + db.Database.EnsureCreated(); + _dbFactory = new TestDbContextFactory(options); + } + + public void Dispose() + { + _connection.Dispose(); + try { Directory.Delete(_root, recursive: true); } catch { /* best effort */ } + GC.SuppressFinalize(this); + } + + [Fact] + public async Task Cleanup_UsesRecordedDestinationAfterCurrentProviderChanges() + { + var oldRoot = Path.Combine(_root, "old"); + var newRoot = Path.Combine(_root, "current"); + var oldLocation = new StorageLocation(StorageProvider.Local, LocalRoot: oldRoot); + var key = await SeedSnapshotAsync(oldLocation); + await SetCurrentLocalStorageAsync(newRoot); + var storedPath = Path.Combine(oldRoot, key.Replace('/', Path.DirectorySeparatorChar)); + File.SetLastWriteTimeUtc(storedPath, DateTime.UtcNow.AddDays(-10)); + + await ExecuteCleanupAsync(); + + File.Exists(storedPath).ShouldBeTrue("a referenced snapshot must survive a storage provider change"); + + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + db.CameraEvents.RemoveRange(await db.CameraEvents.ToListAsync()); + await db.SaveChangesAsync(); + } + + await ExecuteCleanupAsync(); + File.Exists(storedPath).ShouldBeFalse("the old destination remains eligible for orphan cleanup"); + } + + [Fact] + public async Task Cleanup_RetainsDatabaseReferencesWhenHistoricalS3IsUnavailable() + { + var inaccessible = new StorageLocation(StorageProvider.S3, + S3Endpoint: "http://127.0.0.1:1", S3Bucket: "unavailable"); + await SeedSnapshotAsync(inaccessible); + await SetCurrentLocalStorageAsync(Path.Combine(_root, "current")); + + await ExecuteCleanupAsync(); + + await using var db = await _dbFactory.CreateDbContextAsync(); + (await db.CameraEvents.CountAsync()).ShouldBe(1); + (await db.StorageDestinations.CountAsync()).ShouldBe(1); + } + + private async Task SeedSnapshotAsync(StorageLocation location) + { + var eventId = Guid.NewGuid(); + await using var db = await _dbFactory.CreateDbContextAsync(); + var site = new Site("Storage cleanup test"); + db.Sites.Add(site); + await db.SaveChangesAsync(); + var camera = new Camera(site.Id, "Storage cleanup camera", "rtsp://localhost/test"); + db.Cameras.Add(camera); + await db.SaveChangesAsync(); + var key = $"snapshots/{site.Id:D}/{camera.Id:D}/{eventId:N}.jpg"; + var cameraEvent = new CameraEvent(camera.Id, EventType.PersonDetected, 0.9, id: eventId); + cameraEvent.SetStoredSnapshot(key, location); + db.CameraEvents.Add(cameraEvent); + db.StorageDestinations.Add(new StorageDestination(location)); + await db.SaveChangesAsync(); + + if (location.Provider == StorageProvider.Local) + { + var provider = new LocalStorageProvider(location.LocalRoot, + Substitute.For>()); + await provider.UploadAsync(key, new MemoryStream(new byte[] { 1, 2, 3 }), "image/jpeg"); + } + return key; + } + + private async Task SetCurrentLocalStorageAsync(string path) + { + await using var db = await _dbFactory.CreateDbContextAsync(); + db.AppSettings.Add(new AppSetting("storage.provider", "Local")); + db.AppSettings.Add(new AppSetting("storage.local.path", path)); + await db.SaveChangesAsync(); + } + + private async Task ExecuteCleanupAsync() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddScoped(_ => _dbFactory.CreateDbContext()); + services.AddScoped(sp => sp.GetRequiredService()); + using var root = services.BuildServiceProvider(); + var job = new StorageFinalOrphanCleanupJob(_dbFactory, + new StorageProviderFactory(root), Substitute.For>()); + await job.ExecuteAsync(CancellationToken.None); + } + + private sealed class TestDbContextFactory(DbContextOptions options) + : IDbContextFactory + { + private static readonly AuditInterceptor Audit = new(); + public AppDbContext CreateDbContext() => new(options, Audit); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) + => Task.FromResult(new AppDbContext(options, Audit)); + } +} -- 2.54.1 From 864bf026f92e80a0416076e9352198e8a78d1649 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 19:33:16 +0100 Subject: [PATCH 2/2] fix(test): import application storage context contract --- .../StorageFinalOrphanCleanupJobTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs b/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs index f88b308..5a9cf02 100644 --- a/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/StorageFinalOrphanCleanupJobTests.cs @@ -1,4 +1,4 @@ -using Heimdall.Application.Common.Persistence; +using Heimdall.Application.Common; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; -- 2.54.1