diff --git a/docs/audits/2026-10-20-audit-complet.md b/docs/audits/2026-10-20-audit-complet.md
index d8ed373..bc1f89a 100644
--- a/docs/audits/2026-10-20-audit-complet.md
+++ b/docs/audits/2026-10-20-audit-complet.md
@@ -4,7 +4,7 @@ Date de l’audit initial : 20 octobre 2026. Révision initiale : `7792353`. La
## État des corrections au 23 octobre 2026
-La revue initiale ci-dessous décrit les constats à la révision `7792353`. Les constats restent utiles pour comprendre le défaut, mais leur état opérationnel est désormais celui de cette matrice. Au 23 octobre, `main` inclut les PR #2–#55; la capture manuelle est traitée par la PR suivante. Les PR #52 et #53 mettent à jour les guides et filtrent la CI pour les changements sans incidence sur le build. Les PR #38–#44 durcissent le diagnostic et l’enrôlement agent, les mises à jour, l’image depuis Central, les rapports de statut et le tri des utilisateurs. La PR #45 traite PIPE-10, la #46 raccorde les détections aux notifications, la #47 sécurise la rétention des recordings, la #49 persiste leur destination historique, la #50 corrige le filtrage par identité dans l’historique et la #51 expose l’état réel de capture dans `/healthz`. Le run #155 a compilé les projets et révélé sept erreurs héritées dans les notifications, l’agent Docker et le spool SQLite; elles ont été corrigées dans la PR #49. Le run #161 a compilé `Heimdall.Agent.dll` après correction de deux erreurs, puis a échoué lors de la copie des runtimes vers les tests faute d’espace disque; aucun test n’a démarré. Les essais #156–#160 ont aussi été interrompus par des erreurs réseau au checkout. Domain compile localement avec SDK 10.0.112; les tests et la compilation complète restent à confirmer sur un runner fonctionnel. Les PR antérieures et leurs résultats restent détaillés ci-dessous; la publication d’une release n’a pas été exercée.
+La revue initiale ci-dessous décrit les constats à la révision `7792353`. Les constats restent utiles pour comprendre le défaut, mais leur état opérationnel est désormais celui de cette matrice. Au 23 octobre, `main` inclut les PR #2–#56, dont la capture manuelle corrélée. Les PR #52 et #53 mettent à jour les guides et filtrent la CI pour les changements sans incidence sur le build. Les PR #38–#44 durcissent le diagnostic et l’enrôlement agent, les mises à jour, l’image depuis Central, les rapports de statut et le tri des utilisateurs. La PR #45 traite PIPE-10, la #46 raccorde les détections aux notifications, la #47 sécurise la rétention des recordings, la #49 persiste leur destination historique, la #50 corrige le filtrage par identité dans l’historique et la #51 expose l’état réel de capture dans `/healthz`. Le run #155 a compilé les projets et révélé sept erreurs héritées dans les notifications, l’agent Docker et le spool SQLite; elles ont été corrigées dans la PR #49. Le run #161 a compilé `Heimdall.Agent.dll` après correction de deux erreurs, puis a échoué lors de la copie des runtimes vers les tests faute d’espace disque; aucun test n’a démarré. Les essais #156–#160 ont aussi été interrompus par des erreurs réseau au checkout. La solution complète compile localement avec SDK 10.0.402 sans avertissement ni erreur; la CI #176 échoue avant checkout car le conteneur runner ne peut pas joindre la forge. La publication d’une release reste à confirmer sur un runner fonctionnel. Les PR antérieures et leurs résultats restent détaillés ci-dessous; la publication d’une release n’a pas été exercée.
| État | Constats | Preuve / réserve |
|---|---|---|
@@ -16,8 +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. |
-| Partiellement corrigé | OPS-02 | PR #49 capture la destination des nouveaux recordings. Le raccordement des snapshots ajoute cette provenance aux nouveaux événements, la lecture depuis l’ancienne destination et la suppression avant effacement d’événement ou de partition. Les références anciennes, les objets staging et les autres médias restent à réconcilier. |
-| Partiellement corrigé | PIPE-09 | PR #54 : la capture issue de l’analyse est conservée avec l’événement dans le spool SQLite, puis téléversée vers une destination enregistrée. Une lecture sous contrôle d’accès caméra remplace les URL publiques pour les nouveaux JPEG. La solution compile avec SDK 10.0.402; 25 tests ciblés et le test d’intégration PostgreSQL passent localement. La capture manuelle corrélée utilise le prochain frame de l'agent, avec livraison par la même boîte d'envoi. Miniatures, état d'échec de la commande et validation sur caméra réelle restent ouverts. |
+| Partiellement corrigé | OPS-02 | PR #49 capture la destination des nouveaux recordings. Le raccordement des snapshots ajoute cette provenance aux nouveaux événements, la lecture depuis l’ancienne destination et la suppression avant effacement d’événement ou de partition. La branche en cours ajoute la purge quotidienne des objets staging âgés de plus de 24 h sur la destination active. Les références anciennes, les destinations antérieures, les objets finaux orphelins et les autres médias restent à réconcilier. |
+| Partiellement corrigé | PIPE-09 | PR #54 : la capture issue de l’analyse est conservée avec l’événement dans le spool SQLite, puis téléversée vers une destination enregistrée. Une lecture sous contrôle d’accès caméra remplace les URL publiques pour les nouveaux JPEG. La solution compile avec SDK 10.0.402; 25 tests ciblés et le test d’intégration PostgreSQL passent localement. La capture manuelle corrélée utilise le prochain frame de l'agent, avec livraison par la même boîte d'envoi. La branche en cours ajoute un statut persistant pour les commandes et leur échec; miniatures et validation sur caméra réelle restent ouverts. |
| Partiellement corrigé | UI-02 | PR #50 ajoute PersonId aux événements, filtre l’historique et les véhicules côté API et charge l’historique par pages. Le détecteur biométrique FEAT-03 devra renseigner PersonId lors de la création des événements pour que les nouvelles détections apparaissent par identité. |
| Partiellement corrigé | AGENT-09 | PR #51 distingue capture et santé d’enregistrement, expose les identifiants caméras en retard, compteurs et date du dernier frame analysé dans `/healthz`. Les seuils et scénarios panne restent à valider sur un agent déployé. |
| Corrigé dans le périmètre documentaire | DOC-01 | Les guides identifient le plan MVP comme historique, pointent vers l’audit comme état courant, décrivent les projets présents et corrigent routes et limites API. Les spécifications plus anciennes restent des descriptions de cible et ne prouvent pas la livraison. |
@@ -216,7 +216,7 @@ Sources : `Agent/Services/DetectionReporterService.cs`, `Web/Controllers/EventsC
L’agent publie les métadonnées mais n’upload pas le JPEG et ne raccorde pas l’image à l’événement. Les providers Upload/Download n’ont pas d’appel métier trouvé. Aucun endpoint de capture/upload/lecture caméra n’est exposé. Le bouton TakeSnapshot affiche seulement un snackbar puis Task.CompletedTask ; RefreshSnapshot relit l’historique.
-Correction en cours : l’agent persiste le JPEG avec la détection et le rejoue après coupure réseau; Central vérifie l’identité agent, borne le corps JPEG, persiste la destination et sert l’image via une route autorisée à la caméra. Les suppressions d’événement et de partition retirent d’abord les objets gérés. Une commande manuelle corrélée demande le prochain frame de l'agent; l'UI suit l'événement par son identifiant. Restent les miniatures, l'état d'échec explicite de la commande, le nettoyage des objets orphelins et la réception sur caméra réelle.
+Correction en cours : l’agent persiste le JPEG avec la détection et le rejoue après coupure réseau; Central vérifie l’identité agent, borne le corps JPEG, persiste la destination et sert l’image via une route autorisée à la caméra. Les suppressions d’événement et de partition retirent d’abord les objets gérés. Une commande manuelle corrélée demande le prochain frame de l'agent; l'UI suit l'événement par son identifiant. Restent les miniatures, les miniatures, le nettoyage des objets finaux orphelins et la réception sur caméra réelle. La branche en cours ajoute le statut durable des demandes et la purge des objets temporaires anciens.
### PIPE-10 — P1 — Événements perdus pendant une indisponibilité réseau — confirmé
diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs
index e5a4ec8..066c3ed 100644
--- a/src/Heimdall.Agent/Services/CameraConfigStore.cs
+++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs
@@ -1,4 +1,3 @@
-using System.Collections.Concurrent;
using System.Text.Json;
using Heimdall.Application.DTOs;
@@ -7,15 +6,16 @@ namespace Heimdall.Agent.Services;
///
/// Holds the camera assignments the agent must capture. The Central is the
/// source of truth: cameras are shipped as flat camera.<id>.name|rtsp|sub_rtsp|enabled
-/// keys through the settings pipeline (full reload + live SettingChanged).
+/// keys through the settings pipeline as one complete, versioned snapshot.
/// A local list from AgentOptions.Cameras serves as a fallback until
/// the first Central config is received.
///
public sealed class CameraConfigStore
{
- private ConcurrentDictionary _central = new();
+ private sealed record CameraSnapshot(IReadOnlyDictionary Cameras, string Version);
+ private CameraSnapshot? _central;
+ private readonly object _updateGate = new();
private IReadOnlyList _localFallback = [];
- private volatile bool _centralReceived;
/// Raised whenever the effective camera list may have changed.
public event EventHandler? Changed;
@@ -28,30 +28,24 @@ public sealed class CameraConfigStore
}
///
- /// Applies a single camera.<id>.<field> setting key received from
- /// the Central. Any such key marks the Central list as authoritative.
+ /// Legacy single-key setter for local callers. Remote updates must use ReplaceCentral.
///
public void ApplyCameraSetting(string key, string value)
{
// camera..
var parts = key.Split('.', 3);
+ if (!key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
+ return;
if (parts.Length != 3 || !Guid.TryParse(parts[1], out var cameraId))
return;
-
- _centralReceived = true;
-
- _central.AddOrUpdate(
- cameraId,
- _ => BuildConfig(cameraId, parts[2], value),
- (_, existing) => existing with
- {
- DetectionProfile = parts[2] == "profile" ? ParseProfile(value) : existing.DetectionProfile,
- Name = parts[2] == "name" ? value : existing.Name,
- RtspUrl = parts[2] == "rtsp" ? value : existing.RtspUrl,
- SubRtspUrl = parts[2] == "sub_rtsp" ? value : existing.SubRtspUrl,
- Enabled = parts[2] == "enabled" ? ParseBool(value) : existing.Enabled,
- });
-
+ lock (_updateGate)
+ {
+ var previous = _central?.Cameras ?? new Dictionary();
+ var next = new Dictionary(previous);
+ next[cameraId] = ApplyField(next.GetValueOrDefault(cameraId) ??
+ new AgentCameraConfig(cameraId, string.Empty, string.Empty, null, true), parts[2], value);
+ Volatile.Write(ref _central, new CameraSnapshot(next, string.Empty));
+ }
RaiseChanged();
}
@@ -61,34 +55,47 @@ public sealed class CameraConfigStore
///
public void MarkCentralReceived()
{
- if (_centralReceived)
+ if (Interlocked.CompareExchange(ref _central,
+ new CameraSnapshot(new Dictionary(), string.Empty), null) is not null)
return;
- _centralReceived = true;
RaiseChanged();
}
/// Atomically replace the authoritative snapshot, including removals.
- public void ReplaceCentral(IReadOnlyDictionary settings)
+ public void ReplaceCentral(IReadOnlyDictionary settings, string? expectedVersion = null)
{
- var replacement = new CameraConfigStore();
+ var version = CameraConfigVersion.Compute(settings);
+ if (expectedVersion is not null && !string.Equals(expectedVersion, version, StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("Camera configuration version mismatch", nameof(expectedVersion));
+ var replacement = new Dictionary();
foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
- replacement.ApplyCameraSetting(setting.Key, setting.Value);
- Interlocked.Exchange(ref _central, replacement._central);
- _centralReceived = true;
+ {
+ var parts = setting.Key.Split('.', 3);
+ if (parts.Length != 3 || !Guid.TryParse(parts[1], out var id))
+ throw new ArgumentException("Invalid camera setting key", nameof(settings));
+ replacement[id] = ApplyField(replacement.GetValueOrDefault(id) ??
+ new AgentCameraConfig(id, string.Empty, string.Empty, null, true), parts[2], setting.Value);
+ }
+ lock (_updateGate)
+ Volatile.Write(ref _central, new CameraSnapshot(replacement, version));
RaiseChanged();
}
/// Effective camera assignments: Central list, or local fallback before that.
public IReadOnlyList Cameras =>
- _centralReceived ? _central.Values.ToArray() : _localFallback;
+ Volatile.Read(ref _central)?.Cameras.Values.ToArray() ?? _localFallback;
- private static AgentCameraConfig BuildConfig(Guid cameraId, string field, string value) => new(
- cameraId,
- field == "name" ? value : string.Empty,
- field == "rtsp" ? value : string.Empty,
- field == "sub_rtsp" ? value : null,
- field == "enabled" ? ParseBool(value) : true,
- field == "profile" ? ParseProfile(value) : null);
+ public string? CurrentVersion => Volatile.Read(ref _central)?.Version;
+
+ private static AgentCameraConfig ApplyField(AgentCameraConfig existing, string field, string value) => field switch
+ {
+ "name" => existing with { Name = value },
+ "rtsp" => existing with { RtspUrl = value },
+ "sub_rtsp" => existing with { SubRtspUrl = value },
+ "enabled" => existing with { Enabled = ParseBool(value) },
+ "profile" => existing with { DetectionProfile = ParseProfile(value) },
+ _ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field))
+ };
private static DetectionProfileDto ParseProfile(string value)
{
@@ -97,8 +104,13 @@ public sealed class CameraConfigStore
return profile;
}
- private static bool ParseBool(string value) =>
- bool.TryParse(value, out var parsed) ? parsed : value is "1" or "true" or "True";
+ private static bool ParseBool(string value) => value switch
+ {
+ "1" => true,
+ "0" => false,
+ _ when bool.TryParse(value, out var parsed) => parsed,
+ _ => throw new ArgumentException("Invalid camera enabled value", nameof(value))
+ };
private void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);
}
diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs
index d3d8668..9f80ced 100644
--- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs
+++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs
@@ -99,25 +99,38 @@ public sealed class ConfigReceiverService : BackgroundService
_connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger());
_connection.On("ManualSnapshotRequested", async (cameraId, requestId) =>
{
- if (requestId == Guid.Empty || !_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled))
- return;
+ if (requestId == Guid.Empty) return;
try
{
+ if (!_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled))
+ {
+ await ReportSnapshotFailureAsync(cameraId, requestId, "camera_unavailable", stoppingToken);
+ return;
+ }
var snapshot = await _streams.CaptureNextFrameAsync(cameraId, stoppingToken).ConfigureAwait(false);
if (snapshot is null)
{
_logger.LogWarning("Manual snapshot request {RequestId} has no active frame for camera {CameraId}", requestId, cameraId);
+ await ReportSnapshotFailureAsync(cameraId, requestId, "no_frame", stoppingToken);
return;
}
if (!await _detectionReporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
occurredAt: snapshot.TimestampUtc, snapshotJpeg: snapshot.JpegData,
eventId: requestId, ct: stoppingToken).ConfigureAwait(false))
+ {
_logger.LogWarning("Manual snapshot request {RequestId} could not be queued", requestId);
+ await ReportSnapshotFailureAsync(cameraId, requestId, "queue_failed", stoppingToken);
+ }
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
catch (Exception ex)
{
_logger.LogWarning(ex, "Manual snapshot request {RequestId} failed", requestId);
+ try { await ReportSnapshotFailureAsync(cameraId, requestId, "agent_error", stoppingToken); }
+ catch (Exception reportError)
+ {
+ _logger.LogWarning(reportError, "Could not report manual snapshot failure {RequestId}", requestId);
+ }
}
});
_connection.On("AgentUpdateRequested", () => _containerInfo.Collect().IsContainer
@@ -129,7 +142,8 @@ public sealed class ConfigReceiverService : BackgroundService
{
// Keys may identify secret settings; never log their values.
_logger.LogInformation("Config update received: {Key}", key);
- if (key == "config.invalidated") await FetchFullConfigAsync(stoppingToken);
+ if (key == "config.invalidated" || key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
+ await FetchFullConfigAsync(stoppingToken);
else ApplySetting(key, value);
});
@@ -194,6 +208,15 @@ public sealed class ConfigReceiverService : BackgroundService
}
}
+ private async Task ReportSnapshotFailureAsync(Guid cameraId, Guid requestId, string code, CancellationToken ct)
+ {
+ using var http = _httpClientFactory.CreateClient("Central");
+ http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
+ var url = $"{_options.CentralUrl.TrimEnd('/')}/api/cameras/{cameraId:D}/snapshot/{requestId:D}/failure";
+ using var response = await http.PutAsJsonAsync(url, new { code }, ct).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ }
+
public override async Task StopAsync(CancellationToken cancellationToken)
{
if (_connection is not null)
@@ -206,8 +229,8 @@ public sealed class ConfigReceiverService : BackgroundService
private void ApplySetting(string key, string value)
{
- // Camera assignments are applied live: the capture pipeline resyncs
- // on every store change (start new streams, stop removed ones).
+ // Remote camera keys are applied only through an authoritative versioned
+ // full snapshot. This branch remains for local callers.
if (key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
{
_cameraStore.ApplyCameraSetting(key, value);
@@ -311,7 +334,7 @@ public sealed class ConfigReceiverService : BackgroundService
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
- var response = await http.GetAsync(url, ct);
+ using var response = await http.GetAsync(url, ct);
if (!response.IsSuccessStatusCode)
{
@@ -326,6 +349,20 @@ public sealed class ConfigReceiverService : BackgroundService
return;
}
+ var version = response.Headers.TryGetValues("X-Camera-Config-Version", out var values)
+ ? values.SingleOrDefault()
+ : null;
+ if (string.IsNullOrWhiteSpace(version))
+ {
+ _logger.LogWarning("Full camera configuration has no version header");
+ return;
+ }
+
+ // Validate and publish all camera fields together before applying
+ // independent agent settings. An invalid camera snapshot leaves the
+ // previously active assignments intact.
+ _cameraStore.ReplaceCentral(config, version);
+
_logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
// Apply every key through the same pipeline as live SettingChanged
@@ -333,11 +370,15 @@ public sealed class ConfigReceiverService : BackgroundService
// documentation, everything.
foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
ApplySetting(kvp.Key, kvp.Value);
- _cameraStore.ReplaceCentral(config);
-
// The Central camera list is authoritative once the full config
// arrives — even if it is empty, drop the local fallback.
_cameraStore.MarkCentralReceived();
+
+ using var ack = await http.PostAsJsonAsync(
+ $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack",
+ new { version }, ct).ConfigureAwait(false);
+ if (!ack.IsSuccessStatusCode)
+ _logger.LogWarning("Camera configuration ACK was rejected: {StatusCode}", ack.StatusCode);
}
catch (Exception ex)
{
diff --git a/src/Heimdall.Application/Agents/AgentExtensions.cs b/src/Heimdall.Application/Agents/AgentExtensions.cs
index 5cfadc6..ca28612 100644
--- a/src/Heimdall.Application/Agents/AgentExtensions.cs
+++ b/src/Heimdall.Application/Agents/AgentExtensions.cs
@@ -30,5 +30,6 @@ public static class AgentExtensions
// Container info
a.ContainerId, a.ContainerImage,
// Network & Temperature
- a.NetworkInterfacesJson, a.TemperatureJson);
+ a.NetworkInterfacesJson, a.TemperatureJson,
+ a.LastAppliedCameraConfigVersion, a.LastAppliedCameraConfigAt);
}
diff --git a/src/Heimdall.Application/Agents/Commands/AcknowledgeCameraConfig/AcknowledgeCameraConfigCommand.cs b/src/Heimdall.Application/Agents/Commands/AcknowledgeCameraConfig/AcknowledgeCameraConfigCommand.cs
new file mode 100644
index 0000000..5d3850b
--- /dev/null
+++ b/src/Heimdall.Application/Agents/Commands/AcknowledgeCameraConfig/AcknowledgeCameraConfigCommand.cs
@@ -0,0 +1,19 @@
+using Heimdall.Application.Common;
+using MediatR;
+
+namespace Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig;
+
+public sealed record AcknowledgeCameraConfigCommand(Guid AgentId, string Version) : IRequest;
+
+public sealed class AcknowledgeCameraConfigHandler(IApplicationDbContext db)
+ : IRequestHandler
+{
+ public async Task Handle(AcknowledgeCameraConfigCommand request, CancellationToken ct)
+ {
+ var agent = await db.Agents.FindAsync([request.AgentId], ct).ConfigureAwait(false);
+ if (agent is null || agent.IsDeleted) return false;
+ agent.AcknowledgeCameraConfig(request.Version, DateTime.UtcNow);
+ await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
+ return true;
+ }
+}
diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs
index ba81e2e..0650128 100644
--- a/src/Heimdall.Application/Common/IApplicationDbContext.cs
+++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs
@@ -18,6 +18,7 @@ public interface IApplicationDbContext
DbSet CameraDetectionProfiles { get; }
DbSet CameraDiscoveryResults { get; }
DbSet CameraEvents { get; }
+ DbSet ManualSnapshotRequests { get; }
DbSet DiscoveredStreams { get; }
// Notification entities
diff --git a/src/Heimdall.Application/Common/IStorageProvider.cs b/src/Heimdall.Application/Common/IStorageProvider.cs
index b882741..3eda92e 100644
--- a/src/Heimdall.Application/Common/IStorageProvider.cs
+++ b/src/Heimdall.Application/Common/IStorageProvider.cs
@@ -26,6 +26,9 @@ public interface IStorageProvider
/// Delete a batch of objects (S3: 1000/appel).
Task DeleteBatchAsync(IReadOnlyCollection keys, CancellationToken ct = default);
+ /// Remove abandoned temporary uploads older than the cutoff.
+ Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default);
+
/// Check reachability/health of the backend.
Task HealthCheckAsync(CancellationToken ct = default);
}
diff --git a/src/Heimdall.Application/DTOs/AgentDto.cs b/src/Heimdall.Application/DTOs/AgentDto.cs
index 29a8314..09febbb 100644
--- a/src/Heimdall.Application/DTOs/AgentDto.cs
+++ b/src/Heimdall.Application/DTOs/AgentDto.cs
@@ -116,7 +116,9 @@ public record AgentResponse(
string? ContainerImage = null,
// Network & Temperature (JSON)
string? NetworkInterfacesJson = null,
- string? TemperatureJson = null) : AgentTelemetryFields(
+ string? TemperatureJson = null,
+ string? LastAppliedCameraConfigVersion = null,
+ DateTime? LastAppliedCameraConfigAt = null) : AgentTelemetryFields(
CpuUsagePercent, MemoryUsageBytes, DiskUsagePercent, UptimeSeconds,
CpuVendor, CpuModel, CpuArchitecture, PhysicalCores, LogicalCores,
ThreadsPerCore, CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit,
diff --git a/src/Heimdall.Application/DTOs/CameraConfigVersion.cs b/src/Heimdall.Application/DTOs/CameraConfigVersion.cs
new file mode 100644
index 0000000..a2cd420
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/CameraConfigVersion.cs
@@ -0,0 +1,30 @@
+using System.Buffers.Binary;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Heimdall.Application.DTOs;
+
+/// A stable version of the complete camera portion of an agent configuration.
+public static class CameraConfigVersion
+{
+ public static string Compute(IReadOnlyDictionary settings)
+ {
+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ foreach (var entry in settings.Where(x => x.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
+ .OrderBy(x => x.Key, StringComparer.Ordinal))
+ {
+ Append(entry.Key);
+ Append(entry.Value);
+ }
+ return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
+
+ void Append(string value)
+ {
+ var bytes = Encoding.UTF8.GetBytes(value);
+ Span length = stackalloc byte[sizeof(int)];
+ BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length);
+ hash.AppendData(length);
+ hash.AppendData(bytes);
+ }
+ }
+}
diff --git a/src/Heimdall.Application/DTOs/DetectionProfileDto.cs b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs
index 6eafacb..312a862 100644
--- a/src/Heimdall.Application/DTOs/DetectionProfileDto.cs
+++ b/src/Heimdall.Application/DTOs/DetectionProfileDto.cs
@@ -1,6 +1,9 @@
+using System.Text.Json.Serialization;
+
namespace Heimdall.Application.DTOs;
/// Version 1 supports COCO object detection and a normalized pixel motion gate.
+[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record DetectionProfileDto
{
public int Version { get; init; } = 1;
diff --git a/src/Heimdall.Domain/Entities/Agent.cs b/src/Heimdall.Domain/Entities/Agent.cs
index 6343495..88dd0b6 100644
--- a/src/Heimdall.Domain/Entities/Agent.cs
+++ b/src/Heimdall.Domain/Entities/Agent.cs
@@ -11,6 +11,8 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable
public string Version { get; private set; } = string.Empty;
public AgentStatus Status { get; private set; } = AgentStatus.Offline;
public DateTime? LastHeartbeat { get; private set; }
+ public string? LastAppliedCameraConfigVersion { get; private set; }
+ public DateTime? LastAppliedCameraConfigAt { get; private set; }
public string? PublicIp { get; private set; }
/// HMACSHA256 hash of the agent's API key.
@@ -116,6 +118,16 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable
PublicIp = publicIp;
}
+ public void AcknowledgeCameraConfig(string version, DateTime appliedAtUtc)
+ {
+ if (version.Length != 64 || !version.All(Uri.IsHexDigit))
+ throw new ArgumentException("Invalid camera configuration version", nameof(version));
+ if (appliedAtUtc.Kind != DateTimeKind.Utc)
+ throw new ArgumentException("Acknowledgement time must be UTC", nameof(appliedAtUtc));
+ LastAppliedCameraConfigVersion = version.ToLowerInvariant();
+ LastAppliedCameraConfigAt = appliedAtUtc;
+ }
+
public void UpdateLiveMetrics(
double? cpuUsagePercent,
long? memoryUsageBytes,
diff --git a/src/Heimdall.Domain/Entities/ManualSnapshotRequest.cs b/src/Heimdall.Domain/Entities/ManualSnapshotRequest.cs
new file mode 100644
index 0000000..e9bcea5
--- /dev/null
+++ b/src/Heimdall.Domain/Entities/ManualSnapshotRequest.cs
@@ -0,0 +1,54 @@
+using Heimdall.Domain.Enums;
+
+namespace Heimdall.Domain.Entities;
+
+/// Durable outcome of a user-requested frame capture.
+public sealed class ManualSnapshotRequest
+{
+ private ManualSnapshotRequest() { }
+
+ public ManualSnapshotRequest(Guid id, Guid cameraId, Guid agentId, DateTime now)
+ {
+ if (id == Guid.Empty || cameraId == Guid.Empty || agentId == Guid.Empty)
+ throw new ArgumentException("Snapshot request identifiers must be set.");
+ Id = id;
+ CameraId = cameraId;
+ AgentId = agentId;
+ CreatedAt = now;
+ UpdatedAt = now;
+ ExpiresAt = now.AddSeconds(30);
+ }
+
+ public Guid Id { get; private set; }
+ public Guid CameraId { get; private set; }
+ public Guid AgentId { get; private set; }
+ public ManualSnapshotStatus Status { get; private set; } = ManualSnapshotStatus.Pending;
+ public string? FailureReason { get; private set; }
+ public DateTime CreatedAt { get; private set; }
+ public DateTime UpdatedAt { get; private set; }
+ public DateTime ExpiresAt { get; private set; }
+
+ public void Fail(string reason, DateTime now)
+ {
+ if (Status == ManualSnapshotStatus.Completed) return;
+ Status = ManualSnapshotStatus.Failed;
+ FailureReason = reason;
+ UpdatedAt = now;
+ }
+
+ public void Complete(DateTime now)
+ {
+ Status = ManualSnapshotStatus.Completed;
+ FailureReason = null;
+ UpdatedAt = now;
+ }
+
+ public bool TimeoutIfExpired(DateTime now)
+ {
+ if (Status != ManualSnapshotStatus.Pending || now < ExpiresAt) return false;
+ Status = ManualSnapshotStatus.TimedOut;
+ FailureReason = "La capture n'a pas été livrée dans le délai attendu.";
+ UpdatedAt = now;
+ return true;
+ }
+}
diff --git a/src/Heimdall.Domain/Enums/ManualSnapshotStatus.cs b/src/Heimdall.Domain/Enums/ManualSnapshotStatus.cs
new file mode 100644
index 0000000..edc044e
--- /dev/null
+++ b/src/Heimdall.Domain/Enums/ManualSnapshotStatus.cs
@@ -0,0 +1,9 @@
+namespace Heimdall.Domain.Enums;
+
+public enum ManualSnapshotStatus
+{
+ Pending,
+ Completed,
+ Failed,
+ TimedOut
+}
diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs
index 5a933a4..9898d26 100644
--- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs
+++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs
@@ -32,6 +32,16 @@ public static class JobSetup
job => job.ExecuteAsync(CancellationToken.None),
"0 4 * * *"); // Daily at 4:00 — purge logs > retention (7 j par défaut)
+ manager.AddOrUpdate(
+ "storage-staging-cleanup",
+ job => job.ExecuteAsync(CancellationToken.None),
+ "30 4 * * *");
+
+ manager.AddOrUpdate(
+ "manual-snapshot-request-cleanup",
+ job => job.ExecuteAsync(CancellationToken.None),
+ "45 4 * * *");
+
// Maintenance (spec 7.5) — rétention, faces, plaques, DB.
manager.AddOrUpdate(
"retention-check",
diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs
index 0302179..f5e8ee6 100644
--- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs
+++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs
@@ -50,6 +50,7 @@ public class AppDbContext : IdentityDbContext, IApplicat
// Event entities
public DbSet CameraEvents => Set();
+ public DbSet ManualSnapshotRequests => Set();
// Notification entities
public DbSet Notifications => Set();
diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs
index 01c9c0b..469b172 100644
--- a/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs
+++ b/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs
@@ -44,6 +44,10 @@ public class AgentConfiguration : IEntityTypeConfiguration
.HasMaxLength(8)
.IsUnicode(false);
+ builder.Property(a => a.LastAppliedCameraConfigVersion)
+ .HasMaxLength(64)
+ .IsUnicode(false);
+
builder.Property(a => a.GpuType)
.HasConversion()
.HasMaxLength(20)
diff --git a/src/Heimdall.Infrastructure/Data/Configurations/ManualSnapshotRequestConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/ManualSnapshotRequestConfiguration.cs
new file mode 100644
index 0000000..a3f1e2a
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Data/Configurations/ManualSnapshotRequestConfiguration.cs
@@ -0,0 +1,21 @@
+using Heimdall.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Heimdall.Infrastructure.Data.Configurations;
+
+public sealed class ManualSnapshotRequestConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("manual_snapshot_requests");
+ builder.HasKey(x => x.Id);
+ builder.Property(x => x.Status).HasConversion().HasMaxLength(20).IsRequired();
+ builder.Property(x => x.FailureReason).HasMaxLength(200);
+ builder.Property(x => x.CreatedAt).IsRequired();
+ builder.Property(x => x.UpdatedAt).IsRequired();
+ builder.Property(x => x.ExpiresAt).IsRequired();
+ builder.HasIndex(x => new { x.CameraId, x.CreatedAt });
+ builder.HasIndex(x => x.ExpiresAt);
+ }
+}
diff --git a/src/Heimdall.Infrastructure/Jobs/ManualSnapshotRequestCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/ManualSnapshotRequestCleanupJob.cs
new file mode 100644
index 0000000..18e9a6d
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Jobs/ManualSnapshotRequestCleanupJob.cs
@@ -0,0 +1,30 @@
+using Heimdall.Infrastructure.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+
+namespace Heimdall.Infrastructure.Jobs;
+
+/// Bounds the history of manual capture commands independently of camera events.
+public sealed class ManualSnapshotRequestCleanupJob
+{
+ private readonly IDbContextFactory _dbFactory;
+ private readonly ILogger _logger;
+
+ public ManualSnapshotRequestCleanupJob(IDbContextFactory dbFactory,
+ ILogger logger)
+ {
+ _dbFactory = dbFactory;
+ _logger = logger;
+ }
+
+ public async Task ExecuteAsync(CancellationToken ct)
+ {
+ await using var db = await _dbFactory.CreateDbContextAsync(ct);
+ var cutoff = DateTime.UtcNow.AddDays(-30);
+ var count = await db.ManualSnapshotRequests
+ .Where(r => r.CreatedAt < cutoff)
+ .ExecuteDeleteAsync(ct).ConfigureAwait(false);
+ if (count > 0)
+ _logger.LogInformation("Removed {Count} old manual snapshot requests", count);
+ }
+}
diff --git a/src/Heimdall.Infrastructure/Jobs/StorageStagingCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/StorageStagingCleanupJob.cs
new file mode 100644
index 0000000..522666d
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Jobs/StorageStagingCleanupJob.cs
@@ -0,0 +1,26 @@
+using Heimdall.Infrastructure.Storage;
+using Microsoft.Extensions.Logging;
+
+namespace Heimdall.Infrastructure.Jobs;
+
+/// Removes temporary uploads left behind by interrupted writes.
+public sealed class StorageStagingCleanupJob
+{
+ private readonly StorageProviderFactory _storage;
+ private readonly ILogger _logger;
+
+ public StorageStagingCleanupJob(StorageProviderFactory storage, ILogger logger)
+ {
+ _storage = storage;
+ _logger = logger;
+ }
+
+ public async Task ExecuteAsync(CancellationToken ct)
+ {
+ // A long grace period avoids racing a slow in-flight upload.
+ var cutoff = DateTime.UtcNow.AddDays(-1);
+ var count = await _storage.CleanupStagingAsync(cutoff, ct).ConfigureAwait(false);
+ if (count > 0)
+ _logger.LogInformation("Removed {Count} abandoned staging objects", count);
+ }
+}
diff --git a/src/Heimdall.Infrastructure/Migrations/20261023010000_AddManualSnapshotRequests.cs b/src/Heimdall.Infrastructure/Migrations/20261023010000_AddManualSnapshotRequests.cs
new file mode 100644
index 0000000..71a1969
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Migrations/20261023010000_AddManualSnapshotRequests.cs
@@ -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("20261023010000_AddManualSnapshotRequests")]
+public partial class AddManualSnapshotRequests : Migration
+{
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "LastAppliedCameraConfigAt",
+ table: "agents",
+ type: "timestamp with time zone",
+ nullable: true);
+ migrationBuilder.AddColumn(
+ name: "LastAppliedCameraConfigVersion",
+ table: "agents",
+ type: "character varying(64)",
+ maxLength: 64,
+ nullable: true);
+
+ migrationBuilder.CreateTable(
+ name: "manual_snapshot_requests",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ CameraId = table.Column(type: "uuid", nullable: false),
+ AgentId = table.Column(type: "uuid", nullable: false),
+ Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false),
+ FailureReason = table.Column(type: "character varying(200)", maxLength: 200, nullable: true),
+ CreatedAt = table.Column(type: "timestamp with time zone", nullable: false),
+ UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false),
+ ExpiresAt = table.Column(type: "timestamp with time zone", nullable: false)
+ },
+ constraints: table => table.PrimaryKey("PK_manual_snapshot_requests", x => x.Id));
+ migrationBuilder.CreateIndex("IX_manual_snapshot_requests_CameraId_CreatedAt", "manual_snapshot_requests", new[] { "CameraId", "CreatedAt" });
+ migrationBuilder.CreateIndex("IX_manual_snapshot_requests_ExpiresAt", "manual_snapshot_requests", "ExpiresAt");
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable("manual_snapshot_requests");
+ migrationBuilder.DropColumn("LastAppliedCameraConfigAt", "agents");
+ migrationBuilder.DropColumn("LastAppliedCameraConfigVersion", "agents");
+ }
+}
diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs
index 5eb0043..5490d57 100644
--- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs
+++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs
@@ -123,6 +123,14 @@ namespace Heimdall.Infrastructure.Migrations
b.Property("KernelVersion")
.HasColumnType("text");
+ b.Property("LastAppliedCameraConfigAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastAppliedCameraConfigVersion")
+ .HasMaxLength(64)
+ .IsUnicode(false)
+ .HasColumnType("character varying(64)");
+
b.Property("LastHeartbeat")
.HasColumnType("timestamp with time zone");
@@ -1456,6 +1464,44 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("login_challenges", (string)null);
});
+ modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("FailureReason")
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CameraId", "CreatedAt");
+
+ b.HasIndex("ExpiresAt");
+
+ b.ToTable("manual_snapshot_requests", (string)null);
+ });
+
modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b =>
{
b.Property("Id")
diff --git a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs
index 941a236..65d2335 100644
--- a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs
+++ b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs
@@ -143,6 +143,32 @@ public sealed class AlarikStorageProvider : IStorageProvider, IDisposable
}
}
+ public async Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default)
+ {
+ if (_client is null)
+ throw new InvalidOperationException("Alarik/S3 storage is not configured");
+
+ var deleted = 0;
+ string? continuationToken = null;
+ do
+ {
+ var page = await _client.ListObjectsV2Async(new ListObjectsV2Request
+ {
+ BucketName = _bucket,
+ Prefix = "staging/",
+ ContinuationToken = continuationToken,
+ }, ct).ConfigureAwait(false);
+ var expired = page.S3Objects
+ .Where(obj => obj.LastModified is DateTime modified && modified.ToUniversalTime() < olderThanUtc)
+ .Select(obj => obj.Key)
+ .ToArray();
+ await DeleteBatchAsync(expired, ct).ConfigureAwait(false);
+ deleted += expired.Length;
+ continuationToken = page.IsTruncated == true ? page.NextContinuationToken : null;
+ } while (continuationToken is not null);
+ return deleted;
+ }
+
public async Task HealthCheckAsync(CancellationToken ct = default)
{
if (_client is null)
diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs
index b4f87dd..f6bbd5f 100644
--- a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs
+++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs
@@ -107,6 +107,48 @@ public sealed class LocalStorageProvider : IStorageProvider
}
}
+ public Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default)
+ {
+ if (!Directory.Exists(_root))
+ return Task.FromResult(0);
+
+ EnsureNoLinks(_root);
+ var deleted = 0;
+ var pending = new Stack();
+ pending.Push(_root);
+ while (pending.Count > 0)
+ {
+ ct.ThrowIfCancellationRequested();
+ var directory = pending.Pop();
+ EnsureNoLinks(directory);
+ foreach (var entry in Directory.EnumerateFileSystemEntries(directory))
+ {
+ ct.ThrowIfCancellationRequested();
+ // Never follow a link, including a dangling link.
+ if (new FileInfo(entry).LinkTarget is not null ||
+ (File.GetAttributes(entry) & FileAttributes.ReparsePoint) != 0)
+ continue;
+ if (Directory.Exists(entry))
+ {
+ pending.Push(entry);
+ continue;
+ }
+ var name = Path.GetFileName(entry);
+ var marker = name.LastIndexOf(".tmp-", StringComparison.Ordinal);
+ if (marker < 1 || name.Length != marker + 5 + 32 ||
+ !Guid.TryParseExact(name[(marker + 5)..], "N", out _))
+ continue;
+ var info = new FileInfo(entry);
+ if (info.LastWriteTimeUtc >= olderThanUtc)
+ continue;
+ EnsureNoLinks(entry);
+ File.Delete(entry);
+ deleted++;
+ }
+ }
+ return Task.FromResult(deleted);
+ }
+
public Task HealthCheckAsync(CancellationToken ct = default)
{
try
diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs
index 74a035f..a330408 100644
--- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs
+++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs
@@ -209,6 +209,13 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat
finally { DisposeProvider(provider); }
}
+ public async Task CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default)
+ {
+ var provider = Resolve();
+ try { return await provider.CleanupStagingAsync(olderThanUtc, ct).ConfigureAwait(false); }
+ finally { DisposeProvider(provider); }
+ }
+
private static void DisposeProvider(IStorageProvider provider) => (provider as IDisposable)?.Dispose();
private IStorageProvider Resolve(string? providerOverride = null)
diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor
index a86b4cb..67855ee 100644
--- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor
+++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor
@@ -316,19 +316,25 @@ else
}
Snackbar.Add("Capture demandée à l'agent", Severity.Info);
- for (var attempt = 0; attempt < 15 && !_disposed; attempt++)
+ for (var attempt = 0; attempt < 35 && !_disposed; attempt++)
{
await Task.Delay(TimeSpan.FromSeconds(1));
- var events = await Api.GetRecentEventsAsync(Id, 10);
- var snapshot = events?.FirstOrDefault(e => e.Id == request.Data && !string.IsNullOrEmpty(e.SnapshotUrl));
- if (snapshot is null) continue;
+ var status = await Api.GetCameraSnapshotStatusAsync(Id, request.Data);
+ if (status?.Status is "Failed" or "TimedOut")
+ {
+ Snackbar.Add(status.Reason ?? "La capture a échoué.", Severity.Error);
+ return;
+ }
+ if (status?.Status != "Completed") continue;
+ var snapshot = await Api.GetEventAsync(request.Data);
+ if (snapshot is null || string.IsNullOrEmpty(snapshot.SnapshotUrl)) continue;
_latestSnapshotUrl = snapshot.SnapshotThumbUrl ?? snapshot.SnapshotUrl;
_latestSnapshotAt = snapshot.OccurredAt;
await LoadEventsAsync();
Snackbar.Add("Snapshot disponible", Severity.Success);
return;
}
- Snackbar.Add("Capture en cours ; elle apparaîtra dans l'historique dès sa livraison", Severity.Info);
+ Snackbar.Add("Le résultat de la capture est encore en attente ; actualisez la page pour le consulter.", Severity.Info);
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally
diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs
index d4d32a8..cc3e8c8 100644
--- a/src/Heimdall.Web/Controllers/CamerasController.cs
+++ b/src/Heimdall.Web/Controllers/CamerasController.cs
@@ -7,6 +7,7 @@ using Heimdall.Application.Cameras.Queries.GetCamera;
using Heimdall.Application.Cameras.Queries.GetCamerasBySite;
using Heimdall.Application.DTOs;
using Heimdall.Application.Common;
+using Heimdall.Domain.Entities;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
@@ -46,11 +47,67 @@ public class CamerasController : ControllerBase
if (camera.Status != CameraStatus.Online) return Conflict(new { error = "The camera is not online" });
if (camera.AgentId is null) return Conflict(new { error = "No agent is assigned to this camera" });
var requestId = Guid.NewGuid();
+ var snapshotRequest = new ManualSnapshotRequest(requestId, id, camera.AgentId.Value, DateTime.UtcNow);
+ _db.ManualSnapshotRequests.Add(snapshotRequest);
+ await _db.SaveChangesWithRetryAsync(ct: ct);
if (!await _broadcast.RequestManualSnapshot(camera.AgentId.Value, id, requestId, ct))
+ {
+ snapshotRequest.Fail("L'agent affecté est indisponible.", DateTime.UtcNow);
+ await _db.SaveChangesWithRetryAsync(ct: ct);
return Conflict(new { error = "The assigned agent is offline" });
+ }
return Accepted(new { requestId });
}
+ /// Read the durable outcome of a manual capture request.
+ [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
+ [HttpGet("{id:guid}/snapshot/{requestId:guid}")]
+ public async Task GetSnapshotRequest(Guid id, Guid requestId, CancellationToken ct)
+ {
+ var request = await _db.ManualSnapshotRequests.AsNoTracking()
+ .FirstOrDefaultAsync(r => r.Id == requestId && r.CameraId == id, ct);
+ if (request is null) return NotFound();
+ if (request.Status == ManualSnapshotStatus.Pending && request.ExpiresAt <= DateTime.UtcNow)
+ {
+ await _db.ManualSnapshotRequests
+ .Where(r => r.Id == requestId && r.Status == ManualSnapshotStatus.Pending && r.ExpiresAt <= DateTime.UtcNow)
+ .ExecuteUpdateAsync(setters => setters
+ .SetProperty(r => r.Status, ManualSnapshotStatus.TimedOut)
+ .SetProperty(r => r.FailureReason, "La capture n'a pas été livrée dans le délai attendu.")
+ .SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
+ request = await _db.ManualSnapshotRequests.AsNoTracking()
+ .FirstAsync(r => r.Id == requestId, ct);
+ }
+ return Ok(new { requestId = request.Id, status = request.Status.ToString(),
+ reason = request.FailureReason, updatedAt = request.UpdatedAt });
+ }
+
+ /// Record a capture failure reported by the agent assigned when the command was issued.
+ [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
+ [HttpPut("{id:guid}/snapshot/{requestId:guid}/failure")]
+ public async Task FailSnapshotRequest(Guid id, Guid requestId,
+ [FromBody] ManualSnapshotFailure failure, CancellationToken ct)
+ {
+ var exists = await _db.ManualSnapshotRequests.AnyAsync(r => r.Id == requestId && r.CameraId == id, ct);
+ if (!exists) return NotFound();
+ var reason = failure.Code switch
+ {
+ "camera_unavailable" => "La caméra n'est plus affectée ou est désactivée sur l'agent.",
+ "no_frame" => "Aucune image n'a été reçue du flux de la caméra.",
+ "queue_failed" => "L'agent n'a pas pu enregistrer la capture pour livraison.",
+ _ => "La capture a échoué sur l'agent."
+ };
+ await _db.ManualSnapshotRequests
+ .Where(r => r.Id == requestId && r.CameraId == id && r.Status != ManualSnapshotStatus.Completed)
+ .ExecuteUpdateAsync(setters => setters
+ .SetProperty(r => r.Status, ManualSnapshotStatus.Failed)
+ .SetProperty(r => r.FailureReason, reason)
+ .SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
+ return NoContent();
+ }
+
+ public sealed record ManualSnapshotFailure(string Code);
+
/// Create a new camera.
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost]
diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs
index fc0d7cc..cde5941 100644
--- a/src/Heimdall.Web/Controllers/EventsController.cs
+++ b/src/Heimdall.Web/Controllers/EventsController.cs
@@ -133,7 +133,11 @@ public class EventsController : ControllerBase
var ev = await _db.CameraEvents.FirstOrDefaultAsync(e => e.Id == id, ct);
if (ev is null) return NotFound();
- if (ev.SnapshotObjectKey is not null) return Ok(new { url = ev.SnapshotUrl });
+ if (ev.SnapshotObjectKey is not null)
+ {
+ await CompleteManualSnapshotRequestAsync(ev, ct);
+ return Ok(new { url = ev.SnapshotUrl });
+ }
var mediaType = Request.ContentType?.Split(';')[0].Trim();
if (!string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase))
@@ -164,6 +168,10 @@ public class EventsController : ControllerBase
try
{
ev.SetStoredSnapshot(key, location);
+ var manualRequest = ev.Type == EventType.ManualSnapshot
+ ? await _db.ManualSnapshotRequests.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct)
+ : null;
+ manualRequest?.Complete(DateTime.UtcNow);
await _db.SaveChangesWithRetryAsync(ct: ct);
}
catch
@@ -175,6 +183,16 @@ public class EventsController : ControllerBase
return Ok(new { url = ev.SnapshotUrl });
}
+ private async Task CompleteManualSnapshotRequestAsync(Heimdall.Domain.Entities.CameraEvent ev, CancellationToken ct)
+ {
+ if (ev.Type != EventType.ManualSnapshot) return;
+ var request = await _db.ManualSnapshotRequests
+ .FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct);
+ if (request is null || request.Status == ManualSnapshotStatus.Completed) return;
+ request.Complete(DateTime.UtcNow);
+ await _db.SaveChangesWithRetryAsync(ct: ct);
+ }
+
/// Stream a stored JPEG only to a user allowed to read its camera.
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}/snapshot/content")]
diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs
index 898700e..e3f7472 100644
--- a/src/Heimdall.Web/Controllers/SettingsController.cs
+++ b/src/Heimdall.Web/Controllers/SettingsController.cs
@@ -1,4 +1,5 @@
using Heimdall.Application.Agents.Queries.GetAgent;
+using Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
@@ -138,7 +139,7 @@ public class SettingsController : ControllerBase
///
/// Get the effective configuration for an agent: global defaults merged with
/// per-agent overrides, plus the site's camera credential pool inside an
- /// encrypted envelope. Accessible by the agent itself (API key, same site)
+ /// encrypted envelope. Accessible by the agent itself (API key)
/// or by an admin (JWT/Cookie).
///
[Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")]
@@ -147,10 +148,13 @@ public class SettingsController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct)
{
- // API key callers: the agent may only read its own site's config.
+ // The API key is bound to exactly one agent. Same-site agents must not
+ // be able to read each other's RTSP URLs or credential envelopes.
var isApiKey = User.HasClaim(c => c.Type == "auth_method" && c.Value == "api_key");
if (isApiKey)
{
+ if (User.FindFirst("agent_id")?.Value != agentId.ToString())
+ return Forbid();
var siteClaim = User.FindFirst("site_id")?.Value;
if (!Guid.TryParse(siteClaim, out var apiKeySiteId))
return Forbid();
@@ -167,9 +171,38 @@ public class SettingsController : ControllerBase
}
var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
- return result.IsSuccess
- ? Ok(result.Data)
- : NotFound(new { error = result.Error });
+ if (!result.IsSuccess || result.Data is null)
+ return NotFound(new { error = result.Error });
+ Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(result.Data);
+ return Ok(result.Data);
+ }
+
+ public sealed record CameraConfigAckRequest(string Version);
+
+ /// Acknowledge the exact camera snapshot applied by this agent.
+ [Authorize(AuthenticationSchemes = "ApiKey")]
+ [HttpPost("agent/{agentId:guid}/camera-config-ack")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task AcknowledgeCameraConfig(Guid agentId,
+ [FromBody] CameraConfigAckRequest request, CancellationToken ct)
+ {
+ if (User.FindFirst("agent_id")?.Value != agentId.ToString())
+ return Forbid();
+ if (request.Version?.Length != 64 || !request.Version.All(Uri.IsHexDigit))
+ return BadRequest(new { error = "Invalid camera configuration version" });
+
+ var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
+ if (!result.IsSuccess || result.Data is null)
+ return NotFound(new { error = result.Error });
+ if (!string.Equals(CameraConfigVersion.Compute(result.Data), request.Version,
+ StringComparison.OrdinalIgnoreCase))
+ return Conflict(new { error = "Camera configuration changed before acknowledgement" });
+
+ if (!await _mediator.Send(new AcknowledgeCameraConfigCommand(agentId, request.Version), ct))
+ return NotFound();
+ _logger.LogInformation("Agent {AgentId} applied camera configuration {Version}", agentId, request.Version);
+ return NoContent();
}
/// List all setting overrides for a specific agent (Admin only).
diff --git a/src/Heimdall.Web/Security/ResourceAccessFilter.cs b/src/Heimdall.Web/Security/ResourceAccessFilter.cs
index 97e8196..467ae3a 100644
--- a/src/Heimdall.Web/Security/ResourceAccessFilter.cs
+++ b/src/Heimdall.Web/Security/ResourceAccessFilter.cs
@@ -41,6 +41,10 @@ public sealed class ResourceAccessFilter(ResourceAccess access, IApplicationDbCo
{
"Create" => await Site(Id("SiteId")),
"ListBySite" => true, // camera query is filtered before pagination
+ "FailSnapshotRequest" => r.Kind == RequesterKind.Agent && Id("requestId") is Guid snapshotRequestId &&
+ Id("id") is Guid snapshotCameraId &&
+ await db.ManualSnapshotRequests.AnyAsync(s => s.Id == snapshotRequestId &&
+ s.CameraId == snapshotCameraId && s.AgentId == r.Id, ct),
_ => await Camera(Id("id"))
};
break;
diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs
index 7bbb836..7a5e7d9 100644
--- a/src/Heimdall.Web/Services/HeimdallApiClient.cs
+++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs
@@ -456,6 +456,13 @@ public class HeimdallApiClient : IDisposable
: ApiResult.Success(request.RequestId);
}
+ public async Task GetCameraSnapshotStatusAsync(Guid cameraId, Guid requestId)
+ {
+ var client = CreateClient();
+ return await client.GetFromJsonAsync(
+ $"api/cameras/{cameraId:D}/snapshot/{requestId:D}", Json);
+ }
+
public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status,
string? manufacturer = null, string? model = null)
{
@@ -1217,6 +1224,12 @@ public record SetAgentSettingRequest(
public record ManualSnapshotRequestResult(
[property: JsonPropertyName("requestId")] Guid RequestId);
+public record ManualSnapshotStatusItem(
+ [property: JsonPropertyName("requestId")] Guid RequestId,
+ [property: JsonPropertyName("status")] string Status,
+ [property: JsonPropertyName("reason")] string? Reason,
+ [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt);
+
public record EventItem(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("cameraId")] Guid CameraId,