Files
Heimdall/docs/MASTER_SPECIFICATION.md
T
arnaud.dartoisandArnaud Dartois 21f0530b6c chore : Audit incomplete features suite implémentation (#1)
- Nettoyage
- Preparation correction fonctionnalité manquante

---------

Co-authored-by: Arnaud Dartois <nonobis@gmail.com>
Reviewed-on: #1
2026-10-20 02:12:47 +02:00

131 KiB
Raw Blame History

Heimdall — Master Specification Technique

Version : 2.0 | Date : 2026-07-16 Stack : .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents) / SIPSorcery / WebRTC Status : SPECIFICATION FINALE — synthèse de 5600+ lignes de docs, revue par 5 agents experts

Documents sources fusionnés : specs.md, implementation.md, notifications.md, signalr-usage.md, auth-roles.md, pwa.md, hangfire-usage.md, ui-pages.md

Correctifs intégrés : 5 agents (council, security, db, ai, perf) ont analysé la spec originale et identifié 36 issues critiques résolues dans ce document.


Préambule — Décisions Architecturales

D1 — Accès mobile via la PWA du serveur

Le client natif est retiré. L’application Blazor devient la cible mobile installable ; la première version conserve Interactive Server avec une page hors connexion et Web Push. La consultation métier hors ligne nécessitera une couche cliente autonome. Voir l’audit PWA.

D2 — Topologie : API + Web fusionnés (1 conteneur)

Choix Raison
Api + Web = même conteneur Blazor Server + API en appel direct = latence < 2ms
Conteneurs séparés rejeté Double-hop (SignalR → Web → API → DB) ajoute 50-100ms par interaction

Exception : En scaling horizontal, on peut séparer les conteneurs avec un Redis backplane.

D3 — TURN/Coturn obligatoire (pas optionnel)

Choix Raison
Coturn REQUIS CGNAT (4G/5G), pare-feu entreprises, Starlink — toute installation derrière NAT
Optionnel rejeté WebRTC échoue silencieusement sans TURN → support impossible

D4 — Agents : Installation Docker uniquement

Choix Raison
Docker uniquement FFmpeg, SIPSorcery, YOLOv8 (ONNX Runtime) ont des dépendances natives complexes
Installation manuelle rejetée Gestion des versions, dépendances système, mise à jour = cauchemar sans conteneurisation

Conséquence : L'Agent est distribué exclusivement via heimdall/agent:latest (Docker Hub / registry privée). Pas de binaire standalone, pas de .deb, pas d'installation manuelle. La mise à jour se fait par docker pull + redémarrage.

D6 — SFU (MediaMTX) différé à v2

Choix Raison
P2P uniquement en v1 (1 viewer/caméra max) Complexité de transition P2P→SFU sous-estimée
SFU repoussé à v2 Renégociation SDP pendant flux actif = perte d'images, protocole non spécifié

D7 — CQRS avec MediatR in-process (pas de message broker)

Choix Raison
MediatR in-process + CQRS Architecture monolithe — aucun besoin de broker externe
RabbitMQ/Kafka rejeté Overkill pour un monolithe Clean Architecture
SignalR + Hangfire couvrent les besoins asynchrones Events temps réel → SignalR, Jobs différés → Hangfire

Impact : L'Application layer est organisée par domaine (Sites/, Cameras/, etc.) avec séparation Commandes/Requêtes. Les Handlers MediatR remplacent les services. Les pipelines MediatR (ValidationBehavior, LoggingBehavior) remplacent les filtres MVC.

Architecture CQRS :

Contrôleur → IMediator.Send(Command/Query) → [ValidationBehavior]
  → [LoggingBehavior] → Handler → IApplicationDbContext
                                          ↓ (si événement)
                                    INotification → SignalR broadcast

PARTIE 1 : Architecture Globale

1.1 Vision

Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, multi-site. 100% locale — aucun cloud, aucune dépendance externe obligatoire.

1.2 Principes Fondateurs

Principe Application
Privacy First IA ONNX Runtime en local sur les agents, 0 envoi de données au cloud
Multi-site 1 serveur Central + N Agents distants (sites physiques séparés)
Clean Architecture / CQRS Domain → Application → Infrastructure → Api/Web
Temps réel SignalR (5 hubs), WebRTC P2P < 500ms (LAN)
IA locale YOLOv8 nano ONNX (Agent CPU) + GPU NVIDIA/AMD/Intel sur agents équipés, mutualisable inter-sites via broker

1.3 Architecture Logique

┌────────────────────────────────────────────────────────────────────────┐
│                         HEIMDALL CENTRAL (1 container)                  │
│                                                                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌────────────┐ │
│  │ Api REST +   │  │ Web Blazor   │  │ Workers      │  │ Broker IA │ │
│  │ SignalR Hubs │  │ MudBlazor    │  │ Hangfire     │  │ .AI Server │ │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘  │ Ollama     │ │
│         │                  │                 │          └────────────┘ │
│         └──────────────────┴─────────────────┘                        │
│                              │ PostgreSQL / Hangfire (schema séparé)  │
│                              │ Alarik / S3                            │
└──────────────────────────────┼────────────────────────────────────────┘
                               │
              HTTPS REST + SignalR (events + signaling)
                               │
                     ┌─────────┴──────────┐
                     │                     │
            ┌────────┴───────┐   ┌────────┴───────┐
            │ Agent A        │   │ Agent B        │
            │ (site distant) │   │ (site distant)  │
            │                 │   │                 │
            │ SIPSorcery      │   │ SIPSorcery      │
            │ WebRTC Peer     │   │ WebRTC Peer     │
            │ FFmpeg          │   │ FFmpeg          │
            │ YOLOv8 nano     │   │ YOLOv8 nano     │
            │ Hangfire InMem  │   │ Hangfire InMem  │
            └────────┬───────┘   └────────┬───────┘
                     │                    │
       P2P WebRTC (SRTP/H264)            │
       ◄════════════════════════════════►│
                  Navigateur

1.4 Conteneurs Docker

services:
  heimdall-central:     # Api + Web + Workers fusionnés (1 conteneur)
  heimdall-agent:       # SIPSorcery + FFmpeg + YOLOv8 + Hangfire InMemory
  postgresql:           # Base de données (app + hangfire)
  alarik:               # Stockage S3 (enregistrements)
  # L'IA lourde (détection, visages, LPR) tourne sur les agents GPU (ONNX Runtime) — pas de service central
  ollama:               # LLM local (résumés quotidiens)
  coturn:               # TURN relay (OBLIGATOIRE, pas optionnel)
  redis:                # Cache + SignalR backplane (optionnel, scaling)

PARTIE 2 : Domain Model — Entités Complètes

2.1 Définitions

Site                    Agent                      Camera
├── Id (Guid) PK        ├── Id (Guid) PK           ├── Id (Guid) PK
├── Name                ├── SiteId (FK)            ├── SiteId (FK)
├── Address             ├── Name                   ├── AgentId (FK) ← NOUVEAU
├── Timezone            ├── Hostname               ├── Name
├── Enabled             ├── Version                ├── Manufacturer
├── Registration        ├── Status                 ├── Model
│   TokenHash (string)  │   (Online/Offline/Err)   ├── RtspUrl
│   TokenExpiresAt      ├── LastHeartbeat          ├── Status
├── IsDeleted           ├── PublicIp               ├── Capabilities
│   (soft delete)       ├── Capabilities            │   (Ptz, Audio, Motion)
├── CreatedAt            │   HasGpu, CpuCores      ├── Credentials (1:1)
├── UpdatedAt           ├── ApiKeyHash             ├── DetectionProfileId
├── DeletedAt           ├── ApiKeyPrefix           ├── StoragePolicyId (FK)
                         ├── IsDeleted              ├── IsDeleted
                         ├── CreatedAt              ├── CreatedAt
                         ├── UpdatedAt              ├── UpdatedAt
                         └── DeletedAt              └── DeletedAt

CameraCredentials        CameraDetectionProfile    StoragePolicy
├── CameraId (PK, FK)   ├── CameraId (PK, FK)     ├── Id (Guid) PK
├── OnvifUsername        ├── DetectPerson           ├── Name
├── OnvifPassword        ├── DetectVehicle          ├── RetentionDays
│   (chiffré)            ├── DetectAnimal           ├── StorageProvider
├── RtspUsername         ├── DetectPackage         │   (S3, Local)
├── RtspPassword         ├── DetectMotion           ├── CreatedAt
│   (chiffré)            ├── FaceRecognition        └── UpdatedAt
├── UpdatedAt             ├── LicensePlateRecog
└── CreatedAt             ├── SnapshotIntervalMs
                          ├── MotionThreshold
                          ├── MinConfidence       ← NOUVEAU
                          ├── RequireMotionForAI  ← NOUVEAU (DÉFAUT: true)
                          ├── DedupCooldownSec    ← NOUVEAU
                          ├── MaxEventsPerMinute  ← NOUVEAU
                          └── YoloModel

Person                   Vehicle                   Event
├── Id (Guid) PK         ├── Id (Guid) PK          ├── Id (Guid) PK
├── Name                 ├── LicensePlate          ├── SiteId (FK)
├── Photo                ├── PersonId (FK)         ├── CameraId (FK)
├── IsUnknown            ├── Make                  ├── Type (enum)
├── FaceSamples          ├── Model                 ├── Timestamp
├── FaceEmbeddingHash    ├── Color                 ├── CreatedAt
│   (string) ← NOUVEAU   ├── CreatedAt              ├── TrackId (Guid?) ← NOUVEAU
├── Notes                 └── UpdatedAt             ├── DetectionHash ← NOUVEAU
├── IsDeleted                                         │   (string, dedup key)
├── CreatedAt                                         ├── IsSuppressed ← NOUVEAU
└── UpdatedAt                                         ├── PersonId (FK) ← NOUVEAU
                                                     ├── VehicleId (FK) ← NOUVEAU
Recording                   LicensePlate             ├── RecordingId (FK?) ← NOUVEAU
├── Id (Guid) PK         ├── Id (Guid) PK           ├── ParentEventId (FK) ← NOUVEAU
├── CameraId (FK)        ├── PlateText              ├── SnapshotPath
├── Timestamp            ├── VehicleId (FK)         └── Metadata (jsonb)
├── Duration             ├── PersonId (FK?)
├── StoragePath          ├── Confidence
├── SizeBytes            ├── CreatedAt
├── StorageProvider      └── UpdatedAt
├── StoragePolicyId (FK)
├── CreatedAt             UserSite                   UserNotificationConfig
└── UpdatedAt             ├── UserId (FK)            ├── UserId (PK, FK)
                          ├── SiteId (FK)            ├── EmailEnabled
ApiKey                    └── (PK composite)         ├── GotifyEnabled
├── Id (Guid) PK                                      ├── EmailAddress
├── KeyHash (HMACSHA256)  NotificationTemplate       ├── SubscribedEvents
├── KeyPrefix (8 chars)   ├── Id (Guid) PK              (List<EventType>, jsonb)
├── SiteId (FK?)          ├── EventType (enum)       ├── Language
├── CreatedByUserId (FK)  ├── Language               ├── DailyDigest
├── CreatedAt             ├── Channel                ├── WeeklyDigest
├── ExpiresAt?            ├── Subject                ├── PersonCooldownSec ← NOUVEAU
├── Enabled               ├── BodyMarkdown           ├── VehicleCooldownSec ← NOUVEAU
├── LastUsedAt            └── IsDefault              └── UnknownPersonCooldownSec ← NOUVEAU
└── IsDeleted
                         AuditLog (NOUVEAU)
User                      ├── Id (Guid) PK
├── Id (Guid) PK          ├── UserId (FK)
├── DisplayName           ├── Action
├── Theme                 ├── ResourceType
├── Language              ├── ResourceId
├── TwoFactorEnabled      ├── OldValue?
├── CreatedAt             ├── NewValue?
└── (IdentityUser)        ├── IpAddress
                          ├── Timestamp
                          └── (append-only, immuable)

2.2 Relations et Cardinalités

Relation Type Contrainte
Site → Agent 1:N Un Agent appartient à un Site
Site → Camera 1:N Une caméra appartient à un Site
Agent → Camera 1:N Une caméra est gérée par un Agent (nouveau)
Camera → CameraCredentials 1:1 Identifiants chiffrés, stockage séparé
Camera → DetectionProfile 1:1 Profil de détection intégré ou table séparée
Camera → StoragePolicy N:1 Plusieurs caméras partagent une politique
Camera → Recording 1:N Enregistrements vidéo
Camera → Event 1:N Événements de détection
Event → Person N:1 Une personne peut avoir N événements
Event → Vehicle N:1 Un véhicule peut avoir N événements
Event → Event (Parent) N:1 Hiérarchie d'événements (regroupement track)
Event → Recording N:1 Lien événement → enregistrement pour playback

2.3 Index PostgreSQL Essentiels

-- Partitionnement obligatoire dès le jour 1
CREATE TABLE events (
    id UUID, site_id UUID, camera_id UUID, type TEXT,
    timestamp TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    metadata JSONB, ...
) PARTITION BY RANGE (timestamp);

-- Créer les partitions mensuelles (via Hangfire ou pg_cron)
CREATE TABLE events_2026_07 PARTITION OF events
    FOR VALUES FROM ('2026-07-01') TO ('2026-08-01');

-- Index composites critiques
CREATE INDEX idx_events_camera_time ON events (camera_id, timestamp DESC);
CREATE INDEX idx_events_site_time ON events (site_id, timestamp DESC);
CREATE INDEX idx_events_type_time ON events (type, timestamp DESC);
CREATE INDEX idx_events_track_id ON events (track_id);
CREATE INDEX idx_events_detection_hash ON events (detection_hash);
CREATE INDEX idx_events_parent_id ON events (parent_event_id);

-- Index GIN pour jsonb (seulement si requêtes Metadata)
CREATE INDEX idx_events_metadata ON events USING GIN (metadata jsonb_path_ops);

-- Autres index
CREATE INDEX idx_recordings_cleanup ON recordings (camera_id, timestamp);
CREATE INDEX idx_recordings_storage_path ON recordings (storage_path);
CREATE INDEX idx_agents_heartbeat ON agents (site_id, last_heartbeat)
    WHERE status = 'Online';
CREATE INDEX idx_persons_unknown ON persons (is_unknown, created_at);
CREATE INDEX idx_license_plate ON license_plates USING GIN
    (plate_text gin_trgm_ops);  -- pour recherche floue

PARTIE 3 : AI Pipeline et Dédoublonnage

3.1 Problème : Objets Stationnaires

Sans dédoublonnage : une personne immobile 10 minutes génère :

  • 3000 snapshots (200ms × 600s)
  • 3000 inférences YOLOv8 nano
  • 3000 analyses IA (ONNX local ou via broker)
  • 3000 événements en base
  • 3000 notifications (email + gotify + in-app)

Solution : Architecture de dédoublonnage à 4 niveaux.

3.2 Architecture de Dédoublonnage

┌─────────────────────────────────────────────────────────────────────────┐
│                     HEIMDALL DEDUPLICATION LAYER                        │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  NIVEAU 0 — Motion Gate (Agent, pré-YOLO)                              │
│  ├── Pixel diff > MotionThreshold ? → continue vers YOLO               │
│  └── Pas de mouvement depuis 1s ? → SKIP YOLO, pas de snapshot envoyé   │
│                                                                         │
│  NIVEAU 1 — Spatial Dedup (Agent, post-YOLO)                           │
│  ├── IoU(bbox_courante, bbox_précédente) > 0.6 ? → MÊME objet          │
│  │   → Incrémente DetectionCount, ne crée PAS d'événement              │
│  ├── IoU > 0.6 mais > DedupCooldownSec écoulé ? → NOUVEL événement     │
│  └── IoU ≤ 0.6 → NOUVEL objet → envoyer au Central                     │
│                                                                         │
│  NIVEAU 2 — Temporal Cooldown (Central, post-analyse)                   │
│  ├── Cache IMemoryCache par (cameraId, trackId, objectType)            │
│  ├── Si clé existe encore → événement SUPPRIMÉ (IsSuppressed=true)     │
│  └── Si clé expirée → événement CRÉÉ, clé reset avec nouveau cooldown  │
│                                                                         │
│  NIVEAU 3 — Embedding Dedup (Central, visages)                         │
│  ├── Cache LRU d'embeddings faciaux (float[512], 10K entries)           │
│  ├── Distance L2 < 0.6 ? → MÊME personne → supprimé                   │
│  ├── Personne connue trouvée → update last_seen, événement supprimé    │
│  └── Personne inconnue → ajout cache avec TTL (5min défaut)            │
│                                                                         │
│  NIVEAU 4 — Suppression Hiérarchique (Central, post-événement)         │
│  ├── FaceRecognized émis → ne PAS émettre PersonDetected               │
│  ├── LicensePlateDetected émis → ne PAS émettre VehicleDetected        │
│  └── MotionDetected seul → événement SILENCIEUX (pas de notification)  │
└─────────────────────────────────────────────────────────────────────────┘

3.3 Flux de Détection Complet

Agent : snapshot JPEG toutes les 200ms (adaptatif)
    │
    ▼
[NIVEAU 0] Motion Gate (pixel diff)
    │
    ├── Pas de mouvement → retour, pas de YOLO (économie 90%+ CPU)
    │
    └── Mouvement détecté → YOLOv8 nano (Agent CPU)
              │
              ▼
         Objet trouvé ? (confidence > MinConfidence)
              │
         ┌────┴────┐
         │         │
       NON       OUI → [NIVEAU 1] Spatial Dedup
         │              ├── Même track (IoU > 0.6) + cooldown actif ?
         │              │   → IGNORER (pas d'envoi au Central)
         │              └── Nouvel objet OU cooldown expiré
         │                  → ENVOYER snapshot au Central
         │
    Retour attente                     │
                                       ▼
                              Central reçoit snapshot
                                       │
                                       ▼
                         [NIVEAU 3] Analyse IA (ONNX/broker)
                         ├── Object Detection (YOLOv8, ~40ms GPU)
                         ├── Face Recognition (si personne, ~40ms)
                         └── ALPR (si véhicule + LPR, ~200ms)
                                       │
                            ┌──────────┴──────────┐
                            │                     │
                       [NIVEAU 2] Cooldown   [NIVEAU 3] Embedding
                       Cache Central          Cache LRU Visages
                            │                     │
                            └──────────┬──────────┘
                                       ▼
                            [NIVEAU 4] Suppression
                            Hiérarchique
                                       │
                                       ▼
                              Création Événement
                              + Notification (si non supprimé)

3.4 Cooldowns par Défaut (CameraDetectionProfile)

public class CameraDetectionProfile
{
    // -- Types d'objets à détecter --
    public bool DetectPerson { get; set; } = true;
    public bool DetectVehicle { get; set; } = true;
    public bool DetectAnimal { get; set; } = false;
    public bool DetectPackage { get; set; } = false;
    public bool DetectMotion { get; set; } = true;

    // -- IA lourde (Central GPU) --
    public bool FaceRecognition { get; set; } = true;
    public bool LicensePlateRecognition { get; set; } = true;

    // -- Paramètres de snapshot --
    public int IdleIntervalMs { get; set; } = 1000;     // Pas de mouvement
    public int MotionIntervalMs { get; set; } = 500;     // Mouvement détecté
    public int ActiveIntervalMs { get; set; } = 200;     // Objet détecté
    public double MotionThreshold { get; set; } = 0.3;   // Pixel diff

    // -- Paramètres YOLO --
    public string YoloModel { get; set; } = "yolov8n";
    public double MinConfidence { get; set; } = 0.4;     // ← NOUVEAU

    // -- Dédoublonnage (NOUVEAU) --
    public bool RequireMotionForAI { get; set; } = true; // Motion gate
    public double IoUThreshold { get; set; } = 0.6;      // Spatial dedup
    public int PersonCooldownSec { get; set; } = 30;     // Cooldown entre events
    public int VehicleCooldownSec { get; set; } = 60;
    public int AnimalCooldownSec { get; set; } = 120;
    public int UnknownPersonCooldownSec { get; set; } = 300; // 5 min
    public int MaxEventsPerMinute { get; set; } = 20;    // Rate limit
}

3.5 Pipeline Degradation (Circuit Breaker IA)

Niveau État Action
0 Normal Pipeline complet : Agent YOLO → analyse IA (locale ou broker)
1 Exécutant IA lent (>1s) Agent only (YOLOv8 nano, confidence baissée à 0.3)
2 Exécutant IA down / broker injoignable Agent only + détection de mouvement seulement
3 Agent CPU >80% Snapshots réduits de moitié, alert admin
4 Queue overflow Drop oldest snapshots, alert admin

3.6 Gestion des Erreurs IA (exécutant / broker)

Erreur Comportement Récupération
Timeout (5s) Retry 1x après 100ms, puis degrade level 1 Health check toutes les 30s
HTTP 503 Degrade level 2 immédiat Health check toutes les 10s
Prédiction vide Log, aucun événement Normal
Module désactivé Skip cet appel, log Normal (module peut être réactivé via API)

PARTIE 4 : Authentification, Rôles et Sécurité

4.1 Architecture Auth

┌──────────────────────────────────────────────────────────────────┐
│                      AUTHENTIFICATION                             │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│  HUMAINS (email + password + 2FA TOTP)                           │
│  ├── Admin : tous les sites, toutes les permissions              │
│  ├── Superviseur : sites assignés, lecture + écriture limitée    │
│  └── Viewer : sites assignés, lecture seule                      │
│                                                                   │
│  AGENTS (API Key HMACSHA256 + salt)                              │
│  ├── Clé générée par l'Admin via API                             │
│  ├── Liée à un Site (scope automatique)                          │
│  └── Rotation possible, révocation immédiate                     │
│                                                                   │
│  JWT Claims :                                                     │
│  ├── sub (userId)                                                 │
│  ├── role (Admin|Superviseur|Viewer)                             │
│  ├── permission[] (liste plate des permissions)                   │
│  └── ⚠️ Plus de site IDs dans le JWT (sécurité)                  │
│                                                                   │
│  Site-Scope : lookup serveur à chaque requête                    │
│  (Middleware SiteScope) — pas de site IDs dans le token           │
└──────────────────────────────────────────────────────────────────┘

4.2 Permissions (Policies)

Permission Admin Superviseur Viewer
Site.Read ✅ ✅ ✅
Site.Write ✅ ❌ ❌
Site.Delete ✅ ❌ ❌
Camera.Read ✅ ✅ ✅
Camera.Write ✅ ✅ (ses sites) ❌
Camera.Live ✅ ✅ ✅
Camera.Record ✅ ✅ ❌
Camera.Snapshot ✅ ✅ ❌
Event.Read ✅ ✅ ✅
Person.Read ✅ ✅ ✅
Person.Write ✅ ✅ ❌
Admin.Manage ✅ ❌ ❌
Admin.Users ✅ ❌ ❌
Admin.ApiKeys ✅ ❌ ❌
Admin.Jobs ✅ ❌ ❌

4.3 Mesures de Sécurité Implémentées

Mesure Détail Priorité
Rate limiting AspNetCoreRateLimit sur auth (5 tentatives/15min) P0
2FA TOTP Récupération : 10 codes de secours à l'enrôlement P0
CORS Domaines connus uniquement (pas AllowAnyOrigin) P0
API Keys HMACSHA256 Avec salt par clé, préfixe 8 chars pour identification P0
IDataProtector Purposes isolées par type : CameraCredentials, NotificationCredentials, SmtpConfig P0
Key ring partagé Volume Docker monté : /root/.aspnet/DataProtection-Keys P0
Audit logging Table AuditLog append-only (login, admin actions, permissions) P0
HTTPS partout Y compris AMQP TLS vers le broker (certificat CA auto) P1
Docker secrets /run/secrets/ en production, env vars en dev P1
Secrets dans logs Sanitized : password, token, secret, snapshotUrl masqués dans Serilog et Sentry P1
Mot de passe Min 8 car, 1 maj, 1 chiffre. Check HaveIBeenPwned P2

4.4 StreamingHub — Sécurité renforcée

[Authorize(Policy = AppPermissions.CameraLive)]  // ← PERMISSION explicite
public class StreamingHub : Hub
{
    public async Task RequestStream(Guid cameraId)
    {
        // 1. Vérifier que l'utilisateur a accès au site de la caméra
        var camera = await _db.Cameras
            .Where(c => c.Id == cameraId)
            .Select(c => new { c.SiteId })
            .FirstOrDefaultAsync();

        if (camera == null) throw new HubException("Camera not found");

        if (!Context.User.IsInRole(AppRoles.Admin))
        {
            var userId = Context.User.GetUserId();
            var hasAccess = await _db.UserSites
                .AnyAsync(us => us.UserId == userId && us.SiteId == camera.SiteId);

            if (!hasAccess) throw new HubException("Access denied to this camera");
        }

        // 2. Ajouter aux groupes
        await Groups.AddToGroupAsync(Context.ConnectionId, $"viewer-{cameraId}");
        await Clients.Group($"camera-{cameraId}")
            .SendAsync("ViewerConnected", Context.ConnectionId);
    }
}

4.5 Enregistrement Agent — Flux Complet

Admin crée Site
    │
    ▼
POST /api/sites → génère token + API Key (PREMIÈRE ET UNIQUE FOIS)
    │
    ├── RegistrationToken (plain, affiché 1 fois)
    ├── ApiKey (plain, affiché 1 fois — NOUVEAU)
    ├── TokenHash (SHA256) en DB
    ├── ApiKeyHash (HMACSHA256) en DB
    └── docker run command avec les deux clés

Admin donne le token + API Key à l'Agent (hors bande)
    │
    ▼
Agent démarre avec HEIMDALL_SITE_TOKEN + HEIMDALL_API_KEY
    │
    ▼
POST /api/agents/register { token, hostname, version, apiKey }
    │
    ├── Token valide ? → Agent enregistré, statut Online
    ├── ApiKey associée au site pour les appels suivants
    └── Retour : { agentId, iceServers }
    │
    ▼
Agent lance heartbeat (30s) avec API Key
Agent lance CameraHealthCheck (30s) avec API Key
Agent se connecte à SignalR avec API Key

PARTIE 5 : SignalR — 5 Hubs Détaillés

5.1 Hubs

Hub Route Auth Clients Usage
EventsHub /hubs/events JWT + API Key Browser + Agent Événements détection en temps réel
StreamingHub /hubs/streaming JWT + API Key (+ Camera.Live) Browser + Agent Signaling WebRTC (SDP + ICE)
MonitoringHub /hubs/monitoring JWT Browser Status agents, caméras, stockage
NotificationsHub /hubs/notifications JWT Browser Notifications in-app avec badge
AdminHub /hubs/admin JWT (Admin only) Browser (Admin) Broadcast changements config

5.2 Groupes SignalR

// Standardisé sur tous les hubs :
"all-sites"                        // Admin : voit tout (Events, Monitoring)
"site-{siteId}"                    // User : voit ses sites (Events, Monitoring)
"camera-{cameraId}"                // Agent source pour le streaming
"viewer-{cameraId}"                // Browser viewer du flux
"notif-{userId}"                   // Notifications par utilisateur
"admin-broadcast"                  // Broadcast admin (Config changée)

5.3 Événements par Hub

EventsHub

Event Payload Destinataires
EventCreated EventDto Groupe site-{siteId}
PersonDetected PersonEventDto Groupe site-{siteId}
UnknownPerson UnknownPersonDto site-{siteId} + all-sites
VehicleDetected VehicleEventDto Groupe site-{siteId}
LicensePlateRead PlateEventDto Groupe site-{siteId}
MotionDetected MotionDto Groupe site-{siteId} (silencieux)

MonitoringHub

Event Payload Destinataires
AgentStatusChanged AgentStatusDto Groupe monitoring-site-{siteId}
CameraStatusChanged CameraStatusDto Groupe monitoring-site-{siteId}
StorageUsageUpdated StorageDto admin-broadcast
GpuUsageUpdated GpuDto admin-broadcast
JobStatusChanged JobDto admin-broadcast

NotificationsHub

Event Payload Destinataires
NewNotification NotificationDto notif-{userId}
UnreadCount int notif-{userId}

AdminHub

Event Payload Destinataires
ConfigChanged ConfigChangeDto admin-broadcast
CameraAdded CameraDto admin-broadcast + site-{siteId}
CameraRemoved Guid admin-broadcast + site-{siteId}
UserRoleChanged UserRoleDto admin-broadcast

5.4 Scaling (Backplane Redis)

// Program.cs — quand multi-instance Central
builder.Services.AddSignalR()
    .AddStackExchangeRedis(config =>
    {
        config.ConnectionFactory = async _ =>
        {
            var connection = await ConnectionMultiplexer.ConnectAsync(
                builder.Configuration.GetConnectionString("Redis"));
            return connection;
        };
    });

PARTIE 6 : WebRTC et Pipeline Vidéo

6.1 Stack

Composant Technologie Version
WebRTC SIPSorcery 10.0.12+
Capture FFmpeg (via SIPSorceryMedia.FFmpeg) 6+
Streaming WebRTC P2P (SRTP/H264, pas de decode→re-encode) —
TURN Coturn 4.6+
SFU MediaMTX (v2 uniquement) 1.0+

6.2 Pipeline Basse Latence (< 500ms LAN)

Caméra RTSP (H264)
    │
    ├── FFmpeg (mode PASSTHROUGH, pas de decode→re-encode)
    │   │  ffmpeg -rtsp_transport tcp -buffer_size 0 -max_delay 0
    │   │         -i rtsp://... -g 1 -tune zerolatency
    │   │         -preset ultrafast -c:v copy   ← PASSTHROUGH !
    │   │         -f rawvideo pipe:1
    │   └── Latence : ~100ms (1 frame buffer)
    │
    ▼
SIPSorcery WebRTC PeerConnection
    ├── Codec : H264 (pas de transcode)
    ├── DTLS-SRTP : chiffrement natif
    └── ICE : STUN + TURN (coturn obligatoire)
    │
    ▼
SignalR Signaling (/hubs/streaming)
    ├── SDP Offer → Browser
    ├── SDP Answer ← Browser
    └── ICE Candidates ↔ bidirectionnel
    │
    ▼
Navigateur <video> (module JS autonome liveView.js)
    ├── RTCPeerConnection côté browser
    ├── Survit aux reconnexions Blazor Server
    └── Latence : ~100ms (jitter buffer)

Latence estimée :

Segment LAN WAN (sans TURN) WAN (avec TURN)
Capture RTSP 100ms 200ms 200ms
FFmpeg passthrough 16ms 16ms 16ms
SIPSorcery encodage 16ms 16ms 16ms
ICE + DTLS 30ms 100ms 200ms
Réseau 2ms 50ms 100ms
Navigateur 50ms 100ms 150ms
Total ~214ms ~482ms ~682ms

Conclusion : < 500ms tenable en LAN et WAN sans TURN. Avec TURN, prévoir 500-700ms.

6.3 Module JS Autonome (wwwroot/js/liveView.js)

Le module JS gère le cycle de vie WebRTC indépendamment de Blazor Server :

class HeimdallLiveView {
    constructor(cameraId, signalrHubUrl) {
        this.pc = null;
        this.cameraId = cameraId;
        this.hubConnection = new HubConnectionBuilder()
            .withUrl(signalrHubUrl)
            .withAutomaticReconnect()
            .build();
    }

    async start() {
        this.pc = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' },
                { urls: 'turns:turn.heimdall.local:3478',
                  username: '...', credential: '...' }  // creds via signaling
            ]
        });

        this.pc.ontrack = (event) => {
            document.getElementById(`video-${this.cameraId}`)
                .srcObject = event.streams[0];
        };

        this.hubConnection.on('SdpOffer', (sdp) => {
            this.pc.setRemoteDescription({ type: 'offer', sdp });
            this.pc.createAnswer().then(answer => {
                this.pc.setLocalDescription(answer);
                this.hubConnection.send('SendAnswer', answer.sdp);
            });
        });

        // ...
    }
}

PARTIE 7 : Stockage et Hangfire

7.1 Stockage Alarik/S3

File Type Path Pattern Rétention
Enregistrements vidéo recordings/{siteId}/{cameraId}/{date}/{timestamp}.ts Configurable (7-90 jours)
Snapshots snapshots/{siteId}/{cameraId}/{date}/{eventId}.jpg Lié à la durée de vie de l'événement
Visages inconnus snapshots/unknown/{personId}.jpg 30 jours

7.2 Correction : Pas de Race Condition sur S3Cleanup

// Upload sécurisé :
// 1. Uploader vers staging/ avec timestamp
// 2. Créer l'enregistrement en DB
// 3. Move atomique vers recordings/ (ou delete staging si erreur)

public async Task UploadWithTransactionAsync(
    Stream content, string finalPath, CancellationToken ct)
{
    var stagingPath = $"staging/{Guid.NewGuid()}.tmp";

    try
    {
        // 1. Upload vers staging
        await _storage.UploadAsync(stagingPath, content, ct);

        // 2. Move atomique vers destination finale
        await _storage.MoveAsync(stagingPath, finalPath, ct);
    }
    catch
    {
        // Nettoyage staging
        await _storage.DeleteAsync(stagingPath, ct);
        throw;
    }
}

7.3 Correction : RetentionCheckJob Optimisé

// AVANT (N+1 + mémoire) :
var policies = await _db.StoragePolicies.Include(p => p.Camera).ToListAsync();
foreach (var policy in policies) {
    var expired = await _db.Recordings.Where(r => r.CameraId == policy.CameraId ...).ToListAsync();
    foreach (var rec in expired) { await storageProvider.DeleteAsync(rec.StoragePath); }
}

// APRÈS (batch + ExecuteDelete) :
await _db.Database.ExecuteSqlRawAsync(@"
    DELETE FROM recordings
    WHERE timestamp < NOW() - INTERVAL '1 day' * (
        SELECT sp.retention_days FROM storage_policies sp
        WHERE sp.id = recordings.storage_policy_id
    )
    RETURNING recordings.storage_path
", ct);

// Puis S3 batch delete (1000 par appel)
await storageProvider.DeleteBatchAsync(storagePaths, ct);

7.4 Hangfire Configuration

// Central — with schema isolation
builder.Services.AddHangfire(config =>
{
    config.UsePostgreSqlStorage(options =>
    {
        options.ConnectionString = connectionString;
        options.SchemaName = "hangfire";  // ← Isoler du schéma app
    });
});

// Queue isolation
[Queue("email")]
public class SendNotificationEmailJob { ... }

[Queue("gotify")]
public class SendNotificationGotifyJob { ... }

[Queue("digest")]
public class DailyDigestJob { ... }

// Worker counts dédiés
builder.Services.AddHangfireServer(options =>
{
    options.WorkerCount = 4;
    options.Queues = ["default", "email", "gotify", "digest"];
});

7.5 Jobs Hangfire — Tous

Central (PostgreSQL)

Job Schedule Queue Description
RetentionCheckJob Quotidien 3h default Purge enregistrements + S3 batch delete
S3CleanupJob Quotidien 4h default Nettoie fichiers orphelins Alarik (pagination)
CleanupUnknownFacesJob Dimanche 5h default Supprime visages inconnus > 30j
CleanupLicensePlatesJob Dimanche 6h default Plaques non associées > 30j
DatabaseMaintenanceJob Hebdomadaire dimanche 7h default VACUUM events + REINDEX (VACUUM FULL mensuel)
DailyDigestJob Quotidien 8h digest Résumé quotidien email
WeeklyDigestJob Lundi 8h digest Résumé hebdomadaire
SendNotificationJob Fire-and-forget email/gotify Notification avec retry 3x

Agent (InMemory)

Job Schedule Description
CameraHealthCheckJob 30s Vérifie si les caméras répondent
HeartbeatSenderJob 30s POST /heartbeat vers le Central
GpuWatchdogJob 5min Détecte GPU, rapporte au Central
LocalRetentionCleanupJob 1h Nettoie enregistrements locaux (fallback)

PARTIE 8 : Notifications

8.1 Canaux

Canal Usage Priorité Queue Hangfire
Email (SMTP) Importants + résumés P0 email
Gotify Alertes temps réel P0 gotify
In-app (SignalR) Badge UI P0 Direct (pas Hangfire)

8.2 Types d'Événements Notifiables

EventType Email Gotify In-App Cooldown (secondes)
PersonDetected ✅ ✅ ✅ 30
UnknownPerson ✅ (haut) ✅ ✅ 300 (5 min)
FaceRecognized 🟡 (option) 🟡 ✅ 30
VehicleDetected ✅ ✅ ✅ 60
LicensePlateDetected 🟡 ✅ ✅ 60
MotionDetected ❌ (trop) ❌ ✅ (silencieux) 10
CameraOffline ✅ ✅ ✅ 600 (10 min)
CameraOnline 🟡 🟡 ✅ 600
DailySummary ✅ ❌ ❌ N/A
WeeklySummary ✅ ❌ ❌ N/A

8.3 Rate Limiting Notifications

public class NotificationRateLimiter
{
    private readonly IMemoryCache _cache;

    public bool ShouldSend(Guid cameraId, EventType type, Guid? trackId)
    {
        var key = $"notif-rate:{cameraId}:{type}:{trackId ?? Guid.Empty}";
        var count = _cache.GetOrCreate(key, entry =>
        {
            entry.SlidingExpiration = TimeSpan.FromMinutes(1);
            return 0;
        });

        if (count >= 20) return false;  // Max 20 events/min/camera/type

        _cache.Set(key, count + 1, TimeSpan.FromMinutes(1));
        return true;
    }
}

8.4 Templates

  • Moteur : Scriban (Markdown → HTML pour email)
  • Stockés en DB (table NotificationTemplate)
  • Éditables depuis l'UI Admin
  • Fallback : fr → en → template par défaut hardcodé
  • Signature : [Heimdall] dans le sujet

PARTIE 9 : Application web installable (PWA)

La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans la première étape.

Spécification actuelle : audit et plan PWA.


PARTIE 10 : Plan d'Implémentation Optimisé

10.1 7 Étapes Incrémentales

Le plan est structuré en 7 étapes, chacune produisant un logiciel fonctionnel et testable.

Étape Phases Nom Livrable
1 1→12 MVP Multi-Site N sites, N agents enregistrés, heartbeat 30s, status Online, API Key auth, Docker
2 13→14 Caméras + Temps Réel API caméras, ONVIF discovery, 5 hubs SignalR
3 15→16 Vidéo + IA FFmpeg passthrough, WebRTC <500ms, détection YOLO, déduplication 4 niveaux
4 17→19 Événements + Notifications API events/persons/vehicles, Email+Gotify, jobs retention/cleanup
5 20→23 UI Blazor Complète Dashboard, Sites, Caméras, Live, Admin
6 24 Production Hardening Sécurité, monitoring, backup, k6
7 25 PWA Application web installable, reprise et Web Push

> **Principe** : Chaque phase est un **incrément fonctionnel**. À la fin de chaque phase,
> on peut Tester, Build, et Dockeriser. Rien n'est "cassé" entre deux phases.

═══════════════════════════════════════════════════════════════════════ ÉTAPE 1 — MVP MULTI-SITE (Central + Agent fonctionnel sans métier) ═══════════════════════════════════════════════════════════════════════

┌──────────────────────────────────────────────────────────────────┐ │ FOUNDATION — Solution, Tests, CI/CD │ │ Rien ne dépend d'eux, tout dépend d'eux │ └──────────────────────────────────────────────────────────────────┘

Phase 1 — Solution .NET 10 + Clean Architecture ├── Solution .slnx avec 9 projets (Domain, Primitives, Application, │ Infrastructure, Api, Web, Workers, Agent, Contracts) ├── Project references (flux inward) ├── NuGet packages (EF Core, Npgsql, Hangfire, SIPSorcery, Serilog...) ├── Docker Compose de dev (PostgreSQL + Alarik + Redis) ├── Verify: dotnet build → 0 errors │ ✅ Fonctionnel à la fin de cette phase : │ • dotnet build sur TOUS les projets : 0 erreur │ • docker compose up central + postgresql + alarik : démarre │ • Solution navigable dans Rider/VS

Phase 2 — Test Framework & Tooling ├── xUnit + Shouldly + NSubstitute + FluentAssertions ├── Testcontainers (PostgreSQL + Alarik réels) ├── bUnit (Blazor UI), Playwright (E2E) ├── .editorconfig + analyzers + StyleCop ├── Verify: dotnet test → green (skeleton pass) │ ✅ Fonctionnel à la fin de cette phase : │ • dotnet test sur chaque projet : squelette vert │ • Testcontainers lance PostgreSQL + Alarik pour les tests │ • .editorconfig analysers appliqués

Phase 3 — CI/CD ├── Forgejo Actions / GitHub Actions ├── docker buildx multi-arch (linux/amd64 + arm64) ├── dotnet build + test dans le pipeline ├── Images : heimdall-central, heimdall-agent ├── Verify: pipeline vert sur push │ ✅ Fonctionnel à la fin de cette phase : │ • git push → pipeline CI déclenché │ • docker images publiées sur Docker Hub / registry

┌──────────────────────────────────────────────────────────────────┐ │ DOMAIN — Entités + Migrations │ │ Tout le métier repose sur le domaine │ └──────────────────────────────────────────────────────────────────┘

Phase 4 — Domain Model (entités multi-site uniquement) ├── Entités CŒUR : Site, Agent (avec ApiKeyHash, ApiKeyPrefix) ├── Entités AUTH : User, Role (Identity), UserSite, ApiKey, AuditLog ├── Entités MÉTIER (définies mais migrations seules, pas de logique) : │ Camera, CameraCredentials, CameraDetectionProfile, StoragePolicy, │ Person, Vehicle, Event, Recording, LicensePlate, │ NotificationConfig, NotificationTemplate ├── Enums (EventType, CameraStatus, AgentStatus, StorageProvider...) ├── Soft delete sur Site, Camera, Person (IsDeleted, DeletedAt) ├── Audit fields (CreatedAt, UpdatedAt) sur TOUTES les entités ├── Index : Agents(SiteId, LastHeartbeat) WHERE Status='Online' ├── EF Core EntityTypeConfiguration pour chaque entité ├── Migration initiale complète (dotnet ef migrations add InitialCreate) ├── Verify: dotnet build → 0 errors │ ⚠️ Les tables métier (Camera, Person, Event...) existent en DB │ mais ne sont PAS utilisées par les services de l'Étape 1. │ Elles sont créées maintenant pour éviter des migrations futures │ qui toucheraient des tables avec des millions de lignes. │ ✅ Fonctionnel à la fin de cette phase : │ • dotnet ef database update → PostgreSQL avec 20+ tables créées │ • Site et Agent insérables en base │ • Audit fields auto-set (SaveChangesInterceptor) │ • Soft delete activé sur Site (QueryFilter)

┌──────────────────────────────────────────────────────────────────┐ │ SECURITY — Authentification + Autorisation │ │ Prérequis pour toute API │ │ → FIN DE PHASE 5 : on peut se connecter à l'API │ └──────────────────────────────────────────────────────────────────┘

Phase 5 — Security Foundation ├── ASP.NET Core Identity (User, Role, JWT) ├── JWT : claims = sub, role, permission[] (PAS de site IDs) ├── API Key auth handler (HMACSHA256 + salt, préfixe 8 chars) ├── 2FA TOTP + 10 codes de récupération ├── Authorization policies (Admin, Superviseur, Viewer) ├── AuditLog service + middleware (append-only) ├── IDataProtector (purposes isolées, key ring volume Docker) ├── Rate limiting sur auth (5 tentatives/15min) ├── SiteScopeMiddleware (lookup serveur, pas dans le JWT) ├── Verify: dotnet test → auth flows green │ ✅ Fonctionnel à la fin de cette phase : │ • POST /api/auth/login → JWT token (admin + user) │ • POST /api/auth/register → création compte │ • POST /api/auth/2fa → TOTP fonctionnel │ • API Key auth handler : header X-Api-Key → authentifie │ • Policies : [Authorize(Policy = "Admin.Manage")] │ • AuditLog écrit en DB à chaque action sensible │ • IDataProtector peut chiffrer/déchiffrer des credentials

┌──────────────────────────────────────────────────────────────────┐ │ APPLICATION + INFRASTRUCTURE — Logique métier + Accès données │ └──────────────────────────────────────────────────────────────────┘

Phase 6 — Application Layer (CQRS — périmètre multi-site) ├── Commands + Queries + Handlers (Médiator) ├── FluentValidation pour chaque commande ├── DTOs : SiteDto, AgentDto, UserDto, ApiKeyDto ├── Interfaces : ISiteService, IAgentService, IAuthService ├── IStorageProvider (interface seule — implémentée à la Phase 8) ├── Verify: dotnet test → unit tests handlers green │ ✅ Fonctionnel à la fin de cette phase : │ • CreateSiteCommand → Handler → Site créé │ • RegisterAgentCommand → Handler → Agent enregistré │ • GetSitesQuery → Handler → liste des sites (filtré par UserSite) │ • GetAgentsBySiteQuery → Handler → agents d'un site │ • FluentValidation bloque les données invalides │ • Tests unitaires : handlers testés avec NSubstitute

Phase 7 — Infrastructure EF Core ├── HeimdallDbContext (tous DbSet, EntityTypeConfigurations) ├── HangfireDbContext (schéma isolé "hangfire") ├── Repositories concrets (EF Core) ├── SaveChangesInterceptor (auto-set CreatedAt/UpdatedAt) ├── AuditInterceptor ├── Data Protection Key Ring (volume Docker persistant) ├── Connection strings : PostgreSQL, Hangfire, Redis ├── Verify: dotnet test → Testcontainers green │ ✅ Fonctionnel à la fin de cette phase : │ • SiteRepository.GetByIdAsync → retourne Site depuis PostgreSQL │ • AgentRepository.GetOnlineBySiteIdAsync → agents Online par site │ • AuditInterceptor logue les changements dans AuditLog │ • CreatedAt/UpdatedAt auto-set sur toutes les entités │ • Tests intégration : Testcontainers PostgreSQL, vrai DB

Phase 8 — Storage Alarik/S3 ├── AlarikStorageProvider (IStorageProvider) ├── Staging prefix pour uploads atomiques ├── Batch delete (RemoveObjectsAsync, 1000/appel) ├── Health check → /health ├── Verify: dotnet test → Testcontainers Alarik green │ ✅ Fonctionnel à la fin de cette phase : │ • UploadAsync → fichier dans Alarik (bucket recordings/) │ • DownloadAsync → fichier depuis Alarik │ • DeleteBatchAsync → 1000 fichiers supprimés en 1 appel │ • Upload atomique : staging/ → move → recordings/ │ • Si crash pendant upload : staging nettoyé, pas de fichiers orphelins │ • Tests intégration : Testcontainers Alarik, vrai S3

┌──────────────────────────────────────────────────────────────────┐ │ API MULTI-SITE — Auth + Sites + Agents │ │ → JALON 1 : API multi-site fonctionnelle + testable via Swagger │ └──────────────────────────────────────────────────────────────────┘

Phase 9 — API Auth (premier endpoint public) ├── POST /api/auth/register (email verification + rate limit) ├── POST /api/auth/login (JWT + refresh token rotation) ├── POST /api/auth/2fa (verify, setup, recovery codes) ├── POST /api/auth/refresh ├── GET /api/auth/profile ├── PUT /api/auth/profile ├── POST /api/api-keys (create, HMACSHA256 hash) ├── GET /api/api-keys (list, prefix only) ├── DELETE /api/api-keys/{id} (révocation) ├── Verify: dotnet test → WebApplicationFactory green │ ✅ Fonctionnel à la fin de cette phase (tests API via Swagger) : │ ┌─ Requête ─────────────────────────────────────────────┐ │ │ POST /api/auth/login │ │ │ { "email": "admin@heimdall.local", "password": "..." }│ │ └───────────────────────────────────────────────────────┘ │ ┌─ Réponse ─────────────────────────────────────────────┐ │ │ { "token": "eyJ...", "refreshToken": "...", │ │ │ "profile": { "displayName": "Admin", "role": 1 } } │ │ └───────────────────────────────────────────────────────┘ │ │ • Nouvel utilisateur : register → email verification → login │ • Rate limiting : 5 tentatives erronées → bloqué 15 min │ • 2FA : setup → scan QR code → code TOTP valide → login │ • 10 codes de récupération générés à l'enrôlement 2FA │ • API Key : créer → list (prefix only) → révoquer │ • Refresh token : rotation (ancien invalidé)

Phase 10 — API Sites + Agents (ceur multi-site) ├── CRUD Sites ├── POST /api/sites/{id}/generate-token (token + API Key, 1 appel) │ → Retourne docker command pré-remplie ├── POST /api/agents/register (token + apiKey → {agentId}) ├── POST /api/agents/{id}/heartbeat (optimistic concurrency) ├── GET /api/agents (list, filtrés par site, avec status) ├── GET /api/agents/{id} ├── DELETE /api/agents/{id} ├── SiteScopeMiddleware en action sur TOUS les endpoints ├── Verify: dotnet test → API multi-site green │ ✅ Fonctionnel à la fin de cette phase (tests API via Swagger) : │ ┌─ Créer un site ────────────────────────────────────────┐ │ │ POST /api/sites │ │ │ { "name": "Entrepôt A", "address": "Paris", │ │ │ "timezone": "Europe/Paris" } │ │ │ → 201 { "id": "guid-1", "name": "Entrepôt A", ... } │ │ └───────────────────────────────────────────────────────┘ │ │ ┌─ Générer un token d'enregistrement ────────────────────┐ │ │ POST /api/sites/guid-1/generate-token │ │ │ → 200 { "registrationToken": "abc...", │ │ │ "apiKey": "heimdall_sk_abc...", │ │ │ "command": "docker run -e ... -e ... │ │ │ heimdall/agent:latest" } │ │ └───────────────────────────────────────────────────────┘ │ │ ┌─ Agent se register ────────────────────────────────────┐ │ │ POST /api/agents/register │ │ │ { "token": "abc...", "apiKey": "heimdall_sk_abc...", │ │ │ "hostname": "agent-01", "version": "1.0.0" } │ │ │ → 201 { "agentId": "guid-42" } │ │ └───────────────────────────────────────────────────────┘ │ │ ┌─ Heartbeat (toutes les 30s par l'Agent) ──────────────┐ │ │ POST /api/agents/guid-42/heartbeat │ │ │ Headers: X-Api-Key: heimdall_sk_abc... │ │ │ → 200 { "status": "Online", "lastHeartbeat": "..." } │ │ └───────────────────────────────────────────────────────┘ │ │ ┌─ Lister les agents d'un site ──────────────────────────┐ │ │ GET /api/sites/guid-1/agents │ │ │ → 200 [{ "id": "guid-42", "hostname": "agent-01", │ │ │ "status": "Online", │ │ │ "lastHeartbeat": "2026-07-16T12:00:00Z" }] │ │ └───────────────────────────────────────────────────────┘ │ │ • Un User voit UNIQUEMENT les sites auxquels il est assigné │ • Un Admin voit TOUS les sites (même sans UserSite) │ • Token d'enregistrement valable 24h, affiché 1 fois │ • API Key générée en même temps que le token │ • Heartbeat avec optimistic concurrency (pas de race condition) │ • Agent marqué Offline si pas de heartbeat depuis 90s

┌──────────────────────────────────────────────────────────────────┐ │ HANGFIRE — Jobs d'infrastructure │ │ Jobs de fond nécessaires au multi-site │ └──────────────────────────────────────────────────────────────────┘

Phase 11 — Hangfire Foundation + Jobs Multi-Site ├── Hangfire config (PostgreSQL, SchemaName="hangfire", 3 queues) ├── Queues : default, heartbeat, maintenance ├── Workers : default=2, heartbeat=1, maintenance=1 ├── Dashboard [Authorize(Policy = AdminJobs)] ├── Jobs Multi-Site : │ ├── HeartbeatCleanupJob (purge agents sans heartbeat > 90s) │ └── DatabaseMaintenanceJob (VACUUM, REINDEX — hebdo) ├── Verify: jobs s'exécutent, dashboard accessible │ ✅ Fonctionnel à la fin de cette phase : │ • /hangfire accessible (Admin uniquement) │ • HeartbeatCleanupJob tourne toutes les minutes : │ → Passe les agents sans heartbeat depuis 90s en Offline │ • DatabaseMaintenanceJob hebdomadaire : │ → VACUUM, REINDEX pour éviter l'index bloat │ • 3 queues isolées : un job lent ne bloque pas les urgences

┌──────────────────────────────────────────────────────────────────┐ │ AGENT — Premier déploiement Docker │ │ → JALON 2 : Agent qui s'enregistre + heartbeat + Docker │ │ → C'EST L'OBJECTIF DE L'ÉTAPE 1 │ └──────────────────────────────────────────────────────────────────┘

Phase 12 — Agent Foundation (Docker-only) ├── Docker-only : heimdall/agent:latest ├── AgentRegistrationService (register via API au premier démarrage) ├── HeartbeatSenderJob (Hangfire InMemory Central, 30s) ├── Agent → Central : API Key auth (X-Api-Key header) ├── Central → Agent : heartbeat OK renouvelle le statut Online ├── docker-compose.yml minimal pour l'Agent : │ docker run -e HEIMDALL_CENTRAL_URL=https://central.example.com
│ -e HEIMDALL_SITE_TOKEN=abc123def456
│ -e HEIMDALL_API_KEY=heimdall_sk_abc123def456
│ -e HEIMDALL_AGENT_NAME=agent-paris-01
│ heimdall/agent:latest ├── Verify: Agent démarre → register → heartbeat 30s │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ SCÉNARIO DE TEST ─────────────────────────────────────────┐ │ │ │ │ │ 1. Admin se connecte → POST /api/auth/login │ │ │ → JWT token │ │ │ │ │ │ 2. Admin crée un site → POST /api/sites │ │ │ → Site créé : "Entrepôt A" │ │ │ │ │ │ 3. Admin génère token + API Key → │ │ │ POST /api/sites/{id}/generate-token │ │ │ → Token: abc..., API Key: heimdall_sk_... │ │ │ → docker command affichée dans l'UI │ │ │ │ │ │ 4. Admin exécute la docker command sur le site distant │ │ │ → docker run heimdall/agent:latest ... │ │ │ │ │ │ 5. Agent démarre → se registre via API │ │ │ POST /api/agents/register │ │ │ → Agent enregistré avec son API Key │ │ │ │ │ │ 6. Agent envoie heartbeat toutes les 30s │ │ │ POST /api/agents/{id}/heartbeat │ │ │ → Status: Online │ │ │ → Central horodate : lastHeartbeat = now │ │ │ │ │ │ 7. Si l'Agent s'arrête → plus de heartbeat │ │ │ → HeartbeatCleanupJob (Phase 11) marque Offline après 90s │ │ │ │ │ │ 8. On répète pour N sites × N agents │ │ │ │ │ └────────────────────────────────────────────────────────────┘ │ │ • ADMIN peut : │ → Créer N sites │ → Générer token + API Key pour chaque site │ → Lister les agents par site avec leur status │ → Voir les agents Online/Offline en temps réel │ → Voir les agents qui n'ont pas envoyé de heartbeat │ │ • AGENT peut : │ → Se register avec token + API Key (1 seule fois) │ → Envoyer heartbeat toutes les 30s │ → S'authentifier via API Key pour TOUS les appels │ → Être déployé sur N machines distantes │ │ ✔ JALON MVP MULTI-SITE ATTEINT — PRÊT POUR L'ÉTAPE 2 │ ⇒ stack multi-site fonctionnelle : API + Auth + Agents

═══════════════════════════════════════════════════════════════════════ ÉTAPE 2 — CAMÉRAS + TEMPS RÉEL Caméras, ONVIF, SignalR (le socle du métier) ═══════════════════════════════════════════════════════════════════════

Phase 13 — API Caméras + ONVIF ├── CRUD Caméras (avec AgentId, StoragePolicyId, DetectionProfileId) ├── POST /api/cameras (credentials chiffrés IDataProtector) │ Body: { "siteId", "agentId", "name", "manufacturer", "model", │ "rtspUrl", "onvifUsername", "onvifPassword", │ "storagePolicyId" } │ → Credentials (user/pass) chiffrés via IDataProtector en DB ├── GET /api/cameras (list, filtrés par site/agent/status) ├── GET /api/cameras/{id} ├── PUT /api/cameras/{id} (update, y compris credentials) ├── DELETE /api/cameras/{id} (soft delete) ├── GET /api/cameras/{id}/profile → CameraDetectionProfile ├── PUT /api/cameras/{id}/profile → update DetectionProfile ├── POST /api/cameras/{id}/snapshot (trigger snapshot manuel) ├── ONVIF Device Discovery │ ├── POST /api/sites/{siteId}/onvif/discover │ │ → Scan WS-Discovery sur le sous-réseau du site │ │ → Retourne liste des caméras ONVIF trouvées │ └── POST /api/cameras/onvif/probe { "ip", "port", "username", "password" } │ → Interroge une caméra ONVIF spécifique │ → Retourne : capabilities, résolutions, codecs supportés ├── Verify: dotnet test → API caméras green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ Créer une caméra ──────────────────────────────────────────┐ │ │ POST /api/cameras │ │ │ Authorization: Bearer eyJ... (Admin) │ │ │ { │ │ │ "siteId": "guid-1", │ │ │ "agentId": "guid-42", │ │ │ "name": "Entrée principale", │ │ │ "manufacturer": "Imou", │ │ │ "model": "IPC-T2A30P", │ │ │ "rtspUrl": "rtsp://192.168.1.100:554/stream1", │ │ │ "onvifUsername": "admin", │ │ │ "onvifPassword": "password123", │ │ │ "storagePolicyId": "guid-policy-1" │ │ │ } │ │ │ → 201 { │ │ │ "id": "guid-cam-1", │ │ │ "name": "Entrée principale", │ │ │ "status": "Online", │ │ │ "rtspUrl": "rtsp://192.168.1.100:554/stream1", │ │ │ "capabilities": { "ptz": false, "audio": false } │ │ │ } │ │ │ ⚠️ onvifUsername/password NON retournés (chiffrés en DB) │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─ Découverte ONVIF ──────────────────────────────────────────┐ │ │ POST /api/sites/guid-1/onvif/discover │ │ │ → 200 { "cameras": [ │ │ │ { "ip": "192.168.1.100", "manufacturer": "Imou", │ │ │ "model": "IPC-T2A30P", "onvifVersion": "20.06" } │ │ │ ]} │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─ Modifier le profil de détection ───────────────────────────┐ │ │ PUT /api/cameras/guid-cam-1/profile │ │ │ { │ │ │ "detectPerson": true, │ │ │ "detectVehicle": true, │ │ │ "detectAnimal": false, │ │ │ "faceRecognition": true, │ │ │ "licensePlateRecognition": true, │ │ │ "snapshotIntervalMs": 200, │ │ │ "requireMotionForAI": true, │ │ │ "minConfidence": 0.4, │ │ │ "personCooldownSec": 30, │ │ │ "maxEventsPerMinute": 20 │ │ │ } │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─ Lister les caméras d'un site ───────────────────────────────┐ │ │ GET /api/sites/guid-1/cameras │ │ │ → 200 [{ "id": "guid-cam-1", "name": "Entrée principale", │ │ │ "status": "Online", "agentId": "guid-42" }] │ │ └─────────────────────────────────────────────────────────────┘ │ │ • Admin peut créer/modifier/supprimer des caméras │ • Viewer voit les caméras (read-only) sur ses sites │ • Credentials ONVIF/RTSP chiffrés via IDataProtector │ • Soft delete : caméra dans la corbeille, pas vraiment supprimée │ • Découverte ONVIF réseau : scan automatique des caméras

Phase 14 — SignalR Hubs (temps réel) ├── 5 hubs : Events, Streaming, Monitoring, Notifications, Admin ├── EventsHub : │ ├── EventCreated → Groupe "site-{siteId}" │ ├── PersonDetected → "site-{siteId}" │ ├── VehicleDetected → "site-{siteId}" │ └── UnknownPerson → "site-{siteId}" + "all-sites" ├── StreamingHub : │ ├── RequestStream(cameraId) → check site-scope → ajoute au groupe │ ├── RegisterSource(agentId, cameraId) → Agent rejoint "camera-{id}" │ └── SDP/ICE relay entre Agent et Viewer ├── MonitoringHub : │ ├── AgentStatusChanged → "monitoring-site-{siteId}" │ ├── CameraStatusChanged → "monitoring-site-{siteId}" │ └── StorageUsageUpdated → "admin-broadcast" ├── NotificationsHub : NewNotification, UnreadCount → "notif-{userId}" ├── AdminHub : ConfigChanged, CameraAdded/Removed → "admin-broadcast" + "site-{siteId}" ├── Groupes standardisés : "all-sites", "site-{id}", "camera-{id}", │ "viewer-{id}", "notif-{userId}" ├── API Key auth → Agent rejoint le groupe de son site automatiquement ├── Redis backplane préparé (en commentaire, activable pour scaling) ├── Verify: dotnet test + tests hubs connexion/groupes │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ Browser reçoit un événement temps réel ─────────────────────┐ │ │ SignalR Connect: /hubs/events │ │ │ Client → Server: "JoinGroup", "site-guid-1" │ │ │ Server → Client: "EventCreated", { │ │ │ "id": "guid-ev-1", "type": "person", │ │ │ "cameraName": "Entrée", "timestamp": "2026-07-16T14:23Z" │ │ │ } │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─ Agent se connecte et rejoint son site ──────────────────────┐ │ │ SignalR Connect: /hubs/events (Header X-Api-Key: ...) │ │ │ → OnConnectedAsync détecte API Key → lookup siteId │ │ │ → Groups.AddToGroupAsync(connectionId, "site-guid-1") │ │ └─────────────────────────────────────────────────────────────┘ │ │ ┌─ Streaming signaling (WebRTC) ───────────────────────────────┐ │ │ Browser → StreamingHub.RequestStream(guid-cam-1) │ │ │ → Vérifie que l'User a accès au site de la caméra │ │ │ → Ajoute le browser au groupe "viewer-{cameraId}" │ │ │ → Notifie l'Agent via Clients.Group("camera-{id}") │ │ │ .SendAsync("ViewerConnected", connectionId) │ │ │ → Agent envoie SDP Offer via SendSdp │ │ │ → Browser reçoit SdpOffer, crée RTCPeerConnection │ │ │ → ICE candidates relayés bidirectionnellement │ │ └─────────────────────────────────────────────────────────────┘ │ │ • 5 hubs indépendants, chacun avec son niveau d'auth │ • StreamingHub : vérification site-scope OBLIGATOIRE │ • Agent authentifié par API Key rejoint son site │ • Admin voit TOUS les sites (groupe "all-sites") │ • User voit UNIQUEMENT ses sites assignés │ • Le signaling WebRTC est prêt pour l'Étape 3

═══════════════════════════════════════════════════════════════════════ ÉTAPE 3 — VIDÉO + IA Capture, détection, déduplication, streaming ═══════════════════════════════════════════════════════════════════════

Phase 15 — Agent Vidéo (capture + streaming) ├── FFmpeg capture (passthrough H264, zerolatency) │ ffmpeg -rtsp_transport tcp -buffer_size 0 -max_delay 0
│ -i rtsp://... -g 1 -tune zerolatency
│ -preset ultrafast -c:v copy -f rawvideo pipe:1 ├── Snapshot pipeline (intervalle adaptatif 200-1000ms selon scène) ├── Bounded Channel (backpressure, drop oldest si plein) ├── WebRTC P2P (SIPSorcery, pas decode→re-encode, coturn obligatoire) ├── 1 viewer max par caméra (pas de SFU en v1) ├── Coturn config : HMAC auth secret, credential lifetime 24h ├── Verify: flux vidéo navigateur < 500ms LAN │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ SCÉNARIO FLUX LIVE ──────────────────────────────────────────┐ │ │ │ │ │ 1. Agent démarre → FFmpeg se connecte au RTSP de la caméra │ │ │ │ │ │ 2. Agent crée une PeerConnection SIPSorcery par caméra │ │ │ → Encodage H264 passthrough (pas de decode→re-encode) │ │ │ → Latence cible : < 500ms │ │ │ │ │ │ 3. Browser (Admin) ouvre la page Live Vidéo │ │ │ → SignalR StreamingHub.RequestStream(cameraId) │ │ │ │ │ │ 4. Agent reçoit ViewerConnected │ │ │ → Crée OFFRE SDP → l'envoie via SignalR SendSdp │ │ │ │ │ │ 5. Browser reçoit SdpOffer → crée RTCPeerConnection │ │ │ → setRemoteDescription │ │ │ → createAnswer → setLocalDescription │ │ │ → Envoie la réponse via SignalR SendAnswer │ │ │ │ │ │ 6. ICE candidates échangés (via coturn si nécessaire) │ │ │ → Chemin direct P2P si possible │ │ │ → Relay TURN si NAT symétrique (coturn obligatoire) │ │ │ │ │ │ 7. Flux H264 arrive dans le

Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) ├── [Agent] Motion Gate (Niveau 0) │ ├── Pixel diff entre frame N et N-1 > seuil (MotionThreshold) │ └── Pas de mouvement → pas de YOLO (économie 90% CPU) ├── [Agent] ObjectTracker (Niveau 1) │ ├── YOLOv8 nano sur CPU (ONNX Runtime, intraOpNumThreads=2) │ ├── IoU avec la frame précédente > 0.6 → même objet │ ├── TrackId persistant (Guid) pour chaque objet suivi │ └── Si même objet + cooldown actif → pas d'envoi au Central ├── [Agents GPU] Analyse ONNX (local ou via broker) │ ├── Object Detection YOLOv8 (GPU, ~40ms) │ ├── Face Recognition (si personne, ~40ms) │ └── ALPR (si véhicule + LPR activé, ~200ms en async) ├── [Central] Temporal Cooldown (Niveau 2) │ ├── IMemoryCache : clé = "{cameraId}:{objectType}:{trackId}" │ ├── Si la clé existe encore → événement supprimé │ └── Cooldowns : personne=30s, véhicule=60s, inconnu=300s ├── [Central] Embedding Dedup (Niveau 3) │ ├── Cache LRU d'embeddings faciaux (float[512], 10K entries) │ ├── Distance L2 < 0.6 → même visage │ └── Inconnu ajouté au cache avec TTL 5 minutes ├── [Central] Suppression Hiérarchique (Niveau 4) │ ├── FaceRecognized émis → ne PAS émettre PersonDetected │ ├── LicensePlateDetected → ne PAS émettre VehicleDetected │ └── MotionDetected seul → événement silencieux (pas de notif) ├── Pipeline degradation : │ ├── Normal : Agent YOLO → analyse IA (locale ou via broker) │ ├── Degrade 1 : exécutant IA lent → Agent-only (confidence baissée 0.3) │ ├── Degrade 2 : exécutant IA down / broker injoignable → Motion-only (pas d'IA) │ └── Degrade 3 : CPU > 80% → snapshots réduits de moitié ├── Verify: détection + déduplication fonctionnelle │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ SCÉNARIO DÉTECTION AVEC DÉDOUBLONNAGE ─────────────────────┐ │ │ │ │ │ SITUATION : Une personne marche devant la caméra (5s) │ │ │ │ │ │ t+0ms → Motion détecté → YOLO → "person" (conf 0.85) │ │ │ TrackId = "A", IoU = nouveau │ │ │ → Envoi au Central → analyse IA → Face Rec → inconnu │ │ │ → Événement "UnknownPerson" créé │ │ │ → Cooldown personne=30s set pour Track "A" │ │ │ │ │ │ t+200ms → Motion → YOLO → "person" (conf 0.87) │ │ │ IoU avec Track "A" > 0.6 → MÊME objet │ │ │ Cooldown actif → PAS d'envoi au Central │ │ │ ← ÉCONOMIE : pas d'analyse IA, pas d'événement │ │ │ │ │ │ t+10s → Personne partie → plus de mouvement │ │ │ → Motion Gate stoppe YOLO │ │ │ ← ÉCONOMIE : 90% CPU │ │ │ │ │ │ t+45s → Personne revient → Motion + YOLO │ │ │ IoU < 0.6 → Nouvel objet Track "B" │ │ │ Cooldown expiré (30s) │ │ │ → Envoi au Central → Nouvel événement OK │ │ │ │ │ │ RÉSULTAT : 2 événements au lieu de 25 (sans dedup) │ │ │ Économie : 92% des événements supprimés │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ SCÉNARIO VISAGE INCONNU ────────────────────────────────────┐ │ │ │ │ │ t+0s → Visage détecté → analyse IA (ONNX, agent GPU) │ │ │ → Aucun match connu → "UnknownPerson" │ │ │ → Embedding ajouté au cache LRU (TTL 5 min) │ │ │ → Notification "Visage inconnu" envoyée │ │ │ │ │ │ t+10s → Même visage détecté │ │ │ → Embedding match au cache (L2 < 0.6) │ │ │ → Événement SUPPRIMÉ │ │ │ → Pas de nouvelle notification │ │ │ │ │ │ t+6min → Embedding expiré du cache │ │ │ → Nouvelle détection → nouveau UnknownPerson │ │ │ │ │ │ RÉSULTAT : 1 notification au lieu de 36 (sans cache) │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ PIPELINE DEGRADATION ───────────────────────────────────────┐ │ │ │ │ │ Exécutant IA ne répond plus (down ou timeout) │ │ │ → Degrade Level 1 : Agent-only mode │ │ │ • YOLOv8 nano avec confidence abaissée à 0.3 │ │ │ • Résultats moins précis mais système continu │ │ │ → Health check tente l'exécutant toutes les 30s │ │ │ → Exécutant revient → Degrade Level 0 (normal) │ │ │ │ │ │ Si Agent CPU > 80% : Level 3 │ │ │ → Snapshots réduits de moitié (400ms au lieu de 200ms) │ │ │ → Alert Admin "CPU saturation" │ │ │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ ✔ VISION + IA FONCTIONNELLE : │ • Détection YOLO en continu │ • Dédoublonnage : pas d'event storm sur objets stationnaires │ • Visages inconnus : 1 notif toutes les 5 min max │ • Cooldowns configurables par caméra │ • Pipeline degrade gracieusement si l'exécutant IA est down

═══════════════════════════════════════════════════════════════════════ ÉTAPE 4 — ÉVÉNEMENTS + NOTIFICATIONS API événements, alertes, jobs métier ═══════════════════════════════════════════════════════════════════════

Phase 17 — API Events + Persons + Vehicles ├── GET /api/events (filtres : siteId, cameraId, type, dateFrom, │ dateTo, page, pageSize, orderBy) ├── GET /api/events/{id} (snapshot, metadata, lien recording) ├── GET /api/persons (filtres : search, isKnown, isUnknown, page) ├── GET /api/persons/{id} (avec face samples, historique events) ├── POST /api/persons (créer personne connue) │ Body: { "name", "notes", "photo" } → + face sample facultatif ├── POST /api/persons/{id}/face-sample (ajouter un visage) │ → Enregistre le visage via l'analyse IA (ONNX) ├── PUT /api/persons/{id} ├── DELETE /api/persons/{id} (soft delete) ├── GET /api/vehicles (filtres : search par plaque, page) ├── GET /api/vehicles/{id} (avec historique events, personne associée) ├── PUT /api/vehicles/{id} (associer à une personne) ├── Verify: dotnet test → API events green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ Lister les événements du jour ───────────────────────────────┐ │ │ GET /api/events?siteId=guid-1&dateFrom=2026-07-16T00:00:00Z │ │ │ &dateTo=2026-07-16T23:59:59Z&page=1&pageSize=50 │ │ │ Authorization: Bearer eyJ... │ │ │ → 200 { │ │ │ "items": [{ │ │ │ "id": "guid-ev-1", │ │ │ "type": "person", │ │ │ "timestamp": "2026-07-16T14:23:00Z", │ │ │ "cameraName": "Entrée principale", │ │ │ "confidence": 0.92, │ │ │ "snapshotUrl": "/api/events/guid-ev-1/snapshot", │ │ │ "metadata": { │ │ │ "objectType": "person", │ │ │ "trackId": "guid-track-1", │ │ │ "isSuppressed": false │ │ │ } │ │ │ }], │ │ │ "total": 1567, │ │ │ "page": 1, │ │ │ "pageSize": 50, │ │ │ "totalPages": 32 │ │ │ } │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ Détail d'un événement ──────────────────────────────────────┐ │ │ GET /api/events/guid-ev-1 │ │ │ → 200 { │ │ │ "id": "guid-ev-1", │ │ │ "siteId": "guid-1", │ │ │ "cameraId": "guid-cam-1", │ │ │ "type": "unknownPerson", │ │ │ "timestamp": "2026-07-16T14:23:00Z", │ │ │ "snapshotUrl": "/api/events/guid-ev-1/snapshot", │ │ │ "metadata": { "embeddingHash": "a1b2c3..." }, │ │ │ "recording": { │ │ │ "id": "guid-rec-1", │ │ │ "url": "/api/recordings/guid-rec-1/play" │ │ │ } │ │ │ } │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ Rechercher une personne ────────────────────────────────────┐ │ │ GET /api/persons?search=Jean&isKnown=true │ │ │ → 200 [{ "id": "guid-p-1", "name": "Jean Dupont", │ │ │ "photoUrl": "/api/persons/guid-p-1/photo", │ │ │ "isKnown": true, │ │ │ "lastSeen": "2026-07-16T14:23:00Z" }] │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ Rechercher un véhicule par plaque ───────────────────────────┐ │ │ GET /api/vehicles?search=AA-123-XX │ │ │ → 200 [{ "id": "guid-v-1", "licensePlate": "AA-123-XX", │ │ │ "make": "Renault", "model": "Clio", │ │ │ "color": "Gris", │ │ │ "personId": "guid-p-1" }] │ │ └──────────────────────────────────────────────────────────────┘ │ │ • Événements paginés avec filtres multiples │ • Persons : connu/inconnu, search, photos │ • Vehicles : search par plaque (trgm), association personne │ • Tout est filtré par site-scope (User voit ses sites) │ • Données accessibles via API pour l'UI (Étape 5)

Phase 18 — Notifications ├── SendNotificationEmailJob (SMTP, queue=email, retry 3x) ├── SendNotificationGotifyJob (queue=gotify) ├── NotificationRateLimiter (IMemoryCache, max 20 events/min/camera) ├── DetectionCooldownService (cooldown par type d'événement) ├── Scriban templates (DB + fallback hardcodé fr → en) ├── Hiérarchie des notifications : │ ├── "PersonDetected" → Email + Gotify (si configuré) │ ├── "UnknownPerson" → Email + Gotify + In-app (badge rouge) │ ├── "VehicleDetected" → Email (si config) + Gotify │ ├── "CameraOffline" → Email + Gotify (alerte admin) │ └── "MotionDetected" → SILENCIEUX (in-app sans notif) ├── Verify: notifications flows green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ SCÉNARIO NOTIFICATION ──────────────────────────────────────┐ │ │ │ │ │ 1. Personne détectée devant la caméra "Entrée" │ │ │ → Événement créé (Phase 16) │ │ │ │ │ │ 2. Central envoie SendNotificationJob à Hangfire │ │ │ → Queue "email" : SendNotificationEmailJob │ │ │ → Queue "gotify" : SendNotificationGotifyJob │ │ │ │ │ │ 3. SendNotificationEmailJob : │ │ │ → Render template Scriban : "Personne détectée" │ │ │ → Sujet : "[Heimdall] Personne détectée — Entrée" │ │ │ → Corps : snapshot incluse (embed) + heure + lieu │ │ │ → SMTP : envoi à tous les users configurés │ │ │ │ │ │ 4. SendNotificationGotifyJob : │ │ │ → POST Gotify API : "Personne détectée - Entrée" │ │ │ → Priorité : 5 (haute) │ │ │ │ │ │ 5. SignalR NotificationsHub envoie NewNotification │ │ │ → Groupe "notif-{userId}" │ │ │ → Badge dans l'UI : "3 notifications non lues" │ │ │ │ │ │ 6. RateLimiter : max 20 notifs/min/camera │ │ │ → Si seuil atteint → pas de nouvelle notification │ │ │ → Log "Rate limit atteint pour camera guid-cam-1" │ │ │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ CONFIGURER SES NOTIFICATIONS ───────────────────────────────┐ │ │ PUT /api/auth/profile │ │ │ { │ │ │ "notificationConfig": { │ │ │ "emailEnabled": true, │ │ │ "gotifyEnabled": true, │ │ │ "subscribedEvents": ["personDetected", "unknownPerson", │ │ │ "vehicleDetected", "cameraOffline"],│ │ │ "dailyDigest": true │ │ │ } │ │ │ } │ │ └──────────────────────────────────────────────────────────────┘ │ │ • 3 canaux : Email, Gotify, In-app (SignalR) │ • Rate limiting : pas de spam même en rafale │ • Templates personnalisables par l'Admin │ • Chaque user choisit ses types d'événements

Phase 19 — Jobs Métier (retention, cleanup) ├── RetentionCheckJob (quotidien 3h, queue=maintenance) │ ├── ExecuteDelete + S3 batch pour chaque politique de rétention │ └── 1 requête SQL, pas de boucle en mémoire ├── S3CleanupJob (quotidien 4h, queue=maintenance) │ ├── Pagination des fichiers S3 (1000 par page) │ ├── Vérifie chaque StoragePath dans la DB │ └── Supprime les fichiers orphelins (sans entrée DB) ├── CleanupUnknownFacesJob (dimanche 5h, queue=maintenance) │ ├── Supprime les UnknownPerson > 30 jours │ └── Supprime leurs snapshots S3 ├── CleanupLicensePlatesJob (dimanche 6h, queue=maintenance) │ └── Supprime les plaques non associées > 30 jours ├── DailyDigestJob (quotidien 8h, queue=digest) │ └── Email récapitulatif : N événements, N alerts, top caméras ├── Verify: jobs execution green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ RETENTION ───────────────────────────────────────────────────┐ │ │ 3h du matin : RetentionCheckJob s'exécute │ │ │ → Calcule les enregistrements expirés par StoragePolicy │ │ │ → ExecuteDelete : DELETE FROM recordings WHERE │ │ │ timestamp < NOW() - retention_days │ │ │ → Batch S3 : RemoveObjectsAsync (1000 clés par appel) │ │ │ → Enregistrements supprimés = place libérée dans Alarik │ │ │ │ │ │ Résultat : 5 lignes SQL, pas de boucle, pas de OOM │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ S3 CLEANUP ──────────────────────────────────────────────────┐ │ │ 4h du matin : S3CleanupJob s'exécute │ │ │ → Liste les fichiers dans Alarik prefix "recordings/" │ │ │ → Pagination : 1000 fichiers par page (continuation token) │ │ │ → Pour chaque page : vérifie StoragePath dans DB │ │ │ → Supprime ceux qui n'existent pas en DB │ │ │ │ │ │ Résultat : pas de fichiers orphelins, pas de memory bloat │ │ └──────────────────────────────────────────────────────────────┘ │ │ • Tous les jobs utilisent ExecuteDeleteAsync (pas de load en mémoire) │ • S3 batch delete : 1000 fichiers par appel HTTP │ • Pagination : pas de HashSet de 1.5GB (safe pour 15M+ enregistrements) │ • Queues isolées : la maintenance ne bloque pas les notifications

═══════════════════════════════════════════════════════════════════════ ÉTAPE 5 — UI BLAZOR COMPLÈTE Interface utilisateur (toutes les pages) ═══════════════════════════════════════════════════════════════════════

Phase 20 — Blazor UI Auth + Layout ├── Login page (Route: /login, publique) │ ├── Email + Password → Submit │ ├── Loading state (MudButton.Loading=true) │ ├── Erreur → MudAlert rouge │ ├── 2FA requis → champ code authenticator après MDP │ └── Succès → redirection vers Dashboard ├── Register page (email verification link) ├── Profile page (theme light/dark, language, notif config) ├── Layout : │ ├── MudDrawer responsive (se rétracte en icônes sur mobile) │ ├── MudAppBar avec navigation + badge alertes + user menu │ └── MudNavMenu : Dashboard, Sites, Personnes, Admin ├── MudTheme personnalisé (light + dark, couleurs Heimdall) ├── Localisation : T.T("key") — français par défaut ├── Verify: Playwright login flow green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ LOGIN ──────────────────────────────────────────────────────┐ │ │ Utilisateur ouvre /login │ │ │ → Champs email + mot de passe + bouton "Se connecter" │ │ │ → Saisit identifiants → Submit │ │ │ → Loading : bouton désactivé, spinner │ │ │ → Succès : redirigé vers / (Dashboard) │ │ │ → Erreur : MudAlert rouge "Email ou mot de passe invalide" │ │ │ │ │ │ Si 2FA activé : │ │ │ → Après validation MDP → champ "Code authenticator" │ │ │ → TOTP 6 chiffres → Submit │ │ │ → Erreur : "Code invalide" │ │ │ → Succès : Dashboard │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ LAYOUT ─────────────────────────────────────────────────────┐ │ │ App Bar : ☰ Heimdall | 📷 Sites | 👤 Personnes | ⚙️ Admin │ │ │ Notification badge (🔔 3) — ouvre modale alertes │ │ │ User menu : 😊 Jean | Profile | Logout │ │ │ │ │ │ Drawer responsive : │ │ │ Desktop : 🏠Dashboard 📷Sites 👤Persons 🚗Véhicules ⚙️Admin │ │ │ Mobile : icônes seulement (MudBreakpoint.Sm) │ │ └──────────────────────────────────────────────────────────────┘

Phase 21 — Blazor UI Dashboard + Sites ├── Dashboard (Route: /) │ ├── 4 KPIs : caméras total, caméras en ligne, events aujourd'hui, stockage libre │ ├── MudSkeleton pendant le chargement │ ├── Empty state : "Aucune caméra configurée" + lien "Ajouter un site" │ ├── Événements récents (5 dernières lignes) │ ├── Agent status chips (MudChip 🟢/🔴 par site) │ └── SignalR temps réel : nouveaux événements apparaissent sans refresh ├── Sites list (Route: /sites) │ ├── Table avec status chips (🟢 online / 🟠 offline / 🔴 aucun agent) │ └── Boutons : [+ Nouveau site], [Détails], [Supprimer] ├── Site detail (Route: /sites/{id}) │ ├── MudTabs : Caméras | Agents | Configuration │ ├── Token gen : génère token + API Key + docker command │ ├── Token affiché 1 seule fois → [Copier la commande] │ └── Agent list par site avec dernier heartbeat ├── Caméra list + detail │ ├── Liste paginée filtrée par site │ └── Détail : infos, profile editor, detection config ├── Verify: Playwright dashboard+sites green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ DASHBOARD ──────────────────────────────────────────────────┐ │ │ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │ │ │ │📷 24 │ │📹 12 │ │🚗 8 │ │💾 2.4│ │ │ │ │Total │ │En lig.│ │Auj. │ │To. │ │ │ │ └──────┘ └──────┘ └──────┘ └──────┘ │ │ │ │ │ │ Events récents (temps réel via SignalR) │ │ │ 🟢 14:23 — Personne détectée — Entrée │ │ │ 🟡 14:20 — Véhicule détecté — Parking │ │ │ │ │ │ Agents : 🟢 Entrepôt A 🟢 Entrepôt B 🔴 Bureaux │ │ │ Alertes non lues : 3 [Voir]│ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ GÉNÉRER TOKEN D'ENREGISTREMENT ────────────────────────────┐ │ │ Site "Entrepôt A" → Tab Configuration │ │ │ → [Générer un token] │ │ │ → Token + API Key générés (affichés 1 seule fois) │ │ │ → docker run -e HEIMDALL_CENTRAL_URL=... │ │ │ -e HEIMDALL_SITE_TOKEN=... │ │ │ -e HEIMDALL_API_KEY=... │ │ │ heimdall/agent:latest │ │ │ → [Copier la commande] │ │ │ → [× Révoquer le token] │ │ └──────────────────────────────────────────────────────────────┘

Phase 22 — Blazor UI Events + Persons + Live ├── Events list (Route: /events) │ ├── Table paginée (50/page) avec filtres : │ │ Site (MudSelect), Type (MudSelect), Date (MudDateRangePicker) │ ├── Couleur par type : 🔴 Personne, 🟡 Véhicule, 🔵 Inconnu, 🟢 Mouvement │ └── [Voir] → Event detail ├── Event detail (Route: /events/{id}) │ ├── Snapshot image + metadata + lien playback │ └── Si événement lié à un enregistrement → lien /recordings/{id} ├── Persons list (Route: /persons) │ ├── MudGrid de cartes (photo + nom) │ └── Search bar + filtre connu/inconnu ├── Person detail (Route: /persons/{id}) │ ├── Photo, notes, infos contact │ ├── Face samples (MudCarousel) │ ├── Véhicules associés │ └── Historique événements (30 derniers jours) ├── Live video (Route: /cameras/{id}/live) │ ├── Module JS autonome liveView.js (survit aux reconnexions Blazor) │ ├──

Phase 23 — Blazor UI Admin ├── Users management (tab Utilisateurs) │ ├── Liste des users avec rôle, email, 2FA status │ ├── [Modifier le rôle], [Reset 2FA], [Supprimer] │ └── [Inviter un utilisateur] → envoie email d'invitation ├── API Keys management (tab Clés API) │ ├── Liste des clés (préfixe, site, créé le, expire le, status) │ ├── [Créer une clé] → modal, choix scope site │ └── [Révoquer] ├── Hangfire dashboard (route: /hangfire) │ ├── Jobs en cours, en attente, échoués │ ├── [Relancer], [Annuler], [Supprimer] │ └── Filtres par date, type, queue ├── Global config (tab Configuration) │ ├── SMTP : host, port, user, password (+ [Tester]) │ ├── Gotify : URL, token (+ [Tester]) │ └── Ollama : URL + modèle (+ [Tester]) ├── Verify: Playwright admin green │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ ADMIN ──────────────────────────────────────────────────────┐ │ │ Tabs : Utilisateurs | Clés API | Jobs (Hangfire) | Config │ │ │ │ │ │ [Tab Utilisateurs] │ │ │ ┌─────────────────────────────────────────────────────────┐│ │ │ │ Jean Dupont Admin jean@ex.com [×] [Reset 2FA] ││ │ │ │ Marie Martin Viewer marie@ex.com [×] ││ │ │ └─────────────────────────────────────────────────────────┘│ │ │ │ │ │ [Tab Configuration] │ │ │ SMTP : smtp.gmail.com:587 ✅ [Tester] │ │ │ Gotify : https://gotify.example.com ✅ [Tester] │ │ │ │ │ │ Actions : [Sauvegarder] [Tester la connexion] │ │ └──────────────────────────────────────────────────────────────┘

═══════════════════════════════════════════════════════════════════════ ÉTAPE 6 — PRODUCTION HARDENING Sécurité, Observabilité, Backup, Load Tests ═══════════════════════════════════════════════════════════════════════

Phase 24 — Production Hardening ├── Rate limiting (AspNetCoreRateLimit) │ ├── Auth : 5 tentatives/15min par IP │ ├── API : 100 requêtes/min par client │ └── Snapshot upload : 1000 requêtes/min par Agent ├── CORS : domaines connus uniquement (pas AllowAnyOrigin) ├── HTTPS forced (redirection HTTP→HTTPS) ├── Docker secrets (/run/secrets/) pour : │ ├── DB_PASSWORD, JWT_SIGNING_KEY │ ├── COTURN_SECRET, BROKER_AMQP_PASSWORD, SMTP_PASSWORD │ └── ALARIK_ADMIN_USERNAME, ALARIK_ADMIN_PASSWORD, ALARIK_JWT ├── Serilog + Sentry/GlitchTip (PII stripping activé) │ ├── Sanitize : password, token, secret, snapshotUrl, ApiKey │ └── SendDefaultPii = false ├── OpenTelemetry metrics : │ ├── heimdall.events.created, heimdall.events.suppressed │ ├── heimdall.ai.inference_ms, heimdall.ai.queue.depth │ └── heimdall.signalr.connections, heimdall.streaming.viewers ├── Health checks : │ ├── GET /health (basique : API répond) │ ├── GET /health/ready (DB, Alarik, broker, Redis OK) │ └── GET /health/live (ready + pas de degradation active) ├── Backup automatisé (cron) : │ ├── PostgreSQL : pg_dump quotidien → Alarik backup/ │ └── Alarik : alarik mirror hebdomadaire → backup/ (versionné) ├── k6 load tests : │ ├── 10 agents, 50 caméras, 20 viewers simultanés │ ├── Latence API < 200ms p95 │ ├── Latence WebRTC < 700ms p95 │ └── Pas de perte de snapshots sous charge normale ├── Verify: k6 green, backup restore test OK │ ✅ Fonctionnel à la fin de cette phase : │ │ ┌─ HEALTH CHECKS ──────────────────────────────────────────────┐ │ │ GET /health → 200 { "status": "Healthy" } │ │ │ GET /health/ready → 200 { "status": "Healthy", │ │ │ "checks": [{ │ │ │ "name": "postgresql", │ │ │ "status": "Healthy" │ │ │ }, { │ │ │ "name": "broker-ia", │ │ │ "status": "Healthy" │ │ │ }] } │ │ │ GET /health/live → 200 { "status": "Healthy", │ │ │ "degradationLevel": 0 } │ │ │ │ │ │ Si broker/exécutant IA down : │ │ │ GET /health/live → 503 { "status": "Degraded", │ │ │ "degradationLevel": 2, │ │ │ "message": "Analyse IA unavailable"} │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ BACKUP ─────────────────────────────────────────────────────┐ │ │ Quotidien 2h : pg_dump → Alarik backup/heimdall_YYYY-MM-DD.sql.gz │ │ │ Hebdomadaire dimanche 3h : mc mirror → backup/ (versionné) │ │ │ │ │ │ Test de restauration : │ │ │ 1. docker compose down │ │ │ 2. Restaurer PostgreSQL depuis le dump │ │ │ 3. Restaurer Alarik depuis le mirror │ │ │ 4. docker compose up │ │ │ 5. Vérifier les sites, agents, events toujours présents │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ LOAD TEST (k6) ─────────────────────────────────────────────┐ │ │ objectif : 10 agents, 50 caméras, 20 viewers simultanés │ │ │ │ │ │ ✔ Latence API < 200ms p95 │ │ │ ✔ Latence WebRTC < 700ms p95 │ │ │ ✔ Aucune perte de snapshots sous charge normale │ │ │ ✔ Hangfire queue depth stable │ │ │ ✔ PostgreSQL pas de slow queries (> 100ms) │ │ │ │ │ │ Résultat attendu : GREEN │ │ └──────────────────────────────────────────────────────────────┘ │ │ • Production ready pour déploiement réel │ • Monitoring actif (Sentry/GlitchTip avec PII safe) │ • Backup restauré et testé (pas seulement dumpé) │ • Load test validé (les chiffres tiennent)

═══════════════════════════════════════════════════════════════════════ ÉTAPE 7 — APPLICATION WEB INSTALLABLE (PWA) ═══════════════════════════════════════════════════════════════════════

Phase 25 — PWA du serveur Blazor ├── Manifeste, icônes et installation ├── HTTPS, ressources locales et service worker borné ├── Page hors connexion, reprise de session et ergonomie tactile ├── Web Push par utilisateur et appareil └── Vérification : installation et scénarios réels sur mobile/desktop

Plan détaillé : docs/pwa.md


---

## PARTIE 11 : Déploiement Docker

### 11.1 docker-compose.yml (production)

> **L'Agent est distribué EXCLUSIVEMENT via Docker.** Pas de binaire standalone,
> pas d'installation manuelle. La commande Docker est générée par l'UI Admin
> avec le token et l'API Key pré-remplis : `docker run -e HEIMDALL_SITE_TOKEN=... -e HEIMDALL_API_KEY=... heimdall/agent:latest`.

```yaml
services:
  heimdall-central:
    image: heimdall/central:latest
    ports:
      - "5000:5000"   # HTTPS
    environment:
      - ConnectionStrings__PostgreSQL=Server=postgresql;Database=heimdall;...
      - ConnectionStrings__Hangfire=Server=postgresql;Database=heimdall_hangfire;...
      - ConnectionStrings__Redis=redis:6379
      - Alarik__Endpoint=http://alarik:8080
      # L'IA est exécutée par les agents (ONNX Runtime) — plus de service central
      - Ollama__Endpoint=http://ollama:11434
      - Coturn__Url=turns:coturn:3478
      - Coturn__Secret=${COTURN_SECRET}
    volumes:
      - dataprotection_keys:/root/.aspnet/DataProtection-Keys
    secrets:
      - jwt_signing_key
      - coturn_secret
      - smtp_password

  heimdall-agent:
    image: heimdall/agent:latest
    environment:
      - HEIMDALL_CENTRAL_URL=https://heimdall-central:5000
      - HEIMDALL_SITE_TOKEN=${HEIMDALL_SITE_TOKEN}
      - HEIMDALL_API_KEY=${HEIMDALL_API_KEY}
      - HEIMDALL_AGENT_NAME=${HEIMDALL_AGENT_NAME}
    volumes:
      - /dev/dri:/dev/dri  # GPU Intel/AMD (optionnel)
      - /tmp/heimdall:/tmp/heimdall  # Cache snapshots local
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    depends_on:
      postgresql:
        condition: service_healthy
      alarik:
        condition: service_started

  postgresql:
    image: postgres:17
    environment:
      POSTGRES_USER: heimdall
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: heimdall
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U heimdall"]
    ports:
      - "5432:5432"

  alarik:
    image: ghcr.io/achtungsoftware/alarik:latest
    ports:
      - "9000:8080"  # S3 API
    environment:
      API_BASE_URL: http://localhost:9000
      CONSOLE_BASE_URL: http://localhost:9001
      ADMIN_USERNAME: ${ALARIK_ADMIN_USERNAME}
      ADMIN_PASSWORD: ${ALARIK_ADMIN_PASSWORD}
      JWT: ${ALARIK_JWT}
      ALLOW_ACCOUNT_CREATION: false
    volumes:
      - alarik_storage:/app/Storage

  alarik-console:
    image: ghcr.io/achtungsoftware/alarik-console:latest
    ports:
      - "9001:3000"  # Console
    environment:
      NUXT_PUBLIC_API_BASE_URL: http://localhost:9000
      NUXT_PUBLIC_CONSOLE_BASE_URL: http://localhost:9001
      NUXT_PUBLIC_ALLOW_ACCOUNT_CREATION: false
    depends_on:
      - alarik

  coturn:
    image: coturn/coturn:4.6
    command: >
      -n --use-auth-secret
      --static-auth-secret=${COTURN_SECRET}
      --realm=heimdall.local
      --fingerprint
      --no-tlsv1
      --no-tlsv1_1
    network_mode: host  # nécessaire pour TURN (ports UDP)

11.2 GPU Passthrough

Conteneur GPU Docker Compose
agent GPU NVIDIA/AMD/Intel profiles compose GPU (nvidia/rocm/vaapi) — cf. docker
heimdall-agent NVIDIA/Intel/AMD --gpus all ou /dev/dri:/dev/dri
ollama NVIDIA (optionnel) --gpus all

PARTIE 12 : Tests

12.1 Stack de Test

Niveau Technologie Couverture
Unitaires xUnit + Shouldly + NSubstitute Domain 100%, Application 100%
Intégration Testcontainers (PostgreSQL réel) Infrastructure, API
UI Blazor bUnit Pages critiques
E2E Playwright Flux utilisateur complets
Mobile xUnit (Avalonia Headless) ViewModels, UseCases
Charge k6 10 agents, 50 caméras, 20 viewers

12.2 Tests Critiques — Dédoublonnage IA

MotionGate: no motion → no YOLO execution
MotionGate: motion → YOLO execution
SpatialDedup: same bounding box → no new event
SpatialDedup: IoU > 0.6 but cooldown expired → new event
SpatialDedup: IoU < 0.6 → new event (different object)
TemporalCooldown: same trackId within cooldown → suppressed
TemporalCooldown: cooldown expired → event created
EmbeddingDedup: same face embedding → no UnknownPerson
EmbeddingDedup: different face embedding → UnknownPerson created
HierarchicalSuppression: FaceRecognized suppresses PersonDetected
HierarchicalSuppression: LicensePlateDetected suppresses VehicleDetected
AIPipelineDegradation: exécutant IA timeout → Agent-only mode
AIPipelineDegradation: exécutant IA down → motion-only mode
Backpressure: queue full → oldest snapshot dropped
AdaptiveInterval: empty scene → 1000ms
AdaptiveInterval: object detected → 200ms

12.3 Tests — Race Conditions et Concurrence

AgentRegistration: duplicate registration returns 409
AgentRegistration: expired token returns 401
Heartbeat: concurrent heartbeats handled correctly
S3Cleanup: in-progress upload not treated as orphan
RetentionCheck: concurrent recording during batch delete
CameraStatusChange: debounce works when network flapping
SignalR: disconnected user removed from groups
SignalR: agent reconnects and rejoins site group
Hangfire: queue isolation works (email doesn't block gotify)
AnalysisWorker: concurrent requests from multiple cameras

PARTIE 13 : Observabilité

13.1 Métriques OpenTelemetry

Métrique Type Description
heimdall.events.created Counter Événements créés (par type)
heimdall.events.suppressed Counter Événements supprimés par dedup
heimdall.ai.pipeline.level Gauge Niveau de dégradation actuel
heimdall.ai.snapshot.interval Gauge Intervalle snapshot actuel
heimdall.ai.yolo.inference_ms Histogram Temps inférence YOLO Agent
heimdall.ai.inference_ms Histogram Temps inférence IA (ONNX)
heimdall.ai.queue.depth Gauge Profondeur queue snapshots
heimdall.signalr.connections Gauge Connexions SignalR actives
heimdall.streaming.active_viewers Gauge Viewers WebRTC actifs

13.2 Health Checks

Check Endpoint Période
API /health 30s
PostgreSQL Ping DB 30s
Alarik GET /health 30s
Broker IA (RabbitMQ) AMQP / healthcheck 30s
Ollama /api/tags 60s
Agent POST /api/agents/{id}/heartbeat 30s

13.3 Logging (Serilog)

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Heimdall.AI": "Debug",
        "Heimdall.Streaming": "Debug"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": {
          "path": "/var/log/heimdall/log-.log",
          "rollingInterval": "Day"
      }}
    ]
  }
}

PARTIE 14 : Correctifs Applicables aux Documents Sources

Les documents suivants contiennent des informations obsolètes ou erronées. Ce document (MASTER_SPECIFICATION.md) fait foi.

Document source Statut Corrections nécessaires
specs.md Obsolète Stack mobile (Avalonia), architecture conteneur (fusion), TURN obligatoire
implementation.md Obsolète 36+ issues intégrées dans les phases révisées
notifications.md Mise à jour partielle Ajouter cooldowns par type d'événement, rate limiting
signalr-usage.md Mise à jour partielle StreamingHub auth, groupes standardisés
auth-roles.md Mise à jour partielle Site IDs retirés du JWT, audit log
ui-pages.md OK (inchangé) —
— — IA centralisée retirée (ONNX Runtime sur agents)
hangfire-usage.md Mise à jour partielle Queue isolation, pagination, batch delete

Annexe A : Résumé des 36 Issues Critiques Résolues

# Issue Source Résolution
C2 Agent Registration ne retourne pas d'API Key council-agent ApiKey ajoutée à la réponse
C3 AI False Negative (pré-filtre jetable) council-agent Periodic full-scan + degradation levels
C4 S3Cleanup race condition council-agent Staging prefix
C5 Double-hop Blazor Api/Web council-agent Fusion en 1 conteneur
S1 StreamingHub sans vérification site-scope security-agent Vérification ajoutée
S3 Registration publique sans rate limiting security-agent Rate limiting + email verification
S4 Ktor body logging (plus applicable, stack changé) security-agent N/A (Avalonia)
S5 Site IDs dans JWT security-agent Retirés, lookup serveur
S6 API Key SHA256 sans salt security-agent HMACSHA256 + salt
S7 Key ring non partagé entre conteneurs security-agent Volume Docker monté
S8 HttpClient sans validation certificat security-agent IHttpClientFactory + handler
S9 2FA sans codes de récupération security-agent 10 codes à l'enrôlement
S10 Admin voit tous les sites events security-agent Granularité admin implémentée
D1 LicensePlate ambigu (entité ou champ ?) db-agent Entité séparée avec VehicleId
D2 Recording entity non définie db-agent Schéma complet défini
D3 StoragePolicy cardinalité ambiguë db-agent N:1 (plusieurs caméras partagent)
D4 Camera sans AgentId db-agent AgentId ajouté
D5 RetentionCheckJob OOM (15M rows en mémoire) db-agent ExecuteDelete + batch S3
D6 S3CleanupJob HashSet 1.5GB RAM db-agent Pagination par curseur
D7 Events table sans partitionnement db-agent PARTITION BY RANGE (monthly)
D8 Pas d'index définis db-agent Index composites + GIN + partial
A1 Stationary object = event storm (3000 events/10min) ai-agent Architecture dedup 4 niveaux
A2 Motion detection ne gate PAS l'IA ai-agent Motion gate obligatoire
A3 Pas de Track IDs (chaque frame = nouvel objet) ai-agent IoU tracker + Kalman
A4 Pas de backpressure (queue debordée) ai-agent Bounded Channel
A5 UnknownPerson event spam ai-agent Embedding cache LRU + 5min cooldown
A6 ALPR bloque le pipeline (200ms séquentiel) ai-agent ALPR async après commit
A7 Pas de fallback si exécutant IA / broker down ai-agent Degradation levels 0-4 + file durable
P1 FFmpeg decode→re-encode ajoute 1-2s latence perf-optimizer-agent Mode PASSTHROUGH
P2 Pas de SignalR backplane perf-optimizer-agent Redis backplane (préparé)
P3 SendNotification queue non isolée perf-optimizer-agent Queues séparées (email, gotify, digest)
P4 VACUUM mensuel insuffisant (170K inserts/jour) perf-optimizer-agent VACUUM events hebdo
P5 REINDEX DATABASE avec nom hardcodé db-agent + perf REINDEX DATABASE CURRENT
P6 Local Storage fallback non viable council-agent Retiré (incompatible Central playback)