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
1.4 Conteneurs Docker
PARTIE 2 : Domain Model — Entités Complètes
2.1 Définitions
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
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
3.3 Flux de Détection Complet
3.4 Cooldowns par Défaut (CameraDetectionProfile)
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
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
4.5 Enregistrement Agent — Flux Complet
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
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)
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)
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 :
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
7.3 Correction : RetentionCheckJob Optimisé
7.4 Hangfire Configuration
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
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 :
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 :
-
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
-
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.
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
12.3 Tests — Race Conditions et Concurrence
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)
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) |