# Heimdall — Plan d'implémentation > **Document historique (MVP — juillet 2026).** Les statuts de phases ci-dessous ne reflètent pas l’état courant du dépôt. Pour le suivi à jour, consulter la [liste de travaux](../todo.md). **Principe :** On implémente d'abord le **plus simple et le plus important**. La **vidéo live** arrive en dernier dans l'IHM. ## Statut d'avancement (MVP — Juillet 2026) ``` ✅ Phase 1 : Solution .NET 10 + Clean Architecture [FAIT] ✅ Phase 2 : Tests Framework [FAIT - partiel] ✅ Phase 3 : CI/CD [FAIT - Forgejo Actions] ✅ Phase 4 : Domain Model [FAIT - entités core] ✅ Phase 5 : Application Layer [FAIT - services directs, sans MediatR] ✅ Phase 5b : Migration CQRS (MediatR + AutoMapper) [FAIT - 50+ handlers, 11 profiles, pipelines] ✅ Phase 6 : Security [FAIT - Identity, JWT, API Key, 2FA] ✅ Phase 7 : API Sites + Agent Tokens [FAIT] ✅ Phase 8 : Agent Registration + Heartbeat [FAIT] ⏳ Phase 9 : ONVIF Discovery [EN ATTENTE - hardware requis] ✅ Phase 10 : Camera Management API [FAIT] ⏳ Phase 11 : Video Pipeline (FFmpeg) [EN ATTENTE - hardware requis] ⏳ Phase 12 : AI Pipeline [EN ATTENTE - hardware requis] ⏳ Phase 13 : Storage (RustFS/S3) [EN ATTENTE - v2] ⏳ Phase 14 : SignalR Hubs [EN ATTENTE - v2] ✅ Phase 15 : Hangfire Central [FAIT - surveillance heartbeat et failover] ⏳ Phase 16 : Hangfire Agent (InMemory) [EN ATTENTE - v2] ⏳ Phase 17 : Notifications [EN ATTENTE - v2] ✅ Phase 18 : Blazor UI [FAIT - 13 pages] ⏳ Phase 19 : WebRTC Streaming [EN ATTENTE - v2] ⏳ Phase 20 : Blazor UI Live Vidéo [EN ATTENTE - v2] ⏳ Phase 21 : Application web installable (PWA) [À IMPLÉMENTER] ⏳ Phase 22 : Dashboard KPI [FAIT - basique] ⏳ Phase 23 : Production Hardening [EN ATTENTE] ``` **Légende :** ✅ Fait — ⏳ En attente — ❌ Bloqué --- # Phase 1 — Solution .NET 10 + Clean Architecture ## Objectif Créer le socle technique stable : solution .NET 10 avec Clean Architecture. ## Arborescence ``` Heimdall/ ├── src/ │ ├── Heimdall.Domain # Entities, Value Objects, Enums ✅ │ ├── Heimdall.Domain.Primitives # Base types (Entity, ValueObject) ✅ │ ├── Heimdall.Contracts # Shared DTOs, Constants ✅ (vide, prévu) │ ├── Heimdall.Application # Interfaces, DTOs, Validators ✅ │ ├── Heimdall.Infrastructure # EF Core, PostgreSQL, Identity ✅ │ ├── Heimdall.Api # REST API controllers ✅ │ ├── Heimdall.Web # Blazor Web App (MudBlazor) ✅ │ ├── Heimdall.Agent # Worker Service ✅ │ └── Heimdall.Workers # Hangfire background jobs ✅ ├── tests/ │ ├── Heimdall.Domain.Tests # 13 tests ✅ │ ├── Heimdall.Application.Tests # Placeholder ✅ │ ├── Heimdall.Infrastructure.Tests # Placeholder ✅ │ ├── Heimdall.Api.Tests # Placeholder ✅ │ ├── Heimdall.Agent.Tests # Placeholder ✅ │ ├── Heimdall.Web.Tests # Placeholder ✅ │ ├── Heimdall.Workers.Tests # Placeholder ✅ │ └── Heimdall.IntegrationTests # 16 tests (WebApplicationFactory) ✅ ├── docker/ │ ├── Dockerfile.central # Multi-stage ✅ │ ├── Dockerfile.agent # Multi-stage ✅ │ ├── docker-compose.yml # PostgreSQL + RustFS + Central + Agent + Workers ✅ │ └── docker-compose.local.yml # Local compose overrides ├── docs/ │ ├── MASTER_SPECIFICATION.md # Spec complète │ ├── implementation.md # ← ce fichier │ └── specs.md # Spécifications détaillées ├── .forgejo/workflows/ci.yml # CI pipeline ✅ ├── .dockerignore # ✅ ├── Makefile # 20+ commandes ✅ ├── .env.example # ✅ └── README.md # Documentation complète ✅ ``` ## Dépendances entre projets ``` Domain (aucune dépendance) ↑ Application (ref Domain) — FluentValidation ↑ Infrastructure (ref Application) — EF Core, Npgsql, Identity, Hangfire ↑ ┌───┴───┐ Api Web (Blazor) — MudBlazor ├── ── ┘ Agent (ref Application, Infrastructure) — Worker Service Workers (ref Application, Infrastructure) — Hangfire jobs ``` ## Directory.Build.props ```xml net10.0 enable enable true latest-Recommended ``` Build : `dotnet build` — 0 errors, 0 warnings ✅ --- # Phase 2 — Framework de tests ## Objectif Avoir les tests avant le métier (TDD). ## Stack | Outil | Usage | Status | |---|---|---| | **xUnit** | Framework de tests | ✅ | | **Shouldly** | Assertions fluides | ✅ | | **NSubstitute** | Mocking | ⏳ Pas encore utilisé | | **Testcontainers** | PostgreSQL en integration | ⏳ Utilise InMemory pour l'instant | | **bUnit** | Tests composants Blazor | ⏳ Pas encore | ## Projets de test Un par projet source, nommage `Heimdall.X.Tests` — tous créés ✅ ## Tests existants | Suite | Tests | Technologie | |-------|-------|-------------| | Domain (Site, Agent, Camera) | 13 | xUnit + Shouldly | | Integration (Auth, Sites, Users, Cameras, Agents) | 16 | WebApplicationFactory + InMemory | | Placeholder (Api, Application, Infrastructure, Web, Workers) | 5 | xUnit | | **Total** | **34** | | --- # Phase 3 — CI/CD ## Objectif Chaque commit build et push les images Docker. ## Pipeline ```yaml push → restore → build → unit tests → integration tests → docker build ``` ## Implémentation actuelle - **Forgejo Actions** (`./forgejo/workflows/ci.yml`) ✅ - Build + Test sur push (branches main, develop) ✅ - Docker build (central + agent) sur main ✅ - PostgreSQL service pour les tests ✅ ## À faire (v2) - [ ] multi-arch Docker (linux/amd64 + arm64) - [ ] Push vers registry Docker - [ ] Couverture de code --- # Phase 4 — Domain Model ## Objectif Toutes les entités métier, énumérations, value objects. ## Entités implémentées | Entité | Status | Détail | |--------|--------|--------| | **Site** | ✅ | Guid PK, Name, Address, Timezone, RegistrationToken, soft delete | | **Agent** | ✅ | Guid PK, Status, Heartbeat, ApiKeyHash/Prefix, Capabilities | | **Camera** | ✅ | Guid PK, Status, Manufacturer, Model, RtspUrl | | **CameraCredentials** | ✅ | 1:1 avec Camera, credentials chiffrés | | **CameraDetectionProfile** | ✅ | 1:1, tous les paramètres de détection | | **AppUser** (Identity) | ✅ | DisplayName, Theme, Language | | **AppRole** (Identity) | ✅ | Admin, Supervisor, Viewer | | **UserSite** | ✅ | Many-to-many User ↔ Site | | **ApiKey** | ✅ | HMACSHA256 hash, prefix, site scope | | **AuditLog** | ✅ | Append-only, toutes les actions critiques | ## Entités à créer (v2) | Entité | Dans migration ? | |--------|-----------------| | Person | ⏳ Non (v2) | | Vehicle | ⏳ Non (v2) | | LicensePlate | ⏳ Non (v2) | | Event | ⏳ Non (v2) | | Recording | ⏳ Non (v2) | | StoragePolicy | ⏳ Non (v2) | | NotificationConfig | ⏳ Non (v2) | | NotificationTemplate | ⏳ Non (v2) | ## Énumérations ``` CameraStatus { Unknown, Online, Offline, Disabled, Error } ✅ EventType { MotionDetected, PersonDetected, ... } ✅ StorageProvider { Local, S3 } ✅ AgentStatus { Online, Offline, Error } ✅ GpuAcceleration { None, NvidiaCuda, IntelQuickSync, Vaapi } ✅ UserRole { Admin, Supervisor, Viewer } ✅ ``` ## Migration EF Core - `InitialCreate` créée avec toutes les tables actuelles ✅ - `.Designer.cs` présent ✅ - `AppDbContextFactory` pour les migrations design-time ✅ --- # Phase 5 — Application Layer ## Objectif Interfaces, DTOs, validateurs. ## Implémentation actuelle | Composant | Approche | Status | |-----------|----------|--------| | **Services** | Interfaces directes (pas MediatR) | ✅ | | **DTOs** | Records immutables | ✅ | | **Validation** | FluentValidation | ✅ | | **ServiceResult** | Pattern Result success/failure | ✅ | | **Pagination** | PagedResult | ✅ | ## Services implémentés | Service | Méthodes | |---------|----------| | `IAuthService` | Register, Login, Verify2fa, RefreshToken, RegisterAdmin | | `ISiteService` | Create, GetById, List, Update, Delete, GenerateToken | | `IAgentService` | Register, Heartbeat, GetById, ListBySite | | `IUserService` | List, GetById, Create, Update, AssignRoles, AssignSites, ResetPassword, Lock, Unlock | | `ICameraService` | Create, GetById, ListBySite, Update, Delete | | `IStatsService` | GetStats | | `IAuditLogService` | List (filtré, paginé) | ## Note sur CQRS Le MVP utilise des **services directs** (pas MediatR) par simplicité. La migration vers CQRS avec MediatR est prévue en v2 si le besoin se fait sentir. --- # Phase 6 — Security ## Objectif Authentification AVANT d'exposer l'API. ## Implémenté | Fonctionnalité | Priorité | Status | |---|---|---| | ASP.NET Core Identity (User, Role) | 🔴 Requis | ✅ | | JWT Bearer (15min access + refresh 7j) | 🔴 Requis | ✅ | | API Key HMACSHA256 (agents) | 🔴 Requis | ✅ | | 2FA TOTP | 🟠 Important | ✅ | | Rôles (Admin, Supervisor, Viewer) | 🟠 Important | ✅ | | Permissions (Site.Read, Camera.Write, etc.) | 🔴 Requis | ✅ | | Rate limiting (10 req/min auth, 200 API) | 🔴 Requis | ✅ | | Audit logging (append-only) | 🟠 Important | ✅ | | CORS configurable | 🔴 Requis | ✅ | | `[Authorize(AuthenticationSchemes)]` explicite | 🔴 Requis | ✅ | ## Endpoints d'auth | Méthode | Route | Auth | Status | |---|---|---|---| | `POST` | `/api/auth/register` | — | ✅ | | `POST` | `/api/auth/login` | — | ✅ | | `POST` | `/api/auth/2fa/verify` | — | ✅ | | `POST` | `/api/auth/refresh` | — | ✅ | | `POST` | `/api/auth/register-admin` | Test/Dev only | ✅ | --- # Phase 7 — API Sites + Agent Tokens ## Implémenté | Méthode | Route | Auth | Status | |---|---|---|---| | `POST` | `/api/sites` | JWT/Site.Write | ✅ | | `GET` | `/api/sites` | JWT/Site.Read | ✅ | | `GET` | `/api/sites/{id}` | JWT/Site.Read | ✅ | | `PUT` | `/api/sites/{id}` | JWT/Site.Write | ✅ | | `DELETE` | `/api/sites/{id}` | JWT/Site.Delete | ✅ | | `POST` | `/api/sites/{id}/tokens` | JWT/Site.Write | ✅ | Le token d'enregistrement est : - Généré en SHA256, stocké hashé en DB ✅ - Affiché 1 fois dans l'UI (docker-compose snippet) ✅ - Token + docker-compose copiable via bouton ✅ --- # Phase 8 — Agent Registration + Heartbeat ## Implémenté ### Côté Central | Méthode | Route | Auth | Status | |---|---|---|---| | `POST` | `/api/agents/register` | Token site | ✅ | | `POST` | `/api/agents/{id}/heartbeat` | API Key | ✅ | | `GET` | `/api/agents/{id}` | JWT | ✅ | | `GET` | `/api/agents/by-site/{siteId}` | JWT | ✅ | ### Côté Agent | Fonctionnalité | Status | |----------------|--------| | Registration avec token site | ✅ | | Réception API Key | ✅ | | Heartbeat toutes les 30s | ✅ | | API Key envoyée dans header Authorization | ✅ | | Détection GPU/CPU capabilities | ✅ | ### Surveillance heartbeat et failover (Hangfire) - Vérification et failover planifiés toutes les minutes ✅ - Le délai utilise l'intervalle global ou la surcharge de l'agent, avec deux intervalles et une marge d'ordonnanceur (minimum 90 s) ✅ - Le job de failover effectue la transition Offline et réessaie la réaffectation des caméras actives des agents déjà Offline ✅ - Les intervalles sont limités à 5–300 s, conformément à la plage appliquée par l'Agent ✅ --- # Phase 9 — ONVIF Discovery 🔴 **Nécessite du hardware (caméras réseau).** Reporté après le MVP logiciel. --- # Phase 10 — Camera Management API ## Implémenté | Méthode | Route | Auth | Status | |---|---|---|---| | `POST` | `/api/cameras` | JWT/Camera.Write | ✅ | | `GET` | `/api/cameras/{id}` | JWT/Camera.Read | ✅ | | `GET` | `/api/cameras/by-site/{siteId}` | JWT/Camera.Read | ✅ | | `PUT` | `/api/cameras/{id}` | JWT/Camera.Write | ✅ | | `DELETE` | `/api/cameras/{id}` | JWT/Camera.Write | ✅ | ### Interface Blazor | Page | Status | |------|--------| | Liste caméras par site | ✅ | | Détail caméra (éditable) | ✅ | | Création caméra (dialog) | ✅ | --- # Phase 11 — Video Pipeline (FFmpeg) # Phase 12 — AI Pipeline # Phase 13 — Storage (RustFS/S3) # Phase 14 — SignalR Hubs 🔴 **Nécessitent du hardware + dépendances natives.** Reportées en v2. --- # Phase 15 — Hangfire Central ## Implémenté | Composant | Status | |-----------|--------| | Hangfire avec PostgreSQL | ✅ | | Schéma isolé (`hangfire`) | ✅ | | HeartbeatMonitorJob (toutes les minutes) | ✅ | | Queue heartbeat dédiée | ✅ | ## Jobs à implémenter (v2) | Job | Schedule | |-----|----------| | RetentionCheck | Quotidien 3h | | S3Cleanup | Quotidien 4h | | DailyDigest | Quotidien 8h | | DatabaseMaintenance | Hebdomadaire | --- # Phase 16 — Hangfire Agent (InMemory) ⏳ Reporté à la phase de déploiement Agent réel. --- # Phase 17 — Notifications ⏳ Reporté en v2. --- # Phase 18 — Blazor UI ## Implémenté | Page | Route | Auth | Status | |------|-------|------|--------| | **Login** | `/login` | — | ✅ | | **Register** | `/register` | — | ✅ | | **Dashboard** | `/dashboard` | JWT | ✅ | | **Sites** | `/sites` | JWT | ✅ | | **Site détail** | `/sites/{id}` | JWT | ✅ | | **Caméras d'un site** | `/sites/{id}/cameras` | JWT | ✅ | | **Caméra détail** | `/cameras/{id}` | JWT | ✅ | | **Agents d'un site** | `/sites/{id}/agents` | JWT | ✅ | | **Agent détail** | `/agents/{id}` | JWT | ✅ | | **Utilisateurs** | `/users` | JWT/Admin | ✅ | | **Journal d'audit** | `/audit-logs` | JWT/Admin | ✅ | | **RedirectToLogin** | (composant) | — | ✅ | | **NotFound** | (page 404) | — | ✅ | ## Stack UI | Technologie | Status | |-------------|--------| | MudBlazor 9.1.0 | ✅ | | Inter Font | ✅ | | Thème clair/sombre | ✅ | | Navigation responsive | ✅ | | Auth redirect avec returnUrl | ✅ | | Requêtes API parallèles (Dashboard) | ✅ | ## Pages à implémenter (v2) | Page | Priorité | |------|----------| | Événements liste | P1 | | Personnes liste | P1 | | Administration (jobs Hangfire) | P1 | | Live vidéo | P2 | --- # Phase 19 — WebRTC Streaming # Phase 20 — Blazor UI Live Vidéo ⏳ Reporté en v2. --- # Phase 21 — Application web installable (PWA) Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et la [liste de travaux](../todo.md). --- # Phase 22 — Dashboard KPI ## Implémenté | Widget | Source | Status | |--------|--------|--------| | Total sites | `GET /api/stats` | ✅ | | Total caméras | `GET /api/stats` | ✅ | | Agents en ligne | `GET /api/stats` | ✅ | | Sites actifs | `GET /api/stats` | ✅ | | Sites récents (tableau) | `GET /api/sites` | ✅ | | Chargement parallèle | `Task.WhenAll` | ✅ | --- # Phase 23 — Production Hardening ## Implémenté - [x] Health checks (/healthz, /readyz) - [x] Rate limiting (Auth: 10/min, API: 200/min) - [x] CORS configurable - [x] Docker Compose production-ready - [x] Documentation API (Scalar UI) - [x] README avec architecture + setup ## À faire - [ ] Serilog + Seq/GlitchTip - [ ] Métriques Prometheus - [ ] Backup PostgreSQL automatisé - [ ] Backup RustFS (S3 → S3) - [ ] Tests de charge (k6) - [ ] Security audit (pentest) --- ## Résumé — Stats MVP | Métrique | Valeur | |----------|--------| | Projets | 17 (9 src + 8 tests) | | Fichiers .cs | 83 | | Pages Blazor | 13 | | Tests | 34 (13 domain + 16 integration + 5 placeholder) | | Build | 0 errors, 0 warnings | | Commits | 45 | | Conteneurs Docker | 5 (postgresql, rustfs, central, workers, agent) | | Endpoints API | 30+ |