diff --git a/docs/audits/2026-10-20-audit-complet.md b/docs/audits/2026-10-20-audit-complet.md index da463c0..fcc3ac0 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 22 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 22 octobre, `main` inclut les PR #2–#51. 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 22 octobre, `main` inclut les PR #2–#53. 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. | État | Constats | Preuve / réserve | |---|---|---| @@ -16,11 +16,12 @@ 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 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. | +| 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 | 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. Capture manuelle, miniatures et validation sur caméra réelle restent ouvertes. | | 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. | -| Ouvert sur `main` | PIPE-01, PIPE-02, PIPE-09, OPS-02 (médias hors recordings et lignes historiques), UI-02 (liaison FEAT-03), FEAT-01, FEAT-02, FEAT-03, QA-01, AGENT-08, AGENT-09 (validation terrain), 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. | +| Ouvert sur `main` | PIPE-01, PIPE-02, PIPE-09 (capture manuelle, miniatures et validation terrain), OPS-02 (objets staging, autres médias et lignes historiques), UI-02 (liaison FEAT-03), FEAT-01, FEAT-02, FEAT-03, QA-01, AGENT-08, AGENT-09 (validation terrain), 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é. | @@ -215,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 : commande de capture avec identifiant de corrélation, upload authentifié et borné, miniature, association événement, lecture autorisée ou URL signée et état réel dans l’UI. +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. Restent la commande manuelle avec corrélation, les miniatures, le nettoyage des objets orphelins et la réception sur caméra réelle. ### PIPE-10 — P1 — Événements perdus pendant une indisponibilité réseau — confirmé diff --git a/docs/audits/2026-10-20-plan-implementation.md b/docs/audits/2026-10-20-plan-implementation.md index 98377ac..4109e38 100644 --- a/docs/audits/2026-10-20-plan-implementation.md +++ b/docs/audits/2026-10-20-plan-implementation.md @@ -72,6 +72,8 @@ Acceptation : saturation contrôlée sans attente infinie, arrêt sans tâches o Priorité P1. Défauts PIPE-09, SEC-08, UI-01. Estimation : 5–8 jours. Dépend des lots 2 et 3. +État : confinement local, filtres de galerie, upload et lecture autorisés des JPEG de détection sont raccordés dans le code. Chaque nouveau snapshot porte sa destination de stockage; la boîte d’envoi de l’agent conserve le JPEG jusqu’à son acquittement. La capture manuelle, les miniatures, la réconciliation des orphelins et la validation sur caméra réelle restent à livrer. + Travaux : 1. Corriger ResolvePath et les tests de confinement avant d’exposer les opérations de stockage. diff --git a/readme.md b/readme.md index 949bf43..2b48ec5 100644 --- a/readme.md +++ b/readme.md @@ -260,7 +260,9 @@ Compte par défaut (dev) : | GET | `/api/settings` | JWT | Configuration | | PUT | `/api/settings` | JWT | Modifier configuration | | GET | `/healthz` | - | Health check | -| POST | `/api/events/{id}/snapshot` | API Key | Associer à l’événement une URL de snapshot déjà téléversée ; cette route ne capture ni ne téléverse l’image | +| PUT | `/api/events/{id}/snapshot/content` | API Key | Téléverser un JPEG borné pour un événement de la caméra de l’agent | +| GET | `/api/events/{id}/snapshot/content` | JWT/cookie | Lire le JPEG stocké après contrôle d’accès à la caméra | +| POST | `/api/events/{id}/snapshot` | API Key | Ancienne route retirée (`410 Gone`) | | GET | `/api/events/camera/{cameraId}` | JWT | Événements récents d'une caméra (`count` optionnel) | | GET | `/api/events` | JWT | Rechercher des événements paginés et filtrés | | POST | `/api/agents/{id}/discovery` | API Key | Soumettre les résultats de découverte de caméras d'un agent | diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs index 5af8ef1..c6f4698 100644 --- a/src/Heimdall.Agent/Services/DetectionReporterService.cs +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -17,7 +17,8 @@ public interface IDetectionReporter /// Durably enqueue a detection event. True means queued, not yet delivered. Task ReportAsync( Guid cameraId, EventType type, double confidence, string? label, - string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default); + string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null, + CancellationToken ct = default); } /// @@ -31,6 +32,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo private const int MaxDeadLetterEvents = 1_000; private const long MaxOutboxBytes = 64L * 1024 * 1024; private const int MaxEventPayloadBytes = 512 * 1024; + private const int MaxSnapshotBytes = 2 * 1024 * 1024; private const int ReadBatchSize = 100; private static readonly TimeSpan DefaultCooldown = TimeSpan.FromSeconds(10); private static readonly TimeSpan MotionCooldown = TimeSpan.FromSeconds(30); @@ -83,7 +85,8 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo public async Task ReportAsync( Guid cameraId, EventType type, double confidence, string? label, - string? metadataJson = null, DateTime? occurredAt = null, CancellationToken ct = default) + string? metadataJson = null, DateTime? occurredAt = null, byte[]? snapshotJpeg = null, + CancellationToken ct = default) { if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return false; @@ -102,7 +105,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo cameraId, type, confidence, label, metadataJson, occurredAt ?? now, Guid.NewGuid()); try { - var queued = await EnqueueAsync(request, ct).ConfigureAwait(false); + var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false); if (!queued) return false; @@ -177,6 +180,30 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo using var response = await client.PostAsJsonAsync("api/events", item.Request, Json, ct).ConfigureAwait(false); if (response.IsSuccessStatusCode) { + if (item.SnapshotJpeg is not null) + { + using var content = new ByteArrayContent(item.SnapshotJpeg); + content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); + using var upload = await client.PutAsync( + $"api/events/{item.EventId:D}/snapshot/content", content, ct).ConfigureAwait(false); + if (!upload.IsSuccessStatusCode) + { + if (IsPermanentFailure(upload.StatusCode)) + { + await MoveToDeadLetterAsync(item, $"Snapshot upload HTTP {(int)upload.StatusCode}", ct).ConfigureAwait(false); + Interlocked.Increment(ref _deadLettered); + HeimdallMetrics.RecordEventOutboxRejected("dead-letter", item.Request.Type.ToString()); + _logger.LogError("Snapshot for event {EventId} moved to the local dead-letter store after HTTP {StatusCode}", + item.EventId, upload.StatusCode); + return true; + } + Interlocked.Increment(ref _failedReports); + await IncrementAttemptsAsync(item.EventId, ct).ConfigureAwait(false); + _logger.LogWarning("Snapshot upload for event {EventId} failed: HTTP {StatusCode}; retaining event and JPEG in the outbox", + item.EventId, (int)upload.StatusCode); + return false; + } + } await DeletePendingAsync(item.EventId, ct).ConfigureAwait(false); return true; } @@ -224,8 +251,19 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo await using var command = connection.CreateCommand(); command.CommandText = _databaseInitialized ? "PRAGMA synchronous=FULL;" - : "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS pending_detection_events (event_id TEXT PRIMARY KEY NOT NULL, event_type INTEGER NOT NULL, priority INTEGER NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS ix_pending_detection_events_priority_created ON pending_detection_events(priority DESC, created_at); CREATE TABLE IF NOT EXISTS dead_letter_detection_events (event_id TEXT PRIMARY KEY NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, last_error TEXT NOT NULL, attempts INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS ix_dead_letter_detection_events_created ON dead_letter_detection_events(created_at); PRAGMA user_version=1;"; + : "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS pending_detection_events (event_id TEXT PRIMARY KEY NOT NULL, event_type INTEGER NOT NULL, priority INTEGER NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS ix_pending_detection_events_priority_created ON pending_detection_events(priority DESC, created_at); CREATE TABLE IF NOT EXISTS dead_letter_detection_events (event_id TEXT PRIMARY KEY NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, last_error TEXT NOT NULL, attempts INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS ix_dead_letter_detection_events_created ON dead_letter_detection_events(created_at);"; await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + if (!_databaseInitialized) + { + await using var check = connection.CreateCommand(); + check.CommandText = "SELECT COUNT(*) FROM pragma_table_info('pending_detection_events') WHERE name='snapshot_jpeg';"; + if (Convert.ToInt32(await check.ExecuteScalarAsync(ct).ConfigureAwait(false), System.Globalization.CultureInfo.InvariantCulture) == 0) + { + await using var upgrade = connection.CreateCommand(); + upgrade.CommandText = "ALTER TABLE pending_detection_events ADD COLUMN snapshot_jpeg BLOB NULL; PRAGMA user_version=2;"; + await upgrade.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + } + } _databaseInitialized = true; } finally { _databaseInitializationGate.Release(); } @@ -245,7 +283,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo } } - private async Task EnqueueAsync(CreateCameraEventRequest request, CancellationToken ct) + private async Task EnqueueAsync(CreateCameraEventRequest request, byte[]? snapshotJpeg, CancellationToken ct) { var payload = JsonSerializer.Serialize(request, Json); var payloadBytes = Encoding.UTF8.GetByteCount(payload); @@ -258,6 +296,18 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo return false; } + if (snapshotJpeg is not null && + (snapshotJpeg.Length < 4 || snapshotJpeg.Length > MaxSnapshotBytes || + snapshotJpeg[0] != 0xff || snapshotJpeg[1] != 0xd8 || + snapshotJpeg[^2] != 0xff || snapshotJpeg[^1] != 0xd9)) + { + _logger.LogWarning("Captured JPEG for camera {CameraId} is invalid or exceeds {MaxBytes} bytes; retaining the event without an image", + request.CameraId, MaxSnapshotBytes); + snapshotJpeg = null; + } + + var itemBytes = payloadBytes + (snapshotJpeg?.Length ?? 0); + var eventId = request.EventId!.Value; var priority = request.Type == EventType.MotionDetected ? 0 : 1; await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false); @@ -266,7 +316,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, (SqliteTransaction)transaction, ct).ConfigureAwait(false); - while (count >= MaxPendingEvents || bytes + payloadBytes > MaxOutboxBytes) + while (count >= MaxPendingEvents || bytes + itemBytes > MaxOutboxBytes) { var evictedBytes = await EvictOldestMotionEventAsync(connection, transaction, ct).ConfigureAwait(false); if (evictedBytes is null) @@ -286,15 +336,16 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo await using var insert = connection.CreateCommand(); insert.Transaction = (SqliteTransaction)transaction; - insert.CommandText = "INSERT INTO pending_detection_events(event_id,event_type,priority,payload_json,created_at) VALUES($id,$type,$priority,$payload,$created);"; + insert.CommandText = "INSERT INTO pending_detection_events(event_id,event_type,priority,payload_json,created_at,snapshot_jpeg) VALUES($id,$type,$priority,$payload,$created,$snapshot);"; insert.Parameters.AddWithValue("$id", eventId.ToString("D")); insert.Parameters.AddWithValue("$type", (int)request.Type); insert.Parameters.AddWithValue("$priority", priority); insert.Parameters.AddWithValue("$payload", payload); insert.Parameters.AddWithValue("$created", DateTimeOffset.UtcNow.ToString("O")); + insert.Parameters.AddWithValue("$snapshot", (object?)snapshotJpeg ?? DBNull.Value); await insert.ExecuteNonQueryAsync(ct).ConfigureAwait(false); await transaction.CommitAsync(ct).ConfigureAwait(false); - HeimdallMetrics.SetEventOutboxState((int)count + 1, bytes + payloadBytes); + HeimdallMetrics.SetEventOutboxState((int)count + 1, bytes + itemBytes); HeimdallMetrics.RecordEventCreated(request.Type.ToString(), request.CameraId); return true; } @@ -306,7 +357,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo { await using var command = connection.CreateCommand(); command.Transaction = transaction; - command.CommandText = "SELECT COUNT(*), COALESCE(SUM(length(CAST(payload_json AS BLOB))),0) FROM pending_detection_events;"; + command.CommandText = "SELECT COUNT(*), COALESCE(SUM(length(CAST(payload_json AS BLOB)) + COALESCE(length(snapshot_jpeg),0)),0) FROM pending_detection_events;"; await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false); await reader.ReadAsync(ct).ConfigureAwait(false); return (reader.GetInt64(0), reader.GetInt64(1)); @@ -317,7 +368,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo { await using var command = connection.CreateCommand(); command.Transaction = (SqliteTransaction)transaction; - command.CommandText = "DELETE FROM pending_detection_events WHERE event_id=(SELECT event_id FROM pending_detection_events WHERE priority=0 ORDER BY created_at LIMIT 1) RETURNING length(CAST(payload_json AS BLOB));"; + command.CommandText = "DELETE FROM pending_detection_events WHERE event_id=(SELECT event_id FROM pending_detection_events WHERE priority=0 ORDER BY created_at LIMIT 1) RETURNING length(CAST(payload_json AS BLOB)) + COALESCE(length(snapshot_jpeg),0);"; var result = await command.ExecuteScalarAsync(ct).ConfigureAwait(false); return result is null or DBNull ? null : Convert.ToInt64(result, System.Globalization.CultureInfo.InvariantCulture); } @@ -328,7 +379,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false); HeimdallMetrics.SetEventOutboxState((int)count, bytes); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT event_id,payload_json,attempts FROM pending_detection_events ORDER BY priority DESC,created_at LIMIT $limit;"; + command.CommandText = "SELECT event_id,payload_json,attempts,snapshot_jpeg FROM pending_detection_events ORDER BY priority DESC,created_at LIMIT $limit;"; command.Parameters.AddWithValue("$limit", ReadBatchSize); var results = new List(); await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false); @@ -336,7 +387,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo { var request = JsonSerializer.Deserialize(reader.GetString(1), Json); if (request is not null && Guid.TryParse(reader.GetString(0), out var id)) - results.Add(new PendingDetection(id, request, reader.GetInt32(2))); + results.Add(new PendingDetection(id, request, reader.GetInt32(2), reader.IsDBNull(3) ? null : reader.GetFieldValue(3))); } return results; } @@ -410,5 +461,5 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo return EventType.MotionDetected; } - private sealed record PendingDetection(Guid EventId, CreateCameraEventRequest Request, int Attempts); + private sealed record PendingDetection(Guid EventId, CreateCameraEventRequest Request, int Attempts, byte[]? SnapshotJpeg); } diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index 3a95af8..86b7c4f 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -288,14 +288,14 @@ public sealed class SnapshotPipelineService : BackgroundService if (profile.RequireMotionForAI && !motion) { _sceneState.UpdateFromAnalysis(false, false); - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + await ReportSceneTransitionsAsync(snapshot, ct).ConfigureAwait(false); continue; } if (level >= DegradationLevel.ExecutorDown) { _sceneState.UpdateFromAnalysis(false, motion); Interlocked.Increment(ref _snapshotsSkippedByDegradation); - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); + await ReportSceneTransitionsAsync(snapshot, ct).ConfigureAwait(false); continue; } @@ -323,8 +323,8 @@ public sealed class SnapshotPipelineService : BackgroundService result?.Detections.Count > 0, motion); - await ReportSceneTransitionsAsync(snapshot.CameraId, ct).ConfigureAwait(false); - await ReportDetectionsAsync(snapshot.CameraId, result, ct).ConfigureAwait(false); + await ReportSceneTransitionsAsync(snapshot, ct).ConfigureAwait(false); + await ReportDetectionsAsync(snapshot, result, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -407,28 +407,29 @@ public sealed class SnapshotPipelineService : BackgroundService /// (per camera, once per transition — the reporter's cooldown prevents /// spam while the scene stays active). /// - private async Task ReportSceneTransitionsAsync(Guid cameraId, CancellationToken ct) + private async Task ReportSceneTransitionsAsync(Snapshot snapshot, CancellationToken ct) { var current = _sceneState.State; - var reported = _reportedSceneState.GetOrAdd(cameraId, SceneState.Idle); + var reported = _reportedSceneState.GetOrAdd(snapshot.CameraId, SceneState.Idle); // Rising edge: idle → motion/object detected. if (current != SceneState.Idle && reported == SceneState.Idle) { await _detectionReporter.ReportAsync( - cameraId, Heimdall.Domain.Enums.EventType.MotionDetected, - confidence: 0.9, label: "motion", occurredAt: DateTime.UtcNow, ct: ct) + snapshot.CameraId, Heimdall.Domain.Enums.EventType.MotionDetected, + confidence: 0.9, label: "motion", occurredAt: snapshot.TimestampUtc, + ct: ct, snapshotJpeg: snapshot.JpegData) .ConfigureAwait(false); } - _reportedSceneState[cameraId] = current; + _reportedSceneState[snapshot.CameraId] = current; } /// /// Report analyzer detections as typed events (PersonDetected, /// VehicleDetected, …). The reporter dedupes by (camera, type) cooldown. /// - private async Task ReportDetectionsAsync(Guid cameraId, FrameAnalysisResult? result, CancellationToken ct) + private async Task ReportDetectionsAsync(Snapshot snapshot, FrameAnalysisResult? result, CancellationToken ct) { if (result is null || result.Detections.Count == 0) return; @@ -450,9 +451,9 @@ public sealed class SnapshotPipelineService : BackgroundService }); await _detectionReporter.ReportAsync( - cameraId, eventType.Value, + snapshot.CameraId, eventType.Value, detection.Confidence, detection.Label, metadata, - occurredAt: DateTime.UtcNow, ct: ct) + occurredAt: snapshot.TimestampUtc, ct: ct, snapshotJpeg: snapshot.JpegData) .ConfigureAwait(false); } } diff --git a/src/Heimdall.Application/Events/Commands/AttachSnapshot/AttachSnapshotHandler.cs b/src/Heimdall.Application/Events/Commands/AttachSnapshot/AttachSnapshotHandler.cs index 914cda4..f648410 100644 --- a/src/Heimdall.Application/Events/Commands/AttachSnapshot/AttachSnapshotHandler.cs +++ b/src/Heimdall.Application/Events/Commands/AttachSnapshot/AttachSnapshotHandler.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using MediatR; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Events.Commands.AttachSnapshot; @@ -13,7 +14,7 @@ public class AttachSnapshotHandler : IRequestHandler Handle(AttachSnapshotCommand request, CancellationToken ct) { - var ev = await _context.CameraEvents.FindAsync([request.EventId], ct).ConfigureAwait(false); + var ev = await _context.CameraEvents.FirstOrDefaultAsync(e => e.Id == request.EventId, ct).ConfigureAwait(false); if (ev is null) return ServiceResult.NotFound("Event not found"); diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs index 3041301..0d174a7 100644 --- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs +++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventCommand.cs @@ -13,4 +13,5 @@ public record CreateEventCommand( string? MetadataJson, DateTime? OccurredAt, Guid? EventId = null, - Guid? PersonId = null) : IRequest>; + Guid? PersonId = null, + Guid? AgentId = null) : IRequest>; diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs index ccf1a13..32d698e 100644 --- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs +++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs @@ -45,6 +45,9 @@ public class CreateEventHandler : IRequestHandler.Failure("Event ID already belongs to another source", 409); var existingResponse = MapResponse(existing); await _publisher.Publish(new EventCreatedNotification(existingResponse), ct).ConfigureAwait(false); return ServiceResult.Success(existingResponse); @@ -56,6 +59,8 @@ public class CreateEventHandler : IRequestHandler e.Id == eventId && e.OccurredAt == occurredAt, ct) .ConfigureAwait(false); if (duplicate is null) throw; + if (duplicate.CameraId != request.CameraId || + (request.AgentId.HasValue && duplicate.AgentId != request.AgentId)) + return ServiceResult.Failure("Event ID already belongs to another source", 409); var duplicateResponse = MapResponse(duplicate); await _publisher.Publish(new EventCreatedNotification(duplicateResponse), ct).ConfigureAwait(false); return ServiceResult.Success(duplicateResponse); diff --git a/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs b/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs index 3111dae..0fad0c1 100644 --- a/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs +++ b/src/Heimdall.Application/Events/Commands/DeleteEvent/DeleteEventHandler.cs @@ -1,5 +1,6 @@ using Heimdall.Application.Common; using MediatR; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Events.Commands.DeleteEvent; @@ -8,15 +9,27 @@ public class DeleteEventHandler : IRequestHandler _context = context; + public DeleteEventHandler(IApplicationDbContext context, IStorageObjectDeletion storage) + { + _context = context; + _storage = storage; + } public async Task Handle(DeleteEventCommand request, CancellationToken ct) { - var ev = await _context.CameraEvents.FindAsync([request.Id], ct).ConfigureAwait(false); + var ev = await _context.CameraEvents.FirstOrDefaultAsync(e => e.Id == request.Id, ct).ConfigureAwait(false); if (ev is null) return ServiceResult.NotFound("Event not found"); + var location = ev.GetSnapshotLocation(); + if (ev.SnapshotObjectKey is not null) + { + if (location is null) return ServiceResult.Failure("Snapshot destination is incomplete", 409); + await _storage.DeleteBatchAsync([ev.SnapshotObjectKey], location, ct).ConfigureAwait(false); + } + _context.CameraEvents.Remove(ev); await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); diff --git a/src/Heimdall.Domain/Entities/CameraEvent.cs b/src/Heimdall.Domain/Entities/CameraEvent.cs index 4f27949..8f0677f 100644 --- a/src/Heimdall.Domain/Entities/CameraEvent.cs +++ b/src/Heimdall.Domain/Entities/CameraEvent.cs @@ -16,6 +16,11 @@ public class CameraEvent : Entity, IAuditableEntity public string? Label { get; private set; } // Human-readable label (e.g. "John Doe", "AB-123-CD") public string? SnapshotUrl { get; private set; } // S3 key or URL to snapshot image public string? SnapshotThumbUrl { get; private set; } // Thumbnail S3 key or URL + public string? SnapshotObjectKey { get; private set; } + public StorageProvider? SnapshotStorageProvider { get; private set; } + public string? SnapshotStorageRoot { get; private set; } + public string? SnapshotStorageEndpoint { get; private set; } + public string? SnapshotStorageBucket { get; private set; } public string? MetadataJson { get; private set; } // JSON: bounding boxes, track ID, etc. public DateTime OccurredAt { get; private set; } @@ -83,6 +88,29 @@ public class CameraEvent : Entity, IAuditableEntity SnapshotThumbUrl = thumbUrl; } + public StorageLocation? GetSnapshotLocation() + { + if (SnapshotObjectKey is null || SnapshotStorageProvider is null) return null; + var location = new StorageLocation(SnapshotStorageProvider.Value, + SnapshotStorageRoot, SnapshotStorageEndpoint, SnapshotStorageBucket); + return location.IsComplete ? location : null; + } + + public void SetStoredSnapshot(string objectKey, StorageLocation location) + { + if (string.IsNullOrWhiteSpace(objectKey)) throw new ArgumentException("Snapshot object key is required", nameof(objectKey)); + ArgumentNullException.ThrowIfNull(location); + if (!location.IsComplete) throw new ArgumentException("Snapshot storage location is incomplete", nameof(location)); + + SnapshotObjectKey = objectKey; + SnapshotStorageProvider = location.Provider; + SnapshotStorageRoot = location.LocalRoot; + SnapshotStorageEndpoint = location.S3Endpoint; + SnapshotStorageBucket = location.S3Bucket; + SnapshotUrl = $"/api/events/{Id:D}/snapshot/content"; + SnapshotThumbUrl = null; + } + public void SetMetadata(string? label, string? metadataJson) { Label = label; diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs index 2cc1cf7..dc31da7 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraEventConfiguration.cs @@ -32,6 +32,12 @@ public class CameraEventConfiguration : IEntityTypeConfiguration .HasMaxLength(2000) .IsUnicode(false); + builder.Property(e => e.SnapshotObjectKey).HasMaxLength(2000).IsUnicode(false); + builder.Property(e => e.SnapshotStorageProvider).HasConversion().HasMaxLength(20).IsUnicode(false); + builder.Property(e => e.SnapshotStorageRoot).HasMaxLength(2000); + builder.Property(e => e.SnapshotStorageEndpoint).HasMaxLength(2000); + builder.Property(e => e.SnapshotStorageBucket).HasMaxLength(256); + builder.Property(e => e.MetadataJson) .HasColumnType("jsonb"); diff --git a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs index 40f6634..86353c8 100644 --- a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs @@ -1,4 +1,5 @@ using System.Globalization; +using Heimdall.Application.Common; using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -14,6 +15,7 @@ public class PartitionManagerJob { private readonly IDbContextFactory _dbFactory; private readonly ILogger _logger; + private readonly IStorageObjectDeletion? _storage; /// Number of months to retain old partitions. private const int RetentionMonths = 12; @@ -25,10 +27,12 @@ public class PartitionManagerJob public PartitionManagerJob( IDbContextFactory dbFactory, - ILogger logger) + ILogger logger, + IStorageObjectDeletion? storage = null) { _dbFactory = dbFactory; _logger = logger; + _storage = storage; } public static bool TryParsePartitionDate(string name, out DateTime date) @@ -124,6 +128,12 @@ public class PartitionManagerJob { try { + // Delete managed snapshots first. A failed object deletion keeps + // the partition so the next sweep can retry with its metadata. + var partitionDate = DateTime.SpecifyKind( + DateTime.ParseExact(partition[14..], "yyyy_MM", InvariantCulture), DateTimeKind.Utc); + await DeletePartitionSnapshotsAsync(db, partitionDate, ct).ConfigureAwait(false); + // Partition name is validated above (alphanumeric + underscore only) #pragma warning disable EF1002 // DDL — table name cannot be parameterized await db.Database.ExecuteSqlRawAsync( @@ -147,4 +157,30 @@ public class PartitionManagerJob "Partition management complete: {Created} ensured, {Dropped} dropped (retention {Retention} months)", created, dropped, RetentionMonths); } + + private async Task DeletePartitionSnapshotsAsync(AppDbContext db, DateTime from, CancellationToken ct) + { + const int batchSize = 500; + var to = from.AddMonths(1); + var offset = 0; + while (true) + { + var events = await db.CameraEvents.AsNoTracking() + .Where(e => e.OccurredAt >= from && e.OccurredAt < to && e.SnapshotObjectKey != null) + .OrderBy(e => e.Id).Skip(offset).Take(batchSize).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.Select(e => e.SnapshotObjectKey!).ToArray(), group.Key, ct).ConfigureAwait(false); + + offset += events.Count; + if (events.Count < batchSize) break; + } + } } diff --git a/src/Heimdall.Infrastructure/Migrations/20261022010000_AddStoredEventSnapshots.cs b/src/Heimdall.Infrastructure/Migrations/20261022010000_AddStoredEventSnapshots.cs new file mode 100644 index 0000000..5edd419 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261022010000_AddStoredEventSnapshots.cs @@ -0,0 +1,30 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261022010000_AddStoredEventSnapshots")] +public partial class AddStoredEventSnapshots : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn("SnapshotObjectKey", "camera_events", type: "character varying(2000)", maxLength: 2000, nullable: true); + migrationBuilder.AddColumn("SnapshotStorageProvider", "camera_events", type: "character varying(20)", maxLength: 20, nullable: true); + migrationBuilder.AddColumn("SnapshotStorageRoot", "camera_events", type: "character varying(2000)", maxLength: 2000, nullable: true); + migrationBuilder.AddColumn("SnapshotStorageEndpoint", "camera_events", type: "character varying(2000)", maxLength: 2000, nullable: true); + migrationBuilder.AddColumn("SnapshotStorageBucket", "camera_events", type: "character varying(256)", maxLength: 256, nullable: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn("SnapshotObjectKey", "camera_events"); + migrationBuilder.DropColumn("SnapshotStorageProvider", "camera_events"); + migrationBuilder.DropColumn("SnapshotStorageRoot", "camera_events"); + migrationBuilder.DropColumn("SnapshotStorageEndpoint", "camera_events"); + migrationBuilder.DropColumn("SnapshotStorageBucket", "camera_events"); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 538c393..5eb0043 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1147,6 +1147,28 @@ namespace Heimdall.Infrastructure.Migrations .IsUnicode(false) .HasColumnType("character varying(2000)"); + b.Property("SnapshotObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageProvider") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SnapshotStorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + b.Property("SnapshotUrl") .HasMaxLength(2000) .IsUnicode(false) diff --git a/src/Heimdall.Infrastructure/Services/CameraEventService.cs b/src/Heimdall.Infrastructure/Services/CameraEventService.cs index 3bdcb6c..f39d48e 100644 --- a/src/Heimdall.Infrastructure/Services/CameraEventService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraEventService.cs @@ -162,6 +162,15 @@ public sealed class CameraEventService : ICameraEventService if (ev is null) return ServiceResult.NotFound("Event not found"); + if (ev.SnapshotObjectKey is not null) + { + var location = ev.GetSnapshotLocation(); + if (location is null) return ServiceResult.Failure("Snapshot destination is incomplete", 409); + using var scope = _serviceProvider.CreateScope(); + var storage = scope.ServiceProvider.GetRequiredService(); + await storage.DeleteBatchAsync([ev.SnapshotObjectKey], location, ct).ConfigureAwait(false); + } + db.CameraEvents.Remove(ev); await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); return ServiceResult.Success(); diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index 10e1eb7..74a035f 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -124,6 +124,30 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat } } + /// Reads an object from the destination recorded with its owning event. + public async Task DownloadAsync( + string key, + Heimdall.Domain.Entities.StorageLocation location, + CancellationToken ct = default) + { + var provider = Resolve(location); + try + { + var stream = await provider.DownloadAsync(key, ct).ConfigureAwait(false); + if (stream is null) + { + DisposeProvider(provider); + return null; + } + return new ProviderOwnedStream(stream, provider as IDisposable); + } + catch + { + DisposeProvider(provider); + throw; + } + } + public async Task DeleteAsync(string key, CancellationToken ct = default) { var provider = Resolve(); diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs index 496d285..fc0d7cc 100644 --- a/src/Heimdall.Web/Controllers/EventsController.cs +++ b/src/Heimdall.Web/Controllers/EventsController.cs @@ -1,17 +1,20 @@ using System.Security.Claims; +using Heimdall.Api.Security; +using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Events.Commands.CreateEvent; -using Heimdall.Application.Events.Commands.AttachSnapshot; using Heimdall.Application.Events.Commands.DeleteEvent; using Heimdall.Application.Events.Queries.GetEvent; using Heimdall.Application.Events.Queries.GetEvents; using Heimdall.Application.Events.Queries.GetRecentByCamera; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; +using Heimdall.Infrastructure.Storage; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Api.Controllers; @@ -24,9 +27,22 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class EventsController : ControllerBase { + private const int MaxSnapshotBytes = 2 * 1024 * 1024; private readonly IMediator _mediator; + private readonly IApplicationDbContext _db; + private readonly ResourceAccess _access; + private readonly StorageProviderFactory _storage; + private readonly ILogger _logger; - public EventsController(IMediator mediator) => _mediator = mediator; + public EventsController(IMediator mediator, IApplicationDbContext db, ResourceAccess access, + StorageProviderFactory storage, ILogger logger) + { + _mediator = mediator; + _db = db; + _access = access; + _storage = storage; + _logger = logger; + } /// Record a new detection event (called by agents). [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] @@ -35,7 +51,10 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateCameraEventRequest request, CancellationToken ct) { - var command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt, request.EventId, request.PersonId); + var requester = await _access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await _access.CameraAsync(requester, request.CameraId, ct)) return Forbid(); + var command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt, request.EventId, request.PersonId, requester.Id); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) @@ -94,17 +113,85 @@ public class EventsController : ControllerBase return Ok(result.Data); } - /// Attach a snapshot URL to an event (called by agents after upload). + /// Legacy URL attachment is retired; snapshots must be uploaded to managed storage. [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] [HttpPost("{id:guid}/snapshot")] + [ProducesResponseType(StatusCodes.Status410Gone)] + public IActionResult AttachSnapshot(Guid id) => StatusCode(StatusCodes.Status410Gone, + new { eventId = id, error = "Use PUT /api/events/{id}/snapshot/content with image/jpeg" }); + + /// Persist a bounded JPEG for an event from its assigned agent. + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPut("{id:guid}/snapshot/content")] + [RequestSizeLimit(MaxSnapshotBytes)] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task AttachSnapshot(Guid id, [FromBody] AttachSnapshotRequest request, CancellationToken ct) + public async Task UploadSnapshot(Guid id, CancellationToken ct) { - var result = await _mediator.Send(new AttachSnapshotCommand(id, request.SnapshotUrl, request.ThumbUrl), ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + var requester = await _access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await _access.EventUploadAsync(requester, id, ct)) return Forbid(); + + 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 }); + + var mediaType = Request.ContentType?.Split(';')[0].Trim(); + if (!string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase)) + return StatusCode(StatusCodes.Status415UnsupportedMediaType); + if (Request.ContentLength is > MaxSnapshotBytes) + return StatusCode(StatusCodes.Status413PayloadTooLarge); + + using var payload = new MemoryStream(); + var buffer = new byte[64 * 1024]; + while (true) + { + var read = await Request.Body.ReadAsync(buffer, ct); + if (read == 0) break; + if (payload.Length + read > MaxSnapshotBytes) + return StatusCode(StatusCodes.Status413PayloadTooLarge); + payload.Write(buffer, 0, read); + } + var bytes = payload.ToArray(); + if (bytes.Length < 4 || bytes[0] != 0xff || bytes[1] != 0xd8 || + bytes[^2] != 0xff || bytes[^1] != 0xd9) + return BadRequest(new { error = "A complete JPEG image is required" }); + + var location = _storage.CaptureCurrentLocation(); + var key = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}.jpg"; + await using (var content = new MemoryStream(bytes, writable: false)) + await _storage.UploadAsync(key, content, "image/jpeg", location, ct); + + try + { + ev.SetStoredSnapshot(key, location); + await _db.SaveChangesWithRetryAsync(ct: ct); + } + catch + { + try { await _storage.DeleteAsync(key, location, CancellationToken.None); } + catch (Exception cleanupError) { _logger.LogWarning(cleanupError, "Could not remove unreferenced snapshot for event {EventId}", id); } + throw; + } + return Ok(new { url = ev.SnapshotUrl }); + } + + /// 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")] + public async Task DownloadSnapshot(Guid id, CancellationToken ct) + { + var requester = await _access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await _access.EventAsync(requester, id, ct)) return Forbid(); + + var ev = await _db.CameraEvents.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id, ct); + var location = ev?.GetSnapshotLocation(); + if (ev?.SnapshotObjectKey is null || location is null) return NotFound(); + var stream = await _storage.DownloadAsync(ev.SnapshotObjectKey, location, ct); + if (stream is null) return NotFound(); + Response.Headers["Cache-Control"] = "private, no-store"; + Response.Headers["X-Content-Type-Options"] = "nosniff"; + return File(stream, "image/jpeg"); } /// Delete an event. diff --git a/src/Heimdall.Web/Security/ResourceAccess.cs b/src/Heimdall.Web/Security/ResourceAccess.cs index 761fba1..4f0de67 100644 --- a/src/Heimdall.Web/Security/ResourceAccess.cs +++ b/src/Heimdall.Web/Security/ResourceAccess.cs @@ -72,6 +72,13 @@ public sealed class ResourceAccess( return camera.HasValue && await CameraAsync(r, camera.Value, ct); } + /// Allows a detection's originating agent to finish uploading its JPEG after camera failover. + public Task EventUploadAsync(Requester r, Guid eventId, CancellationToken ct = default) => + r.Kind == RequesterKind.Agent && r.SiteId.HasValue + ? db.CameraEvents.AnyAsync(e => e.Id == eventId && e.Camera.SiteId == r.SiteId && + (e.AgentId == r.Id || (e.AgentId == null && e.Camera.AgentId == r.Id)), ct) + : Task.FromResult(false); + public async Task> FullSiteIdsAsync(Requester r, CancellationToken ct = default) { if (r.Kind == RequesterKind.Agent) return r.SiteId.HasValue ? [r.SiteId.Value] : []; diff --git a/src/Heimdall.Web/Security/ResourceAccessFilter.cs b/src/Heimdall.Web/Security/ResourceAccessFilter.cs index 9c5d760..97e8196 100644 --- a/src/Heimdall.Web/Security/ResourceAccessFilter.cs +++ b/src/Heimdall.Web/Security/ResourceAccessFilter.cs @@ -54,7 +54,10 @@ public sealed class ResourceAccessFilter(ResourceAccess access, IApplicationDbCo if (allowed && Id("siteId") is Guid agentSite) allowed = await Site(agentSite); break; case "Events": - if (Id("id") is Guid ev) allowed = await Event(ev); + if (Id("id") is Guid ev) + allowed = action.ActionName == "UploadSnapshot" + ? await access.EventUploadAsync(r, ev, ct) + : await Event(ev); if (allowed && Id("cameraId") is Guid eventCamera) allowed = await Camera(eventCamera); break; case "Assignments": diff --git a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs index fb73476..59d2408 100644 --- a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs @@ -1,6 +1,8 @@ using Heimdall.Agent.Services; using Heimdall.Domain.Enums; +using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using NSubstitute; using Shouldly; @@ -52,4 +54,32 @@ public class DetectionReporterServiceTests var task = reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected, 0.8, "person"); task.IsCompleted.ShouldBeTrue(); } + + [Fact] + public async Task ReportAsync_PersistsSnapshotWithPendingEvent() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-snapshot-outbox-{Guid.NewGuid():N}"); + try + { + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" }; + using var reporter = new DetectionReporterService(state, + Substitute.For(), + Substitute.For>(), + Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory })); + var jpeg = new byte[] { 0xff, 0xd8, 0xff, 0xd9 }; + + (await reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected, + 0.9, "person", snapshotJpeg: jpeg)).ShouldBeTrue(); + + await using var db = new SqliteConnection($"Data Source={Path.Combine(directory, "agent-events.db")}"); + await db.OpenAsync(); + await using var command = db.CreateCommand(); + command.CommandText = "SELECT snapshot_jpeg FROM pending_detection_events LIMIT 1;"; + ((byte[])(await command.ExecuteScalarAsync())!).ShouldBe(jpeg); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } } diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs index 939eead..9057070 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs @@ -14,9 +14,10 @@ public class DeleteEventHandlerTests { var ev = new CameraEvent(Guid.NewGuid(), EventType.MotionDetected, 0.9); var context = Substitute.For(); + var storage = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor([ev])); context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); - var handler = new DeleteEventHandler(context); + var handler = new DeleteEventHandler(context, storage); var result = await handler.Handle(new DeleteEventCommand(ev.Id), CancellationToken.None); @@ -27,12 +28,33 @@ public class DeleteEventHandlerTests public async Task Delete_unknown_event_should_return_not_found() { var context = Substitute.For(); + var storage = Substitute.For(); context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); - var handler = new DeleteEventHandler(context); + var handler = new DeleteEventHandler(context, storage); var result = await handler.Handle(new DeleteEventCommand(Guid.NewGuid()), CancellationToken.None); result.IsSuccess.ShouldBeFalse(); result.StatusCode.ShouldBe(404); } + + [Fact] + public async Task Delete_stored_event_removes_object_and_database_row() + { + var ev = new CameraEvent(Guid.NewGuid(), EventType.PersonDetected, 0.9); + var location = new StorageLocation(StorageProvider.Local, LocalRoot: "/var/lib/heimdall/media"); + ev.SetStoredSnapshot($"snapshots/{ev.Id:D}.jpg", location); + var context = Substitute.For(); + var storage = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor([ev])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new DeleteEventHandler(context, storage); + + var result = await handler.Handle(new DeleteEventCommand(ev.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + await storage.Received(1).DeleteBatchAsync( + Arg.Is>(keys => keys != null && keys.Count == 1 && keys.Contains(ev.SnapshotObjectKey!)), + location, Arg.Any()); + } } diff --git a/tests/Heimdall.Domain.Tests/Entities/CameraEventTests.cs b/tests/Heimdall.Domain.Tests/Entities/CameraEventTests.cs index 52b0c1c..d0a73fe 100644 --- a/tests/Heimdall.Domain.Tests/Entities/CameraEventTests.cs +++ b/tests/Heimdall.Domain.Tests/Entities/CameraEventTests.cs @@ -58,6 +58,20 @@ public class CameraEventTests evt.SnapshotThumbUrl.ShouldBe("thumb.jpg"); } + [Fact] + public void Stored_snapshot_keeps_its_destination_and_uses_an_authorized_url() + { + var evt = new CameraEvent(Guid.NewGuid(), EventType.PersonDetected, 0.9); + var location = new StorageLocation(StorageProvider.S3, + S3Endpoint: "https://objects.example.test", S3Bucket: "heimdall"); + + evt.SetStoredSnapshot($"snapshots/{evt.Id:D}.jpg", location); + + evt.GetSnapshotLocation().ShouldBe(location); + evt.SnapshotUrl.ShouldBe($"/api/events/{evt.Id:D}/snapshot/content"); + evt.SnapshotThumbUrl.ShouldBeNull(); + } + [Fact] public void SetMetadata_should_set_label_and_json() { diff --git a/tests/Heimdall.IntegrationTests/Controllers/EventsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/EventsControllerTests.cs index b410685..dc441e6 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/EventsControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/EventsControllerTests.cs @@ -3,6 +3,7 @@ using System.Text.Json; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Storage; using Heimdall.IntegrationTests.Factories; using Microsoft.Extensions.DependencyInjection; using Shouldly; @@ -106,6 +107,46 @@ public class EventsControllerTests : PostgresTestBase items[0].GetProperty("label").GetString().ShouldBe("North second"); } + [Fact] + public async Task StoredSnapshot_IsReadFromCapturedLocation_OnlyWithCameraAccess() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-event-snapshot-{Guid.NewGuid():N}"); + try + { + var site = new Site($"Snapshot {Guid.NewGuid():N}"); + var camera = new Camera(site.Id, "Stored JPEG"); + var ev = new CameraEvent(camera.Id, EventType.PersonDetected, 0.9); + var location = new StorageLocation(StorageProvider.Local, LocalRoot: directory); + var key = $"snapshots/{camera.Id:D}/{ev.Id:D}.jpg"; + ev.SetStoredSnapshot(key, location); + var bytes = new byte[] { 0xff, 0xd8, 0xff, 0xd9 }; + + await using (var scope = Factory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Sites.Add(site); + db.Cameras.Add(camera); + db.CameraEvents.Add(ev); + await db.SaveChangesAsync(); + var storage = scope.ServiceProvider.GetRequiredService(); + await using var content = new MemoryStream(bytes); + await storage.UploadAsync(key, content, "image/jpeg", location); + } + + var anonymous = await Factory.CreateClient().GetAsync($"api/events/{ev.Id:D}/snapshot/content"); + anonymous.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + + var response = await (await AdminClient()).GetAsync($"api/events/{ev.Id:D}/snapshot/content"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + (response.Content.Headers.ContentType?.MediaType).ShouldBe("image/jpeg"); + (await response.Content.ReadAsByteArrayAsync()).ShouldBe(bytes); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + private static CameraEvent Snapshot(Guid cameraId, DateTime occurredAt, string label, bool hasSnapshot) { var cameraEvent = new CameraEvent(cameraId, EventType.PersonDetected, 0.9, occurredAt); diff --git a/tests/Heimdall.Web.Tests/Components/Pages/A11yPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/A11yPageTests.cs index 98f6d46..a8c1708 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/A11yPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/A11yPageTests.cs @@ -63,7 +63,7 @@ public class A11yPageTests : PageTestBase { // Une liste non vide pour que la timeline rende le bouton snapshot applicatif. Handler.OnGet("api/events", new EventPageResult( - [new(Guid.NewGuid(), Guid.NewGuid(), "MotionDetected", 0.9, "Personne", + [new(Guid.NewGuid(), Guid.NewGuid(), null, "MotionDetected", 0.9, "Personne", "/snapshots/1.jpg", null, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow)], 1, 1, 50)); LoginAs(); diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index dc4ae78..4ded1f7 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -77,7 +77,7 @@ public class CameraDetailTests : PageTestBase HandlerCamera(Camera()); Handler.OnGet("api/events/camera/", new List { - new(Guid.NewGuid(), CameraId, "PersonDetected", 0.9, "Personne", + new(Guid.NewGuid(), CameraId, null, "PersonDetected", 0.9, "Personne", "http://alarik/snapshots/live.jpg", "http://alarik/thumbs/live.jpg", DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow) }); diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs index aa47328..d55e1f4 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CamerasPageTests.cs @@ -76,7 +76,7 @@ public class CamerasPageTests : PageTestBase Handler.OnGet("api/cameras/by-site", new PagedData([camera], 1, 1, 100)); Handler.OnGet("api/events/camera/", new List { - new(Guid.NewGuid(), camera.Id, "MotionDetected", 0.9, "Personne", + new(Guid.NewGuid(), camera.Id, null, "MotionDetected", 0.9, "Personne", "http://alarik/snapshots/1.jpg", "http://alarik/thumbs/1.jpg", DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow) }); diff --git a/tests/Heimdall.Web.Tests/Components/Pages/EventsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/EventsPageTests.cs index 0a07f19..ff6e966 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/EventsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/EventsPageTests.cs @@ -17,7 +17,7 @@ public class EventsPageTests : PageTestBase double confidence = 0.87, string? label = "Personne", string? snapshotUrl = "/snapshots/1.jpg") => - new(Guid.NewGuid(), CameraId, type, confidence, label, snapshotUrl, snapshotUrl, + new(Guid.NewGuid(), CameraId, null, type, confidence, label, snapshotUrl, snapshotUrl, DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow); [Fact] diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs index 75c8ef6..22a105f 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs @@ -44,7 +44,7 @@ public class PersonDetailPageTests : PageTestBase }; private static EventItem Ev(string label = "Alice Dupont") => - new(Guid.NewGuid(), CameraId, "FaceRecognized", 0.92, label, + new(Guid.NewGuid(), CameraId, PersonId, "FaceRecognized", 0.92, label, "https://example.com/snap.jpg", null, DateTime.UtcNow.AddHours(-2), DateTime.UtcNow.AddHours(-2)); @@ -264,4 +264,4 @@ public class PersonDetailPageTests : PageTestBase .ShouldContain(m => m.Contains("updated", StringComparison.OrdinalIgnoreCase)); }); } -} \ No newline at end of file +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs index 3917f79..29744a1 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SnapshotsPageTests.cs @@ -18,7 +18,7 @@ public class SnapshotsPageTests : PageTestBase string? label = "Personne", string? snapshotUrl = "/snapshots/1.jpg", string? thumbUrl = null) => - new(Guid.NewGuid(), CameraId, type, confidence, label, snapshotUrl, thumbUrl, + new(Guid.NewGuid(), CameraId, null, type, confidence, label, snapshotUrl, thumbUrl, DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow); [Fact]