feat(storage): retain known destination inventory #63

Merged
arnaud.dartois merged 2 commits from feat/ops02-storage-destination-inventory into main 2026-10-24 17:36:43 +02:00
9 changed files with 232 additions and 1 deletions

No files matched your search

@@ -35,6 +35,7 @@ public interface IApplicationDbContext
DbSet<Site> Sites { get; }
DbSet<SiteCredential> SiteCredentials { get; }
DbSet<StoragePolicy> StoragePolicies { get; }
DbSet<StorageDestination> StorageDestinations { get; }
DbSet<UserGroup> UserGroups { get; }
DbSet<UserRecoveryCode> UserRecoveryCodes { get; }
DbSet<UserCamera> UserCameras { get; }
@@ -0,0 +1,40 @@
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// 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.
/// </summary>
public sealed class StorageDestination : Entity<Guid>
{
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)
};
}
@@ -80,6 +80,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
public DbSet<Recording> Recordings => Set<Recording>();
public DbSet<LicensePlate> LicensePlates => Set<LicensePlate>();
public DbSet<StoragePolicy> StoragePolicies => Set<StoragePolicy>();
public DbSet<StorageDestination> StorageDestinations => Set<StorageDestination>();
// Analysis job scheduling
public DbSet<AnalysisJob> AnalysisJobs => Set<AnalysisJob>();
@@ -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<StorageDestination>
{
public void Configure(EntityTypeBuilder<StorageDestination> builder)
{
builder.ToTable("storage_destinations");
builder.HasKey(destination => destination.Id);
builder.Property(destination => destination.Provider)
.HasConversion<string>()
.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");
}
}
@@ -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()
@@ -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<Guid>(type: "uuid", nullable: false),
Provider = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
LocalRoot = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: false),
S3Endpoint = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: false),
S3Bucket = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
FirstSeenAt = table.Column<DateTime>(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");
}
@@ -1928,6 +1928,49 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("storage_policies", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("FirstSeenAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("LocalRoot")
.IsRequired()
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("Provider")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<string>("S3Bucket")
.IsRequired()
.HasMaxLength(256)
.IsUnicode(false)
.HasColumnType("character varying(256)");
b.Property<string>("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<Guid>("UserId")
@@ -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;
@@ -99,11 +100,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<IDbContextFactory<AppDbContext>>();
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<Stream?> DownloadAsync(string key, CancellationToken ct = default)
{
var provider = Resolve();
+1 -1
View File
@@ -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.