Files
Heimdall/docs/MASTER_SPECIFICATION.md
T
Arnaud Dartois 9fff2ec917 fix: mobile stack Kotlin (not Avalonia), agents Docker-only
Corrections après feedback utilisateur : stack mobile = Kotlin + Jetpack Compose (Android natif, WebRTC natif), Agents installés exclusivement via Docker (pas de binaire standalone).
2026-07-16 20:00:48 +00:00

59 KiB
Raw Blame History

Heimdall — Master Specification Technique

Version : 2.0 | Date : 2026-07-16 Stack : .NET 10+ / Blazor MudBlazor / PostgreSQL / CodeProject.AI / 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, mobile-app.md, hangfire-usage.md, ui-pages.md, codeproject-ai.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 — Stack Mobile : Kotlin + Jetpack Compose

Choix Raison
Kotlin + Jetpack Compose Application Android native, performances WebRTC optimales, écosystème Google
.NET Avalonia rejeté Latence WebRTC accrue via WebView, expérience Android non-native, maturité Avalonia insuffisante pour le streaming vidéo

Impact : L'app mobile est un projet séparé (Heimdall.Mobile/) avec son propre build Gradle. L'architecture Clean Architecture (data/domain/presentation) et les DTOs REST sont partagés via contrat OpenAPI/NSwag généré depuis le Central.

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é

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 CodeProject.AI + Ollama en local, 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 (Agent CPU) + CodeProject.AI GPU (Central)

1.3 Architecture Logique

┌────────────────────────────────────────────────────────────────────────┐
│                         HEIMDALL CENTRAL (1 container)                  │
│                                                                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌────────────┐ │
│  │ Api REST +   │  │ Web Blazor   │  │ Workers      │  │ CodeProject│ │
│  │ SignalR Hubs │  │ MudBlazor    │  │ Hangfire     │  │ .AI Server │ │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘  │ Ollama     │ │
│         │                  │                 │          └────────────┘ │
│         └──────────────────┴─────────────────┘                        │
│                              │ PostgreSQL / Hangfire (schema séparé)  │
│                              │ MinIO / 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)
  minio:                # Stockage S3 (enregistrements)
  codeproject-ai:       # IA lourde GPU (détection, visages, LPR)
  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 appels CodeProject.AI
  • 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-CPAI)                     │
│  ├── 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] CodeProject.AI
                         ├── 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 → Central CPAI
1 CPAI lent (>1s) Agent only (YOLOv8 nano, confidence baissée à 0.3)
2 CPAI down 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 CodeProject.AI Gestion des Erreurs

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 CodeProject.AI interne (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 MinIO/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 MinIO (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 Mobile (Kotlin + Jetpack Compose)

9.1 Stack

Technologie Version Usage
Kotlin 2.1+ Langage
Jetpack Compose 1.7+ UI déclarative Material 3
Clean Architecture — data / domain / presentation
Ktor 3.0+ HTTP client + refresh token automatique
Hilt 2.53+ Injection de dépendances
SignalR Java Client 8.0+ Temps réel (Microsoft SignalR)
WebRTC 1.0.32006+ WebRTC natif Android (SurfaceViewRenderer)
FCM 24.1+ Notifications push
Room 2.7+ Cache local offline (LRU 50 Mo)
DataStore 1.1+ Stockage préférences (dont tokens)
Coil 3.0+ Chargement images
Kotlinx Serialization 1.7+ JSON sérialisation
JUnit 5 + MockK + Turbine — Tests unitaires
Compose UI Test 1.7+ Tests UI
Gradle 8.10+ Build

Architecture :

app/
├── data/
│   ├── remote/
│   │   ├── api/                ← Ktor API client (endpoints mobiles)
│   │   ├── dto/                ← DTOs (SiteDto, CameraDto, EventDto...)
│   │   └── signalr/            ← SignalR client (events + streaming hubs)
│   ├── local/
│   │   ├── db/                 ← Room database (cache offline)
│   │   ├── datastore/          ← DataStore (tokens, préférences)
│   │   └── cache/              ← Image cache (Coil)
│   └── repository/             ← Implémentation repositories
├── domain/
│   ├── model/                  ← Modèles métier (Site, Camera, Event...)
│   ├── repository/             ← Interfaces repository
│   └── usecase/                ← Cas d'utilisation
├── presentation/
│   ├── MainActivity.kt
│   ├── HeimdallApp.kt
│   ├── navigation/             ← NavGraph, Screen sealed class
│   ├── theme/                  ← Material 3 theme
│   ├── components/             ← Composants réutilisables
│   ├── auth/                   ← LoginScreen + LoginViewModel
│   ├── dashboard/              ← DashboardScreen + DashboardViewModel
│   ├── sites/                  ← SiteListScreen, SiteDetailScreen
│   ├── camera/                 ← CameraLiveScreen (WebRTC natif)
│   ├── events/                 ← EventListScreen, EventDetailScreen
│   └── settings/               ← SettingsScreen
└── di/                         ← Hilt modules (Network, Database, SignalR)

9.2 Périmètre

  • Lecture seule (pas de configuration)
  • Connexion par email + mot de passe + 2FA (comme le web)
  • WebRTC natif Android (SurfaceViewRenderer, pas de WebView)
  • SignalR temps réel (events, notifications, streaming signaling)
  • Notifications push FCM (Gotify en fallback si pas de Google Services)
  • Cache offline Room (LRU 50 Mo)
  • 8 écrans : Login, Dashboard, Sites liste, Site détail, Caméra Live, Événements liste, Événement détail, Réglages

PARTIE 10 : Plan d'Implémentation Révisé

10.1 Phases (ordre corrigé avec les correctifs intégrés)

Phase   1 : Solution .NET 10 + Clean Architecture (inchangé)
Phase   2 : Tests Framework (inchangé)
Phase   3 : CI/CD DockerHub (inchangé)

Phase   4 : Domain Model — ENTITÉS COMPLÈTES (corrigé)
           ├── Toutes les entités + champs manquants (Recording, ApiKey, AuditLog...)
           ├── Index + partitionnement Events (dès le jour 1)
           ├── Soft delete sur Site/Camera/Person
           ├── Audit fields (CreatedAt, UpdatedAt) sur TOUTES les entités
           └── Value Conversions pour les enums (string en DB)

Phase   5 : Application Layer (CQRS) — inchangé
Phase   6 : Security — avec correctifs
           ├── API Key HMACSHA256 + salt (pas SHA256)
           ├── 2FA avec codes de récupération
           ├── Rate limiting sur auth
           ├── AuditLog service + table
           └── Site IDs retirés du JWT

Phase   7 : API Sites + Agent Tokens (avec correctif Agent Registration)
           ├── Registration retourne API Key en plus du token
           └── Key ring DataProtection partagé (volume Docker)

Phase   8 : Agent Registration + Heartbeat (corrigé)
           ├── Heartbeat avec optimisic concurrency (row version)
           └── Agent reçoit API Key dès l'enregistrement

Phase   9 : ONVIF Discovery (inchangé)
Phase  10 : Camera Management API (avec AgentId ajouté)

Phase  11 : Video Pipeline FFmpeg (corrigé)
           ├── Mode PASSTHROUGH (pas de decode→re-encode)
           ├── FFmpeg zerolatency, keyframe interval=1
           └── Détection GPU via NvidiaML (pas file check)

Phase  12 : AI Pipeline — AVEC DÉDOUBLONNAGE (NOUVEAU contenu)
           ├── Motion Gate (Niveau 0)
           ├── Spatial Dedup + Tracker (Niveau 1)
           ├── Temporal Cooldown (Niveau 2)
           ├── Embedding Dedup (Niveau 3)
           ├── Suppression Hiérarchique (Niveau 4)
           ├── Pipeline degradation (circuit breaker)
           ├── Adaptive snapshot interval
           └── Backpressure (bounded Channel)

Phase  13 : Storage MinIO/S3 (corrigé)
           ├── Staging prefix pour éviter race condition S3Cleanup
           ├── Batch delete (DeleteObjectsAsync, 1000/call)
           └── Pas de fallback local (retiré, non viable)

Phase  14 : SignalR Hubs (corrigé)
           ├── StreamingHub avec vérification site-scope
           ├── Agent rejoint groupe site (pas JWT UserSites)
           ├── Group names standardisés ("all-sites", pas "admin-monitoring")
           ├── CameraAdded/Removed → site-{siteId} aussi
           └── Redis backplane préparé

Phase  15 : Hangfire Central (corrigé)
           ├── Schéma hangfire isolé (SchemaName="hangfire")
           ├── Queue isolation (email, gotify, digest, default)
           ├── RetentionCheckJob : ExecuteDelete + S3 batch
           ├── S3CleanupJob : pagination (pas de HashSet 1.5GB)
           ├── DatabaseMaintenanceJob : VACUUM events hebdo + VACUUM FULL mensuel
           └── Hardcoded DB name retiré

Phase  16 : Hangfire Agent (corrigé)
           ├── 30s heartbeat (pas 60s) — synchronisé avec timeout 90s
           └── Debounce CameraHealthCheck (pas de spam si réseau instable)

Phase  17 : Notifications (avec rate limiting + cooldowns)
Phase  18 : Blazor UI Auth + Sites + Caméras
Phase  19 : WebRTC Streaming (P2P only, pas SFU)
Phase  20 : Blazor UI Live Vidéo

Phase  21 : Application Mobile Android (Kotlin + Jetpack Compose)

Phase  22 : Dashboard KPI
Phase  23 : Production Hardening
           ├── Observabilité Serilog + OpenTelemetry
           ├── Sentry/GlitchTip avec PII stripping
           ├── Health checks complets
           ├── Rate limiting partout
           ├── CORS configuré
           ├── SSL/TLS + Docker secrets
           ├── Backup automatisé PostgreSQL + MinIO
           └── Tests de charge k6

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.

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
      - MinIO__Endpoint=minio:9000
      - MinIO__AccessKey=${MINIO_ROOT_USER}
      - MinIO__SecretKey=${MINIO_ROOT_PASSWORD}
      - CPAI__Endpoint=http://codeproject-ai:32168
      - 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
      minio:
        condition: service_healthy

  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"

  minio:
    image: minio/minio
    command: server /data --console-address ":9001"
    ports:
      - "9000:9000"  # S3 API
      - "9001:9001"  # Console
    environment:
      MINIO_ROOT_USER: ${MINIO_ROOT_USER}
      MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
    volumes:
      - minio_data:/data
    healthcheck:
      test: ["CMD", "mc", "ready", "local"]

  codeproject-ai:
    image: codeproject/ai-server:2.9.5
    ports:
      - "32168:32168"
    environment:
      - CPAI_PORT=32168
      - CPAI_API_KEY=${CPAI_API_KEY}  # ← Authentification
      - CPAI_LAUNCHER_GPU=GPU
      - CPAI_MODULE_OBJECTDETECTION=true
      - CPAI_MODULE_ALPR=true
      - CPAI_MODULE_FACE=true
    volumes:
      - cpai_modules:/app/modules
      - cpai_models:/app/../../../models
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]

  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
codeproject-ai NVIDIA CUDA deploy.resources.reservations.devices
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: CPAI timeout → Agent-only mode
AIPipelineDegradation: CPAI 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)
CodeProjectAI: 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.cpai.inference_ms Histogram Temps inférence CPAI
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
MinIO mc ready 30s
CodeProject.AI /v1/status/ping 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
mobile-app.md À RÉÉCRIRE (Avalonia, pas Kotlin) Stack complet, architecture MVVM
ui-pages.md OK (inchangé) —
codeproject-ai.md Mise à jour partielle Auth API key, erreurs, degradation
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
C1 Stack mobile contradictoire (Avalonia vs Kotlin) council-agent Choix Avalonia
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
S2 Android cleartext HTTP security-agent Stack changé pour Avalonia (HTTPS natif)
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 CodeProject.AI down ai-agent Degradation levels 0-4
P1 FFmpeg decode→re-encode ajoute 1-2s latence perf-agent Mode PASSTHROUGH
P2 Pas de SignalR backplane perf-agent Redis backplane (préparé)
P3 SendNotification queue non isolée perf-agent Queues séparées (email, gotify, digest)
P4 VACUUM mensuel insuffisant (170K inserts/jour) perf-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)