refactor: split implementation in 2 stages — MVP multi-site then business features

Étape 1 (Phases 1-12) : Foundation + API multi-site (Sites, Agents, Auth) + Agent Docker avec heartbeat. Pas de caméra, pas d'IA, pas de vidéo. L'objectif est d'avoir N sites avec N agents enregistrés, heartbeats, status Online, le tout via API.

Étape 2 (Phases 13-25) : on ajoute le métier par-dessus — caméras, vidéo, IA, notifications, UI, mobile.
This commit is contained in:
Arnaud Dartois committed 2026-07-16 20:05:19 +00:00
1 parent 098a05aceb
commit eb59ffd4f6
1 file changed
+321 -74
+321 -74
View File
@@ -984,96 +984,343 @@ app/
---
## PARTIE 10 : Plan d'Implémentation Révisé
## PARTIE 10 : Plan d'Implémentation Optimisé
### 10.1 Phases (ordre corrigé avec les correctifs intégrés)
### 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.
```
Phase 1 : Solution .NET 10 + Clean Architecture (inchangé)
Phase 2 : Tests Framework (inchangé)
Phase 3 : CI/CD DockerHub (inchangé)
═══════════════════════════════════════════════════════════════════════
ÉTAPE 1 — MVP MULTI-SITE (Central + Agent fonctionnel sans métier)
═══════════════════════════════════════════════════════════════════════
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)
┌──────────────────────────────────────────────────────────────────┐
│ FOUNDATION — Solution, Tests, CI/CD │
│ Rien ne dépend d'eux, tout dépend d'eux │
└──────────────────────────────────────────────────────────────────┘
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 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 7 : API Sites + Agent Tokens (avec correctif Agent Registration)
├── Registration retourne API Key en plus du token
└── Key ring DataProtection partagé (volume Docker)
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 8 : Agent Registration + Heartbeat (corrigé)
├── Heartbeat avec optimisic concurrency (row version)
└── Agent reçoit API Key dès l'enregistrement
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
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)
┌──────────────────────────────────────────────────────────────────┐
│ DOMAIN — Entités + Migrations │
│ Tout le métier repose sur le domaine │
└──────────────────────────────────────────────────────────────────┘
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 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
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é
┌──────────────────────────────────────────────────────────────────┐
│ SECURITY — Authentification + Autorisation │
│ Prérequis pour toute API │
└──────────────────────────────────────────────────────────────────┘
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 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
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
┌──────────────────────────────────────────────────────────────────┐
│ APPLICATION + INFRASTRUCTURE — Logique métier + Accès données │
└──────────────────────────────────────────────────────────────────┘
Phase 21 : Dashboard KPI
Phase 22 : Production Hardening
Phase 23 : Application Mobile Android (Kotlin + Jetpack Compose) — dernière phase
├── 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
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
```
---