diff --git a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs index 130e61e..6973f02 100644 --- a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs @@ -1,5 +1,6 @@ using System.Globalization; using Heimdall.Application.Common; +using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -168,18 +169,32 @@ public class PartitionManagerJob var events = await db.CameraEvents.AsNoTracking() .Where(e => e.OccurredAt >= from && e.OccurredAt < to && (e.SnapshotObjectKey != null || e.SnapshotThumbObjectKey != null)) - .OrderBy(e => e.Id).Skip(offset).Take(batchSize).ToListAsync(ct).ConfigureAwait(false); + .OrderBy(e => e.Id).Skip(offset).Take(batchSize) + .Select(e => new + { + e.Id, e.SnapshotObjectKey, e.SnapshotThumbObjectKey, + e.SnapshotStorageProvider, e.SnapshotStorageRoot, + e.SnapshotStorageEndpoint, e.SnapshotStorageBucket + }).ToListAsync(ct).ConfigureAwait(false); if (events.Count == 0) break; if (_storage is null) throw new InvalidOperationException("Snapshot storage deletion is unavailable"); - var incomplete = events.FirstOrDefault(e => e.GetSnapshotLocation() is null); - if (incomplete is not null) - throw new InvalidOperationException($"Snapshot destination is incomplete for event {incomplete.Id}"); - - foreach (var group in events.GroupBy(e => e.GetSnapshotLocation()!)) - await _storage.DeleteBatchAsync( - group.SelectMany(e => new[] { e.SnapshotObjectKey, e.SnapshotThumbObjectKey }) - .OfType().ToArray(), group.Key, ct).ConfigureAwait(false); + var objectsByLocation = new Dictionary>(); + foreach (var ev in events) + { + if (ev.SnapshotStorageProvider is null) + throw new InvalidOperationException($"Snapshot destination is incomplete for event {ev.Id}"); + var location = new StorageLocation(ev.SnapshotStorageProvider.Value, + ev.SnapshotStorageRoot, ev.SnapshotStorageEndpoint, ev.SnapshotStorageBucket); + if (!location.IsComplete) + throw new InvalidOperationException($"Snapshot destination is incomplete for event {ev.Id}"); + if (!objectsByLocation.TryGetValue(location, out var keys)) + objectsByLocation[location] = keys = []; + if (ev.SnapshotObjectKey is { } snapshot) keys.Add(snapshot); + if (ev.SnapshotThumbObjectKey is { } thumb) keys.Add(thumb); + } + foreach (var (location, keys) in objectsByLocation) + await _storage.DeleteBatchAsync(keys, location, ct).ConfigureAwait(false); offset += events.Count; if (events.Count < batchSize) break; diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 1184e45..4331e7a 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -1,7 +1,9 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR; using System.Reflection; +using System.Text.Json; using Heimdall.Agent.Services; using Heimdall.Application.DTOs; using Heimdall.Application.Security; @@ -75,7 +77,13 @@ public class ConfigReceiverServiceTests builder.Services.AddSignalR(); await using var app = builder.Build(); app.MapHub("/hubs/config"); - app.MapGet("/api/settings/agent/{id}", () => Volatile.Read(ref config)); + app.MapGet("/api/settings/agent/{id}", (HttpContext context) => + { + var snapshot = Volatile.Read(ref config); + context.Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(snapshot); + return Results.Json(snapshot); + }); + app.MapPost("/api/settings/agent/{id}/camera-config-ack", () => Results.NoContent()); await app.StartAsync(); var factory = Substitute.For(); factory.CreateClient("Central").Returns(_ => new HttpClient()); @@ -504,7 +512,7 @@ public class ConfigReceiverServiceTests await service.StopAsync(CancellationToken.None); } - /// Returns a fixed JSON body for any request (used to stub the Central config API). + /// Returns the versioned Central config and accepts its acknowledgement. private sealed class StubHttpMessageHandler : HttpMessageHandler { private readonly string _json; @@ -514,10 +522,14 @@ public class ConfigReceiverServiceTests protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { + if (request.Method == HttpMethod.Post) + return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent)); var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent(_json, System.Text.Encoding.UTF8, "application/json") }; + var settings = JsonSerializer.Deserialize>(_json)!; + response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(settings)); return Task.FromResult(response); } } diff --git a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs index 1edb3f4..3010693 100644 --- a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs @@ -54,7 +54,16 @@ public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres) var unrelatedName = $"camera_events_{old.AddMonths(-2):yyyy_MM}"; #pragma warning disable EF1002 // Test DDL identifiers generated exclusively from dates. await db.Database.ExecuteSqlRawAsync($""" - CREATE TABLE camera_events (occurred_at timestamptz NOT NULL) PARTITION BY RANGE (occurred_at); + CREATE TABLE camera_events ( + "Id" uuid NOT NULL DEFAULT gen_random_uuid(), + "OccurredAt" timestamptz NOT NULL, + "SnapshotObjectKey" text NULL, + "SnapshotThumbObjectKey" text NULL, + "SnapshotStorageProvider" text NULL, + "SnapshotStorageRoot" text NULL, + "SnapshotStorageEndpoint" text NULL, + "SnapshotStorageBucket" text NULL + ) PARTITION BY RANGE ("OccurredAt"); CREATE TABLE "{expiredName}" PARTITION OF camera_events FOR VALUES FROM ('{old:yyyy-MM-dd}') TO ('{old.AddMonths(1):yyyy-MM-dd}'); CREATE TABLE "{boundaryName}" PARTITION OF camera_events FOR VALUES FROM ('{boundary:yyyy-MM-dd}') TO ('{boundary.AddMonths(1):yyyy-MM-dd}'); CREATE TABLE camera_events_bad PARTITION OF camera_events DEFAULT; diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs index 22a105f..351797b 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs @@ -193,12 +193,11 @@ public class PersonDetailPageTests : PageTestBase } [Fact] - public void PersonDetail_HistoriqueFiltreParNom() + public void PersonDetail_HistoriqueFiltreParPersonId() { Handler.OnGet($"api/persons/{PersonId}/faces", new List()); Handler.OnGet("api/vehicles", new List()); - Handler.OnGet("api/events", - new EventPageResult([Ev("Alice Dupont"), Ev("Bob Martin")], 2, 1, 50)); + Handler.OnGet("api/events", new EventPageResult([Ev("Alice Dupont")], 1, 1, 50)); Handler.OnGet("api/persons/", Person()); LoginAs(); @@ -208,6 +207,7 @@ public class PersonDetailPageTests : PageTestBase { cut.Markup.ShouldContain("Alice Dupont"); cut.Markup.ShouldNotContain("Bob Martin"); + Handler.Requests.ShouldContain(r => r.RequestUri!.PathAndQuery.Contains($"personId={PersonId}", StringComparison.OrdinalIgnoreCase)); }); } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs index 847fc85..e9abc13 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs @@ -44,6 +44,7 @@ public class SiteDetailTests : PageTestBase [Fact] public void SiteDetail_GenererToken_AfficheDockerCompose() { + Handler.OnGet("api/updates/latest", AgentRelease()); Handler.OnGet("api/sites/", new SiteItem( SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10))); Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24))); @@ -66,6 +67,7 @@ public class SiteDetailTests : PageTestBase [Fact] public void SiteDetail_CopierDockerCompose_AppellePressePapier() { + Handler.OnGet("api/updates/latest", AgentRelease()); Handler.OnGet("api/sites/", new SiteItem( SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10))); Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24))); @@ -117,6 +119,13 @@ public class SiteDetailTests : PageTestBase LastUsedAt = lastUsed, }; + private static LatestReleaseInfo AgentRelease() => new() + { + Version = "1.0.0", + ContainerImage = "registry.example/heimdall-agent", + ContainerImageDigest = "sha256:" + new string('a', 64) + }; + [Fact] public void SiteDetail_AucunIdentifiant_AfficheMessage() { diff --git a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs index 14f789e..c3db57a 100644 --- a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs +++ b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using NSubstitute; using Shouldly; namespace Heimdall.Web.Tests.Security; @@ -37,6 +38,7 @@ public sealed class HttpIsolationTests builder.Services.AddSingleton(f.Db); builder.Services.AddSingleton(f.Db); builder.Services.AddSingleton(f.Cameras); + builder.Services.AddSingleton(Substitute.For()); builder.Services.AddScoped(); builder.Services.AddMediatR(c => c.RegisterServicesFromAssemblyContaining()); builder.Services.AddControllers(o => o.Filters.Add()).AddApplicationPart(typeof(CamerasController).Assembly);