From 5cf508950f5eae346322035fab01cdfa0b9b8d23 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 17:04:57 +0200 Subject: [PATCH 1/2] feat(storage): retain known destination inventory --- .../Common/IApplicationDbContext.cs | 1 + .../Entities/StorageDestination.cs | 40 ++++++++++++ .../Data/AppDbContext.cs | 1 + .../StorageDestinationConfiguration.cs | 36 +++++++++++ .../Jobs/StorageFinalOrphanCleanupJob.cs | 9 +++ ...24020000_AddStorageDestinationInventory.cs | 64 +++++++++++++++++++ .../Migrations/AppDbContextModelSnapshot.cs | 43 +++++++++++++ .../Storage/StorageProviderFactory.cs | 36 +++++++++++ todo.md | 2 +- 9 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 src/Heimdall.Domain/Entities/StorageDestination.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/StorageDestinationConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261024020000_AddStorageDestinationInventory.cs diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 86d91a3..9e3f679 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -35,6 +35,7 @@ public interface IApplicationDbContext DbSet Sites { get; } DbSet SiteCredentials { get; } DbSet StoragePolicies { get; } + DbSet StorageDestinations { get; } DbSet UserGroups { get; } DbSet UserRecoveryCodes { get; } DbSet UserCameras { get; } diff --git a/src/Heimdall.Domain/Entities/StorageDestination.cs b/src/Heimdall.Domain/Entities/StorageDestination.cs new file mode 100644 index 0000000..41f032b --- /dev/null +++ b/src/Heimdall.Domain/Entities/StorageDestination.cs @@ -0,0 +1,40 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// A non-secret storage location that has held Heimdall objects. +/// Destinations are retained after configuration changes so orphan cleanup can +/// continue to inspect old locations safely. +/// +public sealed class StorageDestination : Entity +{ + public StorageProvider Provider { get; private set; } + public string LocalRoot { get; private set; } = string.Empty; + public string S3Endpoint { get; private set; } = string.Empty; + public string S3Bucket { get; private set; } = string.Empty; + public DateTime FirstSeenAt { get; private set; } + + private StorageDestination() { } + + public StorageDestination(StorageLocation location) : base(Guid.NewGuid()) + { + ArgumentNullException.ThrowIfNull(location); + if (!location.IsComplete) + throw new ArgumentException("Storage destination must be complete.", nameof(location)); + + Provider = location.Provider; + LocalRoot = location.LocalRoot ?? string.Empty; + S3Endpoint = location.S3Endpoint ?? string.Empty; + S3Bucket = location.S3Bucket ?? string.Empty; + FirstSeenAt = DateTime.UtcNow; + } + + public StorageLocation ToLocation() => Provider switch + { + StorageProvider.Local => new StorageLocation(Provider, LocalRoot: LocalRoot), + StorageProvider.S3 => new StorageLocation(Provider, S3Endpoint: S3Endpoint, S3Bucket: S3Bucket), + _ => new StorageLocation(Provider) + }; +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index f5e8ee6..91b2ef6 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -80,6 +80,7 @@ public class AppDbContext : IdentityDbContext, IApplicat public DbSet Recordings => Set(); public DbSet LicensePlates => Set(); public DbSet StoragePolicies => Set(); + public DbSet StorageDestinations => Set(); // Analysis job scheduling public DbSet AnalysisJobs => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/StorageDestinationConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/StorageDestinationConfiguration.cs new file mode 100644 index 0000000..57a7cb3 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/StorageDestinationConfiguration.cs @@ -0,0 +1,36 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public sealed class StorageDestinationConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("storage_destinations"); + builder.HasKey(destination => destination.Id); + builder.Property(destination => destination.Provider) + .HasConversion() + .HasMaxLength(20) + .IsUnicode(false) + .IsRequired(); + builder.Property(destination => destination.LocalRoot) + .HasMaxLength(2000) + .IsUnicode(false) + .IsRequired(); + builder.Property(destination => destination.S3Endpoint) + .HasMaxLength(2000) + .IsUnicode(false) + .IsRequired(); + builder.Property(destination => destination.S3Bucket) + .HasMaxLength(256) + .IsUnicode(false) + .IsRequired(); + builder.Property(destination => destination.FirstSeenAt) + .HasDefaultValueSql("NOW()") + .IsRequired(); + builder.HasIndex(destination => destination.Provider) + .HasDatabaseName("ix_storage_destinations_provider"); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs index 78e2943..c078b34 100644 --- a/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/StorageFinalOrphanCleanupJob.cs @@ -25,6 +25,15 @@ public sealed class StorageFinalOrphanCleanupJob( 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() diff --git a/src/Heimdall.Infrastructure/Migrations/20261024020000_AddStorageDestinationInventory.cs b/src/Heimdall.Infrastructure/Migrations/20261024020000_AddStorageDestinationInventory.cs new file mode 100644 index 0000000..c5addc7 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261024020000_AddStorageDestinationInventory.cs @@ -0,0 +1,64 @@ +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261024020000_AddStorageDestinationInventory")] +public partial class AddStorageDestinationInventory : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "storage_destinations", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Provider = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + LocalRoot = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: false), + S3Endpoint = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: false), + S3Bucket = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + FirstSeenAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()") + }, + constraints: table => table.PrimaryKey("PK_storage_destinations", x => x.Id)); + + migrationBuilder.CreateIndex( + name: "ix_storage_destinations_provider", + table: "storage_destinations", + column: "Provider"); + + migrationBuilder.Sql(""" + INSERT INTO storage_destinations ("Id", "Provider", "LocalRoot", "S3Endpoint", "S3Bucket") + SELECT gen_random_uuid(), "SnapshotStorageProvider", + COALESCE("SnapshotStorageRoot", ''), COALESCE("SnapshotStorageEndpoint", ''), + COALESCE("SnapshotStorageBucket", '') + FROM camera_events + WHERE "SnapshotStorageProvider" IS NOT NULL + AND (("SnapshotStorageProvider" = 'Local' AND COALESCE("SnapshotStorageRoot", '') <> '') + OR ("SnapshotStorageProvider" = 'S3' AND COALESCE("SnapshotStorageEndpoint", '') <> '' + AND COALESCE("SnapshotStorageBucket", '') <> '')) + GROUP BY "SnapshotStorageProvider", COALESCE("SnapshotStorageRoot", ''), + COALESCE("SnapshotStorageEndpoint", ''), COALESCE("SnapshotStorageBucket", ''); + """); + + migrationBuilder.Sql(""" + INSERT INTO storage_destinations ("Id", "Provider", "LocalRoot", "S3Endpoint", "S3Bucket") + SELECT gen_random_uuid(), "StorageProvider", + COALESCE("StorageRoot", ''), COALESCE("StorageEndpoint", ''), COALESCE("StorageBucket", '') + FROM recordings + WHERE "StorageLocationCaptured" = TRUE + AND (("StorageProvider" = 'Local' AND COALESCE("StorageRoot", '') <> '') + OR ("StorageProvider" = 'S3' AND COALESCE("StorageEndpoint", '') <> '' + AND COALESCE("StorageBucket", '') <> '')) + GROUP BY "StorageProvider", COALESCE("StorageRoot", ''), COALESCE("StorageEndpoint", ''), + COALESCE("StorageBucket", ''); + """); + } + + protected override void Down(MigrationBuilder migrationBuilder) + => migrationBuilder.DropTable(name: "storage_destinations"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 639438a..59b66c1 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1928,6 +1928,49 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("storage_policies", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstSeenAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LocalRoot") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("S3Bucket") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("character varying(256)"); + + b.Property("S3Endpoint") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("Provider") + .HasDatabaseName("ix_storage_destinations_provider"); + + b.ToTable("storage_destinations", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => { b.Property("UserId") diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index db782d0..fefc075 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -99,11 +99,47 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat Heimdall.Domain.Entities.StorageLocation location, CancellationToken ct = default) { + await RememberLocationAsync(location, ct).ConfigureAwait(false); var provider = Resolve(location); try { await provider.UploadAsync(key, content, contentType, ct).ConfigureAwait(false); } finally { DisposeProvider(provider); } } + private async Task RememberLocationAsync(Heimdall.Domain.Entities.StorageLocation location, CancellationToken ct) + { + if (!location.IsComplete) + throw new InvalidOperationException("Storage destination is incomplete; refusing to upload an untracked object."); + + var localRoot = location.LocalRoot ?? string.Empty; + var endpoint = location.S3Endpoint ?? string.Empty; + var bucket = location.S3Bucket ?? string.Empty; + await using var scope = _services.CreateAsyncScope(); + var factory = scope.ServiceProvider.GetRequiredService>(); + await using var db = await factory.CreateDbContextAsync(ct).ConfigureAwait(false); + await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false); + var identity = System.Text.Json.JsonSerializer.Serialize(new[] + { + location.Provider.ToString(), localRoot, endpoint, bucket + }); + // The advisory lock makes the read-then-insert idempotent across concurrent + // uploads. A hash collision only serializes unrelated destinations; equality + // is still checked against all stored fields below. + await db.Database.ExecuteSqlInterpolatedAsync( + $"SELECT pg_advisory_xact_lock(hashtextextended({identity}, 0))", ct).ConfigureAwait(false); + var exists = await db.StorageDestinations.AsNoTracking().AnyAsync(destination => + destination.Provider == location.Provider && destination.LocalRoot == localRoot && + destination.S3Endpoint == endpoint && destination.S3Bucket == bucket, ct).ConfigureAwait(false); + if (exists) + { + await transaction.CommitAsync(ct).ConfigureAwait(false); + return; + } + + db.StorageDestinations.Add(new Heimdall.Domain.Entities.StorageDestination(location)); + await db.SaveChangesAsync(ct).ConfigureAwait(false); + await transaction.CommitAsync(ct).ConfigureAwait(false); + } + public async Task DownloadAsync(string key, CancellationToken ct = default) { var provider = Resolve(); diff --git a/todo.md b/todo.md index 9d06b8d..9241ce2 100644 --- a/todo.md +++ b/todo.md @@ -22,7 +22,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** Valider sur caméra réelle capture automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. CI et parcours avec deux agents, timeout/réessai et résultats tardifs restent à valider ; les autres types d'analyse ne sont pas pris en charge. - [ ] **PIPE-10 / FEAT-05** Vérifier une coupure réseau et reprise sans perte ni doublon ; ajouter outbox transactionnelle serveur, état de livraison et limitation par destinataire/canal. Tester SMTP/ntfy réels et échappement HTML. -- [ ] **OPS-02** Correctif en cours : le nettoyage final inclut désormais les références de caméras supprimées logiquement pour ne pas effacer leurs snapshots encore référencés. Restent l'inventaire durable des destinations après suppression des derniers médias, la réconciliation staging/finale et les références historiques sans destination ; ne jamais deviner une destination. Vérifier le changement de provider. +- [ ] **OPS-02** La PR #62 protège les références de caméras supprimées logiquement ; une verticale en cours enregistre les destinations avant upload et les fait parcourir par le nettoyage. Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), le test des anciens stockages inaccessibles et la vérification du changement de provider. - [ ] **OPS-05 / AGENT-06** Installer clés de signature CI et clés publiques indépendantes de Central côté Agent ; tester release réelle, digest/signature, mise à jour native et Docker, arrêt propre et rollback. - [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé. - [ ] **AGENT-09** Mesurer seuils de capture et santé d'enregistrement sous panne caméra/modèle/disque ; rendre alertes et métriques exploitables. -- 2.54.1 From 9bdf0f67a8dab6cce492958e7624c6f9becd1b63 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 17:10:44 +0200 Subject: [PATCH 2/2] fix(storage): resolve database context for registry --- src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index fefc075..d7b8c59 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -1,6 +1,7 @@ using Heimdall.Application.Common; using Heimdall.Application.Common.Persistence; using Heimdall.Infrastructure.Storage; +using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -- 2.54.1