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)); } }