Files
Heimdall/docs/MASTER_SPECIFICATION.md
T

1615 lines
74 KiB
Markdown
Raw Normal View 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
```yaml
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
```sql
-- 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)
```csharp
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
```csharp
[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
```csharp
// 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)
```csharp
// 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 :
```javascript
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
```csharp
// 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é
```csharp
// 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
```csharp
// 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
```csharp
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 Optimisé
### 10.1 Philosophie : MVP Multi-Site d'abord, Métier ensuite
Le plan est structuré en **2 grandes étapes** :
1. **MVP Multi-Site (Phases 1-12)** : Foundation + API + Agent de base.
À la fin de cette étape, on doit pouvoir :
- Créer N sites avec N agents chacun
- Voir les agents en ligne/offline
- Avoir l'API complète Sites/Agents/Auth
- Avoir un Agent qui s'enregistre, envoie son heartbeat, et reste connecté
- Toute la stack multi-site fonctionnelle sans caméra ni IA
2. **Métier + UI (Phases 13-25)** : Caméras, Vidéo, IA, Notifications, UI, Mobile.
Le métier (détection, enregistrement, événements) s'ajoute PAR-DESSUS
l'infrastructure multi-site déjà rodée.
```
═══════════════════════════════════════════════════════════════════════
É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 + MinIO + Redis)
└── Verify: dotnet build → 0 errors
Phase 2 — Test Framework & Tooling
├── xUnit + Shouldly + NSubstitute + FluentAssertions
├── Testcontainers (PostgreSQL + MinIO réels)
├── bUnit (Blazor UI), Playwright (E2E)
├── .editorconfig + analyzers + StyleCop
└── Verify: dotnet test → green (skeleton pass)
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
┌──────────────────────────────────────────────────────────────────┐
│ 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 (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
│ ⚠️ Les tables métier (Camera, Person, Event...) existent en DB
│ mais ne sont pas utilisées par le code de l'Étape 1
└── Verify: dotnet build → 0 errors
┌──────────────────────────────────────────────────────────────────┐
│ SECURITY — Authentification + Autorisation │
│ Prérequis pour toute 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
┌──────────────────────────────────────────────────────────────────┐
│ 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
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
Phase 8 — Storage MinIO/S3
├── MinioStorageProvider (IStorageProvider)
├── Staging prefix pour uploads atomiques
├── Batch delete (RemoveObjectsAsync, 1000/appel)
├── Path pattern : recordings/{site}/{camera}/{date}/{ts}.ts
├── Health check → /health
└── Verify: dotnet test → Testcontainers MinIO green
┌──────────────────────────────────────────────────────────────────┐
│ API MULTI-SITE — Auth + Sites + Agents │
│ → PREMIER JALON : API multi-site fonctionnelle │
└──────────────────────────────────────────────────────────────────┘
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
⏺ JALON : on peut s'inscrire, se connecter, gérer ses clés API
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
⏺ JALON : API multi-site complète (N sites, N agents par site)
┌──────────────────────────────────────────────────────────────────┐
│ HANGFIRE — Jobs d'infrastructure │
├── Uniquement les jobs 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
┌──────────────────────────────────────────────────────────────────┐
│ AGENT — Premier déploiement Docker │
│ → DEUXIÈME JALON : Agent qui s'enregistre + heartbeat │
└──────────────────────────────────────────────────────────────────┘
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=... \
│ -e HEIMDALL_SITE_TOKEN=... \
│ -e HEIMDALL_API_KEY=... \
│ heimdall/agent:latest
└── Verify: Agent démarre → register → heartbeat 30s
⏺ JALON MVP MULTI-SITE ATTEINT :
✔ N sites dans le Central
✔ N agents par site, chacun avec son API Key
✔ Agents enregistrés + heartbeat → status Online
✔ API Key auth fonctionnelle
✔ Docker push + pull fonctionnel
⇒ PRÊT À AJOUTER LE MÉTIER
═══════════════════════════════════════════════════════════════════════
ÉTAPE 2 — MÉTIER + UI (Caméras, Vidéo, IA, Notifications, Mobile)
═══════════════════════════════════════════════════════════════════════
┌──────────────────────────────────────────────────────────────────┐
│ CAMÉRAS + STOCKAGE │
└──────────────────────────────────────────────────────────────────┘
Phase 13 — API Caméras + ONVIF
├── CRUD Caméras (avec AgentId, StoragePolicyId, DetectionProfileId)
├── POST /api/cameras (credentials chiffrés IDataProtector)
├── GET/PUT /api/cameras/{id}/profile (DetectionProfile)
├── ONVIF Device Discovery (WS-Discovery, scan sous-réseau)
└── Verify: dotnet test → API caméras green
Phase 14 — SignalR Hubs (temps réel)
├── 5 hubs : Events, Streaming, Monitoring, Notifications, Admin
├── EventsHub : EventCreated, PersonDetected, UnknownPerson...
├── StreamingHub : RequestStream (check site-scope), SDP relay
├── MonitoringHub : AgentStatusChanged, CameraStatusChanged...
├── NotificationsHub : NewNotification, UnreadCount
├── AdminHub : ConfigChanged, CameraAdded/Removed, UserRoleChanged
├── API Key auth → rejoint groupe site automatiquement
└── Verify: dotnet test + tests hubs
┌──────────────────────────────────────────────────────────────────┐
│ VIDÉO + IA — Pipeline de détection │
└──────────────────────────────────────────────────────────────────┘
Phase 15 — Agent Vidéo (capture + streaming)
├── FFmpeg capture (passthrough H264, zerolatency)
├── Snapshot pipeline (intervalle adaptatif 200-1000ms selon scène)
├── Bounded Channel<Snapshot> (backpressure)
├── WebRTC P2P (SIPSorcery, pas decode→re-encode, coturn obligatoire)
├── 1 viewer max par caméra (pas de SFU en v1)
└── Verify: flux vidéo navigateur < 500ms LAN
Phase 16 — IA Pipeline (dédoublonnage 4 niveaux)
├── Motion Gate (Niveau 0 : pixel diff → prerequisite YOLO)
├── ObjectTracker (Niveau 1 : IoU + Kalman, trackId)
├── CodeProject.AI integration (Object Detection, ALPR, Face)
├── Temporal Cooldown (Niveau 2 : IMemoryCache)
├── Embedding Dedup (Niveau 3 : cache LRU visages)
├── Hierarchical Suppression (Niveau 4)
├── Pipeline degradation (CPAI down → Agent-only → motion-only)
└── Verify: détection + déduplication fonctionnelle
┌──────────────────────────────────────────────────────────────────┐
│ ÉVÉNEMENTS + NOTIFICATIONS │
└──────────────────────────────────────────────────────────────────┘
Phase 17 — API Events + Persons + Vehicles
├── GET /api/events (filtres : site, caméra, type, date, pagination)
├── GET /api/events/{id} (snapshot, metadata, lien recording)
├── CRUD Persons (connus + inconnus, face samples, historique)
├── CRUD Vehicles (search plaque, association personne)
└── Verify: dotnet test → API events green
Phase 18 — Notifications
├── SendNotificationEmailJob (SMTP, queue=email, retry 3x)
├── SendNotificationGotifyJob (queue=gotify)
├── RateLimiter (max 20 events/min/camera)
├── DetectionCooldownService
├── Scriban templates (DB + fallback hardcodé)
└── Verify: notifications flows green
Phase 19 — Jobs Métier (retention, cleanup)
├── RetentionCheckJob (ExecuteDelete + S3 batch)
├── S3CleanupJob (pagination, staging exclus)
├── CleanupUnknownFacesJob
├── CleanupLicensePlatesJob
├── DailyDigestJob (queue=digest)
└── Verify: jobs execution green
┌──────────────────────────────────────────────────────────────────┐
│ UI BLAZOR — Interface utilisateur complète │
└──────────────────────────────────────────────────────────────────┘
Phase 20 — Blazor UI Auth + Layout
├── Login (email + password + 2FA)
├── MudDrawer + MudAppBar + MudNavMenu responsive
├── MudTheme (light + dark, personnalisé)
├── Localisation T.T("key")
└── Verify: Playwright login green
Phase 21 — Blazor UI Dashboard + Sites
├── Dashboard : KPIs (caméras, events, stockage)
├── Sites list + Site detail (tabs, token gen, docker command)
├── Caméras list + detail (profile editor)
└── Verify: Playwright dashboard+sites green
Phase 22 — Blazor UI Events + Persons + Live
├── Events list (filtres, pagination)
├── Event detail (snapshot, metadata, playback link)
├── Persons list + detail (photos, history)
├── Live video (JS module liveView.js, <video> natif)
└── Verify: Playwright events+live green
Phase 23 — Blazor UI Admin
├── Users management
├── API Keys management
├── Hangfire dashboard
├── Global config (SMTP, Gotify, Ollama)
└── Verify: Playwright admin green
┌──────────────────────────────────────────────────────────────────┐
│ PRODUCTION HARDENING — Sécurité, Observabilité, Backup │
└──────────────────────────────────────────────────────────────────┘
Phase 24 — Production Hardening
├── Rate limiting partout (AspNetCoreRateLimit)
├── CORS domaines connus
├── HTTPS forced + Docker secrets
├── Serilog + Sentry/GlitchTip (PII safe)
├── OpenTelemetry metrics
├── Health checks (/health, /health/ready, /health/live)
├── Backup pg_dump + MinIO mc mirror (cron)
├── k6 load tests (10 agents, 50 caméras, 20 viewers)
└── Verify: k6 green, backup restore OK
┌──────────────────────────────────────────────────────────────────┐
│ MOBILE — Dernière phase │
└──────────────────────────────────────────────────────────────────┘
Phase 25 — Application Mobile Android (Kotlin + Jetpack Compose)
├── Projet Gradle séparé (Heimdall.Mobile/)
├── Clean Architecture : data / domain / presentation
├── Ktor HTTP client + refresh token auto
├── SignalR Android client (events + notifications)
├── WebRTC natif (SurfaceViewRenderer)
├── Room cache offline (LRU 50 Mo)
├── FCM push (Gotify fallback)
├── 8 écrans : Login, Dashboard, Sites, Caméras,
│ Live Vidéo, Événements, Détail, Réglages
└── Verify: build Gradle vert + tests instrumentés green
```
---
## 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
- 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)
```json
{
"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<T> |
| 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) |