fix(storage): record historical object destinations #49
No files matched your search
@@ -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é. |
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -265,7 +265,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
|
||||
{
|
||||
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
|
||||
await using var transaction = await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
|
||||
var (count, bytes) = await GetOutboxSizeAsync(connection, transaction, ct).ConfigureAwait(false);
|
||||
var (count, bytes) = await GetOutboxSizeAsync(connection, (SqliteTransaction)transaction, ct).ConfigureAwait(false);
|
||||
while (count >= MaxPendingEvents || bytes + payloadBytes > MaxOutboxBytes)
|
||||
{
|
||||
var evictedBytes = await EvictOldestMotionEventAsync(connection, transaction, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -325,6 +325,7 @@ internal sealed class ContainerConfig
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Image { get; set; }
|
||||
public string? ImageId { get; set; }
|
||||
public string? User { get; set; }
|
||||
public List<string> Environment { get; set; } = [];
|
||||
public List<string> Ports { get; set; } = [];
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
|
||||
namespace Heimdall.Application.Common;
|
||||
|
||||
/// <summary>Deletes objects from the exact destination persisted with their owning records.</summary>
|
||||
public interface IStorageObjectDeletion
|
||||
{
|
||||
Task DeleteBatchAsync(IReadOnlyCollection<string> keys, StorageLocation location, CancellationToken ct = default);
|
||||
}
|
||||
@@ -15,6 +15,10 @@ public class Recording : Entity<Guid>, 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<Guid>, IAuditableEntity
|
||||
string storagePath,
|
||||
long sizeBytes,
|
||||
StorageProvider storageProvider,
|
||||
StorageLocation storageLocation,
|
||||
Guid? storagePolicyId = null)
|
||||
: base(Guid.NewGuid())
|
||||
{
|
||||
@@ -42,7 +47,20 @@ public class Recording : Entity<Guid>, 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Immutable destination details captured when a stored object is written.
|
||||
/// Credentials remain in the current secret store and are never persisted here.
|
||||
/// </summary>
|
||||
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 => IsSafeEndpoint(S3Endpoint) && !string.IsNullOrWhiteSpace(S3Bucket),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static bool IsSafeEndpoint(string? endpoint) =>
|
||||
Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) &&
|
||||
string.IsNullOrEmpty(uri.UserInfo) &&
|
||||
string.IsNullOrEmpty(uri.Query) &&
|
||||
string.IsNullOrEmpty(uri.Fragment);
|
||||
}
|
||||
@@ -32,6 +32,11 @@ public class RecordingConfiguration : IEntityTypeConfiguration<Recording>
|
||||
.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()");
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ public static class DependencyInjection
|
||||
// chaque résolution → changement UI sans redémarrage).
|
||||
services.AddSingleton<StorageProviderFactory>();
|
||||
services.AddScoped<IStorageProvider>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
||||
services.AddScoped<IStorageObjectDeletion>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
||||
|
||||
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
|
||||
services.AddHealthChecks()
|
||||
|
||||
@@ -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<AppDbContext> _dbFactory;
|
||||
private readonly ILogger<RetentionCheckJob> _logger;
|
||||
private readonly StorageProviderFactory? _storage;
|
||||
private readonly IStorageObjectDeletion _storage;
|
||||
|
||||
public RetentionCheckJob(
|
||||
IDbContextFactory<AppDbContext> dbFactory,
|
||||
ILogger<RetentionCheckJob> 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<Recording>();
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<string>(
|
||||
name: "StorageRoot",
|
||||
table: "recordings",
|
||||
type: "character varying(2000)",
|
||||
maxLength: 2000,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "StorageEndpoint",
|
||||
table: "recordings",
|
||||
type: "character varying(2000)",
|
||||
maxLength: 2000,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "StorageBucket",
|
||||
table: "recordings",
|
||||
type: "character varying(256)",
|
||||
maxLength: 256,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1618,12 +1618,29 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<long>("SizeBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("StorageBucket")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("StorageEndpoint")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("StoragePath")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("StorageRoot")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<bool>("StorageLocationCaptured")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<Guid?>("StoragePolicyId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Domain.Helpers;
|
||||
using Heimdall.Infrastructure.Jobs;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace Heimdall.Infrastructure.Storage;
|
||||
/// (<c>STORAGE__PROVIDER</c>). Reads the DB each resolution so a change made
|
||||
/// in the UI is picked up without restart (broadcast reload on top).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Captures the current destination for persistence alongside an object reference.</summary>
|
||||
public Heimdall.Domain.Entities.StorageLocation CaptureCurrentLocation()
|
||||
{
|
||||
using var scope = _services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
||||
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}'.");
|
||||
}
|
||||
|
||||
/// <summary>Uploads to an explicitly captured destination so persisted metadata matches the object.</summary>
|
||||
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); }
|
||||
}
|
||||
|
||||
/// <summary>Deletes using the exact non-secret destination captured on the owning object.</summary>
|
||||
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<string> keys, CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
@@ -104,6 +167,17 @@ public sealed class StorageProviderFactory : IStorageProvider
|
||||
finally { DisposeProvider(provider); }
|
||||
}
|
||||
|
||||
/// <summary>Deletes a batch from the exact non-secret destination captured on the owning objects.</summary>
|
||||
public async Task DeleteBatchAsync(
|
||||
IReadOnlyCollection<string> 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<bool> HealthCheckAsync(CancellationToken ct = default)
|
||||
{
|
||||
var provider = Resolve();
|
||||
@@ -149,6 +223,36 @@ public sealed class StorageProviderFactory : IStorageProvider
|
||||
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
|
||||
}
|
||||
|
||||
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<IApplicationDbContext>();
|
||||
if (location.Provider == Heimdall.Domain.Enums.StorageProvider.Local)
|
||||
return new LocalStorageProvider(location.LocalRoot,
|
||||
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
|
||||
|
||||
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<ILogger<AlarikStorageProvider>>());
|
||||
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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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<RetentionCheckJob> _logger = Substitute.For<ILogger<RetentionCheckJob>>();
|
||||
private readonly IStorageObjectDeletion _storage = Substitute.For<IStorageObjectDeletion>();
|
||||
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user